@davoodmehraban89 / Aram / commits / 03f1e7f
Fork 0

feat(auth): require signed grant intersected with refreshed draft year and company

davoodmehraban89 committed Oct 30, 2026 at 22:24 UTC 03f1e7f146178c1002e8c9833290efc72a0a38db
1 file changed +66
backend/src/aram_backend/mapping_year_authorization.py new
+66
@@ -0,0 +1,66 @@
1 +"""Company/year/role authorization preflight for signed Mapping JWT scopes.
2 +
3 +An issuer-signed identity is not enough: permission is the intersection of a
4 +specific signed grant with the current FiscalYear/Company database boundary.
5 +This is read-only and NOT finance approval, an actor-directory authorization
6 +replacement, or a race-free apply permission.
7 +"""
8 +from __future__ import annotations
9 +
10 +from time import time
11 +
12 +from fastapi import HTTPException
13 +from sqlalchemy.orm import Session
14 +
15 +from aram_backend.authenticated_identity import (
16 + SignedYearScope, TRUSTED_ROLES, VerifiedPrincipal,
17 +)
18 +from aram_backend.models import Company, FiscalYear, FiscalYearStatus
19 +
20 +
21 +def _deny() -> None:
22 + # Keep foreign-company/year and missing-year responses indistinguishable.
23 + raise HTTPException(status_code=403, detail="Mapping year access denied")
24 +
25 +
26 +def require_year_access(
27 + session: Session, *, principal: VerifiedPrincipal, year_id: int,
28 + required_role: str,
29 +) -> SignedYearScope:
30 + """Require a matching signed grant for the *currently Draft* year.
31 +
32 + Call only after FastAPI's verified RSA-bearer dependency. A caller-created
33 + Python VerifiedPrincipal object is NOT an authentication mechanism.
34 + Every eventual staging/approval API must enforce this preflight inside
35 + its trusted request handler AND repeat checks in its write transaction.
36 + """
37 + if (
38 + not isinstance(principal, VerifiedPrincipal)
39 + or type(year_id) is not int or year_id <= 0
40 + or type(required_role) is not str or required_role not in TRUSTED_ROLES
41 + or required_role not in principal.roles
42 + or type(principal.expires_at) is not int
43 + or principal.expires_at <= int(time())
44 + ):
45 + _deny()
46 +
47 + with session.no_autoflush:
48 + # Related pending edits might describe a different fiscal boundary.
49 + if any(
50 + isinstance(item, (FiscalYear, Company))
51 + for item in session.new | session.dirty | session.deleted
52 + ):
53 + _deny()
54 + year = session.get(FiscalYear, year_id, populate_existing=True)
55 + if year is None or year.status is not FiscalYearStatus.DRAFT:
56 + _deny()
57 + company = session.get(Company, year.company_id, populate_existing=True)
58 + if company is None:
59 + _deny()
60 + allowed = SignedYearScope(
61 + company_code=company.code, fiscal_year=year.year,
62 + role=required_role,
63 + )
64 + if allowed not in principal.year_scopes:
65 + _deny()
66 + return allowed