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

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

Synced Dec 4, 14:15 UTC

dependabot/github_actions/actions/setup-node-6
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
py 279 lines 9.69 KB
Raw
1 """Local identity: password hashing, login lockout, and server-side sessions.
2
3 R1 (booklet 2.1): identity is established **only** here. A login issues a random
4 256-bit bearer token; the database stores its SHA-256 hash, never the token. No
5 endpoint may accept a client-supplied ``actor`` string as proof of identity.
6
7 Hashing: PBKDF2-HMAC-SHA256 with a per-user 128-bit salt. Argon2 is not available
8 in the offline install (no new runtime dependency is permitted), so the work
9 factor is 600,000 iterations — see ADR-030. Legacy 200,000-round hashes are still
10 verifiable and are transparently rehashed on the first successful login.
11 """
12
13 from __future__ import annotations
14
15 import hashlib
16 import hmac
17 import secrets
18 from datetime import UTC, datetime, timedelta
19
20 from sqlalchemy import select, update
21 from sqlalchemy.orm import Session
22
23 from aram_backend.models import AuthSession, User, UserRole
24 from aram_backend.services.audit import append_entry
25
26 # --- conservative parameters fixed by ADR-030 (booklet 2.1, R1) --------------
27 PBKDF2_ROUNDS = 600_000
28 LEGACY_PBKDF2_ROUNDS = 200_000
29 SESSION_TTL = timedelta(hours=8)
30 MAX_FAILED_LOGINS = 5
31 LOCKOUT_DURATION = timedelta(minutes=15)
32 MIN_PASSWORD_LENGTH = 8
33 TOKEN_BYTES = 32 # 256 bits
34
35 _GENERIC_LOGIN_ERROR = "نام کاربری یا گذرواژه نادرست است."
36 # Fixed salt used to burn the same work factor when the username is unknown, so
37 # response time does not reveal whether an account exists.
38 _TIMING_SALT = "0" * 32
39
40
41 class UserError(ValueError):
42 """Raised for invalid user input or failed authentication."""
43
44
45 class AuthorizationError(PermissionError):
46 """Raised when an authenticated user lacks the required role."""
47
48
49 class AuthenticationError(PermissionError):
50 """Raised when a bearer token is missing, unknown, expired, or revoked."""
51
52
53 def _aware(value: datetime) -> datetime:
54 """SQLite returns naive datetimes; treat stored times as UTC."""
55 return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
56
57
58 def hash_password(password: str, salt: str, rounds: int = PBKDF2_ROUNDS) -> str:
59 """PBKDF2-HMAC-SHA256. ``salt`` is hex, decoded exactly as in Phase 7 so that
60 pre-R1 hashes stay verifiable and are upgraded on first login."""
61 return hashlib.pbkdf2_hmac(
62 "sha256", password.encode("utf-8"), bytes.fromhex(salt), rounds
63 ).hex()
64
65
66 def token_hash(token: str) -> str:
67 return hashlib.sha256(token.encode("utf-8")).hexdigest()
68
69
70 def _find(session: Session, username: str) -> User | None:
71 return session.scalar(select(User).where(User.username == username))
72
73
74 def list_users(session: Session) -> list[User]:
75 return list(session.scalars(select(User).order_by(User.username)).all())
76
77
78 def create_user(
79 session: Session,
80 *,
81 username: str,
82 password: str,
83 role: UserRole = UserRole.PREPARER,
84 display_name: str = "",
85 actor: str = "",
86 ) -> User:
87 """Create a user. ``actor`` is the *authenticated* username, for the audit log
88 only — it is never accepted from a request body."""
89 username = username.strip()
90 if not username or len(username) > 64:
91 raise UserError("نام کاربری باید بین ۱ و ۴ نویسه باشد.")
92 if len(password) < MIN_PASSWORD_LENGTH:
93 raise UserError(f"گذرواژه باید دست‌کم {MIN_PASSWORD_LENGTH} نویسه باشد.")
94 if _find(session, username) is not None:
95 raise UserError("این نام کاربری پیش‌تر ثبت شده است.")
96 salt = secrets.token_hex(16)
97 user = User(
98 username=username,
99 display_name=display_name or username,
100 role=role,
101 password_hash=hash_password(password, salt),
102 salt=salt,
103 password_rounds=PBKDF2_ROUNDS,
104 )
105 session.add(user)
106 session.flush()
107 append_entry(
108 session,
109 action="user.create",
110 actor=actor,
111 payload={"username": username, "role": role.value},
112 )
113 return user
114
115
116 def authenticate(session: Session, *, username: str, password: str) -> User:
117 """Verify credentials, enforcing lockout; return the user or raise UserError."""
118 now = datetime.now(UTC)
119 user = _find(session, username.strip())
120 if user is None:
121 hash_password(password, _TIMING_SALT)
122 raise UserError(_GENERIC_LOGIN_ERROR)
123 if user.locked_until is not None:
124 if _aware(user.locked_until) > now:
125 raise UserError("حساب به‌دلیل تلاش‌های ناموفق موقتاً قفل است؛ بعداً دوباره تلاش کنید.")
126 user.locked_until = None
127 user.failed_login_count = 0
128 if not user.active:
129 raise UserError("حساب کاربری غیرفعال است.")
130
131 rounds = user.password_rounds or LEGACY_PBKDF2_ROUNDS
132 candidate = hash_password(password, user.salt, rounds)
133 if not hmac.compare_digest(candidate, user.password_hash):
134 user.failed_login_count += 1
135 if user.failed_login_count >= MAX_FAILED_LOGINS:
136 user.locked_until = now + LOCKOUT_DURATION
137 append_entry(
138 session,
139 action="auth.locked",
140 actor=user.username,
141 payload={"failed_attempts": user.failed_login_count},
142 )
143 session.commit()
144 raise UserError(_GENERIC_LOGIN_ERROR)
145
146 user.failed_login_count = 0
147 user.locked_until = None
148 if rounds < PBKDF2_ROUNDS:
149 # Transparent upgrade of a legacy hash while we still hold the plaintext.
150 user.salt = secrets.token_hex(16)
151 user.password_hash = hash_password(password, user.salt)
152 user.password_rounds = PBKDF2_ROUNDS
153 append_entry(
154 session,
155 action="auth.rehash",
156 actor=user.username,
157 payload={"rounds": PBKDF2_ROUNDS},
158 )
159 session.commit()
160 return user
161
162
163 def issue_session(session: Session, user: User) -> str:
164 """Create a server-side session and return the plaintext token exactly once."""
165 token = secrets.token_urlsafe(TOKEN_BYTES)
166 session.add(
167 AuthSession(
168 user_id=user.id,
169 token_hash=token_hash(token),
170 expires_at=datetime.now(UTC) + SESSION_TTL,
171 )
172 )
173 append_entry(session, action="auth.login", actor=user.username, payload={})
174 session.commit()
175 return token
176
177
178 def resolve_session(session: Session, token: str | None) -> User:
179 """Map a bearer token to its active user, or raise AuthenticationError."""
180 if not token:
181 raise AuthenticationError("ورود لازم است.")
182 row = session.scalar(select(AuthSession).where(AuthSession.token_hash == token_hash(token)))
183 if row is None or row.revoked or _aware(row.expires_at) <= datetime.now(UTC):
184 raise AuthenticationError("نشست نامعتبر یا منقضی است؛ دوباره وارد شوید.")
185 user = session.get(User, row.user_id)
186 if user is None or not user.active:
187 raise AuthenticationError("نشست نامعتبر یا منقضی است؛ دوباره وارد شوید.")
188 return user
189
190
191 def revoke_session(session: Session, token: str | None) -> bool:
192 """Log out: revoke the presented session. Returns True when one was revoked."""
193 if not token:
194 return False
195 row = session.scalar(select(AuthSession).where(AuthSession.token_hash == token_hash(token)))
196 if row is None or row.revoked:
197 return False
198 row.revoked = True
199 user = session.get(User, row.user_id)
200 append_entry(session, action="auth.logout", actor=user.username if user else "", payload={})
201 session.commit()
202 return True
203
204
205 def revoke_user_sessions(session: Session, user_id: int) -> None:
206 """Kill every session of a user (used when an account is deactivated)."""
207 session.execute(update(AuthSession).where(AuthSession.user_id == user_id).values(revoked=True))
208 session.flush()
209
210
211 def ensure_role(user: User, allowed: set[UserRole]) -> None:
212 """Role gate for an already-authenticated user (identity comes from the session)."""
213 if user.role not in allowed:
214 raise AuthorizationError("نقش شما اجازهٔ این اقدام را ندارد.")
215
216
217 def require_role(session: Session, *, username: str, allowed: set[UserRole]) -> User:
218 """Service-level role gate by username (used by domain services, not by HTTP)."""
219 user = _find(session, username)
220 if user is None or not user.active:
221 raise AuthorizationError("کاربر شناخته نشد یا غیرفعال است.")
222 ensure_role(user, allowed)
223 return user
224
225
226 def set_role(session: Session, *, username: str, role: UserRole, actor: str = "") -> User:
227 user = _find(session, username)
228 if user is None:
229 raise UserError("کاربر یافت نشد.")
230 user.role = role
231 session.flush()
232 append_entry(
233 session,
234 action="user.set_role",
235 actor=actor,
236 payload={"username": username, "role": role.value},
237 )
238 return user
239
240
241 def set_active(session: Session, *, username: str, active: bool, actor: str = "") -> User:
242 user = _find(session, username)
243 if user is None:
244 raise UserError("کاربر یافت نشد.")
245 user.active = active
246 session.flush()
247 if not active:
248 revoke_user_sessions(session, user.id)
249 append_entry(
250 session,
251 action="user.set_active",
252 actor=actor,
253 payload={"username": username, "active": active},
254 )
255 return user
256
257
258 __all__ = [
259 "AuthenticationError",
260 "AuthorizationError",
261 "LOCKOUT_DURATION",
262 "MAX_FAILED_LOGINS",
263 "PBKDF2_ROUNDS",
264 "SESSION_TTL",
265 "UserError",
266 "authenticate",
267 "create_user",
268 "ensure_role",
269 "hash_password",
270 "issue_session",
271 "list_users",
272 "require_role",
273 "resolve_session",
274 "revoke_session",
275 "revoke_user_sessions",
276 "set_active",
277 "set_role",
278 "token_hash",
279 ]