codex/gate3-signed-year-scope-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 | MAX_SIGNED_YEAR_SCOPES = 32 |
| 24 | TRUSTED_ROLES = frozenset(("mapping_proposer", "mapping_reviewer")) |
| 25 | bearer_scheme = HTTPBearer(auto_error=False) |
| 26 | |
| 27 | |
| 28 | @dataclass(frozen=True) |
| 29 | class SignedYearScope: |
| 30 | """Exact signed company, fiscal-year and role boundary; no wildcards.""" |
| 31 | |
| 32 | company_code: str |
| 33 | fiscal_year: int |
| 34 | role: str |
| 35 | |
| 36 | |
| 37 | @dataclass(frozen=True) |
| 38 | class VerifiedPrincipal: |
| 39 | """Identity from successfully validated RS256 issuer/audience claims only.""" |
| 40 | |
| 41 | issuer: str |
| 42 | subject: str |
| 43 | roles: tuple[str, ...] |
| 44 | expires_at: int |
| 45 | # Older valid tokens with no explicit grants may authenticate, but can |
| 46 | # NEVER authorize year-specific Mapping operations. |
| 47 | year_scopes: tuple[SignedYearScope, ...] = () |
| 48 | |
| 49 | |
| 50 | def _fail_invalid() -> None: |
| 51 | raise HTTPException( |
| 52 | status_code=401, detail="Invalid bearer token", |
| 53 | headers={"WWW-Authenticate": "Bearer"}, |
| 54 | ) |
| 55 | |
| 56 | |
| 57 | def _is_safe_string(value: object, limit: int) -> bool: |
| 58 | return ( |
| 59 | isinstance(value, str) and 0 < len(value) <= limit |
| 60 | and value == value.strip() |
| 61 | and not any(category(char) in ("Cc", "Cf", "Cs") for char in value) |
| 62 | ) |
| 63 | |
| 64 | |
| 65 | def _validated_signed_scopes(raw: object, *, permitted_role: str) -> tuple[SignedYearScope, ...]: |
| 66 | if type(raw) is not list or len(raw) > MAX_SIGNED_YEAR_SCOPES: |
| 67 | _fail_invalid() |
| 68 | seen: set[SignedYearScope] = set() |
| 69 | result: list[SignedYearScope] = [] |
| 70 | for item in raw: |
| 71 | if type(item) is not dict or set(item) != {"company_code", "fiscal_year", "role"}: |
| 72 | _fail_invalid() |
| 73 | code, year, role = item["company_code"], item["fiscal_year"], item["role"] |
| 74 | if ( |
| 75 | not _is_safe_string(code, 64) |
| 76 | or "*" in code or "?" in code |
| 77 | or type(year) is not int or year <= 0 or year > 9999 |
| 78 | or type(role) is not str or role != permitted_role |
| 79 | ): |
| 80 | _fail_invalid() |
| 81 | scope = SignedYearScope(company_code=code, fiscal_year=year, role=role) |
| 82 | if scope in seen: |
| 83 | _fail_invalid() |
| 84 | seen.add(scope) |
| 85 | result.append(scope) |
| 86 | return tuple(result) |
| 87 | |
| 88 | |
| 89 | def _trusted_public_key(settings: Settings) -> RSAPublicKey: |
| 90 | if ( |
| 91 | not _is_safe_string(settings.auth_issuer, 512) |
| 92 | or not settings.auth_issuer.startswith("https://") |
| 93 | or not _is_safe_string(settings.auth_audience, 256) |
| 94 | or not settings.auth_public_key_pem |
| 95 | ): |
| 96 | raise HTTPException(status_code=503, detail="Identity provider is not configured") |
| 97 | try: |
| 98 | key = serialization.load_pem_public_key( |
| 99 | settings.auth_public_key_pem.encode("ascii"), |
| 100 | ) |
| 101 | except (ValueError, TypeError, UnicodeError) as exc: |
| 102 | raise HTTPException( |
| 103 | status_code=503, detail="Identity provider is not configured", |
| 104 | ) from exc |
| 105 | if not isinstance(key, RSAPublicKey) or key.key_size < 2048: |
| 106 | raise HTTPException(status_code=503, detail="Identity provider is not configured") |
| 107 | return key |
| 108 | |
| 109 | |
| 110 | def verify_access_token(token: str, *, settings: Settings) -> VerifiedPrincipal: |
| 111 | """Verify a short-lived RSA-signed access token, fail closed on all claims. |
| 112 | |
| 113 | Static public-key pinning is intentional here; rotating/jwks validation and |
| 114 | a deployed enterprise IdP must be separately configured and reviewed. |
| 115 | """ |
| 116 | key = _trusted_public_key(settings) |
| 117 | if not isinstance(token, str) or not token or len(token) > MAX_TOKEN_LENGTH: |
| 118 | _fail_invalid() |
| 119 | try: |
| 120 | claims = jwt.decode( |
| 121 | token, |
| 122 | key, |
| 123 | algorithms=["RS256"], |
| 124 | audience=settings.auth_audience, |
| 125 | issuer=settings.auth_issuer, |
| 126 | leeway=0, |
| 127 | options={ |
| 128 | "require": [ |
| 129 | "iss", "aud", "sub", "exp", "iat", "nbf", |
| 130 | "token_use", "aram_roles", |
| 131 | ], |
| 132 | }, |
| 133 | ) |
| 134 | except (jwt.InvalidTokenError, ValueError, TypeError) as exc: |
| 135 | raise HTTPException( |
| 136 | status_code=401, detail="Invalid bearer token", |
| 137 | headers={"WWW-Authenticate": "Bearer"}, |
| 138 | ) from exc |
| 139 | roles = claims.get("aram_roles") |
| 140 | exp = claims.get("exp") |
| 141 | iat = claims.get("iat") |
| 142 | nbf = claims.get("nbf") |
| 143 | if ( |
| 144 | claims.get("token_use") != "access" |
| 145 | or not _is_safe_string(claims.get("sub"), 128) |
| 146 | or type(exp) is not int or type(iat) is not int or type(nbf) is not int |
| 147 | or exp <= iat or exp - iat > MAX_LIFETIME_SECONDS |
| 148 | or nbf > exp |
| 149 | or not isinstance(roles, list) or not roles |
| 150 | or any(type(role) is not str or role not in TRUSTED_ROLES for role in roles) |
| 151 | or len(set(roles)) != len(roles) |
| 152 | or len(roles) > 1 |
| 153 | ): |
| 154 | _fail_invalid() |
| 155 | scopes = _validated_signed_scopes( |
| 156 | claims.get("aram_scopes", []), permitted_role=roles[0], |
| 157 | ) |
| 158 | return VerifiedPrincipal( |
| 159 | issuer=claims["iss"], subject=claims["sub"], |
| 160 | roles=tuple(sorted(roles)), expires_at=exp, year_scopes=scopes, |
| 161 | ) |
| 162 | |
| 163 | |
| 164 | def require_verified_principal( |
| 165 | credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme), |
| 166 | settings: Settings = Depends(get_settings), |
| 167 | ) -> VerifiedPrincipal: |
| 168 | """FastAPI dependency; never trust X-User / X-Role headers.""" |
| 169 | # Misconfigured deployment cannot accidentally become authenticated. |
| 170 | _trusted_public_key(settings) |
| 171 | if credentials is None or credentials.scheme.lower() != "bearer": |
| 172 | _fail_invalid() |
| 173 | return verify_access_token(credentials.credentials, settings=settings) |