Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 22:00 UTC
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
| 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 |