Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 3, 17:00 UTC
codex/windows-native-pilot-shell-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 | """Synthetic identity-bound proposal staging; never a finance approval.""" |
| 2 | from dataclasses import replace |
| 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 | from sqlalchemy import delete, insert, select, update |
| 11 | from sqlalchemy.exc import IntegrityError |
| 12 | from sqlalchemy.orm import Session |
| 13 | |
| 14 | from aram_backend.authenticated_identity import verify_access_token |
| 15 | from aram_backend.authored_mapping_draft import ( |
| 16 | mapping_draft_authors, SQLITE_AUTHOR_GUARD_DDL, |
| 17 | stage_authored_unreviewed_batch, get_draft_author, |
| 18 | check_independent_mapping_reviewer, |
| 19 | ) |
| 20 | from aram_backend.config import Settings, get_settings |
| 21 | from aram_backend.database import get_session |
| 22 | from aram_backend.main import app |
| 23 | from aram_backend.mapping_batch_review import ProposedMappingRow, preview_mapping_batch |
| 24 | from aram_backend.mapping_draft_store import mapping_review_drafts, get_unreviewed_batch |
| 25 | from aram_backend.mapping_draft_audit import ( |
| 26 | mapping_draft_events, SQLITE_AUDIT_GUARD_DDL, |
| 27 | ) |
| 28 | from aram_backend.mapping_service import MappingValidationError |
| 29 | from aram_backend.models import ( |
| 30 | AccountVersion, Company, FiscalYear, FiscalYearStatus, MappingRule, |
| 31 | NoteDefinition, |
| 32 | ) |
| 33 | |
| 34 | ISSUER = "https://synthetic-authorship.example.invalid/" |
| 35 | AUDIENCE = "aram-mapping-api" |
| 36 | |
| 37 | |
| 38 | @pytest.fixture(scope="module") |
| 39 | def rsa_pair(): |
| 40 | signer = rsa.generate_private_key(public_exponent=65537, key_size=2048) |
| 41 | public = signer.public_key().public_bytes( |
| 42 | serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo, |
| 43 | ).decode() |
| 44 | return signer, public |
| 45 | |
| 46 | |
| 47 | @pytest.fixture |
| 48 | def bound_environment(session, rsa_pair): |
| 49 | engine = session.get_bind() |
| 50 | mapping_review_drafts.create(engine) |
| 51 | mapping_draft_events.create(engine) |
| 52 | mapping_draft_authors.create(engine) |
| 53 | with engine.begin() as conn: |
| 54 | for ddl in (*SQLITE_AUDIT_GUARD_DDL, *SQLITE_AUTHOR_GUARD_DDL): |
| 55 | conn.exec_driver_sql(ddl) |
| 56 | company = Company(code="FIN-LEGAL", name="Synthetic reporting company") |
| 57 | other_company = Company(code="FIN-OTHER", name="Other synthetic") |
| 58 | year = FiscalYear(company=company, year=1404) |
| 59 | other_year = FiscalYear(company=other_company, year=1404) |
| 60 | session.add_all([year, other_year]) |
| 61 | session.flush() |
| 62 | note = NoteDefinition(year_id=year.id, note_number="1", title="Cash", version=1) |
| 63 | account = AccountVersion( |
| 64 | year_id=year.id, account_code="001", account_name="Cash", version=1, |
| 65 | ) |
| 66 | session.add_all([note, account]) |
| 67 | session.commit() |
| 68 | config = Settings(auth_issuer=ISSUER, auth_audience=AUDIENCE, |
| 69 | auth_public_key_pem=rsa_pair[1]) |
| 70 | app.dependency_overrides[get_settings] = lambda: config |
| 71 | |
| 72 | def isolated_session(): |
| 73 | with Session(engine, expire_on_commit=False) as request_db: |
| 74 | yield request_db |
| 75 | app.dependency_overrides[get_session] = isolated_session |
| 76 | try: |
| 77 | with TestClient(app) as client: |
| 78 | yield client, session, year, other_year, note, config |
| 79 | finally: |
| 80 | app.dependency_overrides.pop(get_session, None) |
| 81 | app.dependency_overrides.pop(get_settings, None) |
| 82 | session.rollback() |
| 83 | mapping_draft_authors.drop(engine) |
| 84 | mapping_draft_events.drop(engine) |
| 85 | mapping_review_drafts.drop(engine) |
| 86 | |
| 87 | |
| 88 | def signed_token(rsa_pair, *, subject="employee-author-01", role="mapping_proposer", |
| 89 | company="FIN-LEGAL", year=1404, include_scope=True): |
| 90 | now = int(time()) |
| 91 | claims = { |
| 92 | "iss": ISSUER, "aud": AUDIENCE, "sub": subject, |
| 93 | "iat": now - 5, "nbf": now - 5, "exp": now + 250, |
| 94 | "token_use": "access", "aram_roles": [role], |
| 95 | } |
| 96 | if include_scope: |
| 97 | claims["aram_scopes"] = [{ |
| 98 | "company_code": company, "fiscal_year": year, "role": role, |
| 99 | }] |
| 100 | return jwt.encode(claims, rsa_pair[0], algorithm="RS256") |
| 101 | |
| 102 | |
| 103 | def posted_rows(note_id): |
| 104 | return [{ |
| 105 | "source_locator": "Mapping!2", "rule_key": "cash", |
| 106 | "account_code": "001", "target_note_id": note_id, |
| 107 | "mapping_type": "manual", "expected_base_version": 0, |
| 108 | }] |
| 109 | |
| 110 | |
| 111 | def stage(client, key, year_id, token, note_id): |
| 112 | return client.post( |
| 113 | "/api/v1/mapping/unreviewed-drafts", |
| 114 | json={ |
| 115 | "year_id": year_id, "request_key": key, |
| 116 | "rows": posted_rows(note_id), |
| 117 | }, |
| 118 | headers={"Authorization": f"Bearer {token}"}, |
| 119 | ) |
| 120 | |
| 121 | |
| 122 | def test_signed_proposer_stages_exactly_one_authored_draft_and_system_event( |
| 123 | bound_environment, rsa_pair, |
| 124 | ): |
| 125 | client, session, year, _, note, _ = bound_environment |
| 126 | response = stage(client, "author-a1", year.id, signed_token(rsa_pair), note.id) |
| 127 | assert response.status_code == 201, response.text |
| 128 | data = response.json() |
| 129 | assert data["draft_id"] > 0 |
| 130 | assert data["year_id"] == year.id |
| 131 | assert data["state"] == "Unreviewed" |
| 132 | assert set(data) == {"draft_id", "year_id", "state", "request_key"} |
| 133 | author = get_draft_author(session, draft_id=data["draft_id"], year_id=year.id) |
| 134 | assert author.subject == "employee-author-01" |
| 135 | assert author.issuer == ISSUER |
| 136 | assert author.company_code == "FIN-LEGAL" |
| 137 | assert author.fiscal_year == 1404 |
| 138 | assert author.role == "mapping_proposer" |
| 139 | assert session.execute(select(mapping_draft_authors)).all() |
| 140 | assert len(session.execute(select(mapping_draft_events)).all()) == 1 |
| 141 | assert len(session.execute(select(mapping_review_drafts)).all()) == 1 |
| 142 | assert session.scalars(select(MappingRule)).all() == [] |
| 143 | |
| 144 | |
| 145 | def test_repeated_request_by_same_author_is_idempotent(bound_environment, rsa_pair): |
| 146 | client, session, year, _, note, _ = bound_environment |
| 147 | jwt_token = signed_token(rsa_pair) |
| 148 | first = stage(client, "author-a2", year.id, jwt_token, note.id) |
| 149 | second = stage(client, "author-a2", year.id, jwt_token, note.id) |
| 150 | assert first.status_code == second.status_code == 201 |
| 151 | assert first.json() == second.json() |
| 152 | assert len(session.execute(select(mapping_draft_authors)).all()) == 1 |
| 153 | assert len(session.execute(select(mapping_draft_events)).all()) == 1 |
| 154 | |
| 155 | |
| 156 | def test_same_idempotency_key_cannot_be_claimed_by_another_author( |
| 157 | bound_environment, rsa_pair, |
| 158 | ): |
| 159 | client, session, year, _, note, _ = bound_environment |
| 160 | first = stage(client, "author-a3", year.id, signed_token(rsa_pair), note.id) |
| 161 | second = stage(client, "author-a3", year.id, signed_token( |
| 162 | rsa_pair, subject="other-employee", |
| 163 | ), note.id) |
| 164 | assert first.status_code == 201 |
| 165 | assert second.status_code == 409 |
| 166 | assert len(session.execute(select(mapping_draft_authors)).all()) == 1 |
| 167 | original = get_draft_author(session, draft_id=first.json()["draft_id"], |
| 168 | year_id=year.id) |
| 169 | assert original.subject == "employee-author-01" |
| 170 | |
| 171 | |
| 172 | @pytest.mark.parametrize("role,company,include_scope", [ |
| 173 | ("mapping_reviewer", "FIN-LEGAL", True), |
| 174 | ("mapping_proposer", "FIN-OTHER", True), |
| 175 | ("mapping_proposer", "FIN-LEGAL", False), |
| 176 | ]) |
| 177 | def test_signed_role_or_company_scope_is_required( |
| 178 | bound_environment, rsa_pair, role, company, include_scope, |
| 179 | ): |
| 180 | client, session, year, _, note, _ = bound_environment |
| 181 | response = stage(client, "auth-denied", year.id, signed_token( |
| 182 | rsa_pair, role=role, company=company, include_scope=include_scope, |
| 183 | ), note.id) |
| 184 | assert response.status_code == 403 |
| 185 | assert session.execute(select(mapping_review_drafts)).all() == [] |
| 186 | assert session.execute(select(mapping_draft_authors)).all() == [] |
| 187 | |
| 188 | |
| 189 | def test_cross_year_and_locked_year_cannot_stage(bound_environment, rsa_pair): |
| 190 | client, session, year, other_year, note, _ = bound_environment |
| 191 | token = signed_token(rsa_pair) |
| 192 | assert stage(client, "wrong-company", other_year.id, token, note.id).status_code == 403 |
| 193 | session.execute(update(FiscalYear).where(FiscalYear.id == year.id).values( |
| 194 | status=FiscalYearStatus.APPROVED, |
| 195 | )) |
| 196 | session.commit() |
| 197 | assert stage(client, "approved", year.id, token, note.id).status_code == 403 |
| 198 | assert session.execute(select(mapping_review_drafts)).all() == [] |
| 199 | |
| 200 | |
| 201 | def test_missing_bearer_and_forged_author_headers_do_not_stage( |
| 202 | bound_environment, rsa_pair, |
| 203 | ): |
| 204 | client, session, year, _, note, _ = bound_environment |
| 205 | payload = {"year_id": year.id, "request_key": "unauth", |
| 206 | "rows": posted_rows(note.id)} |
| 207 | assert client.post( |
| 208 | "/api/v1/mapping/unreviewed-drafts", json=payload, |
| 209 | headers={"X-User": "director", "X-ARAM-Roles": "mapping_proposer"}, |
| 210 | ).status_code == 401 |
| 211 | wrong_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) |
| 212 | signed_wrong = jwt.encode({ |
| 213 | "iss": ISSUER, "aud": AUDIENCE, "sub": "fake-director", |
| 214 | "iat": int(time()) - 3, "nbf": int(time()) - 3, |
| 215 | "exp": int(time()) + 100, "token_use": "access", |
| 216 | "aram_roles": ["mapping_proposer"], "aram_scopes": [{ |
| 217 | "company_code": "FIN-LEGAL", "fiscal_year": 1404, |
| 218 | "role": "mapping_proposer", |
| 219 | }], |
| 220 | }, wrong_key, algorithm="RS256") |
| 221 | assert stage(client, "wrong-sig", year.id, signed_wrong, note.id).status_code == 401 |
| 222 | assert session.execute(select(mapping_review_drafts)).all() == [] |
| 223 | |
| 224 | |
| 225 | def test_existing_unattributed_draft_cannot_be_retroactively_claimed( |
| 226 | bound_environment, rsa_pair, |
| 227 | ): |
| 228 | from aram_backend.mapping_draft_store import save_unreviewed_batch |
| 229 | client, session, year, _, note, _ = bound_environment |
| 230 | snapshot = preview_mapping_batch(session, year_id=year.id, rows=( |
| 231 | ProposedMappingRow("Mapping!2", "cash", "001", note.id, "manual", 0), |
| 232 | )) |
| 233 | original = save_unreviewed_batch( |
| 234 | session, snapshot, request_key="legacy-unattributed", |
| 235 | ) |
| 236 | session.commit() |
| 237 | assert stage(client, "legacy-unattributed", year.id, |
| 238 | signed_token(rsa_pair), note.id).status_code == 409 |
| 239 | assert original.id > 0 |
| 240 | assert session.execute(select(mapping_draft_authors)).all() == [] |
| 241 | |
| 242 | |
| 243 | def test_author_binding_is_insert_only_on_sqlite(bound_environment, rsa_pair): |
| 244 | client, session, year, _, note, _ = bound_environment |
| 245 | response = stage(client, "author-lock", year.id, signed_token(rsa_pair), note.id) |
| 246 | assert response.status_code == 201 |
| 247 | author = get_draft_author( |
| 248 | session, draft_id=response.json()["draft_id"], year_id=year.id, |
| 249 | ) |
| 250 | with pytest.raises(IntegrityError): |
| 251 | session.execute(update(mapping_draft_authors) |
| 252 | .values(subject="impersonator")) |
| 253 | session.rollback() |
| 254 | with pytest.raises(IntegrityError): |
| 255 | session.execute(delete(mapping_draft_authors)) |
| 256 | session.rollback() |
| 257 | assert get_draft_author( |
| 258 | session, draft_id=response.json()["draft_id"], year_id=year.id, |
| 259 | ) == author |
| 260 | |
| 261 | |
| 262 | def test_bound_draft_and_events_atomic_rollback_on_binding_failure( |
| 263 | bound_environment, rsa_pair, monkeypatch, |
| 264 | ): |
| 265 | import aram_backend.authored_mapping_draft as module |
| 266 | client, session, year, _, note, _ = bound_environment |
| 267 | def unavailable(*args, **kwargs): |
| 268 | raise RuntimeError("synthetic author evidence insert failed") |
| 269 | monkeypatch.setattr(module, "_insert_author_evidence", unavailable) |
| 270 | # The route must rollback staging+event when author evidence insert fails. |
| 271 | with pytest.raises(RuntimeError, match="synthetic author"): |
| 272 | stage(client, "atomic-rollback", year.id, signed_token(rsa_pair), note.id) |
| 273 | session.expire_all() |
| 274 | assert session.execute(select(mapping_review_drafts)).all() == [] |
| 275 | assert session.execute(select(mapping_draft_events)).all() == [] |
| 276 | |
| 277 | |
| 278 | def test_reviewer_separation_is_read_only_and_never_self_approves( |
| 279 | bound_environment, rsa_pair, |
| 280 | ): |
| 281 | from fastapi import HTTPException |
| 282 | client, session, year, _, note, config = bound_environment |
| 283 | response = stage(client, "review-separation", year.id, |
| 284 | signed_token(rsa_pair), note.id) |
| 285 | assert response.status_code == 201 |
| 286 | draft_id = response.json()["draft_id"] |
| 287 | author_as_reviewer = verify_access_token(signed_token( |
| 288 | rsa_pair, subject="employee-author-01", role="mapping_reviewer", |
| 289 | ), settings=config) |
| 290 | with pytest.raises(HTTPException) as same: |
| 291 | check_independent_mapping_reviewer( |
| 292 | session, draft_id=draft_id, year_id=year.id, |
| 293 | reviewer=author_as_reviewer, |
| 294 | ) |
| 295 | assert same.value.status_code == 403 |
| 296 | distinct = verify_access_token(signed_token( |
| 297 | rsa_pair, subject="employee-reviewer-02", role="mapping_reviewer", |
| 298 | ), settings=config) |
| 299 | assert check_independent_mapping_reviewer( |
| 300 | session, draft_id=draft_id, year_id=year.id, reviewer=distinct, |
| 301 | ) is None |
| 302 | assert get_unreviewed_batch(session, draft_id=draft_id, |
| 303 | year_id=year.id).state == "Unreviewed" |
| 304 | assert session.scalars(select(MappingRule)).all() == [] |
| 305 | |
| 306 | |
| 307 | def test_reviewer_missing_grant_or_proposer_role_never_passes_preflight( |
| 308 | bound_environment, rsa_pair, |
| 309 | ): |
| 310 | from fastapi import HTTPException |
| 311 | client, session, year, _, note, config = bound_environment |
| 312 | response = stage(client, "review-grants", year.id, signed_token(rsa_pair), note.id) |
| 313 | assert response.status_code == 201 |
| 314 | draft_id = response.json()["draft_id"] |
| 315 | for token_value in [ |
| 316 | signed_token(rsa_pair, subject="other", role="mapping_reviewer", |
| 317 | include_scope=False), |
| 318 | signed_token(rsa_pair, subject="other", role="mapping_proposer"), |
| 319 | ]: |
| 320 | person = verify_access_token(token_value, settings=config) |
| 321 | with pytest.raises(HTTPException) as denied: |
| 322 | check_independent_mapping_reviewer( |
| 323 | session, draft_id=draft_id, year_id=year.id, reviewer=person, |
| 324 | ) |
| 325 | assert denied.value.status_code == 403 |
| 326 | |
| 327 | |
| 328 | def test_unconfigured_identity_does_not_create_authored_drafts( |
| 329 | bound_environment, rsa_pair, |
| 330 | ): |
| 331 | client, session, year, _, note, _ = bound_environment |
| 332 | app.dependency_overrides[get_settings] = lambda: Settings() |
| 333 | assert stage(client, "unconfigured", year.id, signed_token(rsa_pair), |
| 334 | note.id).status_code == 503 |
| 335 | assert session.execute(select(mapping_review_drafts)).all() == [] |
| 336 | |
| 337 | |
| 338 | def test_proposal_body_cannot_supply_actor_and_bad_rows_never_stage( |
| 339 | bound_environment, rsa_pair, |
| 340 | ): |
| 341 | client, session, year, _, note, _ = bound_environment |
| 342 | bearer = signed_token(rsa_pair) |
| 343 | base = {"year_id": year.id, "request_key": "bad-body", |
| 344 | "rows": posted_rows(note.id)} |
| 345 | assert client.post( |
| 346 | "/api/v1/mapping/unreviewed-drafts", |
| 347 | json={**base, "author_subject": "fake-director"}, |
| 348 | headers={"Authorization": f"Bearer {bearer}"}, |
| 349 | ).status_code == 422 |
| 350 | assert client.post( |
| 351 | "/api/v1/mapping/unreviewed-drafts", |
| 352 | json={**base, "rows": [ |
| 353 | {**posted_rows(note.id)[0], "expected_base_version": True}, |
| 354 | ]}, |
| 355 | headers={"Authorization": f"Bearer {bearer}"}, |
| 356 | ).status_code == 422 |
| 357 | assert session.execute(select(mapping_review_drafts)).all() == [] |