feat(security): add tested Argon2id and explicit PBKDF2 upgrade verifier
Davood Mehraban committed
Nov 3, 2026 at 17:27 UTC
f3f37ee8fb4894006d4faa866dfa140926b1d96a
4 files changed
+149
backend/pyproject.toml
+1
@@ -14,6 +14,7 @@ dependencies = [
14
"sqlalchemy>=2.0,<3",
15
"uvicorn>=0.34,<1",
16
"openpyxl>=3.1,<4",
17
+ "argon2-cffi>=23.1,<26",
18
]
19
20
[project.optional-dependencies]
backend/src/aram_backend/password_security.py
new
+73
@@ -0,0 +1,73 @@
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 _validate_password(password: str) -> bytes:
28
+ if not isinstance(password, str):
29
+ raise TypeError("invalid password")
30
+ raw = password.encode("utf-8")
31
+ if not 14 <= len(password) <= 1024 or len(raw) > _MAX_PASSWORD_BYTES:
32
+ raise ValueError("invalid password")
33
+ return raw
34
+
35
+
36
+def hash_password(password: str) -> str:
37
+ _validate_password(password)
38
+ return _HASHER.hash(password)
39
+
40
+
41
+def verify_password(password: str, encoded: str) -> PasswordVerification:
42
+ if not isinstance(password, str) or not isinstance(encoded, str):
43
+ return PasswordVerification(False)
44
+ if len(password) > 1024 or len(password.encode("utf-8")) > _MAX_PASSWORD_BYTES:
45
+ return PasswordVerification(False)
46
+ if encoded.startswith("$argon2id$"):
47
+ try:
48
+ valid = _HASHER.verify(encoded, password)
49
+ return PasswordVerification(valid, _HASHER.hash(password) if valid and _HASHER.check_needs_rehash(encoded) else None)
50
+ except (InvalidHashError, VerificationError, ValueError):
51
+ return PasswordVerification(False)
52
+ # Explicit legacy format: pbkdf2_sha256$600000$<hex salt>$<hex digest>.
53
+ parts = encoded.split("$")
54
+ if len(parts) != 4 or parts[0] != "pbkdf2_sha256" or parts[1] != str(_LEGACY_ITERATIONS):
55
+ return PasswordVerification(False)
56
+ try:
57
+ salt = bytes.fromhex(parts[2])
58
+ expected = bytes.fromhex(parts[3])
59
+ if len(salt) != 32 or len(expected) != 32:
60
+ return PasswordVerification(False)
61
+ candidate = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, _LEGACY_ITERATIONS)
62
+ if not hmac.compare_digest(candidate, expected):
63
+ return PasswordVerification(False)
64
+ return PasswordVerification(True, hash_password(password))
65
+ except ValueError:
66
+ return PasswordVerification(False)
67
+
68
+
69
+def encode_legacy_credential(salt: bytes, digest: bytes) -> str:
70
+ """Serialize existing credential hashes without ever exposing the password."""
71
+ if not isinstance(salt, bytes) or len(salt) != 32 or not isinstance(digest, bytes) or len(digest) != 32:
72
+ raise ValueError("invalid legacy credential")
73
+ return f"pbkdf2_sha256${_LEGACY_ITERATIONS}${salt.hex()}${digest.hex()}"
backend/tests/test_password_security.py
new
+55
@@ -0,0 +1,55 @@
1
+"""Security tests: correct, invalid, malformed, migration and boundary paths."""
2
+import hashlib
3
+import secrets
4
+
5
+import pytest
6
+
7
+from aram_backend.password_security import (
8
+ encode_legacy_credential,
9
+ hash_password,
10
+ verify_password,
11
+)
12
+
13
+PASSWORD = "correct horse battery staple"
14
+
15
+
16
+def test_argon2id_round_trip_and_wrong_password():
17
+ encoded = hash_password(PASSWORD)
18
+ assert encoded.startswith("$argon2id$")
19
+ assert verify_password(PASSWORD, encoded).valid
20
+ assert verify_password(PASSWORD, encoded).upgraded_hash is None
21
+ assert not verify_password("incorrect password", encoded).valid
22
+
23
+
24
+def test_legacy_migration_and_no_plaintext_storage():
25
+ salt = secrets.token_bytes(32)
26
+ digest = hashlib.pbkdf2_hmac("sha256", PASSWORD.encode(), salt, 600_000)
27
+ encoded = encode_legacy_credential(salt, digest)
28
+ assert PASSWORD not in encoded
29
+ result = verify_password(PASSWORD, encoded)
30
+ assert result.valid and result.upgraded_hash.startswith("$argon2id$")
31
+ assert verify_password(PASSWORD, result.upgraded_hash).valid
32
+ assert not verify_password("incorrect password", encoded).valid
33
+
34
+
35
+@pytest.mark.parametrize("encoded", ["", "garbage", "$argon2id$bad", "pbkdf2_sha256$600000$00$00",
36
+ "pbkdf2_sha256$1$00$00", None])
37
+def test_malformed_hashes_fail_closed(encoded):
38
+ assert not verify_password(PASSWORD, encoded).valid
39
+
40
+
41
+@pytest.mark.parametrize("password", ["", "short", "x" * 1025, None])
42
+def test_invalid_provisioning(password):
43
+ with pytest.raises((ValueError, TypeError)):
44
+ hash_password(password)
45
+
46
+
47
+def test_password_unicode_and_boundary():
48
+ password = "رمز-آرام-" + "a" * 14
49
+ assert verify_password(password, hash_password(password)).valid
50
+ assert verify_password("x" * 1025, hash_password(PASSWORD)).valid is False
51
+
52
+
53
+def test_reject_bad_legacy_material():
54
+ with pytest.raises(ValueError):
55
+ encode_legacy_credential(b"x", b"y")
docs/GATE3_PACKAGE9_1_SECURITY_REPORT.md
new
+20
@@ -0,0 +1,20 @@
1
+# Gate 3 Package 9.1 — Security implementation evidence
2
+
3
+## Scope implemented
4
+- New isolated Argon2id password hash/verification module.
5
+- Explicit, read-only PBKDF2-SHA256 (600,000 iterations) legacy verification and one-way upgrade output.
6
+- Rejects malformed stored hashes, oversized input and invalid provisioning.
7
+- Argon2id configuration: 64 MiB, 3 passes, parallelism 2.
8
+- New tests cover valid, wrong, malformed, Unicode, size boundaries, legacy migration.
9
+
10
+## Architecture and safety
11
+- The legacy `local_auth.py` is intentionally **not migrated** in this patch: replacing a running credential provider without durable protected provisioning could lock out the owner.
12
+- Caller must atomically persist `upgraded_hash` after successful authentication before claiming a completed migration.
13
+- This isolated library is not yet an operational API identity provider.
14
+- Windows DPAPI provisioning, durable lockout, independent recovery escrow, session binding and end-to-end API authentication remain open.
15
+- No production financial data or credentials touched; no merge/release.
16
+- Review status: self-audit only, **not** independent approval.
17
+- Gate 3 remains **NO-GO**.
18
+
19
+## Verification
20
+See local terminal and GitHub CI on exact commit SHA. Do not mark the full security gate PASS solely because unit tests succeed.