# Story 4.11: Audit Integrity (HMAC/Signature)

## Status: Planned

## Priority: High

## Estimated Effort: Medium (2-3 days)

## Dependencies: None

## Epic / Series

Part of Epic 4: Enterprise Compliance & Observability / Series 4.x

---

## Context / Background

Compliance auditors need optional HMAC/signature support for audit logs in core. This enables tamper-evidence verification without heavy dependencies. Advanced key management lives in enterprise extras.

---

## User Story

**As a** compliance auditor  
**I want** optional HMAC/signature support for audit logs in core  
**So that** I can verify tamper-evidence without heavy dependencies; advanced key management lives in enterprise extras

---

## Scope (In / Out)

### In Scope

- Config-driven integrity: enable/disable and select mode (none, hmac-sha256)
- When enabled, `AuditTrail` computes and stores checksum per event
- Verification utility provided for offline checks
- Key sources: env var or file path in core
- No-op when disabled
- Unit tests

### Out of Scope

- KMS/Sigstore integration (deferred to extras)
- Advanced key management (deferred to extras)
- Real-time verification
- Multiple signature algorithms (start with HMAC-SHA256)

---

## Acceptance Criteria

### AC1: Configuration

- [ ] Integrity can be enabled/disabled via config
- [ ] Mode selection: `none` or `hmac-sha256`
- [ ] Key source: env var or file path
- [ ] Configuration is clear and documented

### AC2: Checksum Computation

- [ ] When enabled, `AuditTrail` computes checksum per event
- [ ] Checksum is stored with event
- [ ] HMAC-SHA256 algorithm used
- [ ] Checksum is base64-encoded

### AC3: Verification Utility

- [ ] Verification utility provided for offline checks
- [ ] Utility can verify single events
- [ ] Utility can verify event chains
- [ ] Clear error messages on verification failure

### AC4: Key Management

- [ ] Key can be provided via env var
- [ ] Key can be provided via file path
- [ ] Key loading is secure (no logging of keys)
- [ ] Key validation on load

### AC5: Performance

- [ ] No-op when disabled (no performance impact)
- [ ] Existing performance characteristics preserved when enabled
- [ ] Checksum computation is efficient

### AC6: Testing

- [ ] Unit tests: checksum present and verifiable
- [ ] Unit tests: incorrect key fails verification
- [ ] Unit tests: disabled mode writes no checksum
- [ ] Integration tests with real audit events

---

## Technical Design / Implementation Notes

### Configuration

Add to `CompliancePolicy`:
```python
class CompliancePolicy:
    # ... existing fields ...
    integrity_enabled: bool = False
    integrity_mode: str = "none"  # "none" | "hmac-sha256"
    integrity_key_source: str | None = None  # env var name or file path
```

### Event Schema Extension

Extend `AuditEvent`:
```python
class AuditEvent(BaseModel):
    # ... existing fields ...
    integrity_checksum: str | None = None
    integrity_algorithm: str | None = None
```

### Implementation

Location: `src/fapilog/core/audit.py`

```python
def _compute_checksum(self, event_data: dict) -> str:
    """Compute HMAC-SHA256 checksum for event."""
    key = self._load_integrity_key()
    canonical = self._canonical_json(event_data)
    hmac_obj = hmac.new(key, canonical.encode(), hashlib.sha256)
    return base64.b64encode(hmac_obj.digest()).decode()
```

### Verification Utility

Location: `src/fapilog/core/audit.py` or new `src/fapilog/core/verification.py`

```python
def verify_event_integrity(
    event: AuditEvent,
    key: bytes
) -> bool:
    """Verify event integrity checksum."""
    # Implementation
```

---

## Tasks

### Phase 1: Configuration
- [ ] Add integrity fields to `CompliancePolicy`
- [ ] Add key loading logic
- [ ] Add configuration validation
- [ ] Document configuration

### Phase 2: Checksum Computation
- [ ] Implement HMAC-SHA256 computation
- [ ] Integrate into `AuditTrail.log_event()`
- [ ] Store checksum with event
- [ ] Handle disabled mode (no-op)

### Phase 3: Verification Utility
- [ ] Implement verification function
- [ ] Add chain verification
- [ ] Add CLI helper (optional)
- [ ] Document usage

### Phase 4: Testing
- [ ] Unit tests for checksum computation
- [ ] Unit tests for verification
- [ ] Integration tests
- [ ] Performance tests

---

## Tests

### Unit Tests

- [ ] Checksum is computed when enabled
- [ ] Checksum is verifiable with correct key
- [ ] Verification fails with incorrect key
- [ ] No checksum when disabled
- [ ] Key loading from env var
- [ ] Key loading from file

### Integration Tests

- [ ] Full audit trail with integrity enabled
- [ ] Verification of stored events
- [ ] Chain verification

---

## Documentation Updates

- [ ] Document integrity configuration
- [ ] Document key management
- [ ] Document verification utility
- [ ] Add examples

---

## Definition of Done

Story is complete when ALL of the following are true:

### Code Complete
- [ ] All acceptance criteria met and verified
- [ ] All tasks completed
- [ ] Code follows project style guide
- [ ] No linting errors or warnings
- [ ] Type checking passes (mypy strict)

### Quality Assurance
- [ ] Unit tests: >90% coverage of new code
- [ ] Integration tests: all scenarios passing
- [ ] Regression tests: no existing functionality broken
- [ ] Performance tests: no regression vs baseline
- [ ] Manual testing completed (if applicable)

### Documentation
- [ ] User-facing docs updated
- [ ] API reference updated (if applicable)
- [ ] Code examples added/updated
- [ ] CHANGELOG.md updated
- [ ] Inline code documentation complete

### Review & Release
- [ ] Code review approved
- [ ] Documentation reviewed for clarity
- [ ] CI/CD pipeline passing
- [ ] Ready for merge to main branch

### Backwards Compatibility
- [ ] No breaking changes OR breaking changes documented with migration guide
- [ ] Existing tests still pass
- [ ] Deprecation warnings added (if applicable)

---

## Risks / Rollback / Monitoring

### Risks

- **Risk:** Key management complexity
  - **Mitigation:** Keep it simple in core, defer advanced features to extras

- **Risk:** Performance impact
  - **Mitigation:** Benchmark, optimize, make it optional

### Rollback Plan

- Disable integrity by default
- Remove checksum computation
- Keep verification utility for existing data

---

## Related Documents

- [Audit Trail Documentation](../api-reference/audit-trail.md)
- [Story 4.10: Pluggable Audit Storage Interface](./4.10.pluggable-audit-storage.md)

---

## Change Log

| Date       | Change                    | Author |
| ---------- | ------------------------- | ------ |
| 2025-01-10 | Initial story creation    | System |
