@davoodmehraban89 / Aram-2 Mirror · read-only
Fork 0

Mirrored from https://github.com/davoodmehraban89/Aram.git

Synced Dec 3, 23:15 UTC

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
py 483 lines 17.7 KB
Raw
1 """Synthetic RSA token checks only; NOT a connected real enterprise IdP."""
2 from datetime import UTC, datetime
3 from time import time
4
5 import jwt
6 import pytest
7 from cryptography.hazmat.primitives import serialization
8 from cryptography.hazmat.primitives.asymmetric import rsa
9 from fastapi.testclient import TestClient
10
11 from aram_backend.config import Settings, get_settings
12 from aram_backend.main import app
13
14 ISSUER = "https://synthetic-identity.example.invalid/"
15 AUDIENCE = "aram-mapping-api"
16
17
18 @pytest.fixture(scope="module")
19 def keys():
20 private = rsa.generate_private_key(public_exponent=65537, key_size=2048)
21 public = private.public_key().public_bytes(
22 encoding=serialization.Encoding.PEM,
23 format=serialization.PublicFormat.SubjectPublicKeyInfo,
24 ).decode("ascii")
25 other = rsa.generate_private_key(public_exponent=65537, key_size=2048)
26 return private, public, other
27
28
29 @pytest.fixture
30 def auth_client(keys):
31 private, public, other = keys
32 app.dependency_overrides[get_settings] = lambda: Settings(
33 auth_issuer=ISSUER, auth_audience=AUDIENCE,
34 auth_public_key_pem=public,
35 )
36 try:
37 with TestClient(app) as client:
38 yield client
39 finally:
40 app.dependency_overrides.pop(get_settings, None)
41
42
43 def claims(**extra):
44 now = int(time())
45 data = {
46 "iss": ISSUER, "aud": AUDIENCE, "sub": "employee-108",
47 "exp": now + 300, "iat": now - 10, "nbf": now - 10,
48 "token_use": "access", "aram_roles": ["mapping_proposer"],
49 }
50 data.update(extra)
51 return data
52
53
54 def token(private, **extra):
55 return jwt.encode(claims(**extra), private, algorithm="RS256")
56
57
58 def request(client, bearer, **headers):
59 return client.get(
60 "/api/v1/auth/me",
61 headers={"Authorization": f"Bearer {bearer}", **headers},
62 )
63
64
65 def test_valid_rs256_access_token_returns_verified_subject_and_role(auth_client, keys):
66 response = request(auth_client, token(keys[0]))
67 assert response.status_code == 200
68 body = response.json()
69 assert body["issuer"] == ISSUER
70 assert body["subject"] == "employee-108"
71 assert body["roles"] == ["mapping_proposer"]
72 assert body["expires_at"] > int(time())
73 assert "token" not in body
74 assert "private_key" not in body
75
76
77 def test_missing_bearer_or_forged_identity_headers_are_not_authentication(auth_client):
78 response = auth_client.get(
79 "/api/v1/auth/me",
80 headers={"X-User": "admin", "X-ARAM-Roles": "mapping_reviewer"},
81 )
82 assert response.status_code == 401
83 assert response.headers["www-authenticate"] == "Bearer"
84
85
86 def test_wrong_key_signed_token_cannot_impersonate_user(auth_client, keys):
87 response = request(
88 auth_client,
89 token(keys[2], sub="finance-director", aram_roles=["mapping_reviewer"]),
90 )
91 assert response.status_code == 401
92 assert response.json()["detail"] == "Invalid bearer token"
93
94
95 @pytest.mark.parametrize("overrides", [
96 {"iss": "https://attacker.invalid/"},
97 {"aud": "not-aram"},
98 {"exp": 1},
99 {"nbf": int(time()) + 10000},
100 {"iat": int(time()) + 10000},
101 {"exp": int(time()) + 20000},
102 {"sub": ""},
103 {"sub": " invalid "},
104 {"sub": 123},
105 {"token_use": "id"},
106 {"aram_roles": "mapping_reviewer"},
107 {"aram_roles": ["system_administrator"]},
108 {"aram_roles": ["mapping_reviewer", "mapping_reviewer"]},
109 {"aram_roles": ["mapping_proposer", "mapping_reviewer"]},
110 {"aram_roles": []},
111 {"aram_roles": [123]},
112 ])
113 def test_invalid_or_overprivileged_claims_are_rejected(auth_client, keys, overrides):
114 assert request(auth_client, token(keys[0], **overrides)).status_code == 401
115
116
117 @pytest.mark.parametrize("missing", [
118 "iss", "aud", "sub", "exp", "iat", "nbf", "token_use", "aram_roles",
119 ])
120 def test_required_claims_cannot_be_omitted(auth_client, keys, missing):
121 data = claims()
122 del data[missing]
123 assert request(
124 auth_client, jwt.encode(data, keys[0], algorithm="RS256")
125 ).status_code == 401
126
127
128 def test_unsigned_and_hmac_algorithms_are_never_accepted(auth_client, keys):
129 unsigned = jwt.encode(claims(), key="", algorithm="none")
130 hmac_signed = jwt.encode(claims(), key="untrusted", algorithm="HS256")
131 assert request(auth_client, unsigned).status_code == 401
132 assert request(auth_client, hmac_signed).status_code == 401
133
134
135 def test_roles_must_come_from_signed_claims_not_http_headers(auth_client, keys):
136 response = request(
137 auth_client, token(keys[0]),
138 **{"X-ARAM-Roles": "mapping_reviewer", "X-Approver-ID": "boss"},
139 )
140 assert response.status_code == 200
141 assert response.json()["roles"] == ["mapping_proposer"]
142
143
144 def test_unconfigured_identity_is_closed_and_never_bypasses(auth_client, keys):
145 app.dependency_overrides[get_settings] = lambda: Settings()
146 response = request(auth_client, token(keys[0]))
147 assert response.status_code == 503
148 assert "not configured" in response.json()["detail"].lower()
149
150
151 def test_private_key_misconfiguration_is_rejected(auth_client, keys):
152 secret_pem = keys[0].private_bytes(
153 encoding=serialization.Encoding.PEM,
154 format=serialization.PrivateFormat.PKCS8,
155 encryption_algorithm=serialization.NoEncryption(),
156 ).decode()
157 app.dependency_overrides[get_settings] = lambda: Settings(
158 auth_issuer=ISSUER, auth_audience=AUDIENCE,
159 auth_public_key_pem=secret_pem,
160 )
161 assert request(auth_client, token(keys[0])).status_code == 503
162
163
164 def test_only_bearer_scheme_allowed(auth_client, keys):
165 response = auth_client.get(
166 "/api/v1/auth/me",
167 headers={"Authorization": "Basic abc"},
168 )
169 assert response.status_code == 401
170
171
172 def test_long_bearer_token_is_rejected(auth_client):
173 response = request(auth_client, "x" * 9000)
174 assert response.status_code == 401
175
176
177 def test_only_a_read_only_identity_endpoint_is_exposed(auth_client, keys):
178 assert auth_client.post(
179 "/api/v1/auth/me", headers={"Authorization": f"Bearer {token(keys[0])}"}
180 ).status_code == 405
181 assert auth_client.get("/api/v1/health").status_code == 200
182
183
184 def test_signed_reviewer_role_is_accepted_but_no_approval_action_exists(auth_client, keys):
185 response = request(
186 auth_client, token(keys[0], sub="independent-reviewer-22",
187 aram_roles=["mapping_reviewer"]),
188 )
189 assert response.status_code == 200
190 assert response.json()["roles"] == ["mapping_reviewer"]
191 assert auth_client.post(
192 "/api/v1/mapping/approve",
193 headers={"Authorization": f"Bearer {token(keys[0], aram_roles=['mapping_reviewer'])}"},
194 ).status_code == 404
195
196
197 def test_token_payload_tampering_invalidates_signature(auth_client, keys):
198 import base64
199 import json
200 signed = token(keys[0])
201 header, payload, signature = signed.split(".")
202 decoded = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
203 decoded["aram_roles"] = ["mapping_reviewer"]
204 tampered_payload = base64.urlsafe_b64encode(
205 json.dumps(decoded, separators=(",", ":")).encode()
206 ).rstrip(b"=").decode()
207 assert request(auth_client, f"{header}.{tampered_payload}.{signature}").status_code == 401
208
209
210 def test_weak_rsa_verification_key_is_not_accepted(auth_client, keys):
211 weak = rsa.generate_private_key(public_exponent=65537, key_size=1024)
212 weak_public_pem = weak.public_key().public_bytes(
213 encoding=serialization.Encoding.PEM,
214 format=serialization.PublicFormat.SubjectPublicKeyInfo,
215 ).decode("ascii")
216 app.dependency_overrides[get_settings] = lambda: Settings(
217 auth_issuer=ISSUER, auth_audience=AUDIENCE,
218 auth_public_key_pem=weak_public_pem,
219 )
220 assert request(auth_client, token(keys[0])).status_code == 503
221
222
223 def test_invalid_or_non_rsa_public_key_disables_identity(auth_client, keys):
224 app.dependency_overrides[get_settings] = lambda: Settings(
225 auth_issuer=ISSUER, auth_audience=AUDIENCE,
226 auth_public_key_pem="not a PEM public key",
227 )
228 assert request(auth_client, token(keys[0])).status_code == 503
229
230
231 def _year(session, *, company_code="FIN-OPERATIONS", year_number=1404):
232 from aram_backend.models import Company, FiscalYear
233 company = Company(code=company_code, name="Synthetic scope")
234 year = FiscalYear(company=company, year=year_number)
235 session.add(year)
236 session.commit()
237 return year
238
239
240 def _scope(company_code="FIN-OPERATIONS", fiscal_year=1404, role="mapping_proposer"):
241 return {
242 "company_code": company_code, "fiscal_year": fiscal_year, "role": role,
243 }
244
245
246 def _scope_request(auth_client, signing_key, year_id, **claim_overrides):
247 return auth_client.get(
248 f"/api/v1/auth/year-access/{year_id}",
249 headers={"Authorization": f"Bearer {token(signing_key, **claim_overrides)}"},
250 )
251
252
253 def test_scoped_proposer_can_query_only_matching_draft_year(auth_client, keys, session):
254 from aram_backend.database import get_session
255 from aram_backend.main import app
256 from aram_backend.models import MappingRule
257 from sqlalchemy import select
258 year = _year(session)
259 app.dependency_overrides[get_session] = lambda: session
260 try:
261 response = _scope_request(
262 auth_client, keys[0], year.id, aram_scopes=[_scope()],
263 )
264 assert response.status_code == 200
265 assert response.json() == {
266 "year_id": year.id,
267 "company_code": "FIN-OPERATIONS", "fiscal_year": 1404,
268 "role": "mapping_proposer", "verified_scope": True,
269 }
270 assert session.scalars(select(MappingRule)).all() == []
271 finally:
272 app.dependency_overrides.pop(get_session, None)
273
274
275 def test_role_only_token_without_explicit_company_year_grant_is_denied(
276 auth_client, keys, session,
277 ):
278 from aram_backend.database import get_session
279 year = _year(session)
280 app.dependency_overrides[get_session] = lambda: session
281 try:
282 assert _scope_request(auth_client, keys[0], year.id).status_code == 403
283 assert request(auth_client, token(keys[0])).status_code == 200
284 finally:
285 app.dependency_overrides.pop(get_session, None)
286
287
288 @pytest.mark.parametrize("signed_grant", [
289 _scope(company_code="DIFFERENT"),
290 _scope(fiscal_year=1403),
291 _scope(role="mapping_reviewer"),
292 ])
293 def test_wrong_company_year_or_role_is_denied(auth_client, keys, session, signed_grant):
294 from aram_backend.database import get_session
295 year = _year(session)
296 app.dependency_overrides[get_session] = lambda: session
297 try:
298 response = _scope_request(
299 auth_client, keys[0], year.id, aram_scopes=[signed_grant],
300 )
301 # Role mismatches inside signed claims are an invalid credential
302 # (401); a valid token for a different company/year is forbidden (403).
303 expected = 401 if signed_grant["role"] != "mapping_proposer" else 403
304 assert response.status_code == expected
305 assert "company_code" not in response.text
306 finally:
307 app.dependency_overrides.pop(get_session, None)
308
309
310 def test_two_years_of_same_company_are_distinct_permissions(auth_client, keys, session):
311 from aram_backend.database import get_session
312 from aram_backend.models import FiscalYear
313 first = _year(session)
314 second = FiscalYear(company_id=first.company_id, year=1403)
315 session.add(second)
316 session.commit()
317 app.dependency_overrides[get_session] = lambda: session
318 try:
319 assert _scope_request(
320 auth_client, keys[0], first.id, aram_scopes=[_scope()],
321 ).status_code == 200
322 assert _scope_request(
323 auth_client, keys[0], second.id, aram_scopes=[_scope()],
324 ).status_code == 403
325 finally:
326 app.dependency_overrides.pop(get_session, None)
327
328
329 def test_reviewer_must_possess_explicit_reviewer_grant(auth_client, keys, session):
330 from aram_backend.database import get_session
331 year = _year(session)
332 app.dependency_overrides[get_session] = lambda: session
333 try:
334 assert _scope_request(
335 auth_client, keys[0], year.id,
336 aram_roles=["mapping_reviewer"], aram_scopes=[_scope(role="mapping_reviewer")],
337 ).status_code == 200
338 assert _scope_request(
339 auth_client, keys[0], year.id,
340 aram_roles=["mapping_reviewer"], aram_scopes=[_scope(role="mapping_proposer")],
341 ).status_code == 401
342 assert auth_client.post("/api/v1/mapping/approve").status_code == 404
343 finally:
344 app.dependency_overrides.pop(get_session, None)
345
346
347 @pytest.mark.parametrize("bad_scope", [
348 True, "all", 5, {}, {"company_code": "*", "fiscal_year": 1404,
349 "role": "mapping_proposer"},
350 {"company_code": "FIN-OPERATIONS", "fiscal_year": True,
351 "role": "mapping_proposer"},
352 {"company_code": "FIN-OPERATIONS", "fiscal_year": 0,
353 "role": "mapping_proposer"},
354 {"company_code": "FIN-OPERATIONS", "fiscal_year": 1404,
355 "role": "mapping_admin"},
356 {"company_code": "FIN-OPERATIONS", "fiscal_year": 1404,
357 "role": "mapping_proposer", "admin": True},
358 {"company_code": "FIN-OPERATIONS", "fiscal_year": 1404,
359 "role": "mapping_reviewer"},
360 {"company_code": " FIN-OPERATIONS ", "fiscal_year": 1404,
361 "role": "mapping_proposer"},
362 ])
363 def test_malformed_or_untrusted_signed_scope_fails_token_verification(
364 auth_client, keys, bad_scope,
365 ):
366 # A scope entry in a verified token must be fully typed, exact and
367 # compatible with its sole token role; never silently ignore bad items.
368 assert request(
369 auth_client, token(keys[0], aram_scopes=[bad_scope]),
370 ).status_code == 401
371
372
373 @pytest.mark.parametrize("bad_scopes", [
374 {}, "all", True, [123], [_scope(), _scope()], [_scope()] * 33,
375 ])
376 def test_invalid_scopes_collection_or_duplicates_fail_closed(auth_client, keys, bad_scopes):
377 assert request(auth_client, token(keys[0], aram_scopes=bad_scopes)).status_code == 401
378
379
380 def test_signed_scopes_do_not_accept_forged_role_or_company_headers(
381 auth_client, keys, session,
382 ):
383 from aram_backend.database import get_session
384 year = _year(session)
385 app.dependency_overrides[get_session] = lambda: session
386 try:
387 response = auth_client.get(
388 f"/api/v1/auth/year-access/{year.id}",
389 headers={
390 "Authorization": f"Bearer {token(keys[0], aram_scopes=[_scope(company_code='OTHER')])}",
391 "X-ARAM-Company": "FIN-OPERATIONS",
392 "X-ARAM-Roles": "mapping_reviewer",
393 "X-ARAM-Year": "1404",
394 },
395 )
396 assert response.status_code == 403
397 finally:
398 app.dependency_overrides.pop(get_session, None)
399
400
401 def test_year_protection_change_in_second_db_session_is_rechecked(auth_client, keys, session):
402 from sqlalchemy import update
403 from sqlalchemy.orm import Session
404 from aram_backend.database import get_session
405 from aram_backend.models import FiscalYear, FiscalYearStatus
406 year = _year(session)
407 app.dependency_overrides[get_session] = lambda: session
408 try:
409 valid = token(keys[0], aram_scopes=[_scope()])
410 assert auth_client.get(
411 f"/api/v1/auth/year-access/{year.id}",
412 headers={"Authorization": f"Bearer {valid}"},
413 ).status_code == 200
414 with Session(session.get_bind()) as other:
415 other.execute(
416 update(FiscalYear).where(FiscalYear.id == year.id)
417 .values(status=FiscalYearStatus.APPROVED)
418 )
419 other.commit()
420 assert auth_client.get(
421 f"/api/v1/auth/year-access/{year.id}",
422 headers={"Authorization": f"Bearer {valid}"},
423 ).status_code == 403
424 finally:
425 app.dependency_overrides.pop(get_session, None)
426
427
428 def test_not_found_and_bool_year_identifiers_are_denied(auth_client, keys, session):
429 from aram_backend.database import get_session
430 _year(session)
431 app.dependency_overrides[get_session] = lambda: session
432 try:
433 assert _scope_request(
434 auth_client, keys[0], 999999, aram_scopes=[_scope()],
435 ).status_code == 403
436 assert _scope_request(
437 auth_client, keys[0], 0, aram_scopes=[_scope()],
438 ).status_code == 403
439 finally:
440 app.dependency_overrides.pop(get_session, None)
441
442
443 def test_access_check_rejects_uncommitted_fiscal_changes_without_flush(session, keys):
444 from aram_backend.authenticated_identity import verify_access_token
445 from aram_backend.mapping_year_authorization import require_year_access
446 from aram_backend.config import Settings
447 from aram_backend.models import AccountVersion
448 private, public, _ = keys
449 year = _year(session)
450 settings = Settings(auth_issuer=ISSUER, auth_audience=AUDIENCE,
451 auth_public_key_pem=public)
452 principal = verify_access_token(
453 token(private, aram_scopes=[_scope()]), settings=settings,
454 )
455 pending = AccountVersion(
456 year_id=year.id, account_code="0001", account_name="Pending", version=1,
457 )
458 session.add(pending)
459 # Unrelated uncommitted accounting entities are never automatically saved.
460 scope = require_year_access(
461 session, principal=principal, year_id=year.id,
462 required_role="mapping_proposer",
463 )
464 assert scope.company_code == "FIN-OPERATIONS"
465 assert pending in session.new and pending.id is None
466
467
468 def test_valid_proposer_cannot_assume_reviewer_role_with_scope_check(session, keys):
469 from fastapi import HTTPException
470 from aram_backend.authenticated_identity import verify_access_token
471 from aram_backend.mapping_year_authorization import require_year_access
472 year = _year(session)
473 principal = verify_access_token(
474 token(keys[0], aram_scopes=[_scope()]),
475 settings=Settings(auth_issuer=ISSUER, auth_audience=AUDIENCE,
476 auth_public_key_pem=keys[1]),
477 )
478 with pytest.raises(HTTPException) as denied:
479 require_year_access(
480 session, principal=principal, year_id=year.id,
481 required_role="mapping_reviewer",
482 )
483 assert denied.value.status_code == 403