fix/password-unicode-validation-20261111
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 85 lines 3.27 KB
Raw
1 """Argon2id password hashing with explicit legacy PBKDF2 verification.
2
3 Only hashes are stored. Legacy verification is read-only; successful authentication
4 returns a replacement Argon2id hash for the caller to persist atomically.
5 """
6 from __future__ import annotations
7
8 import hashlib
9 import hmac
10 from dataclasses import dataclass
11
12 from argon2 import PasswordHasher, Type
13 from argon2.exceptions import InvalidHashError, VerificationError
14
15 _HASHER = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=2,
16 hash_len=32, salt_len=16, type=Type.ID)
17 _MAX_PASSWORD_BYTES = 4096
18 _LEGACY_ITERATIONS = 600_000
19
20
21 @dataclass(frozen=True)
22 class PasswordVerification:
23 valid: bool
24 upgraded_hash: str | None = None
25
26
27 def _encode_password(password: str) -> bytes:
28 """Encode a password strictly; reject lone surrogates as invalid input."""
29 if not isinstance(password, str):
30 raise TypeError("invalid password")
31 try:
32 return password.encode("utf-8")
33 except UnicodeEncodeError as exc:
34 raise ValueError("invalid password") from exc
35
36
37 def _validate_password(password: str) -> bytes:
38 raw = _encode_password(password)
39 if not 14 <= len(password) <= 1024 or len(raw) > _MAX_PASSWORD_BYTES:
40 raise ValueError("invalid password")
41 return raw
42
43
44 def hash_password(password: str) -> str:
45 _validate_password(password)
46 return _HASHER.hash(password)
47
48
49 def verify_password(password: str, encoded: str) -> PasswordVerification:
50 if not isinstance(password, str) or not isinstance(encoded, str):
51 return PasswordVerification(False)
52 try:
53 raw = _encode_password(password)
54 except (TypeError, ValueError):
55 return PasswordVerification(False)
56 if len(password) > 1024 or len(raw) > _MAX_PASSWORD_BYTES:
57 return PasswordVerification(False)
58 if encoded.startswith("$argon2id$"):
59 try:
60 valid = _HASHER.verify(encoded, password)
61 return PasswordVerification(valid, _HASHER.hash(password) if valid and _HASHER.check_needs_rehash(encoded) else None)
62 except (InvalidHashError, VerificationError, ValueError):
63 return PasswordVerification(False)
64 # Explicit legacy format: pbkdf2_sha256$600000$<hex salt>$<hex digest>.
65 parts = encoded.split("$")
66 if len(parts) != 4 or parts[0] != "pbkdf2_sha256" or parts[1] != str(_LEGACY_ITERATIONS):
67 return PasswordVerification(False)
68 try:
69 salt = bytes.fromhex(parts[2])
70 expected = bytes.fromhex(parts[3])
71 if len(salt) != 32 or len(expected) != 32:
72 return PasswordVerification(False)
73 candidate = hashlib.pbkdf2_hmac("sha256", raw, salt, _LEGACY_ITERATIONS)
74 if not hmac.compare_digest(candidate, expected):
75 return PasswordVerification(False)
76 return PasswordVerification(True, hash_password(password))
77 except ValueError:
78 return PasswordVerification(False)
79
80
81 def encode_legacy_credential(salt: bytes, digest: bytes) -> str:
82 """Serialize existing credential hashes without ever exposing the password."""
83 if not isinstance(salt, bytes) or len(salt) != 32 or not isinstance(digest, bytes) or len(digest) != 32:
84 raise ValueError("invalid legacy credential")
85 return "pbkdf2_sha256$" + str(_LEGACY_ITERATIONS) + "$" + salt.hex() + "$" + digest.hex()