Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 14:15 UTC
dependabot/github_actions/actions/upload-artifact-7
add-index-html-10623938925177053894
arena/094f314c-aram
arena/2d4eda07-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
dependabot/github_actions/actions/checkout-7
dependabot/github_actions/actions/setup-node-6
dependabot/github_actions/actions/setup-python-7
dependabot/github_actions/actions/upload-artifact-7
dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1
dependabot/npm_and_yarn/frontend/globals-17.15.0
dependabot/npm_and_yarn/frontend/vite-8.4.0
dependabot/npm_and_yarn/frontend/vitest-5.1.2
dependabot/npm_and_yarn/frontend/vitest/coverage-v8-5.1.2
dependabot/pip/backend/mypy-gte-1.13-and-lt-3
dependabot/pip/backend/pytest-cov-gte-6.0-and-lt-8
dependabot/pip/backend/setuptools-gte-75-and-lt-85
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 | """HTTP API for administration: session auth, users, audit, reopen/lock, backup. |
| 2 | |
| 3 | R1 (booklet 2.1): no endpoint accepts an ``actor`` field. Identity comes only from |
| 4 | the server-side session resolved by ``current_user``; the audit log is attributed |
| 5 | to that authenticated username. ``public_router`` holds the three routes that must |
| 6 | work before a session exists (login, desktop launch exchange, first-admin |
| 7 | bootstrap); everything else is behind the single authentication dependency. |
| 8 | """ |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | from fastapi import APIRouter, Depends, HTTPException, Request |
| 13 | from pydantic import BaseModel, Field |
| 14 | from sqlalchemy import select |
| 15 | from sqlalchemy.orm import Session |
| 16 | |
| 17 | from aram_backend.auth import ( |
| 18 | LAUNCH_HEADER, |
| 19 | bearer_token, |
| 20 | current_user, |
| 21 | launch_guard, |
| 22 | optional_user, |
| 23 | require_launch, |
| 24 | ) |
| 25 | from aram_backend.config import get_settings |
| 26 | from aram_backend.database import get_session |
| 27 | from aram_backend.models import AuditEntry, User, UserRole |
| 28 | from aram_backend.services.audit import verify_chain |
| 29 | from aram_backend.services.backup import BackupError, create_backup, verify_backup |
| 30 | from aram_backend.services.reopen import ( |
| 31 | ReopenError, |
| 32 | approve_reopen, |
| 33 | list_reopen_requests, |
| 34 | lock_year, |
| 35 | reopen_year, |
| 36 | request_reopen, |
| 37 | ) |
| 38 | from aram_backend.services.users import ( |
| 39 | AuthenticationError, |
| 40 | AuthorizationError, |
| 41 | UserError, |
| 42 | authenticate, |
| 43 | create_user, |
| 44 | ensure_role, |
| 45 | issue_session, |
| 46 | list_users, |
| 47 | revoke_session, |
| 48 | set_active, |
| 49 | set_role, |
| 50 | ) |
| 51 | |
| 52 | # /auth/launch must itself be reachable *before* a grant exists, so it sits on a |
| 53 | # router without the launch dependency; it is protected by the one-time token. |
| 54 | launch_router = APIRouter(prefix="/api/v1", tags=["auth"]) |
| 55 | public_router = APIRouter(prefix="/api/v1", tags=["auth"], dependencies=[Depends(require_launch)]) |
| 56 | router = APIRouter( |
| 57 | prefix="/api/v1", |
| 58 | tags=["admin"], |
| 59 | dependencies=[Depends(require_launch), Depends(current_user)], |
| 60 | ) |
| 61 | |
| 62 | _ADMIN = {UserRole.ADMIN} |
| 63 | _REVIEW = {UserRole.ADMIN, UserRole.REVIEWER} |
| 64 | |
| 65 | |
| 66 | def _require(user: User, allowed: set[UserRole]) -> None: |
| 67 | try: |
| 68 | ensure_role(user, allowed) |
| 69 | except AuthorizationError as exc: |
| 70 | raise HTTPException(status_code=403, detail=str(exc)) from exc |
| 71 | |
| 72 | |
| 73 | def _identity(user: User) -> dict: |
| 74 | return { |
| 75 | "username": user.username, |
| 76 | "display_name": user.display_name, |
| 77 | "role": user.role.value, |
| 78 | } |
| 79 | |
| 80 | |
| 81 | # ------------------------------------------------------------------ auth (public) |
| 82 | class LoginIn(BaseModel): |
| 83 | username: str = Field(min_length=1, max_length=64) |
| 84 | password: str = Field(min_length=1, max_length=256) |
| 85 | |
| 86 | |
| 87 | @public_router.post("/auth/login") |
| 88 | def login(body: LoginIn, session: Session = Depends(get_session)) -> dict: |
| 89 | try: |
| 90 | user = authenticate(session, username=body.username, password=body.password) |
| 91 | except UserError as exc: |
| 92 | raise HTTPException(status_code=401, detail=str(exc)) from exc |
| 93 | token = issue_session(session, user) |
| 94 | return {"token": token, "token_type": "Bearer", **_identity(user)} |
| 95 | |
| 96 | |
| 97 | @router.post("/auth/logout") |
| 98 | def logout(request: Request, session: Session = Depends(get_session)) -> dict: |
| 99 | """Revoke the presented session. Idempotent; never reveals token validity.""" |
| 100 | revoke_session(session, bearer_token(request)) |
| 101 | return {"logged_out": True} |
| 102 | |
| 103 | |
| 104 | class LaunchIn(BaseModel): |
| 105 | token: str = Field(min_length=1, max_length=256) |
| 106 | |
| 107 | |
| 108 | @launch_router.post("/auth/launch") |
| 109 | def launch_exchange(body: LaunchIn, request: Request) -> dict: |
| 110 | """Exchange the desktop launcher's one-time token for a launch grant.""" |
| 111 | guard = launch_guard(request) |
| 112 | if guard is None: |
| 113 | raise HTTPException(status_code=404, detail="راهانداز محلی در این حالت فعال نیست.") |
| 114 | try: |
| 115 | grant = guard.exchange(body.token) |
| 116 | except AuthenticationError as exc: |
| 117 | raise HTTPException(status_code=401, detail=str(exc)) from exc |
| 118 | return {"grant": grant, "header": LAUNCH_HEADER} |
| 119 | |
| 120 | |
| 121 | @router.get("/auth/me") |
| 122 | def me(user: User = Depends(current_user)) -> dict: |
| 123 | return _identity(user) |
| 124 | |
| 125 | |
| 126 | # --------------------------------------------------------------------- users |
| 127 | class UserIn(BaseModel): |
| 128 | username: str = Field(min_length=1, max_length=64) |
| 129 | password: str = Field(min_length=8, max_length=256) |
| 130 | role: UserRole = UserRole.PREPARER |
| 131 | display_name: str = Field(default="", max_length=128) |
| 132 | |
| 133 | |
| 134 | def bootstrap_guard(request: Request, session: Session = Depends(get_session)) -> None: |
| 135 | """Once any user exists, /users demands a session *before* body validation.""" |
| 136 | if list_users(session): |
| 137 | current_user(request, session) |
| 138 | |
| 139 | |
| 140 | @public_router.post("/users", dependencies=[Depends(bootstrap_guard)]) |
| 141 | def create_user_endpoint( |
| 142 | body: UserIn, |
| 143 | session: Session = Depends(get_session), |
| 144 | user: User | None = Depends(optional_user), |
| 145 | ) -> dict: |
| 146 | """First-admin bootstrap **only while the database has zero users**. |
| 147 | |
| 148 | Once any user exists this route requires an authenticated ADMIN, exactly like |
| 149 | the rest of the admin surface. The bootstrap can therefore happen once. |
| 150 | """ |
| 151 | if list_users(session): |
| 152 | if user is None: |
| 153 | raise HTTPException( |
| 154 | status_code=401, |
| 155 | detail="ورود لازم است.", |
| 156 | headers={"WWW-Authenticate": "Bearer"}, |
| 157 | ) |
| 158 | _require(user, _ADMIN) |
| 159 | role, actor = body.role, user.username |
| 160 | else: |
| 161 | role, actor = UserRole.ADMIN, "bootstrap" |
| 162 | try: |
| 163 | created = create_user( |
| 164 | session, |
| 165 | username=body.username, |
| 166 | password=body.password, |
| 167 | role=role, |
| 168 | display_name=body.display_name, |
| 169 | actor=actor, |
| 170 | ) |
| 171 | except UserError as exc: |
| 172 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 173 | session.commit() |
| 174 | return {"username": created.username, "role": created.role.value} |
| 175 | |
| 176 | |
| 177 | @router.get("/users") |
| 178 | def list_users_endpoint( |
| 179 | session: Session = Depends(get_session), user: User = Depends(current_user) |
| 180 | ) -> dict: |
| 181 | _require(user, _ADMIN) |
| 182 | return { |
| 183 | "users": [ |
| 184 | { |
| 185 | "username": u.username, |
| 186 | "display_name": u.display_name, |
| 187 | "role": u.role.value, |
| 188 | "active": u.active, |
| 189 | } |
| 190 | for u in list_users(session) |
| 191 | ] |
| 192 | } |
| 193 | |
| 194 | |
| 195 | class RoleIn(BaseModel): |
| 196 | role: UserRole |
| 197 | |
| 198 | |
| 199 | @router.post("/users/{username}/role") |
| 200 | def set_role_endpoint( |
| 201 | username: str, |
| 202 | body: RoleIn, |
| 203 | session: Session = Depends(get_session), |
| 204 | user: User = Depends(current_user), |
| 205 | ) -> dict: |
| 206 | _require(user, _ADMIN) |
| 207 | try: |
| 208 | target = set_role(session, username=username, role=body.role, actor=user.username) |
| 209 | except UserError as exc: |
| 210 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 211 | session.commit() |
| 212 | return {"username": target.username, "role": target.role.value} |
| 213 | |
| 214 | |
| 215 | class ActiveIn(BaseModel): |
| 216 | active: bool |
| 217 | |
| 218 | |
| 219 | @router.post("/users/{username}/active") |
| 220 | def set_active_endpoint( |
| 221 | username: str, |
| 222 | body: ActiveIn, |
| 223 | session: Session = Depends(get_session), |
| 224 | user: User = Depends(current_user), |
| 225 | ) -> dict: |
| 226 | _require(user, _ADMIN) |
| 227 | try: |
| 228 | target = set_active(session, username=username, active=body.active, actor=user.username) |
| 229 | except UserError as exc: |
| 230 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 231 | session.commit() |
| 232 | return {"username": target.username, "active": target.active} |
| 233 | |
| 234 | |
| 235 | # --------------------------------------------------------------------- audit |
| 236 | @router.get("/audit") |
| 237 | def list_audit(year_id: int | None = None, session: Session = Depends(get_session)) -> dict: |
| 238 | stmt = select(AuditEntry).order_by(AuditEntry.id.asc()) |
| 239 | if year_id is not None: |
| 240 | stmt = stmt.where(AuditEntry.year_id == year_id) |
| 241 | entries = session.scalars(stmt).all() |
| 242 | return { |
| 243 | "chain_valid": verify_chain(session), |
| 244 | "entries": [ |
| 245 | { |
| 246 | "id": e.id, |
| 247 | "year_id": e.year_id, |
| 248 | "actor": e.actor, |
| 249 | "action": e.action, |
| 250 | "chain_hash": e.chain_hash, |
| 251 | "created_at": e.created_at.isoformat(), |
| 252 | } |
| 253 | for e in entries |
| 254 | ], |
| 255 | } |
| 256 | |
| 257 | |
| 258 | @router.get("/audit/verify") |
| 259 | def verify_audit(session: Session = Depends(get_session)) -> dict: |
| 260 | return {"chain_valid": verify_chain(session)} |
| 261 | |
| 262 | |
| 263 | # --------------------------------------------------------------- reopen/lock |
| 264 | class ReopenRequestIn(BaseModel): |
| 265 | reason: str = Field(min_length=1, max_length=2000) |
| 266 | |
| 267 | |
| 268 | @router.post("/years/{year_id}/reopen/request") |
| 269 | def reopen_request( |
| 270 | year_id: int, |
| 271 | body: ReopenRequestIn, |
| 272 | session: Session = Depends(get_session), |
| 273 | user: User = Depends(current_user), |
| 274 | ) -> dict: |
| 275 | _require(user, _REVIEW) |
| 276 | try: |
| 277 | request = request_reopen(session, year_id, reason=body.reason, requested_by=user.username) |
| 278 | except ReopenError as exc: |
| 279 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 280 | session.commit() |
| 281 | return {"request_id": request.id, "status": request.status} |
| 282 | |
| 283 | |
| 284 | @router.post("/reopen/{request_id}/approve") |
| 285 | def reopen_approve( |
| 286 | request_id: int, session: Session = Depends(get_session), user: User = Depends(current_user) |
| 287 | ) -> dict: |
| 288 | _require(user, _REVIEW) |
| 289 | try: |
| 290 | request = approve_reopen(session, request_id, approved_by=user.username) |
| 291 | except ReopenError as exc: |
| 292 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 293 | session.commit() |
| 294 | return {"request_id": request.id, "status": request.status} |
| 295 | |
| 296 | |
| 297 | @router.post("/years/{year_id}/reopen") |
| 298 | def reopen( |
| 299 | year_id: int, session: Session = Depends(get_session), user: User = Depends(current_user) |
| 300 | ) -> dict: |
| 301 | _require(user, _REVIEW) |
| 302 | try: |
| 303 | year = reopen_year(session, year_id, actor=user.username) |
| 304 | except ReopenError as exc: |
| 305 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 306 | session.commit() |
| 307 | return {"year_id": year.id, "status": year.status.value} |
| 308 | |
| 309 | |
| 310 | @router.post("/years/{year_id}/lock") |
| 311 | def lock( |
| 312 | year_id: int, session: Session = Depends(get_session), user: User = Depends(current_user) |
| 313 | ) -> dict: |
| 314 | _require(user, _REVIEW) |
| 315 | try: |
| 316 | year = lock_year(session, year_id, actor=user.username) |
| 317 | except ReopenError as exc: |
| 318 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 319 | session.commit() |
| 320 | return {"year_id": year.id, "status": year.status.value} |
| 321 | |
| 322 | |
| 323 | @router.get("/years/{year_id}/reopen/requests") |
| 324 | def reopen_requests(year_id: int, session: Session = Depends(get_session)) -> dict: |
| 325 | return { |
| 326 | "requests": [ |
| 327 | { |
| 328 | "id": r.id, |
| 329 | "reason": r.reason, |
| 330 | "requested_by": r.requested_by, |
| 331 | "approved_by": r.approved_by, |
| 332 | "status": r.status, |
| 333 | } |
| 334 | for r in list_reopen_requests(session, year_id) |
| 335 | ] |
| 336 | } |
| 337 | |
| 338 | |
| 339 | # -------------------------------------------------------------------- backup |
| 340 | class BackupIn(BaseModel): |
| 341 | dest: str = Field(min_length=1, max_length=512) |
| 342 | |
| 343 | |
| 344 | @router.post("/backup") |
| 345 | def backup( |
| 346 | body: BackupIn, session: Session = Depends(get_session), user: User = Depends(current_user) |
| 347 | ) -> dict: |
| 348 | _require(user, _ADMIN) |
| 349 | settings = get_settings() |
| 350 | try: |
| 351 | manifest = create_backup( |
| 352 | session, |
| 353 | body.dest, |
| 354 | store_root=settings.source_store_root, |
| 355 | backup_root=settings.backup_root, |
| 356 | ) |
| 357 | except BackupError as exc: |
| 358 | raise HTTPException(status_code=422, detail=str(exc)) from exc |
| 359 | return {"dest": body.dest, "manifest": manifest} |
| 360 | |
| 361 | |
| 362 | class VerifyBackupIn(BaseModel): |
| 363 | dest: str = Field(min_length=1, max_length=512) |
| 364 | |
| 365 | |
| 366 | @router.post("/backup/verify") |
| 367 | def backup_verify( |
| 368 | body: VerifyBackupIn, |
| 369 | session: Session = Depends(get_session), |
| 370 | user: User = Depends(current_user), |
| 371 | ) -> dict: |
| 372 | _require(user, _ADMIN) |
| 373 | settings = get_settings() |
| 374 | try: |
| 375 | return verify_backup( |
| 376 | body.dest, store_root=settings.source_store_root, backup_root=settings.backup_root |
| 377 | ) |
| 378 | except BackupError as exc: |
| 379 | raise HTTPException(status_code=422, detail=str(exc)) from exc |