Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 04:15 UTC
codex/gate3-authenticated-principal-boundary-20261030
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 | """Fail-closed public-key verification of identity-provider access tokens. |
| 2 | |
| 3 | Only the operator-configured public RSA key can verify a token; no client |
| 4 | headers, unsigned JWTs, HS256 shared secrets or user-supplied public keys can |
| 5 | create a verified principal. This module has NO finance approve/apply action. |
| 6 | """ |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | from dataclasses import dataclass |
| 10 | from time import time |
| 11 | from unicodedata import category |
| 12 | |
| 13 | import jwt |
| 14 | from cryptography.hazmat.primitives import serialization |
| 15 | from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey |
| 16 | from fastapi import Depends, HTTPException |
| 17 | from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer |
| 18 | |
| 19 | from aram_backend.config import Settings, get_settings |
| 20 | |
| 21 | MAX_TOKEN_LENGTH = 8192 |
| 22 | MAX_LIFETIME_SECONDS = 900 |
| 23 | TRUSTED_ROLES = frozenset(("mapping_proposer", "mapping_reviewer")) |
| 24 | bearer_scheme = HTTPBearer(auto_error=False) |
| 25 | |
| 26 | |
| 27 | @dataclass(frozen=True) |
| 28 | class VerifiedPrincipal: |
| 29 | """Identity from successfully validated RS256 issuer/audience claims only.""" |
| 30 | |
| 31 | issuer: str |
| 32 | subject: str |
| 33 | roles: tuple[str, ...] |
| 34 | expires_at: int |
| 35 | |
| 36 | |
| 37 | def _fail_invalid() -> None: |
| 38 | raise HTTPException( |
| 39 | status_code=401, detail="Invalid bearer token", |
| 40 | headers={"WWW-Authenticate": "Bearer"}, |
| 41 | ) |
| 42 | |
| 43 | |
| 44 | def _is_safe_string(value: object, limit: int) -> bool: |
| 45 | return ( |
| 46 | isinstance(value, str) and 0 < len(value) <= limit |
| 47 | and value == value.strip() |
| 48 | and not any(category(char) in ("Cc", "Cf", "Cs") for char in value) |
| 49 | ) |
| 50 | |
| 51 | |
| 52 | def _trusted_public_key(settings: Settings) -> RSAPublicKey: |
| 53 | if ( |
| 54 | not _is_safe_string(settings.auth_issuer, 512) |
| 55 | or not settings.auth_issuer.startswith("https://") |
| 56 | or not _is_safe_string(settings.auth_audience, 256) |
| 57 | or not settings.auth_public_key_pem |
| 58 | ): |
| 59 | raise HTTPException(status_code=503, detail="Identity provider is not configured") |
| 60 | try: |
| 61 | key = serialization.load_pem_public_key( |
| 62 | settings.auth_public_key_pem.encode("ascii"), |
| 63 | ) |
| 64 | except (ValueError, TypeError, UnicodeError) as exc: |
| 65 | raise HTTPException( |
| 66 | status_code=503, detail="Identity provider is not configured", |
| 67 | ) from exc |
| 68 | if not isinstance(key, RSAPublicKey) or key.key_size < 2048: |
| 69 | raise HTTPException(status_code=503, detail="Identity provider is not configured") |
| 70 | return key |
| 71 | |
| 72 | |
| 73 | def verify_access_token(token: str, *, settings: Settings) -> VerifiedPrincipal: |
| 74 | """Verify a short-lived RSA-signed access token, fail closed on all claims. |
| 75 | |
| 76 | Static public-key pinning is intentional here; rotating/jwks validation and |
| 77 | a deployed enterprise IdP must be separately configured and reviewed. |
| 78 | """ |
| 79 | key = _trusted_public_key(settings) |
| 80 | if not isinstance(token, str) or not token or len(token) > MAX_TOKEN_LENGTH: |
| 81 | _fail_invalid() |
| 82 | try: |
| 83 | claims = jwt.decode( |
| 84 | token, |
| 85 | key, |
| 86 | algorithms=["RS256"], |
| 87 | audience=settings.auth_audience, |
| 88 | issuer=settings.auth_issuer, |
| 89 | leeway=0, |
| 90 | options={ |
| 91 | "require": [ |
| 92 | "iss", "aud", "sub", "exp", "iat", "nbf", |
| 93 | "token_use", "aram_roles", |
| 94 | ], |
| 95 | }, |
| 96 | ) |
| 97 | except (jwt.InvalidTokenError, ValueError, TypeError) as exc: |
| 98 | raise HTTPException( |
| 99 | status_code=401, detail="Invalid bearer token", |
| 100 | headers={"WWW-Authenticate": "Bearer"}, |
| 101 | ) from exc |
| 102 | roles = claims.get("aram_roles") |
| 103 | exp = claims.get("exp") |
| 104 | iat = claims.get("iat") |
| 105 | nbf = claims.get("nbf") |
| 106 | if ( |
| 107 | claims.get("token_use") != "access" |
| 108 | or not _is_safe_string(claims.get("sub"), 128) |
| 109 | or type(exp) is not int or type(iat) is not int or type(nbf) is not int |
| 110 | or exp <= iat or exp - iat > MAX_LIFETIME_SECONDS |
| 111 | or nbf > exp |
| 112 | or not isinstance(roles, list) or not roles |
| 113 | or any(type(role) is not str or role not in TRUSTED_ROLES for role in roles) |
| 114 | or len(set(roles)) != len(roles) |
| 115 | or len(roles) > 1 |
| 116 | ): |
| 117 | _fail_invalid() |
| 118 | return VerifiedPrincipal( |
| 119 | issuer=claims["iss"], subject=claims["sub"], |
| 120 | roles=tuple(sorted(roles)), expires_at=exp, |
| 121 | ) |
| 122 | |
| 123 | |
| 124 | def require_verified_principal( |
| 125 | credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme), |
| 126 | settings: Settings = Depends(get_settings), |
| 127 | ) -> VerifiedPrincipal: |
| 128 | """FastAPI dependency; never trust X-User / X-Role headers.""" |
| 129 | # Misconfigured deployment cannot accidentally become authenticated. |
| 130 | _trusted_public_key(settings) |
| 131 | if credentials is None or credentials.scheme.lower() != "bearer": |
| 132 | _fail_invalid() |
| 133 | return verify_access_token(credentials.credentials, settings=settings) |