Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 04:15 UTC
source-data-cleanup
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 | """Local user management and role authorization (Phase 7, booklet §7/§12). |
| 2 | |
| 3 | Offline desktop identity: usernames + roles, passwords hashed with |
| 4 | PBKDF2-HMAC-SHA256 and a per-user random salt (stdlib only, no new dependency, |
| 5 | no plaintext storage, no runtime network). Sensitive actions are gated by role |
| 6 | and attributed to a username in the hash-chained audit log. |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import hashlib |
| 12 | import hmac |
| 13 | import secrets |
| 14 | |
| 15 | from sqlalchemy import select |
| 16 | from sqlalchemy.orm import Session |
| 17 | |
| 18 | from aram_backend.models import User, UserRole |
| 19 | from aram_backend.services.audit import append_entry |
| 20 | |
| 21 | _PBKDF2_ROUNDS = 200_000 |
| 22 | |
| 23 | |
| 24 | class UserError(ValueError): |
| 25 | """Raised when a user operation cannot be performed safely.""" |
| 26 | |
| 27 | |
| 28 | class AuthorizationError(PermissionError): |
| 29 | """Raised when an actor lacks the role required for an action.""" |
| 30 | |
| 31 | |
| 32 | def _hash_password(password: str, salt: str) -> str: |
| 33 | digest = hashlib.pbkdf2_hmac( |
| 34 | "sha256", password.encode("utf-8"), bytes.fromhex(salt), _PBKDF2_ROUNDS |
| 35 | ) |
| 36 | return digest.hex() |
| 37 | |
| 38 | |
| 39 | def create_user( |
| 40 | session: Session, |
| 41 | *, |
| 42 | username: str, |
| 43 | password: str, |
| 44 | role: UserRole = UserRole.PREPARER, |
| 45 | display_name: str = "", |
| 46 | actor: str = "", |
| 47 | ) -> User: |
| 48 | username = username.strip() |
| 49 | if not username: |
| 50 | raise UserError("username is required") |
| 51 | if len(password) < 8: |
| 52 | raise UserError("password must be at least 8 characters") |
| 53 | existing = session.scalar(select(User).where(User.username == username)) |
| 54 | if existing is not None: |
| 55 | raise UserError(f"username '{username}' already exists") |
| 56 | salt = secrets.token_hex(16) |
| 57 | user = User( |
| 58 | username=username, |
| 59 | display_name=display_name or username, |
| 60 | role=role, |
| 61 | salt=salt, |
| 62 | password_hash=_hash_password(password, salt), |
| 63 | ) |
| 64 | session.add(user) |
| 65 | session.flush() |
| 66 | append_entry( |
| 67 | session, |
| 68 | action="user.create", |
| 69 | actor=actor, |
| 70 | payload={"username": username, "role": role.value}, |
| 71 | ) |
| 72 | return user |
| 73 | |
| 74 | |
| 75 | def authenticate(session: Session, *, username: str, password: str) -> User: |
| 76 | user = session.scalar(select(User).where(User.username == username.strip())) |
| 77 | if user is None or not user.active: |
| 78 | raise UserError("invalid credentials") |
| 79 | candidate = _hash_password(password, user.salt) |
| 80 | if not hmac.compare_digest(candidate, user.password_hash): |
| 81 | raise UserError("invalid credentials") |
| 82 | return user |
| 83 | |
| 84 | |
| 85 | def list_users(session: Session) -> list[User]: |
| 86 | return list(session.scalars(select(User).order_by(User.username)).all()) |
| 87 | |
| 88 | |
| 89 | def set_role(session: Session, *, username: str, role: UserRole, actor: str = "") -> User: |
| 90 | user = session.scalar(select(User).where(User.username == username)) |
| 91 | if user is None: |
| 92 | raise UserError(f"user '{username}' not found") |
| 93 | user.role = role |
| 94 | session.flush() |
| 95 | append_entry( |
| 96 | session, |
| 97 | action="user.set_role", |
| 98 | actor=actor, |
| 99 | payload={"username": username, "role": role.value}, |
| 100 | ) |
| 101 | return user |
| 102 | |
| 103 | |
| 104 | def set_active(session: Session, *, username: str, active: bool, actor: str = "") -> User: |
| 105 | user = session.scalar(select(User).where(User.username == username)) |
| 106 | if user is None: |
| 107 | raise UserError(f"user '{username}' not found") |
| 108 | user.active = active |
| 109 | session.flush() |
| 110 | append_entry( |
| 111 | session, |
| 112 | action="user.set_active", |
| 113 | actor=actor, |
| 114 | payload={"username": username, "active": active}, |
| 115 | ) |
| 116 | return user |
| 117 | |
| 118 | |
| 119 | def require_role(session: Session, *, username: str, allowed: set[UserRole]) -> User: |
| 120 | """Return the active user iff their role is in ``allowed``; else raise. |
| 121 | |
| 122 | An empty/unknown username is rejected. This is the single authorization gate |
| 123 | for sensitive actions (approve, reopen, lock, user management, backup). |
| 124 | """ |
| 125 | user = session.scalar(select(User).where(User.username == username.strip())) |
| 126 | if user is None or not user.active: |
| 127 | raise AuthorizationError("actor is not an active user") |
| 128 | if user.role not in allowed: |
| 129 | raise AuthorizationError(f"role '{user.role.value}' is not permitted for this action") |
| 130 | return user |
| 131 | |
| 132 | |
| 133 | __all__ = [ |
| 134 | "UserError", |
| 135 | "AuthorizationError", |
| 136 | "create_user", |
| 137 | "authenticate", |
| 138 | "list_users", |
| 139 | "set_role", |
| 140 | "set_active", |
| 141 | "require_role", |
| 142 | ] |