Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/object_credentials.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_credentials.py · 9.3 KB · 317 lines
1"""File-backed password credentials for DBBASIC identity users.
2
3Credential hashes live in their own TSV under the identity directory, separate
4from users.tsv, so user API payloads can never include credential material.
5Hashes use scrypt from the standard library and verification is constant-time.
6The credentials file is written with owner-only permissions and belongs to the
7runtime data directory, which stays out of source control.
8"""
9
10from __future__ import annotations
11
12import csv
13import hashlib
14import hmac
15import os
16import secrets
17import threading
18from dataclasses import dataclass
19from datetime import datetime, timezone
20from pathlib import Path
21from typing import Iterable, Mapping
22
23from object_versions import DEFAULT_DATA_DIR
24
25IDENTITY_DIR = "identity"
26CREDENTIALS_FILE = "credentials.tsv"
27CREDENTIAL_FIELDS = (
28 "user_id",
29 "password_hash",
30 "created_at",
31 "updated_at",
32)
33MIN_PASSWORD_LENGTH = 8
34MAX_PASSWORD_LENGTH = 1024
35SCRYPT_N = 2**14
36SCRYPT_R = 8
37SCRYPT_P = 1
38SCRYPT_SALT_BYTES = 16
39SCRYPT_KEY_BYTES = 32
40HASH_PREFIX = "scrypt"
41
42_FILE_LOCKS: dict[Path, threading.Lock] = {}
43_FILE_LOCKS_LOCK = threading.Lock()
44
45
46class InvalidPasswordError(ValueError):
47 """Raised when a password payload is not usable."""
48
49
50@dataclass(frozen=True)
51class StoredCredential:
52 """One user's stored password hash."""
53
54 user_id: str
55 password_hash: str
56 created_at: str
57 updated_at: str
58
59
60def credentials_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
61 root = Path(base_dir) / IDENTITY_DIR
62 path = root / CREDENTIALS_FILE
63 resolved_root = root.resolve(strict=False)
64 resolved_path = path.resolve(strict=False)
65
66 try:
67 resolved_path.relative_to(resolved_root)
68 except ValueError as exc:
69 raise ValueError("Credentials path escapes identity directory") from exc
70
71 return path
72
73
74def hash_password(password: str) -> str:
75 """Hash one password into the stored scrypt format."""
76 _validate_password(password)
77 salt = secrets.token_bytes(SCRYPT_SALT_BYTES)
78 derived = _derive_key(password, salt)
79 return (
80 f"{HASH_PREFIX}:{SCRYPT_N}:{SCRYPT_R}:{SCRYPT_P}"
81 f":{salt.hex()}:{derived.hex()}"
82 )
83
84
85def set_password(
86 user_id: str,
87 password: str,
88 *,
89 base_dir: Path | str = DEFAULT_DATA_DIR,
90 now: datetime | None = None,
91) -> dict[str, str]:
92 """Create or replace one user's password hash and return safe metadata."""
93 normalized_user_id = _required_user_id(user_id)
94 password_hash = hash_password(password)
95 timestamp = _format_timestamp(now or _now())
96
97 path = credentials_path(base_dir)
98 with _file_lock(path):
99 credentials = _read_credentials(path)
100 existing = _pop_credential(credentials, normalized_user_id)
101 credentials.append(
102 StoredCredential(
103 user_id=normalized_user_id,
104 password_hash=password_hash,
105 created_at=existing.created_at if existing is not None else timestamp,
106 updated_at=timestamp,
107 )
108 )
109 _write_credentials(path, credentials)
110
111 return {
112 "user_id": normalized_user_id,
113 "operation": "replaced" if existing is not None else "created",
114 "updated_at": timestamp,
115 }
116
117
118def verify_password(
119 user_id: str,
120 password: str,
121 *,
122 base_dir: Path | str = DEFAULT_DATA_DIR,
123) -> bool:
124 """Verify one password in constant time; unknown users burn one dummy hash."""
125 if not isinstance(password, str) or not isinstance(user_id, str):
126 return False
127
128 credential = _find_credential(user_id.strip(), base_dir=base_dir)
129 if credential is None:
130 _burn_dummy_hash(password)
131 return False
132
133 try:
134 salt, expected = _parse_hash(credential.password_hash)
135 except InvalidPasswordError:
136 _burn_dummy_hash(password)
137 return False
138
139 try:
140 derived = _derive_key(password, salt)
141 except (ValueError, TypeError):
142 return False
143 return hmac.compare_digest(derived, expected)
144
145
146def remove_password(
147 user_id: str,
148 *,
149 base_dir: Path | str = DEFAULT_DATA_DIR,
150) -> bool:
151 """Delete one user's stored hash; return whether one existed."""
152 normalized_user_id = _required_user_id(user_id)
153 path = credentials_path(base_dir)
154 with _file_lock(path):
155 credentials = _read_credentials(path)
156 existing = _pop_credential(credentials, normalized_user_id)
157 if existing is None:
158 return False
159 _write_credentials(path, credentials)
160 return True
161
162
163def has_password(
164 user_id: str,
165 *,
166 base_dir: Path | str = DEFAULT_DATA_DIR,
167) -> bool:
168 """Return whether one user has a stored password hash."""
169 if not isinstance(user_id, str):
170 return False
171 return _find_credential(user_id.strip(), base_dir=base_dir) is not None
172
173
174def _validate_password(password: str) -> None:
175 if not isinstance(password, str):
176 raise InvalidPasswordError("password must be a string")
177 if len(password) < MIN_PASSWORD_LENGTH:
178 raise InvalidPasswordError(
179 f"password must be at least {MIN_PASSWORD_LENGTH} characters"
180 )
181 if len(password) > MAX_PASSWORD_LENGTH:
182 raise InvalidPasswordError(
183 f"password must be at most {MAX_PASSWORD_LENGTH} characters"
184 )
185
186
187def _derive_key(password: str, salt: bytes) -> bytes:
188 return hashlib.scrypt(
189 password.encode("utf-8"),
190 salt=salt,
191 n=SCRYPT_N,
192 r=SCRYPT_R,
193 p=SCRYPT_P,
194 dklen=SCRYPT_KEY_BYTES,
195 )
196
197
198def _burn_dummy_hash(password: str) -> None:
199 try:
200 _derive_key(password if isinstance(password, str) else "", b"\x00" * SCRYPT_SALT_BYTES)
201 except (ValueError, TypeError):
202 pass
203
204
205def _parse_hash(stored: str) -> tuple[bytes, bytes]:
206 parts = (stored or "").split(":")
207 if len(parts) != 6 or parts[0] != HASH_PREFIX:
208 raise InvalidPasswordError("stored password hash is invalid")
209 try:
210 n, r, p = int(parts[1]), int(parts[2]), int(parts[3])
211 salt = bytes.fromhex(parts[4])
212 expected = bytes.fromhex(parts[5])
213 except ValueError as exc:
214 raise InvalidPasswordError("stored password hash is invalid") from exc
215 if (n, r, p) != (SCRYPT_N, SCRYPT_R, SCRYPT_P) or not salt or not expected:
216 raise InvalidPasswordError("stored password hash is invalid")
217 return salt, expected
218
219
220def _required_user_id(user_id: str) -> str:
221 if not isinstance(user_id, str):
222 raise InvalidPasswordError("user_id must be a string")
223 text = user_id.strip()
224 if not text:
225 raise InvalidPasswordError("user_id is required")
226 return text
227
228
229def _find_credential(
230 user_id: str,
231 *,
232 base_dir: Path | str,
233) -> StoredCredential | None:
234 if not user_id:
235 return None
236 for credential in _read_credentials(credentials_path(base_dir)):
237 if credential.user_id == user_id:
238 return credential
239 return None
240
241
242def _pop_credential(
243 credentials: list[StoredCredential],
244 user_id: str,
245) -> StoredCredential | None:
246 for index, credential in enumerate(credentials):
247 if credential.user_id == user_id:
248 return credentials.pop(index)
249 return None
250
251
252def _read_credentials(path: Path) -> list[StoredCredential]:
253 if not path.exists():
254 return []
255
256 credentials: list[StoredCredential] = []
257 with path.open(newline="") as handle:
258 rows = csv.DictReader(handle, delimiter="\t")
259 for row in rows:
260 if not row:
261 continue
262 credential = _credential_from_row(row)
263 if credential is not None:
264 credentials.append(credential)
265 return credentials
266
267
268def _write_credentials(path: Path, credentials: Iterable[StoredCredential]) -> None:
269 path.parent.mkdir(parents=True, exist_ok=True)
270 temp_path = path.with_name(f".{path.name}.tmp")
271 with temp_path.open("w", newline="") as handle:
272 writer = csv.DictWriter(handle, fieldnames=CREDENTIAL_FIELDS, delimiter="\t")
273 writer.writeheader()
274 for credential in credentials:
275 writer.writerow(
276 {
277 "user_id": credential.user_id,
278 "password_hash": credential.password_hash,
279 "created_at": credential.created_at,
280 "updated_at": credential.updated_at,
281 }
282 )
283 os.chmod(temp_path, 0o600)
284 temp_path.replace(path)
285
286
287def _credential_from_row(row: Mapping[str, str]) -> StoredCredential | None:
288 user_id = (row.get("user_id") or "").strip()
289 password_hash = (row.get("password_hash") or "").strip()
290 created_at = (row.get("created_at") or "").strip()
291 updated_at = (row.get("updated_at") or "").strip()
292 if not user_id or not password_hash or not created_at or not updated_at:
293 return None
294 return StoredCredential(
295 user_id=user_id,
296 password_hash=password_hash,
297 created_at=created_at,
298 updated_at=updated_at,
299 )
300
301
302def _format_timestamp(value: datetime) -> str:
303 return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
304
305
306def _now() -> datetime:
307 return datetime.now(timezone.utc)
308
309
310def _file_lock(path: Path) -> threading.Lock:
311 resolved = path.resolve(strict=False)
312 with _FILE_LOCKS_LOCK:
313 lock = _FILE_LOCKS.get(resolved)
314 if lock is None:
315 lock = threading.Lock()
316 _FILE_LOCKS[resolved] = lock
317 return lock