Coverage for src/governed_harness/application/exceptions.py: 96%
113 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""Exceptions with expiry, scope, alternative evidence and follow-up (``review.exceptions``).
3``APPROVE_EXCEPTION`` keeps its 1.0.0 meaning without the key. With it, the decision carries an
4expiry and an exception record is stored with its provenance on the run's event chain; the gate
5of a later run does not block on the findings the exception covers while it is in force, and
6blocks on them again once it expires (``gates.exceptions``)."""
8from __future__ import annotations
10import re
11from dataclasses import dataclass
12from datetime import datetime, timedelta
13from typing import Any
15from governed_harness import __version__
16from governed_harness.domain.enums import EvidenceKind, FindingSeverity, PhaseId
17from governed_harness.domain.errors import ConfigurationError
18from governed_harness.domain.ids import new_id
19from governed_harness.domain.models import (
20 ExceptionRecord,
21 ExceptionScope,
22 Execution,
23 Finding,
24 GateEvaluation,
25 HumanDecision,
26 Provenance,
27 utc_now,
28)
29from governed_harness.gates.exceptions import exception_ids
30from governed_harness.orchestration.engine import EngineServices, RunEngine
31from governed_harness.reporting.fingerprint import finding_fingerprint
33MAX_EXCEPTION_DAYS = 365
36@dataclass(frozen=True)
37class ExceptionOptions:
38 """What a person declares with APPROVE_EXCEPTION under ``review.exceptions``."""
40 expires_in: str | None = None
41 expires_at: str | None = None
42 scope: tuple[str, ...] = ()
43 alternative_evidence: str | None = None
44 follow_up: str | None = None
46 @property
47 def given(self) -> bool:
48 return bool(
49 self.expires_in
50 or self.expires_at
51 or self.scope
52 or self.alternative_evidence
53 or self.follow_up
54 )
57_DURATION = re.compile(r"^\s*(\d+)\s*(?:([dhw])\s*)?$", re.IGNORECASE)
60def parse_expiry(
61 *, expires_in: str | None, expires_at: str | None, default_days: int, now: datetime
62) -> datetime:
63 """``expires_in`` is ``N``/``Nd`` days, ``Nh`` hours or ``Nw`` weeks; ``expires_at`` an ISO
64 8601 instant. Neither: ``default_days``. The expiry must be in the future and at most a
65 year away."""
66 if expires_in and expires_at:
67 raise ConfigurationError("use either --expires-in or --expires-at, not both")
68 if expires_at:
69 try:
70 value = datetime.fromisoformat(expires_at)
71 except ValueError as error:
72 raise ConfigurationError(
73 f"--expires-at is not an ISO 8601 instant: {expires_at}"
74 ) from error
75 value = value if value.tzinfo else value.replace(tzinfo=now.tzinfo)
76 elif expires_in:
77 match = _DURATION.match(expires_in)
78 if not match:
79 raise ConfigurationError(f"--expires-in must look like 14d, 36h or 2w: {expires_in}")
80 amount, unit = int(match.group(1)), (match.group(2) or "d").lower()
81 delta = {
82 "d": timedelta(days=amount),
83 "h": timedelta(hours=amount),
84 "w": timedelta(weeks=amount),
85 }
86 value = now + delta[unit]
87 else:
88 value = now + timedelta(days=default_days)
89 if value <= now:
90 raise ConfigurationError("an exception must expire in the future")
91 if value - now > timedelta(days=MAX_EXCEPTION_DAYS):
92 raise ConfigurationError(f"an exception may last at most {MAX_EXCEPTION_DAYS} days")
93 return value
96def parse_scope(items: tuple[str, ...]) -> list[ExceptionScope]:
97 """``rule`` or ``rule:path`` entries from ``--scope``."""
98 scopes: list[ExceptionScope] = []
99 for item in items:
100 rule, _, path = item.strip().partition(":")
101 if not rule:
102 raise ConfigurationError(f"--scope needs a rule id, optionally rule:path: {item!r}")
103 scopes.append(ExceptionScope(rule_id=rule, path=path or None))
104 return scopes
107def default_scope(services: EngineServices, gate: GateEvaluation) -> list[ExceptionScope]:
108 """The blocking findings the gate evaluated, each by rule, path and fingerprint."""
109 names = services.resolved.effective_policies.get("findingBlockSeverities", ["HIGH", "CRITICAL"])
110 blocking = {FindingSeverity(str(name)) for name in names}
111 ids = {
112 ref.removeprefix("record://finding/")
113 for ref in gate.input_refs
114 if ref.startswith("record://finding/")
115 }
116 scopes: dict[str, ExceptionScope] = {}
117 for finding in services.state.list("finding", Finding, execution_id=gate.execution_id):
118 if finding.finding_id in ids and finding.severity in blocking:
119 fingerprint = finding_fingerprint(finding)
120 scopes[fingerprint] = ExceptionScope(
121 rule_id=finding.rule_id,
122 path=finding.location.path if finding.location else None,
123 fingerprint=fingerprint,
124 )
125 return list(scopes.values())
128def record_exception(
129 services: EngineServices,
130 *,
131 decision: HumanDecision,
132 scope: list[ExceptionScope],
133 alternative_evidence: str | None,
134 follow_up: str | None,
135) -> ExceptionRecord:
136 if decision.expires_at is None: # the decision of an exception always carries its expiry 136 ↛ 137line 136 didn't jump to line 137 because the condition on line 136 was never true
137 raise ConfigurationError("an exception needs an expiry (--expires-in or --expires-at)")
138 engine = RunEngine(services)
139 execution = engine.get_execution(decision.execution_id)
140 gate = services.state.get("gate", decision.gate_evaluation_id, GateEvaluation)
141 record = ExceptionRecord(
142 exception_id=new_id("exception"),
143 project_id=execution.project_id,
144 execution_id=execution.execution_id,
145 decision_id=decision.decision_id,
146 gate_evaluation_id=decision.gate_evaluation_id,
147 actor=decision.actor,
148 rationale=decision.rationale,
149 scope=tuple(scope or default_scope(services, gate)),
150 change_set_digest=decision.change_set_digest,
151 granted_at=decision.decided_at,
152 expires_at=decision.expires_at,
153 alternative_evidence=(alternative_evidence or "").strip() or None,
154 follow_up=(follow_up or "").strip() or None,
155 provenance=Provenance(
156 actor=decision.actor,
157 core_version=__version__,
158 configuration_digest=execution.configuration_digest,
159 policy_digest=execution.policy_digest,
160 source_refs=(f"record://decision/{decision.decision_id}",),
161 ),
162 )
163 services.state.put(
164 "exception",
165 record.exception_id,
166 record,
167 execution_id=execution.execution_id,
168 project_id=execution.project_id,
169 )
170 reference = services.artifacts.put_json(
171 record.model_dump(mode="json", by_alias=True),
172 metadata={"kind": "exception", "executionId": execution.execution_id},
173 )
174 engine._record_evidence(
175 execution,
176 PhaseId.DECISION,
177 EvidenceKind.HUMAN_DECISION,
178 reference,
179 f"Exception covering {len(record.scope)} finding scope(s) until "
180 f"{record.expires_at.isoformat()}",
181 supports=(decision.decision_id,),
182 )
183 services.events.append(
184 execution.execution_id,
185 "exception.granted",
186 record.model_dump(mode="json", by_alias=True),
187 actor=decision.actor,
188 )
189 return record
192def exception_entry(
193 record: ExceptionRecord, now: datetime, applied_in: list[str] | None = None
194) -> dict[str, Any]:
195 remaining = record.expires_at - now
196 return {
197 "exceptionId": record.exception_id,
198 "status": "ACTIVE" if record.active_at(now) else "EXPIRED",
199 "executionId": record.execution_id,
200 "decisionId": record.decision_id,
201 "actorId": record.actor.actor_id,
202 "rationale": record.rationale,
203 "grantedAt": record.granted_at.isoformat(),
204 "expiresAt": record.expires_at.isoformat(),
205 "daysLeft": max(0, remaining.days) if remaining.total_seconds() > 0 else 0,
206 "scope": [item.model_dump(mode="json", by_alias=True) for item in record.scope],
207 "alternativeEvidence": record.alternative_evidence,
208 "followUp": record.follow_up,
209 "changeSetDigest": record.change_set_digest,
210 "appliedIn": applied_in or [],
211 }
214def project_exceptions(services: EngineServices) -> list[ExceptionRecord]:
215 return sorted(
216 services.state.list(
217 "exception", ExceptionRecord, project_id=services.resolved.project.project_id
218 ),
219 key=lambda item: item.granted_at,
220 )
223def applications(services: EngineServices) -> dict[str, list[str]]:
224 """For each exception id, the runs whose gate relied on it."""
225 used: dict[str, set[str]] = {}
226 for gate in services.state.list(
227 "gate", GateEvaluation, project_id=services.resolved.project.project_id
228 ):
229 for exception_id in exception_ids(gate.reason_codes):
230 used.setdefault(exception_id, set()).add(gate.execution_id)
231 return {key: sorted(value) for key, value in used.items()}
234def list_exceptions(
235 services: EngineServices, *, status: str = "all", expiring_within: int | None = None
236) -> list[dict[str, Any]]:
237 now = utc_now()
238 used = applications(services)
239 entries = []
240 for record in project_exceptions(services):
241 entry = exception_entry(record, now, used.get(record.exception_id))
242 if status != "all" and entry["status"] != status.upper(): 242 ↛ 243line 242 didn't jump to line 243 because the condition on line 242 was never true
243 continue
244 if expiring_within is not None and (
245 entry["status"] != "ACTIVE" or record.expires_at - now > timedelta(days=expiring_within)
246 ):
247 continue
248 entries.append(entry)
249 return entries
252def brief_exceptions(services: EngineServices, execution: Execution) -> list[dict[str, Any]]:
253 """Exceptions granted in this run or relied on by its current gate."""
254 now = utc_now()
255 relied: set[str] = set()
256 if execution.gate_evaluation_id:
257 gate = services.state.get("gate", execution.gate_evaluation_id, GateEvaluation)
258 relied = set(exception_ids(gate.reason_codes))
259 entries = []
260 for record in project_exceptions(services):
261 if record.execution_id == execution.execution_id or record.exception_id in relied:
262 entry = exception_entry(record, now)
263 entry["reliedOnByGate"] = record.exception_id in relied
264 entries.append(entry)
265 return entries