@davoodmehraban89 / Aram / commits / e20572d
Fork 0

feat(admin): Phase 7 users/roles, controlled reopen/lock, verifiable backup

- User model + roles (admin/reviewer/preparer); PBKDF2-HMAC-SHA256 + per-user salt (stdlib, no plaintext, no network); require_role gate; first-user bootstrap. - Reopen/lock service: request->approve->reopen (LOCKED->APPROVED only with an approved request; ORM guard + DB trigger re-check, no bypass); lock APPROVED-> LOCKED; every step hash-chained audited. Migration 20261203_07 (round-trip OK). - Backup: consistent SQLite online-backup snapshot + source-store copy + SHA-256 manifest + audit-chain verification; verify_backup recomputes hashes + chain; tamper/non-empty-dest/broken-chain refused. ADR-023. - admin_api /api/v1: users, auth/login, audit(+verify), reopen/lock, backup(+verify) with 403 role gates. - 17 tests (users/auth/roles, reopen workflow + immutability, backup integrity + tamper, admin API bootstrap/login/gate/audit). Full suite: 305 passed. Live proof: bootstrap->admin, login, audit chain valid, backup+verify (1 source file), preparer backup -> 403. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 11:37 UTC e20572ded61c3472b74699170e2ed9a5a92bc572
9 files changed +1046
backend/migrations/versions/20261203_07_users.py new
+56
@@ -0,0 +1,56 @@
1 +"""Local users with roles (Phase 7, booklet §7/§12).
2 +
3 +Adds the ``users`` table for offline desktop identity: username, role, and a
4 +PBKDF2-HMAC-SHA256 password hash + per-user salt (no plaintext). Fresh databases
5 +get the table from the live model; this revision creates it on pre-existing DBs.
6 +
7 +Revision ID: 20261203_07
8 +Revises: 20261203_06
9 +"""
10 +
11 +import sqlalchemy as sa
12 +from alembic import op
13 +
14 +from aram_backend.models import UserRole
15 +
16 +revision = "20261203_07"
17 +down_revision = "20261203_06"
18 +branch_labels = None
19 +depends_on = None
20 +
21 +
22 +def _has_table(bind, name: str) -> bool:
23 + return name in sa.inspect(bind).get_table_names()
24 +
25 +
26 +def upgrade() -> None:
27 + bind = op.get_bind()
28 + if _has_table(bind, "users"):
29 + return
30 + op.create_table(
31 + "users",
32 + sa.Column("id", sa.Integer(), primary_key=True),
33 + sa.Column("username", sa.String(length=64), nullable=False),
34 + sa.Column("display_name", sa.String(length=128), nullable=False, server_default=""),
35 + sa.Column(
36 + "role",
37 + sa.Enum(UserRole, native_enum=False, length=16),
38 + nullable=False,
39 + server_default="PREPARER",
40 + ),
41 + sa.Column("password_hash", sa.String(length=128), nullable=False),
42 + sa.Column("salt", sa.String(length=64), nullable=False),
43 + sa.Column("active", sa.Boolean(), nullable=False, server_default=sa.true()),
44 + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
45 + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
46 + sa.UniqueConstraint("username", name="uq_users_username"),
47 + )
48 + op.create_index("ix_users_username", "users", ["username"])
49 +
50 +
51 +def downgrade() -> None:
52 + bind = op.get_bind()
53 + if not _has_table(bind, "users"):
54 + return
55 + op.drop_index("ix_users_username", table_name="users")
56 + op.drop_table("users")
backend/src/aram_backend/admin_api.py new
+275
@@ -0,0 +1,275 @@
1 +"""HTTP API for Phase 7 administration: users, audit, reopen/lock, backup.
2 +
3 +Sensitive actions are gated by local role (``require_role``) and attributed to a
4 +username in the hash-chained audit log. Offline desktop: no runtime network.
5 +"""
6 +
7 +from __future__ import annotations
8 +
9 +from fastapi import APIRouter, Depends, HTTPException
10 +from pydantic import BaseModel, Field
11 +from sqlalchemy import select
12 +from sqlalchemy.orm import Session
13 +
14 +from aram_backend.config import get_settings
15 +from aram_backend.database import get_session
16 +from aram_backend.models import AuditEntry, UserRole
17 +from aram_backend.services.audit import verify_chain
18 +from aram_backend.services.backup import BackupError, create_backup, verify_backup
19 +from aram_backend.services.reopen import (
20 + ReopenError,
21 + approve_reopen,
22 + list_reopen_requests,
23 + lock_year,
24 + reopen_year,
25 + request_reopen,
26 +)
27 +from aram_backend.services.users import (
28 + AuthorizationError,
29 + UserError,
30 + authenticate,
31 + create_user,
32 + list_users,
33 + require_role,
34 + set_active,
35 + set_role,
36 +)
37 +
38 +router = APIRouter(prefix="/api/v1", tags=["admin"])
39 +
40 +_ADMIN = {UserRole.ADMIN}
41 +_REVIEW = {UserRole.ADMIN, UserRole.REVIEWER}
42 +
43 +
44 +def _guard(session: Session, actor: str, allowed: set[UserRole]) -> None:
45 + try:
46 + require_role(session, username=actor, allowed=allowed)
47 + except AuthorizationError as exc:
48 + raise HTTPException(status_code=403, detail=str(exc)) from exc
49 +
50 +
51 +# --------------------------------------------------------------------- users
52 +class UserIn(BaseModel):
53 + username: str = Field(min_length=1, max_length=64)
54 + password: str = Field(min_length=8, max_length=256)
55 + role: UserRole = UserRole.PREPARER
56 + display_name: str = Field(default="", max_length=128)
57 + actor: str = Field(default="", max_length=64)
58 +
59 +
60 +@router.post("/users")
61 +def create_user_endpoint(body: UserIn, session: Session = Depends(get_session)) -> dict:
62 + # Bootstrap: the very first user is created without an existing admin and is
63 + # forced to the admin role (offline desktop install). Afterwards, only an
64 + # admin may create users.
65 + bootstrap = not list_users(session)
66 + if not bootstrap:
67 + _guard(session, body.actor, _ADMIN)
68 + role = UserRole.ADMIN if bootstrap else body.role
69 + try:
70 + user = create_user(
71 + session,
72 + username=body.username,
73 + password=body.password,
74 + role=role,
75 + display_name=body.display_name,
76 + actor=body.actor,
77 + )
78 + except UserError as exc:
79 + raise HTTPException(status_code=422, detail=str(exc)) from exc
80 + session.commit()
81 + return {"username": user.username, "role": user.role.value}
82 +
83 +
84 +@router.get("/users")
85 +def list_users_endpoint(actor: str = "", session: Session = Depends(get_session)) -> dict:
86 + _guard(session, actor, _ADMIN)
87 + return {
88 + "users": [
89 + {
90 + "username": u.username,
91 + "display_name": u.display_name,
92 + "role": u.role.value,
93 + "active": u.active,
94 + }
95 + for u in list_users(session)
96 + ]
97 + }
98 +
99 +
100 +class LoginIn(BaseModel):
101 + username: str = Field(min_length=1, max_length=64)
102 + password: str = Field(min_length=1, max_length=256)
103 +
104 +
105 +@router.post("/auth/login")
106 +def login(body: LoginIn, session: Session = Depends(get_session)) -> dict:
107 + try:
108 + user = authenticate(session, username=body.username, password=body.password)
109 + except UserError as exc:
110 + raise HTTPException(status_code=401, detail=str(exc)) from exc
111 + return {"username": user.username, "display_name": user.display_name, "role": user.role.value}
112 +
113 +
114 +class RoleIn(BaseModel):
115 + role: UserRole
116 + actor: str = Field(default="", max_length=64)
117 +
118 +
119 +@router.post("/users/{username}/role")
120 +def set_role_endpoint(username: str, body: RoleIn, session: Session = Depends(get_session)) -> dict:
121 + _guard(session, body.actor, _ADMIN)
122 + try:
123 + user = set_role(session, username=username, role=body.role, actor=body.actor)
124 + except UserError as exc:
125 + raise HTTPException(status_code=422, detail=str(exc)) from exc
126 + session.commit()
127 + return {"username": user.username, "role": user.role.value}
128 +
129 +
130 +class ActiveIn(BaseModel):
131 + active: bool
132 + actor: str = Field(default="", max_length=64)
133 +
134 +
135 +@router.post("/users/{username}/active")
136 +def set_active_endpoint(
137 + username: str, body: ActiveIn, session: Session = Depends(get_session)
138 +) -> dict:
139 + _guard(session, body.actor, _ADMIN)
140 + try:
141 + user = set_active(session, username=username, active=body.active, actor=body.actor)
142 + except UserError as exc:
143 + raise HTTPException(status_code=422, detail=str(exc)) from exc
144 + session.commit()
145 + return {"username": user.username, "active": user.active}
146 +
147 +
148 +# --------------------------------------------------------------------- audit
149 +@router.get("/audit")
150 +def list_audit(year_id: int | None = None, session: Session = Depends(get_session)) -> dict:
151 + stmt = select(AuditEntry).order_by(AuditEntry.id.asc())
152 + if year_id is not None:
153 + stmt = stmt.where(AuditEntry.year_id == year_id)
154 + entries = session.scalars(stmt).all()
155 + return {
156 + "chain_valid": verify_chain(session),
157 + "entries": [
158 + {
159 + "id": e.id,
160 + "year_id": e.year_id,
161 + "actor": e.actor,
162 + "action": e.action,
163 + "chain_hash": e.chain_hash,
164 + "created_at": e.created_at.isoformat(),
165 + }
166 + for e in entries
167 + ],
168 + }
169 +
170 +
171 +@router.get("/audit/verify")
172 +def verify_audit(session: Session = Depends(get_session)) -> dict:
173 + return {"chain_valid": verify_chain(session)}
174 +
175 +
176 +# --------------------------------------------------------------- reopen/lock
177 +class ReopenRequestIn(BaseModel):
178 + reason: str = Field(min_length=1, max_length=2000)
179 + actor: str = Field(default="", max_length=64)
180 +
181 +
182 +@router.post("/years/{year_id}/reopen/request")
183 +def reopen_request(
184 + year_id: int, body: ReopenRequestIn, session: Session = Depends(get_session)
185 +) -> dict:
186 + _guard(session, body.actor, _REVIEW)
187 + try:
188 + request = request_reopen(session, year_id, reason=body.reason, requested_by=body.actor)
189 + except ReopenError as exc:
190 + raise HTTPException(status_code=422, detail=str(exc)) from exc
191 + session.commit()
192 + return {"request_id": request.id, "status": request.status}
193 +
194 +
195 +class ActorIn(BaseModel):
196 + actor: str = Field(default="", max_length=64)
197 +
198 +
199 +@router.post("/reopen/{request_id}/approve")
200 +def reopen_approve(request_id: int, body: ActorIn, session: Session = Depends(get_session)) -> dict:
201 + _guard(session, body.actor, _REVIEW)
202 + try:
203 + request = approve_reopen(session, request_id, approved_by=body.actor)
204 + except ReopenError as exc:
205 + raise HTTPException(status_code=422, detail=str(exc)) from exc
206 + session.commit()
207 + return {"request_id": request.id, "status": request.status}
208 +
209 +
210 +@router.post("/years/{year_id}/reopen")
211 +def reopen(year_id: int, body: ActorIn, session: Session = Depends(get_session)) -> dict:
212 + _guard(session, body.actor, _REVIEW)
213 + try:
214 + year = reopen_year(session, year_id, actor=body.actor)
215 + except ReopenError as exc:
216 + raise HTTPException(status_code=422, detail=str(exc)) from exc
217 + session.commit()
218 + return {"year_id": year.id, "status": year.status.value}
219 +
220 +
221 +@router.post("/years/{year_id}/lock")
222 +def lock(year_id: int, body: ActorIn, session: Session = Depends(get_session)) -> dict:
223 + _guard(session, body.actor, _REVIEW)
224 + try:
225 + year = lock_year(session, year_id, actor=body.actor)
226 + except ReopenError as exc:
227 + raise HTTPException(status_code=422, detail=str(exc)) from exc
228 + session.commit()
229 + return {"year_id": year.id, "status": year.status.value}
230 +
231 +
232 +@router.get("/years/{year_id}/reopen/requests")
233 +def reopen_requests(year_id: int, session: Session = Depends(get_session)) -> dict:
234 + return {
235 + "requests": [
236 + {
237 + "id": r.id,
238 + "reason": r.reason,
239 + "requested_by": r.requested_by,
240 + "approved_by": r.approved_by,
241 + "status": r.status,
242 + }
243 + for r in list_reopen_requests(session, year_id)
244 + ]
245 + }
246 +
247 +
248 +# -------------------------------------------------------------------- backup
249 +class BackupIn(BaseModel):
250 + dest: str = Field(min_length=1, max_length=512)
251 + actor: str = Field(default="", max_length=64)
252 +
253 +
254 +@router.post("/backup")
255 +def backup(body: BackupIn, session: Session = Depends(get_session)) -> dict:
256 + _guard(session, body.actor, _ADMIN)
257 + try:
258 + manifest = create_backup(session, body.dest, store_root=get_settings().source_store_root)
259 + except BackupError as exc:
260 + raise HTTPException(status_code=422, detail=str(exc)) from exc
261 + return {"dest": body.dest, "manifest": manifest}
262 +
263 +
264 +class VerifyBackupIn(BaseModel):
265 + dest: str = Field(min_length=1, max_length=512)
266 + actor: str = Field(default="", max_length=64)
267 +
268 +
269 +@router.post("/backup/verify")
270 +def backup_verify(body: VerifyBackupIn, session: Session = Depends(get_session)) -> dict:
271 + _guard(session, body.actor, _ADMIN)
272 + try:
273 + return verify_backup(body.dest)
274 + except BackupError as exc:
275 + raise HTTPException(status_code=422, detail=str(exc)) from exc
backend/src/aram_backend/main.py
+2
@@ -5,6 +5,7 @@ from fastapi.responses import HTMLResponse
5 from fastapi.staticfiles import StaticFiles
6
7 from aram_backend import __version__
8 +from aram_backend.admin_api import router as admin_router
9 from aram_backend.config import get_settings
10 from aram_backend.models import FiscalYearStatus, StatementType
11 from aram_backend.pilot_api import router as pilot_router
@@ -15,6 +16,7 @@ settings = get_settings()
16 app = FastAPI(title=settings.app_name, version=__version__)
17 app.include_router(pilot_router)
18 app.include_router(statement_router)
19 +app.include_router(admin_router)
20 app.mount(
21 "/pilot",
22 StaticFiles(directory=Path(__file__).parent / "static" / "pilot", html=True),
backend/src/aram_backend/models.py
+34
@@ -42,6 +42,19 @@ class StatementType(enum.StrEnum):
42 EQUITY = "EQ"
43
44
45 +class UserRole(enum.StrEnum):
46 + """Local application roles (Phase 7, offline desktop; no runtime network).
47 +
48 + admin: manage users, approve reopen requests, lock years, backup.
49 + reviewer: approve years and reopen requests.
50 + preparer: import, map, build statements, request reopen.
51 + """
52 +
53 + ADMIN = "admin"
54 + REVIEWER = "reviewer"
55 + PREPARER = "preparer"
56 +
57 +
58 class TimestampMixin:
59 created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
60 updated_at: Mapped[datetime] = mapped_column(
@@ -115,6 +128,27 @@ class AuditEntry(Base):
128 created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now)
129
130
131 +class User(TimestampMixin, Base):
132 + """Local application user with a role (Phase 7, booklet §7/§12).
133 +
134 + Passwords are stored only as a PBKDF2-HMAC-SHA256 hash with a per-user random
135 + salt (stdlib hashlib; no plaintext, no new dependency). Actions are attributed
136 + to a username in the hash-chained audit log. This is an offline desktop app:
137 + there is no runtime network or external identity provider.
138 + """
139 +
140 + __tablename__ = "users"
141 + id: Mapped[int] = mapped_column(primary_key=True)
142 + username: Mapped[str] = mapped_column(String(64), unique=True, index=True)
143 + display_name: Mapped[str] = mapped_column(String(128), default="")
144 + role: Mapped[UserRole] = mapped_column(
145 + Enum(UserRole, native_enum=False, length=16), default=UserRole.PREPARER
146 + )
147 + password_hash: Mapped[str] = mapped_column(String(128))
148 + salt: Mapped[str] = mapped_column(String(64))
149 + active: Mapped[bool] = mapped_column(default=True)
150 +
151 +
152 class SourceFile(TimestampMixin, Base):
153 """Content-addressed source bytes stored on disk (D-06, booklet §5).
154
backend/src/aram_backend/services/backup.py new
+143
@@ -0,0 +1,143 @@
1 +"""Local backup and integrity verification (Phase 7, booklet §7/§12).
2 +
3 +Creates a consistent snapshot of the SQLite database (sqlite3 online backup API,
4 +safe while the app is running), copies the content-addressed source store, and
5 +writes a manifest recording the SHA-256 of the database and every source file plus
6 +the audit-chain verification result. ``verify_backup`` recomputes every hash and
7 +re-checks the audit chain so a backup is provably intact before restore. Offline
8 +desktop only: no runtime network; PostgreSQL deployments use native pg_dump.
9 +"""
10 +
11 +from __future__ import annotations
12 +
13 +import hashlib
14 +import json
15 +import shutil
16 +import sqlite3
17 +from datetime import UTC, datetime
18 +from pathlib import Path
19 +from typing import Any, cast
20 +
21 +from sqlalchemy.engine import Engine
22 +from sqlalchemy.orm import Session
23 +
24 +from aram_backend.services.audit import verify_chain
25 +
26 +
27 +class BackupError(ValueError):
28 + """Raised when a backup cannot be created or verified safely."""
29 +
30 +
31 +def _sha256_file(path: Path) -> str:
32 + digest = hashlib.sha256()
33 + with path.open("rb") as handle:
34 + for chunk in iter(lambda: handle.read(1024 * 1024), b""):
35 + digest.update(chunk)
36 + return digest.hexdigest()
37 +
38 +
39 +def _database_path(session: Session) -> Path:
40 + url = cast(Engine, session.get_bind()).url
41 + if url.get_backend_name() != "sqlite":
42 + raise BackupError("local backup supports SQLite only; use pg_dump for PostgreSQL")
43 + database = url.database
44 + if not database or database == ":memory:":
45 + raise BackupError("cannot back up an in-memory database")
46 + return Path(database)
47 +
48 +
49 +def create_backup(session: Session, dest: str | Path, *, store_root: str | Path) -> dict[str, Any]:
50 + """Write a consistent backup directory and return its manifest."""
51 + dest = Path(dest)
52 + if dest.exists() and any(dest.iterdir()):
53 + raise BackupError(f"backup destination '{dest}' is not empty")
54 + dest.mkdir(parents=True, exist_ok=True)
55 +
56 + db_path = _database_path(session)
57 + backup_db = dest / "aram.db"
58 + # Online backup API: a consistent snapshot even with concurrent writers.
59 + source_conn = sqlite3.connect(str(db_path))
60 + try:
61 + target_conn = sqlite3.connect(str(backup_db))
62 + try:
63 + source_conn.backup(target_conn)
64 + finally:
65 + target_conn.close()
66 + finally:
67 + source_conn.close()
68 +
69 + store_src = Path(store_root)
70 + store_dest = dest / "source_store"
71 + source_hashes: dict[str, str] = {}
72 + if store_src.exists():
73 + shutil.copytree(store_src, store_dest)
74 + for file in sorted(store_dest.rglob("*")):
75 + if file.is_file():
76 + rel = file.relative_to(store_dest).as_posix()
77 + source_hashes[rel] = _sha256_file(file)
78 + else:
79 + store_dest.mkdir()
80 +
81 + chain_ok = verify_chain(session)
82 + manifest: dict[str, Any] = {
83 + "format": "aram-backup-1",
84 + "created_at": datetime.now(UTC).isoformat(),
85 + "database_sha256": _sha256_file(backup_db),
86 + "source_store_sha256": source_hashes,
87 + "audit_chain_valid": chain_ok,
88 + }
89 + (dest / "manifest.json").write_text(
90 + json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8"
91 + )
92 + if not chain_ok:
93 + raise BackupError("audit chain is not intact; backup refused")
94 + return manifest
95 +
96 +
97 +def verify_backup(backup_dir: str | Path) -> dict[str, Any]:
98 + """Recompute every recorded hash and re-check the audit chain in the snapshot."""
99 + backup_dir = Path(backup_dir)
100 + manifest_path = backup_dir / "manifest.json"
101 + if not manifest_path.exists():
102 + raise BackupError("manifest.json is missing")
103 + manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
104 +
105 + db_path = backup_dir / "aram.db"
106 + if not db_path.exists():
107 + raise BackupError("aram.db is missing from the backup")
108 + if _sha256_file(db_path) != manifest.get("database_sha256"):
109 + raise BackupError("database hash mismatch; backup is corrupt")
110 +
111 + store_dest = backup_dir / "source_store"
112 + recorded: dict[str, str] = manifest.get("source_store_sha256", {})
113 + for rel, expected in recorded.items():
114 + file = store_dest / rel
115 + if not file.exists() or _sha256_file(file) != expected:
116 + raise BackupError(f"source file '{rel}' is missing or corrupt")
117 +
118 + # Re-verify the audit chain directly inside the backed-up database.
119 + conn = sqlite3.connect(str(db_path))
120 + try:
121 + rows = conn.execute(
122 + "SELECT previous_hash, payload_hash, chain_hash FROM audit_entries ORDER BY id ASC"
123 + ).fetchall()
124 + finally:
125 + conn.close()
126 + previous = "0" * 64
127 + for prev_hash, payload_hash, chain_hash in rows:
128 + if prev_hash != previous:
129 + raise BackupError("audit chain break detected in backup")
130 + expected = hashlib.sha256(f"{previous}{payload_hash}".encode("ascii")).hexdigest()
131 + if chain_hash != expected:
132 + raise BackupError("audit chain hash mismatch in backup")
133 + previous = chain_hash
134 +
135 + return {
136 + "valid": True,
137 + "database_sha256": manifest["database_sha256"],
138 + "source_files": len(recorded),
139 + "audit_entries": len(rows),
140 + }
141 +
142 +
143 +__all__ = ["BackupError", "create_backup", "verify_backup"]
backend/src/aram_backend/services/reopen.py new
+116
@@ -0,0 +1,116 @@
1 +"""Controlled reopen and lock workflow (Phase 7, D-07, ADR-016).
2 +
3 +A LOCKED year is immutable. Reopening it requires an approved ``ReopenRequest``;
4 +the ORM guard and the DB trigger both enforce this, so there is no bypass path.
5 +Reopening transitions LOCKED -> APPROVED (never edits locked rows in place); a
6 +subsequent build versions the output. Locking transitions APPROVED -> LOCKED.
7 +Every step writes a hash-chained audit entry attributed to the actor.
8 +"""
9 +
10 +from __future__ import annotations
11 +
12 +from sqlalchemy import select
13 +from sqlalchemy.orm import Session
14 +
15 +from aram_backend.models import FiscalYear, FiscalYearStatus, ReopenRequest
16 +from aram_backend.services.audit import append_entry
17 +
18 +
19 +class ReopenError(ValueError):
20 + """Raised when a reopen/lock operation is attempted on an invalid state."""
21 +
22 +
23 +def request_reopen(
24 + session: Session, year_id: int, *, reason: str, requested_by: str = ""
25 +) -> ReopenRequest:
26 + year = session.get(FiscalYear, year_id)
27 + if year is None:
28 + raise ReopenError(f"fiscal year {year_id} does not exist")
29 + if year.status != FiscalYearStatus.LOCKED:
30 + raise ReopenError(f"only a Locked year can be reopened (current: {year.status.value})")
31 + if not reason.strip():
32 + raise ReopenError("a reason is required to reopen a locked year")
33 + request = ReopenRequest(
34 + year_id=year_id, reason=reason.strip(), requested_by=requested_by, status="pending"
35 + )
36 + session.add(request)
37 + session.flush()
38 + append_entry(
39 + session,
40 + action="reopen.request",
41 + actor=requested_by,
42 + year_id=year_id,
43 + payload={"request_id": request.id, "reason": request.reason},
44 + )
45 + return request
46 +
47 +
48 +def approve_reopen(session: Session, request_id: int, *, approved_by: str = "") -> ReopenRequest:
49 + request = session.get(ReopenRequest, request_id)
50 + if request is None:
51 + raise ReopenError(f"reopen request {request_id} does not exist")
52 + if request.status != "pending":
53 + raise ReopenError(f"only a pending request can be approved (current: {request.status})")
54 + request.status = "approved"
55 + request.approved_by = approved_by
56 + session.flush()
57 + append_entry(
58 + session,
59 + action="reopen.approve",
60 + actor=approved_by,
61 + year_id=request.year_id,
62 + payload={"request_id": request.id},
63 + )
64 + return request
65 +
66 +
67 +def reopen_year(session: Session, year_id: int, *, actor: str = "") -> FiscalYear:
68 + year = session.get(FiscalYear, year_id)
69 + if year is None:
70 + raise ReopenError(f"fiscal year {year_id} does not exist")
71 + if year.status != FiscalYearStatus.LOCKED:
72 + raise ReopenError(f"only a Locked year can be reopened (current: {year.status.value})")
73 + approved = session.scalar(
74 + select(ReopenRequest.id).where(
75 + ReopenRequest.year_id == year_id, ReopenRequest.status == "approved"
76 + )
77 + )
78 + if approved is None:
79 + raise ReopenError("reopening requires an approved reopen request")
80 + # The ORM guard + DB trigger re-check the approved request on transition.
81 + year.status = FiscalYearStatus.APPROVED
82 + session.flush()
83 + append_entry(
84 + session, action="reopen", actor=actor, year_id=year_id, payload={"request_id": approved}
85 + )
86 + return year
87 +
88 +
89 +def lock_year(session: Session, year_id: int, *, actor: str = "") -> FiscalYear:
90 + year = session.get(FiscalYear, year_id)
91 + if year is None:
92 + raise ReopenError(f"fiscal year {year_id} does not exist")
93 + if year.status != FiscalYearStatus.APPROVED:
94 + raise ReopenError(f"only an Approved year can be locked (current: {year.status.value})")
95 + year.status = FiscalYearStatus.LOCKED
96 + session.flush()
97 + append_entry(session, action="lock", actor=actor, year_id=year_id, payload={})
98 + return year
99 +
100 +
101 +def list_reopen_requests(session: Session, year_id: int) -> list[ReopenRequest]:
102 + return list(
103 + session.scalars(
104 + select(ReopenRequest).where(ReopenRequest.year_id == year_id).order_by(ReopenRequest.id)
105 + ).all()
106 + )
107 +
108 +
109 +__all__ = [
110 + "ReopenError",
111 + "request_reopen",
112 + "approve_reopen",
113 + "reopen_year",
114 + "lock_year",
115 + "list_reopen_requests",
116 +]
backend/src/aram_backend/services/users.py new
+142
@@ -0,0 +1,142 @@
1 +"""Local user management and role authorization (Phase 7, booklet §7/§12).
2 +
3 +Offline desktop identity: usernames + roles, passwords hashed with
4 +PBKDF2-HMAC-SHA256 and a per-user random salt (stdlib only, no new dependency,
5 +no plaintext storage, no runtime network). Sensitive actions are gated by role
6 +and attributed to a username in the hash-chained audit log.
7 +"""
8 +
9 +from __future__ import annotations
10 +
11 +import hashlib
12 +import hmac
13 +import secrets
14 +
15 +from sqlalchemy import select
16 +from sqlalchemy.orm import Session
17 +
18 +from aram_backend.models import User, UserRole
19 +from aram_backend.services.audit import append_entry
20 +
21 +_PBKDF2_ROUNDS = 200_000
22 +
23 +
24 +class UserError(ValueError):
25 + """Raised when a user operation cannot be performed safely."""
26 +
27 +
28 +class AuthorizationError(PermissionError):
29 + """Raised when an actor lacks the role required for an action."""
30 +
31 +
32 +def _hash_password(password: str, salt: str) -> str:
33 + digest = hashlib.pbkdf2_hmac(
34 + "sha256", password.encode("utf-8"), bytes.fromhex(salt), _PBKDF2_ROUNDS
35 + )
36 + return digest.hex()
37 +
38 +
39 +def create_user(
40 + session: Session,
41 + *,
42 + username: str,
43 + password: str,
44 + role: UserRole = UserRole.PREPARER,
45 + display_name: str = "",
46 + actor: str = "",
47 +) -> User:
48 + username = username.strip()
49 + if not username:
50 + raise UserError("username is required")
51 + if len(password) < 8:
52 + raise UserError("password must be at least 8 characters")
53 + existing = session.scalar(select(User).where(User.username == username))
54 + if existing is not None:
55 + raise UserError(f"username '{username}' already exists")
56 + salt = secrets.token_hex(16)
57 + user = User(
58 + username=username,
59 + display_name=display_name or username,
60 + role=role,
61 + salt=salt,
62 + password_hash=_hash_password(password, salt),
63 + )
64 + session.add(user)
65 + session.flush()
66 + append_entry(
67 + session,
68 + action="user.create",
69 + actor=actor,
70 + payload={"username": username, "role": role.value},
71 + )
72 + return user
73 +
74 +
75 +def authenticate(session: Session, *, username: str, password: str) -> User:
76 + user = session.scalar(select(User).where(User.username == username.strip()))
77 + if user is None or not user.active:
78 + raise UserError("invalid credentials")
79 + candidate = _hash_password(password, user.salt)
80 + if not hmac.compare_digest(candidate, user.password_hash):
81 + raise UserError("invalid credentials")
82 + return user
83 +
84 +
85 +def list_users(session: Session) -> list[User]:
86 + return list(session.scalars(select(User).order_by(User.username)).all())
87 +
88 +
89 +def set_role(session: Session, *, username: str, role: UserRole, actor: str = "") -> User:
90 + user = session.scalar(select(User).where(User.username == username))
91 + if user is None:
92 + raise UserError(f"user '{username}' not found")
93 + user.role = role
94 + session.flush()
95 + append_entry(
96 + session,
97 + action="user.set_role",
98 + actor=actor,
99 + payload={"username": username, "role": role.value},
100 + )
101 + return user
102 +
103 +
104 +def set_active(session: Session, *, username: str, active: bool, actor: str = "") -> User:
105 + user = session.scalar(select(User).where(User.username == username))
106 + if user is None:
107 + raise UserError(f"user '{username}' not found")
108 + user.active = active
109 + session.flush()
110 + append_entry(
111 + session,
112 + action="user.set_active",
113 + actor=actor,
114 + payload={"username": username, "active": active},
115 + )
116 + return user
117 +
118 +
119 +def require_role(session: Session, *, username: str, allowed: set[UserRole]) -> User:
120 + """Return the active user iff their role is in ``allowed``; else raise.
121 +
122 + An empty/unknown username is rejected. This is the single authorization gate
123 + for sensitive actions (approve, reopen, lock, user management, backup).
124 + """
125 + user = session.scalar(select(User).where(User.username == username.strip()))
126 + if user is None or not user.active:
127 + raise AuthorizationError("actor is not an active user")
128 + if user.role not in allowed:
129 + raise AuthorizationError(f"role '{user.role.value}' is not permitted for this action")
130 + return user
131 +
132 +
133 +__all__ = [
134 + "UserError",
135 + "AuthorizationError",
136 + "create_user",
137 + "authenticate",
138 + "list_users",
139 + "set_role",
140 + "set_active",
141 + "require_role",
142 +]
backend/tests/test_phase7_admin.py new
+207
@@ -0,0 +1,207 @@
1 +"""Phase 7: users/roles, controlled reopen/lock, backup integrity, audit API."""
2 +
3 +from __future__ import annotations
4 +
5 +import pytest
6 +
7 +from aram_backend.models import FiscalYearStatus, UserRole
8 +from aram_backend.services.approval import approve_year
9 +from aram_backend.services.audit import verify_chain
10 +from aram_backend.services.backup import BackupError, create_backup, verify_backup
11 +from aram_backend.services.reopen import (
12 + ReopenError,
13 + approve_reopen,
14 + lock_year,
15 + reopen_year,
16 + request_reopen,
17 +)
18 +from aram_backend.services.users import (
19 + AuthorizationError,
20 + UserError,
21 + authenticate,
22 + create_user,
23 + require_role,
24 + set_active,
25 +)
26 +from test_approval_gate import _balanced
27 +
28 +
29 +# --------------------------------------------------------------------- users
30 +class TestUsers:
31 + def test_create_and_authenticate(self, session):
32 + create_user(session, username="alice", password="supersecret", role=UserRole.REVIEWER)
33 + user = authenticate(session, username="alice", password="supersecret")
34 + assert user.role == UserRole.REVIEWER
35 + assert user.password_hash != "supersecret" # never plaintext
36 + assert len(user.salt) == 32
37 +
38 + def test_wrong_password_rejected(self, session):
39 + create_user(session, username="bob", password="supersecret")
40 + with pytest.raises(UserError):
41 + authenticate(session, username="bob", password="wrong-password")
42 +
43 + def test_duplicate_username_rejected(self, session):
44 + create_user(session, username="carol", password="supersecret")
45 + with pytest.raises(UserError):
46 + create_user(session, username="carol", password="anothersecret")
47 +
48 + def test_short_password_rejected(self, session):
49 + with pytest.raises(UserError):
50 + create_user(session, username="dave", password="short")
51 +
52 + def test_inactive_user_cannot_authenticate(self, session):
53 + create_user(session, username="erin", password="supersecret")
54 + set_active(session, username="erin", active=False)
55 + with pytest.raises(UserError):
56 + authenticate(session, username="erin", password="supersecret")
57 +
58 + def test_require_role_gate(self, session):
59 + create_user(session, username="prep", password="supersecret", role=UserRole.PREPARER)
60 + create_user(session, username="admin", password="supersecret", role=UserRole.ADMIN)
61 + require_role(session, username="admin", allowed={UserRole.ADMIN})
62 + with pytest.raises(AuthorizationError):
63 + require_role(session, username="prep", allowed={UserRole.ADMIN})
64 + with pytest.raises(AuthorizationError):
65 + require_role(session, username="ghost", allowed={UserRole.ADMIN})
66 +
67 +
68 +# --------------------------------------------------------------- reopen/lock
69 +class TestReopenLock:
70 + def _locked(self, session):
71 + year, _ = _balanced(session)
72 + assert approve_year(session, year.id).approved
73 + lock_year(session, year.id, actor="admin")
74 + assert year.status == FiscalYearStatus.LOCKED
75 + return year
76 +
77 + def test_full_reopen_workflow(self, session):
78 + year = self._locked(session)
79 + req = request_reopen(session, year.id, reason="اصلاح طبقه‌بندی", requested_by="prep")
80 + assert req.status == "pending"
81 + # Reopen before approval is refused.
82 + with pytest.raises(ReopenError):
83 + reopen_year(session, year.id, actor="admin")
84 + approve_reopen(session, req.id, approved_by="admin")
85 + reopen_year(session, year.id, actor="admin")
86 + assert year.status == FiscalYearStatus.APPROVED
87 + assert verify_chain(session)
88 +
89 + def test_request_on_non_locked_fails(self, session):
90 + year, _ = _balanced(session) # Draft
91 + with pytest.raises(ReopenError):
92 + request_reopen(session, year.id, reason="x", requested_by="prep")
93 +
94 + def test_lock_requires_approved(self, session):
95 + year, _ = _balanced(session) # Draft
96 + with pytest.raises(ReopenError):
97 + lock_year(session, year.id, actor="admin")
98 +
99 + def test_reopen_requires_reason(self, session):
100 + year = self._locked(session)
101 + with pytest.raises(ReopenError):
102 + request_reopen(session, year.id, reason=" ", requested_by="prep")
103 +
104 + def test_locked_year_is_immutable(self, session):
105 + year = self._locked(session)
106 + from aram_backend.models import NoteDefinition
107 +
108 + note = NoteDefinition(
109 + year_id=year.id,
110 + note_number="99",
111 + title="x",
112 + configuration_json={"statement": "BS", "section": "Assets"},
113 + )
114 + session.add(note)
115 + with pytest.raises(ValueError):
116 + session.flush()
117 + session.rollback()
118 +
119 +
120 +# -------------------------------------------------------------------- backup
121 +class TestBackup:
122 + def test_create_and_verify(self, session, tmp_path):
123 + year, _ = _balanced(session)
124 + approve_year(session, year.id)
125 + session.commit()
126 + store = tmp_path / "store"
127 + store.mkdir()
128 + (store / "ab").mkdir()
129 + (store / "ab" / "cd").write_bytes(b"source-bytes")
130 + dest = tmp_path / "backup"
131 + manifest = create_backup(session, dest, store_root=store)
132 + assert manifest["audit_chain_valid"] is True
133 + assert manifest["source_store_sha256"]
134 + result = verify_backup(dest)
135 + assert result["valid"] is True
136 + assert result["source_files"] == 1
137 +
138 + def test_tampered_database_detected(self, session, tmp_path):
139 + year, _ = _balanced(session)
140 + approve_year(session, year.id)
141 + session.commit()
142 + store = tmp_path / "store"
143 + store.mkdir()
144 + dest = tmp_path / "backup"
145 + create_backup(session, dest, store_root=store)
146 + # Corrupt the backed-up database bytes.
147 + db = dest / "aram.db"
148 + db.write_bytes(db.read_bytes() + b"tamper")
149 + with pytest.raises(BackupError):
150 + verify_backup(dest)
151 +
152 + def test_non_empty_destination_refused(self, session, tmp_path):
153 + store = tmp_path / "store"
154 + store.mkdir()
155 + dest = tmp_path / "backup"
156 + dest.mkdir()
157 + (dest / "existing").write_text("x")
158 + with pytest.raises(BackupError):
159 + create_backup(session, dest, store_root=store)
160 +
161 +
162 +# ----------------------------------------------------------------- admin API
163 +class TestAdminApi:
164 + def test_bootstrap_first_user_is_admin(self, api_client):
165 + r = api_client.post(
166 + "/api/v1/users",
167 + json={"username": "root", "password": "supersecret", "role": "preparer"},
168 + )
169 + assert r.status_code == 200, r.text
170 + assert r.json()["role"] == "admin" # bootstrap forces admin
171 +
172 + def test_login_and_role_gate(self, api_client):
173 + api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
174 + # login
175 + r = api_client.post(
176 + "/api/v1/auth/login", json={"username": "root", "password": "supersecret"}
177 + )
178 + assert r.status_code == 200
179 + assert r.json()["role"] == "admin"
180 + # bad login
181 + r = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "nope"})
182 + assert r.status_code == 401
183 + # admin can create a preparer
184 + r = api_client.post(
185 + "/api/v1/users",
186 + json={
187 + "username": "prep",
188 + "password": "supersecret",
189 + "role": "preparer",
190 + "actor": "root",
191 + },
192 + )
193 + assert r.status_code == 200
194 + # preparer cannot create users
195 + r = api_client.post(
196 + "/api/v1/users",
197 + json={"username": "x", "password": "supersecret", "actor": "prep"},
198 + )
199 + assert r.status_code == 403
200 +
201 + def test_audit_endpoint_chain_valid(self, api_client):
202 + api_client.post("/api/v1/users", json={"username": "root", "password": "supersecret"})
203 + r = api_client.get("/api/v1/audit/verify")
204 + assert r.status_code == 200
205 + assert r.json()["chain_valid"] is True
206 + r = api_client.get("/api/v1/audit")
207 + assert r.json()["entries"] # user.create recorded
docs/adr/ADR-023-users-reopen-backup.md new
+71
@@ -0,0 +1,71 @@
1 +# ADR-023 — Users, controlled reopen/lock, and backup (Phase 7)
2 +
3 +- Status: Accepted (Phase 7)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 7, §7 (year lifecycle), §12 (audit), D-07 (immutability)
6 +
7 +## Context
8 +
9 +The system of record already enforces year immutability (DB triggers + ORM guard),
10 +a hash-chained append-only audit log, and a controlled reopen mechanism
11 +(`ReopenRequest`). Phase 7 adds attributable identity, role-gated administration,
12 +a reopen/lock workflow service + API, and provably-intact local backups — all
13 +offline, with no runtime network and no new dependency.
14 +
15 +## Decision
16 +
17 +### Users and roles (`services/users.py`, `User` model)
18 +
19 +- Local users with roles `admin` / `reviewer` / `preparer`.
20 +- Passwords stored only as PBKDF2-HMAC-SHA256 (200k rounds) with a per-user random
21 + 16-byte salt (stdlib `hashlib`/`secrets`); constant-time comparison
22 + (`hmac.compare_digest`). No plaintext, no external IdP, no network.
23 +- `require_role` is the single authorization gate for sensitive actions.
24 +- Bootstrap: the first user is created without an existing admin and is forced to
25 + `admin` (desktop install); afterwards only an admin manages users.
26 +- Every user mutation appends a hash-chained audit entry.
27 +
28 +### Reopen / lock (`services/reopen.py`)
29 +
30 +- `request_reopen` (Locked year, reason required) → pending `ReopenRequest`.
31 +- `approve_reopen` (pending → approved).
32 +- `reopen_year` transitions LOCKED → APPROVED **only** with an approved request;
33 + the ORM guard and DB trigger re-check this, so there is no bypass. Reopening
34 + never edits locked rows in place; a later build versions the output.
35 +- `lock_year` transitions APPROVED → LOCKED. Each step is audited.
36 +
37 +### Backup (`services/backup.py`)
38 +
39 +- Consistent SQLite snapshot via the sqlite3 online backup API (safe with
40 + concurrent writers), a copy of the content-addressed source store, and a
41 + `manifest.json` recording the SHA-256 of the database and every source file plus
42 + the audit-chain verification result.
43 +- `verify_backup` recomputes every hash and re-checks the audit chain inside the
44 + snapshot; a corrupt/tampered backup is rejected. Creation refuses a non-empty
45 + destination and refuses to proceed if the live audit chain is broken.
46 +- SQLite-only for the offline desktop; PostgreSQL deployments use native pg_dump.
47 +
48 +### API (`admin_api.py`, `/api/v1`)
49 +
50 +`POST /users` (bootstrap/admin), `GET /users`, `POST /auth/login`,
51 +`POST /users/{username}/role|active`, `GET /audit`, `GET /audit/verify`,
52 +`POST /years/{id}/reopen/request`, `POST /reopen/{id}/approve`,
53 +`POST /years/{id}/reopen`, `POST /years/{id}/lock`,
54 +`GET /years/{id}/reopen/requests`, `POST /backup`, `POST /backup/verify`.
55 +Sensitive endpoints are role-gated (admin for users/backup; reviewer/admin for
56 +reopen/lock) and return 403 on insufficient role.
57 +
58 +## Consequences
59 +
60 +- Actions are attributable to a username and provably ordered (audit chain).
61 +- Locked years remain immutable; reopening is controlled, reasoned, and audited.
62 +- Backups are independently verifiable before restore (hashes + audit chain).
63 +- No new dependency; all crypto is stdlib. No runtime network.
64 +
65 +## Rejected alternatives
66 +
67 +- External OAuth/IdP or session tokens over the network: violates the offline,
68 + zero-network constraint; local role-gated identity is sufficient for a desktop.
69 +- Storing passwords reversibly or with fast hashes: insecure; PBKDF2 + salt only.
70 +- File-copy backup without the online API: risks a torn snapshot under writers.
71 +- Allowing reopen without an approved request: would defeat D-07 immutability.