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

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

Synced Dec 3, 22:00 UTC

fix(security): check proposed fiscal-year status before ORM flush

davoodmehraban89 committed Oct 30, 2026 at 16:28 UTC f5f9257563f382f6663bc7b1eb0433a43482e9fd
1 file changed +30 -4
backend/src/aram_backend/models.py
+30 -4
@@ -250,7 +250,35 @@ def _persisted_year_id_for(obj: Any, session: Session) -> int | None:
250 _PROTECTED_YEAR_STATUSES = {FiscalYearStatus.APPROVED, FiscalYearStatus.LOCKED}
251
252
253 +def _protected_year_status(session: Session, year_id: int) -> FiscalYearStatus | None:
254 + """Protect both persisted status and an in-flight approval/locking transition.
255 +
256 + A database SELECT alone sees Draft until the pending FiscalYear status is
257 + flushed, allowing a second dirty object to change in the approval flush.
258 + """
259 + for candidate in session.new | session.dirty | session.deleted:
260 + if (
261 + isinstance(candidate, FiscalYear)
262 + and candidate.id == year_id
263 + and candidate.status in _PROTECTED_YEAR_STATUSES
264 + ):
265 + return candidate.status
266 +
267 + persisted = session.scalar(select(FiscalYear.status).where(FiscalYear.id == year_id))
268 + return persisted if persisted in _PROTECTED_YEAR_STATUSES else None
269 +
270 +
271 +
272 def _company_has_protected_year(session: Session, company_id: int) -> bool:
273 + # A Company edit in the same transaction as Draft -> Approved is forbidden.
274 + for candidate in session.new | session.dirty:
275 + if isinstance(candidate, FiscalYear) and candidate.status in _PROTECTED_YEAR_STATUSES:
276 + linked_id = candidate.company_id
277 + if linked_id is None and candidate.company is not None:
278 + linked_id = candidate.company.id
279 + if linked_id == company_id:
280 + return True
281 +
282 status = session.scalar(
283 select(FiscalYear.status).where(
284 FiscalYear.company_id == company_id,
@@ -320,10 +348,8 @@ def enforce_audit_invariants(session: Session, _flush_context, _instances) -> No
348 year_id = _year_id_for(obj, session)
349 original_year_id = _persisted_year_id_for(obj, session)
350 for affected_year_id in {year_id, original_year_id} - {None}:
323 - status = session.scalar(
324 - select(FiscalYear.status).where(FiscalYear.id == affected_year_id)
325 - )
326 - if status in _PROTECTED_YEAR_STATUSES:
351 + status = _protected_year_status(session, affected_year_id)
352 + if status is not None:
353 raise ValueError(
354 f"Fiscal year {affected_year_id} is {status.value.lower()} and cannot be mutated"
355 )