Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 22:00 UTC
feat(security): wire Argon2id auth, DPAPI vault and recovery envelope
Davood Mehraban committed
Nov 3, 2026 at 18:08 UTC
18d6aa122d9486116c08d6e66b22675e0ebb1792
11 files changed
+608
-24
backend/src/aram_backend/auth_api.py
new
+85
@@ -0,0 +1,85 @@
1
+"""Fail-closed local authentication endpoints.
2
+
3
+The application does not provision credentials at import/startup. An explicit
4
+trusted composition root must configure the authority; otherwise login/logout
5
+return 503. This volatile adapter is for controlled single-user local use only.
6
+"""
7
+from __future__ import annotations
8
+
9
+from fastapi import APIRouter, Header, HTTPException
10
+from pydantic import BaseModel, Field
11
+
12
+from aram_backend.local_auth import LocalSessionAuthority
13
+from aram_backend.mapping_api import configure_mapping_service, reset_mapping_service
14
+from aram_backend.mapping_store import MappingStore
15
+from aram_backend.windows_credential_vault import load_credential
16
+
17
+router = APIRouter(prefix="/api/v1/auth", tags=["authentication"])
18
+_authority: LocalSessionAuthority | None = None
19
+
20
+
21
+class LoginRequest(BaseModel):
22
+ password: str = Field(min_length=1, max_length=1024)
23
+
24
+
25
+class LoginResponse(BaseModel):
26
+ access_token: str
27
+ token_type: str = "bearer"
28
+ expires_in: int
29
+
30
+
31
+class LogoutResponse(BaseModel):
32
+ revoked: bool
33
+
34
+
35
+def configure_local_auth_service(
36
+ *, authority: LocalSessionAuthority, store: MappingStore
37
+) -> None:
38
+ """Explicit server-side opt-in; never accept roles or scopes from HTTP."""
39
+ global _authority
40
+ _authority = authority
41
+ configure_mapping_service(store=store, identity_resolver=authority.resolve)
42
+
43
+
44
+def configure_local_auth_from_vault(
45
+ *, credential_path: str, store: MappingStore
46
+) -> None:
47
+ """Load a CurrentUser-DPAPI credential; any failure leaves service disabled."""
48
+ credential = load_credential(credential_path)
49
+ configure_local_auth_service(
50
+ authority=LocalSessionAuthority(credential), store=store
51
+ )
52
+
53
+
54
+def reset_local_auth_service() -> None:
55
+ global _authority
56
+ if _authority is not None:
57
+ _authority.revoke_all()
58
+ _authority = None
59
+ reset_mapping_service()
60
+
61
+
62
+@router.post("/login", response_model=LoginResponse)
63
+def login(payload: LoginRequest) -> LoginResponse:
64
+ if _authority is None:
65
+ raise HTTPException(status_code=503, detail="authentication service not configured")
66
+ token = _authority.login(payload.password)
67
+ if token is None:
68
+ raise HTTPException(status_code=401, detail="invalid credentials or temporarily locked")
69
+ return LoginResponse(
70
+ access_token=token, expires_in=_authority.lifetime_seconds
71
+ )
72
+
73
+
74
+@router.post("/logout", response_model=LogoutResponse)
75
+def logout(authorization: str | None = Header(default=None)) -> LogoutResponse:
76
+ if _authority is None:
77
+ raise HTTPException(status_code=503, detail="authentication service not configured")
78
+ if not authorization or not authorization.startswith("Bearer "):
79
+ raise HTTPException(status_code=401, detail="Bearer authentication required")
80
+ token = authorization[7:]
81
+ if not token or token != token.strip():
82
+ raise HTTPException(status_code=401, detail="invalid bearer token")
83
+ was_valid = _authority.resolve(token) is not None
84
+ _authority.revoke(token)
85
+ return LogoutResponse(revoked=was_valid)
backend/src/aram_backend/config.py
+2
@@ -7,6 +7,8 @@ class Settings(BaseSettings):
7
app_name: str = "Aram API"
8
environment: str = "development"
9
database_url: str = "sqlite:///./aram.db"
10
+ mapping_store_path: str = "./aram-mappings.db"
11
+ credential_vault_path: str | None = None
12
model_config = SettingsConfigDict(env_prefix="ARAM_", env_file=".env")
13
14
backend/src/aram_backend/credential_recovery.py
new
+83
@@ -0,0 +1,83 @@
1
+"""Passphrase-encrypted offline recovery envelope for a local credential.
2
+
3
+The envelope is portable across Windows profiles. Its passphrase must be stored
4
+separately and never placed beside the envelope. This module does not upload
5
+anything to cloud storage or prove that an external copy exists.
6
+"""
7
+from __future__ import annotations
8
+
9
+import base64
10
+import json
11
+import secrets
12
+
13
+from cryptography.hazmat.primitives.ciphers.aead import AESGCM
14
+from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
15
+
16
+from aram_backend.local_auth import LocalCredential
17
+
18
+_VERSION = 1
19
+_SCRYPT_N = 1 << 15
20
+_SCRYPT_R = 8
21
+_SCRYPT_P = 1
22
+
23
+
24
+def _derive(passphrase: str, salt: bytes) -> bytes:
25
+ if not isinstance(passphrase, str) or not 16 <= len(passphrase) <= 1024:
26
+ raise ValueError("recovery passphrase must be 16 to 1024 characters")
27
+ return Scrypt(salt=salt, length=32, n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P).derive(
28
+ passphrase.encode("utf-8")
29
+ )
30
+
31
+
32
+def export_recovery_envelope(credential: LocalCredential, passphrase: str) -> bytes:
33
+ salt = secrets.token_bytes(16)
34
+ nonce = secrets.token_bytes(12)
35
+ key = _derive(passphrase, salt)
36
+ payload = json.dumps({
37
+ "subject": credential.subject,
38
+ "company_scopes": sorted(credential.company_scopes),
39
+ "roles": sorted(credential.roles),
40
+ "password_hash": credential.password_hash,
41
+ }, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
42
+ ciphertext = AESGCM(key).encrypt(nonce, payload, b"Aram.CredentialRecovery.v1")
43
+ envelope = {
44
+ "version": _VERSION,
45
+ "kdf": "scrypt-32768-8-1",
46
+ "salt": base64.b64encode(salt).decode("ascii"),
47
+ "nonce": base64.b64encode(nonce).decode("ascii"),
48
+ "ciphertext": base64.b64encode(ciphertext).decode("ascii"),
49
+ }
50
+ return json.dumps(envelope, sort_keys=True, separators=(",", ":")).encode("ascii")
51
+
52
+
53
+def import_recovery_envelope(envelope: bytes, passphrase: str) -> LocalCredential:
54
+ if not isinstance(envelope, bytes) or not 1 <= len(envelope) <= 1_048_576:
55
+ raise ValueError("invalid recovery envelope")
56
+ try:
57
+ record = json.loads(envelope)
58
+ if record.get("version") != _VERSION or record.get("kdf") != "scrypt-32768-8-1":
59
+ raise ValueError("unsupported recovery envelope")
60
+ salt = base64.b64decode(record["salt"], validate=True)
61
+ nonce = base64.b64decode(record["nonce"], validate=True)
62
+ ciphertext = base64.b64decode(record["ciphertext"], validate=True)
63
+ if len(salt) != 16 or len(nonce) != 12 or not 16 <= len(ciphertext) <= 65536:
64
+ raise ValueError("invalid recovery envelope")
65
+ key = _derive(passphrase, salt)
66
+ payload = AESGCM(key).decrypt(
67
+ nonce, ciphertext, b"Aram.CredentialRecovery.v1"
68
+ )
69
+ data = json.loads(payload)
70
+ subject = data["subject"]
71
+ companies = frozenset(data["company_scopes"])
72
+ roles = frozenset(data["roles"])
73
+ password_hash = data["password_hash"]
74
+ if (
75
+ not isinstance(subject, str) or not subject.strip() or len(subject) > 200
76
+ or not companies or any(not isinstance(x, str) or not x.strip() or len(x) > 64 for x in companies)
77
+ or not roles or not roles.issubset({"maker", "reviewer", "approver", "owner"})
78
+ or not isinstance(password_hash, str) or len(password_hash) > 1024
79
+ ):
80
+ raise ValueError("invalid recovered credential")
81
+ return LocalCredential(subject, companies, roles, password_hash)
82
+ except (KeyError, TypeError, json.JSONDecodeError, base64.binascii.Error) as exc:
83
+ raise ValueError("invalid recovery envelope") from exc
backend/src/aram_backend/local_auth.py
+44
-24
@@ -1,21 +1,24 @@
1
-"""Opt-in local password verification and bounded opaque sessions.
1
+"""Single-owner local session adapter; not a substitute for an enterprise IdP.
2
3
-This remains a single-owner local adapter. It is not a production IdP and must
4
-not be enabled until credential provisioning, DPAPI key custody, API wiring,
5
-and deployment binding have been reviewed.
3
+Credentials use Argon2id. Imported PBKDF2 credentials are upgraded after a
4
+successful login. Sessions and lockout state are process-local and fail closed
5
+on restart; do not expose this adapter publicly without persistent controls.
6
"""
7
from __future__ import annotations
8
9
import hashlib
10
-import hmac
10
import secrets
11
import threading
12
import time
14
-from dataclasses import dataclass
13
+from dataclasses import dataclass, replace
14
15
from aram_backend.mapping_access import AuthenticatedPrincipal
16
+from aram_backend.password_security import (
17
+ encode_legacy_credential,
18
+ hash_password,
19
+ verify_password,
20
+)
21
18
-_PBKDF2_ITERATIONS = 600_000
22
_MAX_PASSWORD_LENGTH = 1024
23
_ALLOWED_ROLES = frozenset({"maker", "reviewer", "approver", "owner"})
24
@@ -25,8 +28,7 @@ class LocalCredential:
28
subject: str
29
company_scopes: frozenset[str]
30
roles: frozenset[str]
28
- salt: bytes
29
- password_hash: bytes
31
+ password_hash: str
32
33
34
def create_credential(
@@ -47,19 +49,34 @@ def create_credential(
49
or not roles.issubset(_ALLOWED_ROLES)
50
):
51
raise ValueError("invalid local credential configuration")
50
- salt = secrets.token_bytes(32)
51
- digest = hashlib.pbkdf2_hmac(
52
- "sha256", password.encode("utf-8"), salt, _PBKDF2_ITERATIONS
52
+ return LocalCredential(
53
+ subject.strip(), frozenset(companies), frozenset(roles), hash_password(password)
54
)
54
- return LocalCredential(subject.strip(), frozenset(companies), frozenset(roles), salt, digest)
55
+
56
+
57
+def import_legacy_credential(
58
+ subject: str,
59
+ companies: frozenset[str],
60
+ roles: frozenset[str],
61
+ salt: bytes,
62
+ password_hash: bytes,
63
+) -> LocalCredential:
64
+ """Import old PBKDF2 material without receiving or storing plaintext."""
65
+ if (
66
+ not isinstance(subject, str) or not subject.strip() or len(subject) > 200
67
+ or not companies or any(not isinstance(c, str) or not c.strip() or len(c) > 64 for c in companies)
68
+ or not roles or not roles.issubset(_ALLOWED_ROLES)
69
+ ):
70
+ raise ValueError("invalid local credential configuration")
71
+ encoded = encode_legacy_credential(salt, password_hash)
72
+ return LocalCredential(subject.strip(), frozenset(companies), frozenset(roles), encoded)
73
74
75
class LocalSessionAuthority:
58
- """Volatile, single-credential session authority with bounded lockout.
76
+ """Volatile single-credential sessions with bounded lockout.
77
60
- Restart revokes all sessions and clears lockout state. Persisted identity,
61
- multi-user account management, and cross-process rate limiting are out of
62
- scope; do not expose this adapter on a public network.
78
+ Restart revokes all sessions and clears lockout. Lockout is process-local;
79
+ persistent cross-process rate limiting and durable identity are not provided.
80
"""
81
82
def __init__(
@@ -89,6 +106,10 @@ class LocalSessionAuthority:
106
self._sessions: dict[bytes, float] = {}
107
self._lock = threading.RLock()
108
109
+ @property
110
+ def lifetime_seconds(self) -> int:
111
+ return self._lifetime
112
+
113
def login(self, password: str) -> str | None:
114
if not isinstance(password, str) or len(password) > _MAX_PASSWORD_LENGTH:
115
return None
@@ -96,19 +117,18 @@ class LocalSessionAuthority:
117
now = time.monotonic()
118
if now < self._locked_until:
119
return None
99
- candidate = hashlib.pbkdf2_hmac(
100
- "sha256",
101
- password.encode("utf-8"),
102
- self._credential.salt,
103
- _PBKDF2_ITERATIONS,
104
- )
105
- if not hmac.compare_digest(candidate, self._credential.password_hash):
120
+ verification = verify_password(password, self._credential.password_hash)
121
+ if not verification.valid:
122
self._failed_attempts += 1
123
if self._failed_attempts >= self._max_failed_attempts:
124
self._locked_until = now + self._lockout_seconds
125
self._failed_attempts = 0
126
return None
127
128
+ if verification.upgraded_hash is not None:
129
+ self._credential = replace(
130
+ self._credential, password_hash=verification.upgraded_hash
131
+ )
132
self._failed_attempts = 0
133
self._locked_until = 0.0
134
self._prune_expired(now)
backend/src/aram_backend/main.py
+13
@@ -1,8 +1,15 @@
1
from fastapi import FastAPI
2
3
from aram_backend import __version__
4
+from aram_backend.auth_api import (
5
+ configure_local_auth_from_vault,
6
+)
7
+from aram_backend.auth_api import (
8
+ router as auth_router,
9
+)
10
from aram_backend.config import get_settings
11
from aram_backend.mapping_api import router as mapping_router
12
+from aram_backend.mapping_store import MappingStore
13
from aram_backend.models import FiscalYearStatus, StatementType
14
from aram_backend.schemas import (
15
EntityDescriptor,
@@ -13,7 +20,13 @@ from aram_backend.schemas import (
20
21
settings = get_settings()
22
app = FastAPI(title=settings.app_name, version=__version__)
23
+app.include_router(auth_router)
24
app.include_router(mapping_router)
25
+if settings.credential_vault_path:
26
+ configure_local_auth_from_vault(
27
+ credential_path=settings.credential_vault_path,
28
+ store=MappingStore(settings.mapping_store_path),
29
+ )
30
31
32
@app.get("/api/v1/health", response_model=HealthResponse, tags=["system"])
backend/src/aram_backend/windows_credential_vault.py
new
+126
@@ -0,0 +1,126 @@
1
+"""Current-user Windows DPAPI credential vault.
2
+
3
+DPAPI CurrentUser protects a credential record at rest for the Windows user
4
+profile that provisioned it. It is not an independent disaster-recovery copy:
5
+profile loss can make the record unrecoverable. Store the vault on a local,
6
+user-controlled NTFS directory with restrictive ACLs.
7
+"""
8
+from __future__ import annotations
9
+
10
+import ctypes
11
+import json
12
+import os
13
+import tempfile
14
+from ctypes import wintypes
15
+from pathlib import Path
16
+
17
+from aram_backend.local_auth import LocalCredential
18
+
19
+_ENTROPY = b"Aram.LocalCredentialVault.v1"
20
+_UI_FORBIDDEN = 0x1
21
+
22
+
23
+class _DataBlob(ctypes.Structure):
24
+ _fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_byte))]
25
+
26
+
27
+def _dpapi_transform(data: bytes, *, protect: bool) -> bytes:
28
+ if os.name != "nt":
29
+ raise OSError("Windows DPAPI is available only on Windows")
30
+ if not isinstance(data, bytes) or not data or len(data) > 1_048_576:
31
+ raise ValueError("invalid credential vault payload")
32
+ crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
33
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
34
+ crypt32.CryptProtectData.argtypes = [ctypes.POINTER(_DataBlob), wintypes.LPCWSTR, ctypes.POINTER(_DataBlob), ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(_DataBlob)]
35
+ crypt32.CryptProtectData.restype = wintypes.BOOL
36
+ crypt32.CryptUnprotectData.argtypes = [ctypes.POINTER(_DataBlob), ctypes.POINTER(wintypes.LPWSTR), ctypes.POINTER(_DataBlob), ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(_DataBlob)]
37
+ crypt32.CryptUnprotectData.restype = wintypes.BOOL
38
+ kernel32.LocalFree.argtypes = [ctypes.c_void_p]
39
+ kernel32.LocalFree.restype = ctypes.c_void_p
40
+
41
+ def blob(raw: bytes):
42
+ buffer = ctypes.create_string_buffer(raw)
43
+ return _DataBlob(len(raw), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_byte))), buffer
44
+
45
+ source, source_buffer = blob(data)
46
+ entropy, entropy_buffer = blob(_ENTROPY)
47
+ output = _DataBlob()
48
+ if protect:
49
+ ok = crypt32.CryptProtectData(
50
+ ctypes.byref(source), "Aram credential vault",
51
+ ctypes.byref(entropy), None, None, _UI_FORBIDDEN,
52
+ ctypes.byref(output),
53
+ )
54
+ else:
55
+ ok = crypt32.CryptUnprotectData(
56
+ ctypes.byref(source), None, ctypes.byref(entropy),
57
+ None, None, _UI_FORBIDDEN, ctypes.byref(output),
58
+ )
59
+ if not ok:
60
+ raise OSError(ctypes.get_last_error(), "Windows DPAPI operation failed")
61
+ try:
62
+ return ctypes.string_at(output.pbData, output.cbData)
63
+ finally:
64
+ kernel32.LocalFree(output.pbData)
65
+ del source_buffer, entropy_buffer
66
+
67
+
68
+def protect_current_user(data: bytes) -> bytes:
69
+ return _dpapi_transform(data, protect=True)
70
+
71
+
72
+def unprotect_current_user(data: bytes) -> bytes:
73
+ return _dpapi_transform(data, protect=False)
74
+
75
+
76
+def save_credential(path: str | Path, credential: LocalCredential) -> None:
77
+ target = Path(path)
78
+ if not target.is_absolute():
79
+ raise ValueError("credential vault path must be absolute")
80
+ payload = json.dumps({
81
+ "version": 1,
82
+ "subject": credential.subject,
83
+ "company_scopes": sorted(credential.company_scopes),
84
+ "roles": sorted(credential.roles),
85
+ "password_hash": credential.password_hash,
86
+ }, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
87
+ encrypted = protect_current_user(payload)
88
+ target.parent.mkdir(parents=True, exist_ok=True)
89
+ fd, temporary = tempfile.mkstemp(prefix=target.name + ".", suffix=".tmp", dir=target.parent)
90
+ try:
91
+ with os.fdopen(fd, "wb") as stream:
92
+ stream.write(encrypted)
93
+ stream.flush()
94
+ os.fsync(stream.fileno())
95
+ os.replace(temporary, target)
96
+ finally:
97
+ if os.path.exists(temporary):
98
+ os.unlink(temporary)
99
+
100
+
101
+def load_credential(path: str | Path) -> LocalCredential:
102
+ target = Path(path)
103
+ if not target.is_absolute() or not target.is_file():
104
+ raise ValueError("credential vault is unavailable")
105
+ encrypted = target.read_bytes()
106
+ payload = unprotect_current_user(encrypted)
107
+ if len(payload) > 1_048_576:
108
+ raise ValueError("invalid credential vault payload")
109
+ try:
110
+ record = json.loads(payload)
111
+ if record.get("version") != 1:
112
+ raise ValueError("unsupported credential vault version")
113
+ subject = record["subject"]
114
+ companies = frozenset(record["company_scopes"])
115
+ roles = frozenset(record["roles"])
116
+ password_hash = record["password_hash"]
117
+ if (
118
+ not isinstance(subject, str) or not subject.strip() or len(subject) > 200
119
+ or not companies or any(not isinstance(x, str) or not x.strip() or len(x) > 64 for x in companies)
120
+ or not roles or not roles.issubset({"maker", "reviewer", "approver", "owner"})
121
+ or not isinstance(password_hash, str) or len(password_hash) > 1024
122
+ ):
123
+ raise ValueError("invalid credential vault record")
124
+ return LocalCredential(subject, companies, roles, password_hash)
125
+ except (KeyError, TypeError, json.JSONDecodeError) as exc:
126
+ raise ValueError("invalid credential vault record") from exc
backend/tests/test_auth_api.py
new
+83
@@ -0,0 +1,83 @@
1
+import os
2
+
3
+import pytest
4
+from fastapi.testclient import TestClient
5
+
6
+from aram_backend.auth_api import (
7
+ configure_local_auth_from_vault,
8
+ configure_local_auth_service,
9
+ reset_local_auth_service,
10
+)
11
+from aram_backend.local_auth import LocalSessionAuthority, create_credential
12
+from aram_backend.main import app
13
+from aram_backend.mapping_store import MappingStore
14
+from aram_backend.windows_credential_vault import save_credential
15
+
16
+
17
+def test_auth_api_fails_closed_until_explicit_configuration():
18
+ reset_local_auth_service()
19
+ client = TestClient(app)
20
+ assert client.post("/api/v1/auth/login", json={"password": "correct horse battery staple"}).status_code == 503
21
+ assert client.post("/api/v1/auth/logout", headers={"Authorization": "Bearer anything"}).status_code == 503
22
+
23
+
24
+def test_auth_api_login_mapping_and_logout_end_to_end(tmp_path):
25
+ credential = create_credential(
26
+ "owner", "correct horse battery staple",
27
+ frozenset({"001"}), frozenset({"maker"}),
28
+ )
29
+ authority = LocalSessionAuthority(credential)
30
+ configure_local_auth_service(
31
+ authority=authority, store=MappingStore(tmp_path / "auth-api.db")
32
+ )
33
+ client = TestClient(app)
34
+ try:
35
+ assert client.post("/api/v1/auth/login", json={"password": "incorrect password"}).status_code == 401
36
+ response = client.post(
37
+ "/api/v1/auth/login", json={"password": "correct horse battery staple"}
38
+ )
39
+ assert response.status_code == 200
40
+ token = response.json()["access_token"]
41
+ assert response.json()["token_type"] == "bearer"
42
+ proposal = {
43
+ "mapping_id": "AUTH-1", "account_full_code": "0010",
44
+ "target_statement": "BS", "statement_section": "Assets",
45
+ "note_number": "01",
46
+ }
47
+ headers = {"Authorization": "Bearer " + token}
48
+ created = client.post("/api/v1/mapping/001/1405/proposals", json=proposal, headers=headers)
49
+ assert created.status_code == 200
50
+ logged_out = client.post("/api/v1/auth/logout", headers=headers)
51
+ assert logged_out.status_code == 200
52
+ assert logged_out.json() == {"revoked": True}
53
+ rejected = client.post("/api/v1/mapping/001/1405/proposals", json={
54
+ **proposal, "mapping_id": "AUTH-2",
55
+ }, headers=headers)
56
+ assert rejected.status_code == 403
57
+ finally:
58
+ reset_local_auth_service()
59
+
60
+def test_auth_api_can_load_current_user_dpapi_vault(tmp_path):
61
+ if os.name != "nt":
62
+ pytest.skip("Windows DPAPI only")
63
+ credential = create_credential(
64
+ "owner", "correct horse battery staple",
65
+ frozenset({"001"}), frozenset({"maker"}),
66
+ )
67
+ vault = tmp_path / "owner.dpapi"
68
+ save_credential(vault, credential)
69
+ configure_local_auth_from_vault(
70
+ credential_path=str(vault), store=MappingStore(tmp_path / "vault-api.db")
71
+ )
72
+ client = TestClient(app)
73
+ try:
74
+ response = client.post(
75
+ "/api/v1/auth/login", json={"password": "correct horse battery staple"}
76
+ )
77
+ assert response.status_code == 200
78
+ token = response.json()["access_token"]
79
+ assert client.post(
80
+ "/api/v1/auth/logout", headers={"Authorization": "Bearer " + token}
81
+ ).json() == {"revoked": True}
82
+ finally:
83
+ reset_local_auth_service()
backend/tests/test_credential_recovery.py
new
+43
@@ -0,0 +1,43 @@
1
+import pytest
2
+from cryptography.exceptions import InvalidTag
3
+
4
+from aram_backend.credential_recovery import (
5
+ export_recovery_envelope,
6
+ import_recovery_envelope,
7
+)
8
+from aram_backend.local_auth import create_credential
9
+
10
+
11
+def test_recovery_envelope_round_trip_and_wrong_passphrase():
12
+ credential = create_credential(
13
+ "owner", "correct horse battery staple",
14
+ frozenset({"001", "002"}), frozenset({"owner", "maker"}),
15
+ )
16
+ envelope = export_recovery_envelope(credential, "separate recovery passphrase")
17
+ assert b"correct horse battery staple" not in envelope
18
+ assert import_recovery_envelope(envelope, "separate recovery passphrase") == credential
19
+ with pytest.raises(InvalidTag):
20
+ import_recovery_envelope(envelope, "incorrect recovery passphrase")
21
+
22
+
23
+def test_recovery_envelope_rejects_tampering_and_malformed_input():
24
+ credential = create_credential(
25
+ "owner", "correct horse battery staple",
26
+ frozenset({"001"}), frozenset({"owner"}),
27
+ )
28
+ envelope = bytearray(export_recovery_envelope(credential, "separate recovery passphrase"))
29
+ envelope[-3] ^= 1
30
+ with pytest.raises(ValueError):
31
+ import_recovery_envelope(bytes(envelope), "separate recovery passphrase")
32
+ with pytest.raises(ValueError):
33
+ import_recovery_envelope(b"not-json", "separate recovery passphrase")
34
+
35
+
36
+@pytest.mark.parametrize("passphrase", ["short", "", None])
37
+def test_recovery_envelope_requires_strong_passphrase(passphrase):
38
+ credential = create_credential(
39
+ "owner", "correct horse battery staple",
40
+ frozenset({"001"}), frozenset({"owner"}),
41
+ )
42
+ with pytest.raises(ValueError):
43
+ export_recovery_envelope(credential, passphrase)
backend/tests/test_local_auth.py
+37
@@ -59,3 +59,40 @@ def test_local_auth_rejects_unknown_roles_and_oversized_password():
59
authority = LocalSessionAuthority(credential)
60
assert authority.login("x" * 1025) is None
61
assert authority.resolve("x" * 1000) is None
62
+
63
+def test_local_auth_upgrades_legacy_pbkdf2_after_successful_login():
64
+ import hashlib
65
+ import secrets
66
+
67
+ from aram_backend.local_auth import import_legacy_credential
68
+
69
+ password = "correct horse battery staple"
70
+ salt = secrets.token_bytes(32)
71
+ digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 600_000)
72
+ legacy = import_legacy_credential(
73
+ "owner", frozenset({"001"}), frozenset({"owner"}), salt, digest
74
+ )
75
+ assert legacy.password_hash.startswith("pbkdf2_sha256$")
76
+ authority = LocalSessionAuthority(legacy)
77
+ token = authority.login(password)
78
+ assert token is not None
79
+ assert authority._credential.password_hash.startswith("$argon2id$")
80
+ assert authority.resolve(token).subject == "owner"
81
+
82
+
83
+def test_local_auth_does_not_upgrade_legacy_hash_on_wrong_password():
84
+ import hashlib
85
+ import secrets
86
+
87
+ from aram_backend.local_auth import import_legacy_credential
88
+
89
+ salt = secrets.token_bytes(32)
90
+ digest = hashlib.pbkdf2_hmac(
91
+ "sha256", b"correct horse battery staple", salt, 600_000
92
+ )
93
+ legacy = import_legacy_credential(
94
+ "owner", frozenset({"001"}), frozenset({"owner"}), salt, digest
95
+ )
96
+ authority = LocalSessionAuthority(legacy)
97
+ assert authority.login("wrong password") is None
98
+ assert authority._credential.password_hash == legacy.password_hash
backend/tests/test_windows_credential_vault.py
new
+34
@@ -0,0 +1,34 @@
1
+import os
2
+
3
+import pytest
4
+
5
+from aram_backend.local_auth import create_credential
6
+from aram_backend.windows_credential_vault import load_credential, save_credential
7
+
8
+pytestmark = pytest.mark.skipif(os.name != "nt", reason="Windows DPAPI only")
9
+
10
+
11
+def test_dpapi_vault_round_trip_and_tamper_detection(tmp_path):
12
+ path = tmp_path / "owner.credential.dpapi"
13
+ credential = create_credential(
14
+ "owner", "correct horse battery staple",
15
+ frozenset({"001", "002"}), frozenset({"maker", "owner"}),
16
+ )
17
+ save_credential(path, credential)
18
+ assert path.read_bytes() != credential.password_hash.encode()
19
+ restored = load_credential(path)
20
+ assert restored == credential
21
+ encrypted = bytearray(path.read_bytes())
22
+ encrypted[-1] ^= 0x01
23
+ path.write_bytes(encrypted)
24
+ with pytest.raises(OSError):
25
+ load_credential(path)
26
+
27
+
28
+def test_dpapi_vault_requires_absolute_path():
29
+ credential = create_credential(
30
+ "owner", "correct horse battery staple",
31
+ frozenset({"001"}), frozenset({"owner"}),
32
+ )
33
+ with pytest.raises(ValueError):
34
+ save_credential("relative.dpapi", credential)
docs/GATE3_PACKAGE9_1_EXECUTION_REPORT_20261103.md
new
+58
@@ -0,0 +1,58 @@
1
+# Package 9.1 — Security execution evidence (2026-11-03)
2
+
3
+## Decision
4
+**PARTIAL / NO-GO for Gate 3.** The Argon2id login path, FastAPI login/logout integration, DPAPI CurrentUser credential vault, and passphrase-encrypted portable recovery-envelope primitives are implemented and locally tested. This is not yet an operational multi-user identity service and does not satisfy independent recovery evidence or independent review.
5
+
6
+## Baseline and branch
7
+- Repository: davoodmehraban89/Aram
8
+- Parent PR: #89, draft, base SHA `a0b72be87720b1ff08361298b903ba57dd4fb408`
9
+- Working branch: `feat/gate3-package9-1-security-20261103`
10
+- Parent commit before this implementation: `f3f37ee8fb4894006d4faa866dfa140926b1d96a`
11
+- Worktree: `C:\Users\Davood\Documents\Aram-Gate3-Package9-1-Security`
12
+- Canonical financial data not modified. No merge or release performed.
13
+
14
+## Implemented
15
+1. `LocalSessionAuthority` now provisions Argon2id hashes and verifies passwords through the dedicated security module.
16
+2. Legacy PBKDF2 credentials can be imported without plaintext; on successful login the hash is upgraded to Argon2id in memory. Wrong passwords do not trigger migration.
17
+3. FastAPI `/api/v1/auth/login` and `/logout` routes are added. Mapping API uses the resulting opaque session token through the trusted server-side resolver; actor/role/company headers remain untrusted.
18
+4. Startup can opt into a DPAPI vault using `ARAM_CREDENTIAL_VAULT_PATH`; mapping database path is configurable with `ARAM_MAPPING_STORE_PATH`. With no vault configured, authentication stays fail-closed (503).
19
+5. Windows DPAPI CurrentUser encrypted credential vault supports atomic save/load and detects ciphertext tampering.
20
+6. Portable recovery envelope uses Scrypt + AES-256-GCM with a separate passphrase; tests verify round-trip, wrong passphrase, tampering and malformed input. No cloud upload or off-device copy was performed.
21
+7. Regression tests added for API login/logout, bearer token revocation, PBKDF2 migration, DPAPI round-trip/tamper, and portable recovery.
22
+
23
+## Verification
24
+- Full backend test suite: **136 tests passed** (including Windows DPAPI tests on the connected Windows host).
25
+- Ruff: PASS.
26
+- compileall: PASS.
27
+- pip check: PASS.
28
+- git diff --check: PASS.
29
+- One existing Starlette/httpx TestClient deprecation warning remains.
30
+- Test run is local on Aram; this is not remote CI proof for the new candidate until GitHub Actions completes on the final SHA.
31
+
32
+## Three review passes (sequential self-review, not independent)
33
+### Reviewer 1 — Functional QA
34
+- Confirmed successful Argon2id login, PBKDF2 upgrade after successful login only, API login/logout, mapping API session use, and fail-closed behavior when not configured.
35
+- 136/136 local tests passed.
36
+
37
+### Reviewer 2 — Security and architecture
38
+- Confirmed DPAPI CurrentUser protection and authenticated tamper detection, passphrase-encrypted recovery envelope, no credential plaintext in the vault, and explicit opt-in configuration.
39
+- Findings still open: session/lockout state is process-memory only; one local credential identity is supported; there is no cross-process throttling, account lifecycle, MFA, enterprise IdP, account recovery workflow/UI, independent cloud escrow, or proof of restrictive NTFS ACL on deployment path. DPAPI recovery is tied to the Windows user profile; portable envelope passphrase must be separately retained.
40
+
41
+### Reviewer 3 — Adversarial and misuse
42
+- Tested malformed stored hashes, wrong passwords, oversized passwords, bad recovery passphrases, ciphertext tampering, malformed recovery envelope, unconfigured API, unknown bearer tokens, logout/replay, and company-scope rejection.
43
+- Remaining adversarial gap: multi-user/concurrent worker behavior and process restart/session invalidation were not tested as production deployment behavior.
44
+
45
+## Critical limitations / acceptance blockers
46
+- This local adapter supports one credential/subject per authority. It cannot by itself provide independent maker, reviewer, and approver identities. A trusted multi-user IdP or a properly designed multi-account authority is required before workflow deployment.
47
+- PBKDF2 migration updates the active in-memory credential only. Persisting the upgraded hash back into the DPAPI vault atomically is not yet wired; a restart before that persistence would require another PBKDF2 verification.
48
+- The portable recovery envelope is a tested library primitive, not yet part of an attended backup procedure. Its passphrase must be stored separately; no independent cloud copy or restore witness exists.
49
+- DPAPI vault is CurrentUser-bound. Loss of the Windows profile may prevent DPAPI unprotect; portable envelope is the recovery route but has not been copied to an independent destination or tested on a second Windows profile/device.
50
+- No independent reviewer has approved the candidate.
51
+- CI must pass on the final SHA before the code-quality gate can pass.
52
+
53
+## Safe boundaries
54
+- No real financial data was accessed or modified.
55
+- No production login credential was changed.
56
+- No merge, release or force push.
57
+- The app remains fail-closed if no DPAPI vault is configured.
58
+- Gate 3 remains **NO-GO** until the blockers above and the other Gate 3 financial/audit/DR requirements have evidence.