102 lines
4.2 KiB
Python
102 lines
4.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Change the local Pipelines web sign-in password without restarting services."""
|
|
import argparse
|
|
import fcntl
|
|
import getpass
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
import sys
|
|
import tempfile
|
|
|
|
|
|
def auth_path(*, prefix=None, home=None, environ=None):
|
|
home = Path(home or Path.home())
|
|
env = os.environ if environ is None else environ
|
|
selected = Path(prefix or env.get("PIPELINES_PREFIX") or home / ".local/share/pipelines").expanduser().resolve()
|
|
explicit = env.get("PIPELINES_WEB_AUTH_FILE")
|
|
if explicit:
|
|
return Path(explicit).expanduser().absolute()
|
|
manifest = selected / "pipelines-install.json"
|
|
if manifest.exists():
|
|
if manifest.is_symlink() or manifest.stat().st_uid != os.getuid():
|
|
raise ValueError("Refusing an unsafe installation manifest")
|
|
data = json.loads(manifest.read_text())
|
|
if data.get("format") != 1 or data.get("prefix") != str(selected):
|
|
raise ValueError("Invalid Pipelines installation manifest")
|
|
recorded = (data.get("web") or {}).get("auth_file")
|
|
if recorded:
|
|
return Path(recorded).expanduser().absolute()
|
|
return home / ".config/pipelines/web-auth.json"
|
|
|
|
|
|
def read_auth(path):
|
|
path = Path(path)
|
|
info = path.lstat()
|
|
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid():
|
|
raise ValueError("Password file must be a regular file owned by this user")
|
|
if info.st_mode & 0o077:
|
|
raise ValueError(f"Password file must be private: chmod 600 '{path}'")
|
|
data = json.loads(path.read_text())
|
|
if not isinstance(data, dict) or not isinstance(data.get("password"), str) or len(data["password"]) < 8 or not isinstance(data.get("secret"), str) or len(data["secret"]) < 32:
|
|
raise ValueError("Invalid Pipelines password file; it was retained unchanged")
|
|
return data, info
|
|
|
|
|
|
def change_password(path, password):
|
|
if len(password) < 8:
|
|
raise ValueError("Choose a password of at least 8 characters")
|
|
path = Path(path)
|
|
# Lock the directory inode, which remains stable across atomic file replaces.
|
|
directory = os.open(path.parent, os.O_RDONLY)
|
|
try:
|
|
fcntl.flock(directory, fcntl.LOCK_EX)
|
|
data, original = read_auth(path)
|
|
data["password"] = password
|
|
descriptor, temporary = tempfile.mkstemp(prefix=".pipelines-password-", dir=path.parent)
|
|
try:
|
|
with os.fdopen(descriptor, "w") as output:
|
|
os.fchmod(output.fileno(), 0o600)
|
|
json.dump(data, output, indent=2)
|
|
output.write("\n")
|
|
output.flush()
|
|
os.fsync(output.fileno())
|
|
current = path.lstat()
|
|
if (current.st_dev, current.st_ino, current.st_mtime_ns, current.st_size) != (original.st_dev, original.st_ino, original.st_mtime_ns, original.st_size):
|
|
raise ValueError("Password file changed during the update; retry the command")
|
|
os.replace(temporary, path)
|
|
finally:
|
|
Path(temporary).unlink(missing_ok=True)
|
|
finally:
|
|
os.close(directory)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--prefix", type=Path, help="Installation prefix (or PIPELINES_PREFIX)")
|
|
args = parser.parse_args()
|
|
path = auth_path(prefix=args.prefix)
|
|
read_auth(path)
|
|
if not sys.stdin.isatty():
|
|
raise ValueError("Run ./password in an interactive terminal (SSH with a TTY is supported)")
|
|
while True:
|
|
password = getpass.getpass("New Pipelines password: ")
|
|
confirmation = getpass.getpass("Confirm new password: ")
|
|
if len(password) < 8:
|
|
print("Choose a password of at least 8 characters.", file=sys.stderr)
|
|
elif password != confirmation:
|
|
print("Passwords do not match. Try again.", file=sys.stderr)
|
|
else:
|
|
break
|
|
change_password(path, password)
|
|
print("Web sign-in password changed. No service restart is needed.")
|
|
print("Existing sessions remain signed in. The notification password is unchanged.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (OSError, ValueError, KeyboardInterrupt) as error:
|
|
sys.exit(f"Password not changed: {error}")
|