"""User accounts, password hashing, sessions, and the scope matcher. Everything is stdlib crypto: PBKDF2-HMAC-SHA256 for passwords, HMAC-signed stateless tokens for sessions (they survive backend restarts; "logout" is the client dropping its cookie). Users live in config.json -> "users": "julian": { "password": "pbkdf2$600000$$", "scopes": ["admin"], # or charger::, relay: "id_tag": "app-julian" # idTag used for their remote starts } Scopes are matched with fnmatch, so "relay:*" or "charger:eu092025:*" work. "admin" implies every scope and is required for management endpoints. CLI (from the repo root): venv\\Scripts\\python -m backend.users add --scopes admin venv\\Scripts\\python -m backend.users list venv\\Scripts\\python -m backend.users remove """ import base64 import hashlib import hmac import secrets import time from fnmatch import fnmatch from .config import CONFIG, save PBKDF2_ITERATIONS = 600_000 SESSION_TTL = 30 * 24 * 3600 # 30 days # ---- passwords ---- def hash_password(password: str) -> str: salt = secrets.token_hex(16) digest = hashlib.pbkdf2_hmac( "sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS ) return f"pbkdf2${PBKDF2_ITERATIONS}${salt}${digest.hex()}" def verify_password(password: str, stored: str) -> bool: try: scheme, iterations, salt, expected = stored.split("$") if scheme != "pbkdf2": return False digest = hashlib.pbkdf2_hmac( "sha256", password.encode(), bytes.fromhex(salt), int(iterations) ) return hmac.compare_digest(digest.hex(), expected) except (ValueError, AttributeError): return False # ---- sessions (stateless HMAC tokens) ---- def _secret() -> bytes: return CONFIG["session_secret"].encode() def _sign(payload: str) -> str: return hmac.new(_secret(), payload.encode(), hashlib.sha256).hexdigest() def mint_session(username: str) -> str: payload = f"{username}|{int(time.time()) + SESSION_TTL}" token = f"{payload}|{_sign(payload)}" return base64.urlsafe_b64encode(token.encode()).decode() def verify_session(token: str) -> str | None: """Return the username for a valid, unexpired token; None otherwise.""" try: username, expires, signature = ( base64.urlsafe_b64decode(token.encode()).decode().split("|") ) except Exception: return None if not hmac.compare_digest(_sign(f"{username}|{expires}"), signature): return None if int(expires) < time.time(): return None if username not in CONFIG["users"]: return None # deleted users lose their sessions return username # ---- scopes ---- def allowed(scopes: list, needed: str) -> bool: return any( grant in ("*", "admin") or fnmatch(needed, grant) for grant in scopes ) # ---- user management (used by the CLI and the admin API) ---- def set_user(name: str, password: str | None = None, scopes: list | None = None) -> dict: user = CONFIG["users"].get(name, {"scopes": [], "id_tag": f"app-{name}"}) if password is not None: user["password"] = hash_password(password) if scopes is not None: user["scopes"] = scopes user.setdefault("id_tag", f"app-{name}") if "password" not in user: raise ValueError(f"new user {name!r} needs a password") CONFIG["users"][name] = user save() return user def remove_user(name: str) -> None: if CONFIG["users"].pop(name, None) is None: raise KeyError(name) save() def public_view(name: str, user: dict) -> dict: """A user entry without the password hash — safe for /api/me and /api/users.""" return {"name": name, "scopes": user["scopes"], "id_tag": user.get("id_tag")} def _cli() -> None: import argparse import getpass parser = argparse.ArgumentParser(prog="backend.users", description=__doc__) sub = parser.add_subparsers(dest="cmd", required=True) p_add = sub.add_parser("add", help="add a user or update an existing one") p_add.add_argument("name") p_add.add_argument("--scopes", nargs="+", default=None, help='e.g. admin, "charger:eu092025:1", "relay:*"') sub.add_parser("list", help="list users and their scopes") p_rm = sub.add_parser("remove", help="delete a user") p_rm.add_argument("name") args = parser.parse_args() if args.cmd == "list": for name, user in CONFIG["users"].items(): print(f"{name:20} scopes={user['scopes']} id_tag={user.get('id_tag')}") if not CONFIG["users"]: print("no users configured — the API is OPEN (anonymous admin)") elif args.cmd == "add": existing = args.name in CONFIG["users"] password = getpass.getpass(f"{'New ' if not existing else ''}password for {args.name!r}: ") if not existing or password: confirm = getpass.getpass("Repeat password: ") if password != confirm: raise SystemExit("passwords do not match") user = set_user(args.name, password=password or None, scopes=args.scopes) print(f"{'updated' if existing else 'created'} {args.name!r}: scopes={user['scopes']}") elif args.cmd == "remove": remove_user(args.name) print(f"removed {args.name!r}") if __name__ == "__main__": _cli()