askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_credentials.py · 12.0 KB · 379 lines
| 1 | """File-backed password credentials for DBBASIC identity users. |
| 2 | |
| 3 | Credential hashes live in their own TSV under the identity directory, separate |
| 4 | from users.tsv, so user API payloads can never include credential material. |
| 5 | Hashes use scrypt from the standard library and verification is constant-time. |
| 6 | The credentials file is written with owner-only permissions and belongs to the |
| 7 | runtime data directory, which stays out of source control. |
| 8 | |
| 9 | Every write of a password -- set, replace or remove, from any caller -- ends |
| 10 | the user's sessions here, after the credential is written: whoever signed in |
| 11 | with the old password is signed out (object_identity.revoke_user_sessions, the |
| 12 | same revocation the reset link always used). It lives in these two functions, |
| 13 | not in their callers, so a new way of setting a password cannot forget it. |
| 14 | API keys are left alone: a key is a separate credential, not derived from the |
| 15 | password. If the account was compromised, revoke its keys too, or disable the |
| 16 | user (which ends sessions and deletes keys). |
| 17 | """ |
| 18 | |
| 19 | from __future__ import annotations |
| 20 | |
| 21 | import csv |
| 22 | import hashlib |
| 23 | import hmac |
| 24 | import os |
| 25 | import secrets |
| 26 | import threading |
| 27 | from dataclasses import dataclass |
| 28 | from datetime import datetime, timezone |
| 29 | from pathlib import Path |
| 30 | from typing import Any, Iterable, Mapping |
| 31 | |
| 32 | import object_identity |
| 33 | from object_versions import DEFAULT_DATA_DIR |
| 34 | |
| 35 | IDENTITY_DIR = "identity" |
| 36 | CREDENTIALS_FILE = "credentials.tsv" |
| 37 | CREDENTIAL_FIELDS = ( |
| 38 | "user_id", |
| 39 | "password_hash", |
| 40 | "created_at", |
| 41 | "updated_at", |
| 42 | ) |
| 43 | MIN_PASSWORD_LENGTH = 8 |
| 44 | MAX_PASSWORD_LENGTH = 1024 |
| 45 | SCRYPT_N = 2**14 |
| 46 | SCRYPT_R = 8 |
| 47 | SCRYPT_P = 1 |
| 48 | SCRYPT_SALT_BYTES = 16 |
| 49 | SCRYPT_KEY_BYTES = 32 |
| 50 | HASH_PREFIX = "scrypt" |
| 51 | |
| 52 | _FILE_LOCKS: dict[Path, threading.Lock] = {} |
| 53 | _FILE_LOCKS_LOCK = threading.Lock() |
| 54 | |
| 55 | |
| 56 | class InvalidPasswordError(ValueError): |
| 57 | """Raised when a password payload is not usable.""" |
| 58 | |
| 59 | |
| 60 | class SessionRevocationError(RuntimeError): |
| 61 | """The password was written but the user's sessions could not be ended. |
| 62 | |
| 63 | Deliberately not an OSError/ValueError: callers treat those as "nothing |
| 64 | changed", and here something did. The new password is in force (rolling |
| 65 | back would reinstate the old one, which may be the one that leaked); |
| 66 | sessions signed in with the old one may still work. Writing the password |
| 67 | again retries the revocation. |
| 68 | """ |
| 69 | |
| 70 | def __init__(self, user_id: str, cause: BaseException) -> None: |
| 71 | super().__init__( |
| 72 | f"The password for user {user_id} was changed, but their existing sessions " |
| 73 | f"could not be ended ({cause.__class__.__name__}: {cause}). Anyone signed in " |
| 74 | "with the old password may still be signed in. Fix the sessions file and set " |
| 75 | "the password again, or disable the user." |
| 76 | ) |
| 77 | self.user_id = user_id |
| 78 | |
| 79 | |
| 80 | @dataclass(frozen=True) |
| 81 | class StoredCredential: |
| 82 | """One user's stored password hash.""" |
| 83 | |
| 84 | user_id: str |
| 85 | password_hash: str |
| 86 | created_at: str |
| 87 | updated_at: str |
| 88 | |
| 89 | |
| 90 | def credentials_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path: |
| 91 | root = Path(base_dir) / IDENTITY_DIR |
| 92 | path = root / CREDENTIALS_FILE |
| 93 | resolved_root = root.resolve(strict=False) |
| 94 | resolved_path = path.resolve(strict=False) |
| 95 | |
| 96 | try: |
| 97 | resolved_path.relative_to(resolved_root) |
| 98 | except ValueError as exc: |
| 99 | raise ValueError("Credentials path escapes identity directory") from exc |
| 100 | |
| 101 | return path |
| 102 | |
| 103 | |
| 104 | def hash_password(password: str) -> str: |
| 105 | """Hash one password into the stored scrypt format.""" |
| 106 | _validate_password(password) |
| 107 | salt = secrets.token_bytes(SCRYPT_SALT_BYTES) |
| 108 | derived = _derive_key(password, salt) |
| 109 | return ( |
| 110 | f"{HASH_PREFIX}:{SCRYPT_N}:{SCRYPT_R}:{SCRYPT_P}" |
| 111 | f":{salt.hex()}:{derived.hex()}" |
| 112 | ) |
| 113 | |
| 114 | |
| 115 | def set_password( |
| 116 | user_id: str, |
| 117 | password: str, |
| 118 | *, |
| 119 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 120 | now: datetime | None = None, |
| 121 | keep_session_id: str | None = None, |
| 122 | ) -> dict[str, Any]: |
| 123 | """Create or replace one user's password hash and return safe metadata. |
| 124 | |
| 125 | Then end every session of the user except keep_session_id (the caller's |
| 126 | own session when users change their own password, so the page they are on |
| 127 | keeps working). Raises SessionRevocationError if that fails. |
| 128 | """ |
| 129 | normalized_user_id = _required_user_id(user_id) |
| 130 | password_hash = hash_password(password) |
| 131 | timestamp = _format_timestamp(now or _now()) |
| 132 | |
| 133 | path = credentials_path(base_dir) |
| 134 | with _file_lock(path): |
| 135 | credentials = _read_credentials(path) |
| 136 | existing = _pop_credential(credentials, normalized_user_id) |
| 137 | credentials.append( |
| 138 | StoredCredential( |
| 139 | user_id=normalized_user_id, |
| 140 | password_hash=password_hash, |
| 141 | created_at=existing.created_at if existing is not None else timestamp, |
| 142 | updated_at=timestamp, |
| 143 | ) |
| 144 | ) |
| 145 | _write_credentials(path, credentials) |
| 146 | |
| 147 | sessions_revoked = _end_sessions( |
| 148 | normalized_user_id, base_dir=base_dir, now=now, keep_session_id=keep_session_id |
| 149 | ) |
| 150 | return { |
| 151 | "user_id": normalized_user_id, |
| 152 | "operation": "replaced" if existing is not None else "created", |
| 153 | "updated_at": timestamp, |
| 154 | "sessions_revoked": sessions_revoked, |
| 155 | } |
| 156 | |
| 157 | |
| 158 | def verify_password( |
| 159 | user_id: str, |
| 160 | password: str, |
| 161 | *, |
| 162 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 163 | ) -> bool: |
| 164 | """Verify one password in constant time; unknown users burn one dummy hash.""" |
| 165 | if not isinstance(password, str) or not isinstance(user_id, str): |
| 166 | return False |
| 167 | |
| 168 | credential = _find_credential(user_id.strip(), base_dir=base_dir) |
| 169 | if credential is None: |
| 170 | _burn_dummy_hash(password) |
| 171 | return False |
| 172 | |
| 173 | try: |
| 174 | salt, expected = _parse_hash(credential.password_hash) |
| 175 | except InvalidPasswordError: |
| 176 | _burn_dummy_hash(password) |
| 177 | return False |
| 178 | |
| 179 | try: |
| 180 | derived = _derive_key(password, salt) |
| 181 | except (ValueError, TypeError): |
| 182 | return False |
| 183 | return hmac.compare_digest(derived, expected) |
| 184 | |
| 185 | |
| 186 | def remove_password( |
| 187 | user_id: str, |
| 188 | *, |
| 189 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 190 | now: datetime | None = None, |
| 191 | keep_session_id: str | None = None, |
| 192 | ) -> bool: |
| 193 | """Delete one user's stored hash; return whether one existed. |
| 194 | |
| 195 | When one existed, end the user's sessions as set_password does. |
| 196 | """ |
| 197 | normalized_user_id = _required_user_id(user_id) |
| 198 | path = credentials_path(base_dir) |
| 199 | with _file_lock(path): |
| 200 | credentials = _read_credentials(path) |
| 201 | existing = _pop_credential(credentials, normalized_user_id) |
| 202 | if existing is None: |
| 203 | return False |
| 204 | _write_credentials(path, credentials) |
| 205 | _end_sessions(normalized_user_id, base_dir=base_dir, now=now, keep_session_id=keep_session_id) |
| 206 | return True |
| 207 | |
| 208 | |
| 209 | def _end_sessions( |
| 210 | user_id: str, |
| 211 | *, |
| 212 | base_dir: Path | str, |
| 213 | now: datetime | None, |
| 214 | keep_session_id: str | None, |
| 215 | ) -> int: |
| 216 | """Revoke the user's sessions after a password write; never half-silently.""" |
| 217 | try: |
| 218 | return object_identity.revoke_user_sessions( |
| 219 | user_id, base_dir=base_dir, now=now, keep_session_id=keep_session_id |
| 220 | ) |
| 221 | except Exception as exc: # noqa: BLE001 -- any failure here must be reported |
| 222 | raise SessionRevocationError(user_id, exc) from exc |
| 223 | |
| 224 | |
| 225 | def has_password( |
| 226 | user_id: str, |
| 227 | *, |
| 228 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 229 | ) -> bool: |
| 230 | """Return whether one user has a stored password hash.""" |
| 231 | if not isinstance(user_id, str): |
| 232 | return False |
| 233 | return _find_credential(user_id.strip(), base_dir=base_dir) is not None |
| 234 | |
| 235 | |
| 236 | def _validate_password(password: str) -> None: |
| 237 | if not isinstance(password, str): |
| 238 | raise InvalidPasswordError("password must be a string") |
| 239 | if len(password) < MIN_PASSWORD_LENGTH: |
| 240 | raise InvalidPasswordError( |
| 241 | f"password must be at least {MIN_PASSWORD_LENGTH} characters" |
| 242 | ) |
| 243 | if len(password) > MAX_PASSWORD_LENGTH: |
| 244 | raise InvalidPasswordError( |
| 245 | f"password must be at most {MAX_PASSWORD_LENGTH} characters" |
| 246 | ) |
| 247 | |
| 248 | |
| 249 | def _derive_key(password: str, salt: bytes) -> bytes: |
| 250 | return hashlib.scrypt( |
| 251 | password.encode("utf-8"), |
| 252 | salt=salt, |
| 253 | n=SCRYPT_N, |
| 254 | r=SCRYPT_R, |
| 255 | p=SCRYPT_P, |
| 256 | dklen=SCRYPT_KEY_BYTES, |
| 257 | ) |
| 258 | |
| 259 | |
| 260 | def _burn_dummy_hash(password: str) -> None: |
| 261 | try: |
| 262 | _derive_key(password if isinstance(password, str) else "", b"\x00" * SCRYPT_SALT_BYTES) |
| 263 | except (ValueError, TypeError): |
| 264 | pass |
| 265 | |
| 266 | |
| 267 | def _parse_hash(stored: str) -> tuple[bytes, bytes]: |
| 268 | parts = (stored or "").split(":") |
| 269 | if len(parts) != 6 or parts[0] != HASH_PREFIX: |
| 270 | raise InvalidPasswordError("stored password hash is invalid") |
| 271 | try: |
| 272 | n, r, p = int(parts[1]), int(parts[2]), int(parts[3]) |
| 273 | salt = bytes.fromhex(parts[4]) |
| 274 | expected = bytes.fromhex(parts[5]) |
| 275 | except ValueError as exc: |
| 276 | raise InvalidPasswordError("stored password hash is invalid") from exc |
| 277 | if (n, r, p) != (SCRYPT_N, SCRYPT_R, SCRYPT_P) or not salt or not expected: |
| 278 | raise InvalidPasswordError("stored password hash is invalid") |
| 279 | return salt, expected |
| 280 | |
| 281 | |
| 282 | def _required_user_id(user_id: str) -> str: |
| 283 | if not isinstance(user_id, str): |
| 284 | raise InvalidPasswordError("user_id must be a string") |
| 285 | text = user_id.strip() |
| 286 | if not text: |
| 287 | raise InvalidPasswordError("user_id is required") |
| 288 | return text |
| 289 | |
| 290 | |
| 291 | def _find_credential( |
| 292 | user_id: str, |
| 293 | *, |
| 294 | base_dir: Path | str, |
| 295 | ) -> StoredCredential | None: |
| 296 | if not user_id: |
| 297 | return None |
| 298 | for credential in _read_credentials(credentials_path(base_dir)): |
| 299 | if credential.user_id == user_id: |
| 300 | return credential |
| 301 | return None |
| 302 | |
| 303 | |
| 304 | def _pop_credential( |
| 305 | credentials: list[StoredCredential], |
| 306 | user_id: str, |
| 307 | ) -> StoredCredential | None: |
| 308 | for index, credential in enumerate(credentials): |
| 309 | if credential.user_id == user_id: |
| 310 | return credentials.pop(index) |
| 311 | return None |
| 312 | |
| 313 | |
| 314 | def _read_credentials(path: Path) -> list[StoredCredential]: |
| 315 | if not path.exists(): |
| 316 | return [] |
| 317 | |
| 318 | credentials: list[StoredCredential] = [] |
| 319 | with path.open(newline="") as handle: |
| 320 | rows = csv.DictReader(handle, delimiter="\t") |
| 321 | for row in rows: |
| 322 | if not row: |
| 323 | continue |
| 324 | credential = _credential_from_row(row) |
| 325 | if credential is not None: |
| 326 | credentials.append(credential) |
| 327 | return credentials |
| 328 | |
| 329 | |
| 330 | def _write_credentials(path: Path, credentials: Iterable[StoredCredential]) -> None: |
| 331 | path.parent.mkdir(parents=True, exist_ok=True) |
| 332 | temp_path = path.with_name(f".{path.name}.tmp") |
| 333 | with temp_path.open("w", newline="") as handle: |
| 334 | writer = csv.DictWriter(handle, fieldnames=CREDENTIAL_FIELDS, delimiter="\t") |
| 335 | writer.writeheader() |
| 336 | for credential in credentials: |
| 337 | writer.writerow( |
| 338 | { |
| 339 | "user_id": credential.user_id, |
| 340 | "password_hash": credential.password_hash, |
| 341 | "created_at": credential.created_at, |
| 342 | "updated_at": credential.updated_at, |
| 343 | } |
| 344 | ) |
| 345 | os.chmod(temp_path, 0o600) |
| 346 | temp_path.replace(path) |
| 347 | |
| 348 | |
| 349 | def _credential_from_row(row: Mapping[str, str]) -> StoredCredential | None: |
| 350 | user_id = (row.get("user_id") or "").strip() |
| 351 | password_hash = (row.get("password_hash") or "").strip() |
| 352 | created_at = (row.get("created_at") or "").strip() |
| 353 | updated_at = (row.get("updated_at") or "").strip() |
| 354 | if not user_id or not password_hash or not created_at or not updated_at: |
| 355 | return None |
| 356 | return StoredCredential( |
| 357 | user_id=user_id, |
| 358 | password_hash=password_hash, |
| 359 | created_at=created_at, |
| 360 | updated_at=updated_at, |
| 361 | ) |
| 362 | |
| 363 | |
| 364 | def _format_timestamp(value: datetime) -> str: |
| 365 | return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") |
| 366 | |
| 367 | |
| 368 | def _now() -> datetime: |
| 369 | return datetime.now(timezone.utc) |
| 370 | |
| 371 | |
| 372 | def _file_lock(path: Path) -> threading.Lock: |
| 373 | resolved = path.resolve(strict=False) |
| 374 | with _FILE_LOCKS_LOCK: |
| 375 | lock = _FILE_LOCKS.get(resolved) |
| 376 | if lock is None: |
| 377 | lock = threading.Lock() |
| 378 | _FILE_LOCKS[resolved] = lock |
| 379 | return lock |