briefcase-python 2.4.1

Python bindings for Briefcase AI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
"""
SOC2 Type II compliance report generator.

Evaluates Trust Service Categories:
  CC6 - Security (access controls, encryption, logging)
  A1  - Availability (uptime, error rates)
  PI1 - Processing Integrity (data completeness, decision audit trail)
"""

from datetime import datetime
from typing import List
from briefcase.compliance.reports.base import (
    ComplianceReportGenerator,
    ComplianceReport,
    ComplianceStatus,
    ControlResult,
    Violation,
    ViolationSeverity
)


class SOC2ReportGenerator(ComplianceReportGenerator):
    """Generates SOC2 Type II compliance reports.

    Uses the base-class telemetry query layer so that evaluation works
    with real TelemetryProvider clients *and* with in-memory ingested data.
    """

    # ── Thresholds (configurable per-deployment) ──────────────────────

    MAX_UNAUTHORIZED_ATTEMPTS = 0        # Zero-tolerance for unauthorized access
    MIN_ENCRYPTION_PERCENT = 100.0       # 100 % of uploads must be encrypted
    MIN_TRACE_COMPLETENESS = 95.0        # Minimum trace completeness %
    MAX_ERROR_RATE_PERCENT = 5.0         # Maximum acceptable error rate %
    MIN_DECISION_AUDIT_PERCENT = 99.0    # % of decisions with complete audit trail
    MAX_UNENCRYPTED_OBJECTS = 0          # Zero unencrypted objects allowed

    def evaluate(
        self,
        engagement_id: str,
        workstream_id: str,
        start_date: datetime,
        end_date: datetime
    ) -> ComplianceReport:
        """Evaluate SOC2 Type II compliance."""

        report = ComplianceReport(
            framework="SOC2 Type II",
            organization=engagement_id,
            report_period_start=start_date,
            report_period_end=end_date,
            evaluation_date=datetime.now(),
            overall_status=ComplianceStatus.COMPLIANT,
            overall_score=0.0
        )

        # Gather telemetry counts for the report
        all_decisions = self._query_telemetry(
            engagement_id, workstream_id, start_date, end_date
        )
        all_spans = self._query_spans(
            engagement_id, workstream_id, start_date, end_date
        )
        report.total_decisions = len(all_decisions)
        report.total_spans = len(all_spans)

        # Evaluate each Trust Service Category
        results = []
        results.extend(self._evaluate_security(
            engagement_id, workstream_id, start_date, end_date
        ))
        results.extend(self._evaluate_availability(
            engagement_id, workstream_id, start_date, end_date
        ))
        results.extend(self._evaluate_processing_integrity(
            engagement_id, workstream_id, start_date, end_date
        ))

        report.control_results = results
        report.total_controls_evaluated = len(results)
        report.controls_passed = sum(
            1 for r in results if r.status == ComplianceStatus.COMPLIANT
        )
        report.controls_failed = sum(
            1 for r in results if r.status == ComplianceStatus.NON_COMPLIANT
        )
        report.controls_partial = sum(
            1 for r in results if r.status == ComplianceStatus.PARTIAL
        )

        # Collect all violations
        report.violations = []
        for result in results:
            report.violations.extend(result.violations)

        # Calculate overall score
        report.overall_score = self._calculate_score(results)

        # Telemetry completeness
        if report.total_decisions > 0:
            decisions_with_trail = sum(
                1 for d in all_decisions
                if d.get("has_audit_trail", d.get("outputs") is not None)
            )
            report.telemetry_completeness = (
                (decisions_with_trail / report.total_decisions) * 100
            )

        # Determine overall status
        if report.controls_failed > 0:
            report.overall_status = ComplianceStatus.NON_COMPLIANT
        elif report.controls_partial > 0:
            report.overall_status = ComplianceStatus.PARTIAL
        else:
            report.overall_status = ComplianceStatus.COMPLIANT

        return report

    # ── CC6: Security ─────────────────────────────────────────────────

    def _evaluate_security(
        self, engagement_id, workstream_id, start_date, end_date
    ) -> List[ControlResult]:
        """Evaluate CC6: Security controls."""
        results = []
        results.append(self._check_access_controls(
            engagement_id, workstream_id, start_date, end_date
        ))
        results.append(self._check_encryption(
            engagement_id, workstream_id, start_date, end_date
        ))
        results.append(self._check_logging(
            engagement_id, workstream_id, start_date, end_date
        ))
        return results

    def _check_access_controls(
        self, engagement_id, workstream_id, start_date, end_date
    ) -> ControlResult:
        """Check CC6.1: Logical and Physical Access Controls."""
        # Query for unauthorized access attempts
        unauthorized_attempts = self._query_access_logs(
            engagement_id, workstream_id, start_date, end_date,
            filters={"authorized": False}
        )
        total_access = self._query_access_logs(
            engagement_id, workstream_id, start_date, end_date
        )

        if len(unauthorized_attempts) <= self.MAX_UNAUTHORIZED_ATTEMPTS:
            return ControlResult(
                control_id="CC6.1",
                control_name="Logical and Physical Access Controls",
                status=ComplianceStatus.COMPLIANT,
                score=100.0,
                evidence=[
                    f"{len(unauthorized_attempts)} unauthorized access attempts "
                    f"in period (threshold: {self.MAX_UNAUTHORIZED_ATTEMPTS})",
                    f"{len(total_access)} total access events audited",
                ]
            )
        else:
            violation = Violation(
                control_id="CC6.1",
                severity=ViolationSeverity.CRITICAL,
                message=(
                    f"{len(unauthorized_attempts)} unauthorized access attempts "
                    f"detected (max allowed: {self.MAX_UNAUTHORIZED_ATTEMPTS})"
                ),
                affected_items=[
                    str(a.get("id", a.get("timestamp", "unknown")))
                    for a in unauthorized_attempts[:10]
                ],
                remediation=(
                    "Review access logs and revoke compromised credentials. "
                    "Enforce MFA for all admin access. Rotate API keys."
                )
            )

            # Partial compliance if <5 attempts
            if len(unauthorized_attempts) < 5:
                score = max(0.0, 100.0 - len(unauthorized_attempts) * 20)
                status = ComplianceStatus.PARTIAL
            else:
                score = 0.0
                status = ComplianceStatus.NON_COMPLIANT

            return ControlResult(
                control_id="CC6.1",
                control_name="Logical and Physical Access Controls",
                status=status,
                score=score,
                violations=[violation],
                recommendations=[
                    "Enable MFA for all admin access",
                    "Rotate API keys every 90 days",
                    "Implement IP allowlisting"
                ]
            )

    def _check_encryption(
        self, engagement_id, workstream_id, start_date, end_date
    ) -> ControlResult:
        """Check CC6.2: Encryption of data in transit and at rest."""
        # Query for unencrypted data transfers
        unencrypted = self._query_spans(
            engagement_id, workstream_id, start_date, end_date,
            filters={"encrypted": False}
        )
        all_transfers = self._query_spans(
            engagement_id, workstream_id, start_date, end_date,
            filters={"type": "data_transfer"}
        )

        total_transfers = max(len(all_transfers), 1)  # avoid div-by-zero
        encrypted_percent = (
            ((total_transfers - len(unencrypted)) / total_transfers) * 100
        )

        if len(unencrypted) <= self.MAX_UNENCRYPTED_OBJECTS:
            return ControlResult(
                control_id="CC6.2",
                control_name="Encryption of Data",
                status=ComplianceStatus.COMPLIANT,
                score=100.0,
                evidence=[
                    f"{encrypted_percent:.1f}% of transfers encrypted (TLS 1.3)",
                    "Data at rest encrypted (AES-256)",
                    f"{len(unencrypted)} unencrypted objects (max: "
                    f"{self.MAX_UNENCRYPTED_OBJECTS})"
                ]
            )
        else:
            violation = Violation(
                control_id="CC6.2",
                severity=ViolationSeverity.MAJOR,
                message=(
                    f"{len(unencrypted)} unencrypted data transfers detected"
                ),
                affected_items=[
                    str(u.get("id", u.get("path", "unknown")))
                    for u in unencrypted[:10]
                ],
                remediation="Enable TLS for all data in transit. "
                            "Enable S3 server-side encryption for data at rest."
            )
            return ControlResult(
                control_id="CC6.2",
                control_name="Encryption of Data",
                status=ComplianceStatus.NON_COMPLIANT,
                score=encrypted_percent,
                violations=[violation],
                recommendations=[
                    "Enforce TLS 1.3 for all API endpoints",
                    "Enable server-side encryption for LakeFS storage"
                ]
            )

    def _check_logging(
        self, engagement_id, workstream_id, start_date, end_date
    ) -> ControlResult:
        """Check CC6.7: Logging and Monitoring."""
        # Check trace completeness from spans
        all_spans = self._query_spans(
            engagement_id, workstream_id, start_date, end_date
        )
        all_decisions = self._query_telemetry(
            engagement_id, workstream_id, start_date, end_date
        )

        # Calculate completeness: decisions with at least one span
        decisions_with_spans = set()
        for span in all_spans:
            decision_id = span.get("decision_id", span.get("trace_id"))
            if decision_id:
                decisions_with_spans.add(decision_id)

        total_decisions = max(len(all_decisions), 1)
        completeness = (len(decisions_with_spans) / total_decisions) * 100

        if completeness >= self.MIN_TRACE_COMPLETENESS:
            return ControlResult(
                control_id="CC6.7",
                control_name="Logging and Monitoring",
                status=ComplianceStatus.COMPLIANT,
                score=min(completeness, 100.0),
                evidence=[
                    f"Trace completeness: {completeness:.1f}% "
                    f"(threshold: {self.MIN_TRACE_COMPLETENESS}%)",
                    f"{len(all_decisions)} decisions audited",
                    f"{len(all_spans)} spans recorded"
                ]
            )
        elif completeness >= self.MIN_TRACE_COMPLETENESS * 0.9:
            # Near threshold → partial
            return ControlResult(
                control_id="CC6.7",
                control_name="Logging and Monitoring",
                status=ComplianceStatus.PARTIAL,
                score=completeness,
                evidence=[
                    f"Trace completeness: {completeness:.1f}% "
                    f"(threshold: {self.MIN_TRACE_COMPLETENESS}%)"
                ],
                recommendations=[
                    "Increase OpenTelemetry instrumentation coverage",
                    "Add span recording for all decision points"
                ]
            )
        else:
            violation = Violation(
                control_id="CC6.7",
                severity=ViolationSeverity.MAJOR,
                message=(
                    f"Trace completeness {completeness:.1f}% is below "
                    f"threshold of {self.MIN_TRACE_COMPLETENESS}%"
                ),
                remediation=(
                    "Enable comprehensive OpenTelemetry instrumentation. "
                    "Ensure every decision point emits at least one span."
                )
            )
            return ControlResult(
                control_id="CC6.7",
                control_name="Logging and Monitoring",
                status=ComplianceStatus.NON_COMPLIANT,
                score=completeness,
                violations=[violation]
            )

    # ── A1: Availability ──────────────────────────────────────────────

    def _evaluate_availability(
        self, engagement_id, workstream_id, start_date, end_date
    ) -> List[ControlResult]:
        """Evaluate A1: Availability controls."""
        results = []
        results.append(self._check_error_rate(
            engagement_id, workstream_id, start_date, end_date
        ))
        return results

    def _check_error_rate(
        self, engagement_id, workstream_id, start_date, end_date
    ) -> ControlResult:
        """Check A1.1: System availability via error rate analysis."""
        all_decisions = self._query_telemetry(
            engagement_id, workstream_id, start_date, end_date
        )
        errored = [d for d in all_decisions if d.get("error") is not None]

        total = max(len(all_decisions), 1)
        error_rate = (len(errored) / total) * 100

        if error_rate <= self.MAX_ERROR_RATE_PERCENT:
            return ControlResult(
                control_id="A1.1",
                control_name="System Availability",
                status=ComplianceStatus.COMPLIANT,
                score=100.0 - error_rate,
                evidence=[
                    f"Error rate: {error_rate:.2f}% "
                    f"(max: {self.MAX_ERROR_RATE_PERCENT}%)",
                    f"{len(all_decisions)} total decisions, "
                    f"{len(errored)} errors"
                ]
            )
        else:
            violation = Violation(
                control_id="A1.1",
                severity=ViolationSeverity.MAJOR,
                message=(
                    f"Error rate {error_rate:.2f}% exceeds threshold "
                    f"of {self.MAX_ERROR_RATE_PERCENT}%"
                ),
                affected_items=[
                    str(e.get("id", e.get("function_name", "unknown")))
                    for e in errored[:10]
                ],
                remediation="Investigate error root causes. "
                            "Implement retry logic and circuit breakers."
            )
            return ControlResult(
                control_id="A1.1",
                control_name="System Availability",
                status=ComplianceStatus.NON_COMPLIANT,
                score=max(0.0, 100.0 - error_rate),
                violations=[violation]
            )

    # ── PI1: Processing Integrity ─────────────────────────────────────

    def _evaluate_processing_integrity(
        self, engagement_id, workstream_id, start_date, end_date
    ) -> List[ControlResult]:
        """Evaluate PI1: Processing Integrity controls."""
        results = []
        results.append(self._check_decision_audit_trail(
            engagement_id, workstream_id, start_date, end_date
        ))
        return results

    def _check_decision_audit_trail(
        self, engagement_id, workstream_id, start_date, end_date
    ) -> ControlResult:
        """Check PI1.1: Decision audit trail completeness."""
        all_decisions = self._query_telemetry(
            engagement_id, workstream_id, start_date, end_date
        )

        if not all_decisions:
            return ControlResult(
                control_id="PI1.1",
                control_name="Decision Audit Trail",
                status=ComplianceStatus.NEEDS_REVIEW,
                score=0.0,
                evidence=["No decision data available for evaluation"],
                recommendations=[
                    "Ensure Briefcase SDK is capturing decisions",
                    "Verify telemetry pipeline is operational"
                ]
            )

        # A complete audit trail requires: inputs, outputs, model_parameters
        complete = 0
        incomplete_ids = []
        for d in all_decisions:
            has_inputs = bool(d.get("inputs"))
            has_outputs = bool(d.get("outputs"))
            has_model = bool(d.get("model_parameters") or d.get("model_name"))
            if has_inputs and has_outputs and has_model:
                complete += 1
            else:
                incomplete_ids.append(
                    str(d.get("id", d.get("function_name", "unknown")))
                )

        total = len(all_decisions)
        completeness = (complete / total) * 100

        if completeness >= self.MIN_DECISION_AUDIT_PERCENT:
            return ControlResult(
                control_id="PI1.1",
                control_name="Decision Audit Trail",
                status=ComplianceStatus.COMPLIANT,
                score=completeness,
                evidence=[
                    f"{completeness:.1f}% of decisions have complete "
                    f"audit trails (threshold: "
                    f"{self.MIN_DECISION_AUDIT_PERCENT}%)",
                    f"{complete}/{total} decisions fully audited"
                ]
            )
        elif completeness >= self.MIN_DECISION_AUDIT_PERCENT * 0.9:
            return ControlResult(
                control_id="PI1.1",
                control_name="Decision Audit Trail",
                status=ComplianceStatus.PARTIAL,
                score=completeness,
                evidence=[
                    f"{completeness:.1f}% completeness "
                    f"(threshold: {self.MIN_DECISION_AUDIT_PERCENT}%)"
                ],
                recommendations=[
                    "Ensure all decision points capture inputs, outputs, "
                    "and model parameters",
                    f"{len(incomplete_ids)} decisions missing data"
                ]
            )
        else:
            violation = Violation(
                control_id="PI1.1",
                severity=ViolationSeverity.CRITICAL,
                message=(
                    f"Decision audit completeness {completeness:.1f}% "
                    f"is below threshold of "
                    f"{self.MIN_DECISION_AUDIT_PERCENT}%"
                ),
                affected_items=incomplete_ids[:10],
                remediation=(
                    "Add Briefcase decorators to all AI decision functions. "
                    "Ensure inputs, outputs, and model_parameters are captured."
                )
            )
            return ControlResult(
                control_id="PI1.1",
                control_name="Decision Audit Trail",
                status=ComplianceStatus.NON_COMPLIANT,
                score=completeness,
                violations=[violation]
            )