04 — Security & Compliance: Auth, Audit, LGPD, SOC 2 & RBAC
Domain: Authentication, authorization, immutable audit, regulatory compliance, encryption Dependencies: 01-Data Architecture (audit tables, tenant model) Outputs: OpenFGA policies, immudb integration, compliance controls, encryption config
ROLE
You are a Senior Security Architect specializing in financial platform compliance across Brazilian (LGPD, BACEN, CVM) and US (SOX, SOC 2, GAAP) regulatory frameworks. You design zero-trust security architectures with cryptographic audit trails for regulated multi-tenant SaaS.
OBJECTIVE
Design the complete security, compliance, and governance layer for a dual-jurisdiction FP&A platform that satisfies SOC 2 Type II audit requirements, LGPD data protection, BACEN/CVM reporting, SOX audit controls, and EU AI Act explainability mandates.
DELIVERABLES
D1. OpenFGA Authorization Model
Role Hierarchy:
SuperAdmin (platform operator)
└── TenantAdmin (company admin)
├── CFO (full financial access, all entities)
│ ├── Controller (GL, AP, AR, reconciliation, reporting)
│ │ ├── FP&A Analyst (forecasts, budgets, scenarios, reports)
│ │ ├── AP Clerk (accounts payable only)
│ │ ├── AR Clerk (accounts receivable only)
│ │ └── Accountant (GL entries, bank reconciliation)
│ └── Treasurer (cash management, investments, payments)
├── Auditor (read-only, full provenance access, time-limited)
└── Viewer (dashboard-only, no drill-down to transactions)
Entity-Level Scoping:
- Users assigned to specific entities (subsidiaries) within a tenant
- CFO sees all entities; Controller may be scoped to subset
- Cross-entity access requires explicit grant (consolidation role)
AI Service Accounts:
svc_forecast_engine— read GL/budget, write forecasts, no deletesvc_anomaly_detector— read GL, write alerts, no mutationsvc_narrative_generator— read forecasts/variances, write reportssvc_categorization_agent— read uncategorized, write categories
OpenFGA DSL (Zanzibar-style):
type tenant
relations
define admin: [user]
define member: [user] or admin
type entity
relations
define parent_tenant: [tenant]
define viewer: [user] or member from parent_tenant
define editor: [user]
define approver: [user]
type financial_record
relations
define parent_entity: [entity]
define can_view: viewer from parent_entity
define can_edit: editor from parent_entity
define can_approve: approver from parent_entity
define can_delete: [user] # Explicitly empty — no one can hard delete
type forecast
relations
define parent_entity: [entity]
define can_view: viewer from parent_entity
define can_create: [user, service_account]
define can_approve: approver from parent_entity
type audit_record
relations
define can_view: [user#auditor] or admin from parent_tenant
FastAPI Middleware:
- Every API request → OpenFGA check before DB query
- Cache authorization decisions (TTL 60s) with Redis
- Log every authz decision to audit trail
- Deny-by-default: missing policy = denied
D2. Immutable Audit Trail (immudb)
Audit Events to Capture:
| Event Type | Trigger | Fields |
|---|---|---|
data.create | New GL entry, invoice, payment | entity, table, record_id, values, user |
data.update | Any field modification | entity, table, record_id, old_values, new_values, user |
data.soft_delete | Soft delete of any record | entity, table, record_id, user, reason |
auth.login | User authentication | user, method, IP, device, success/fail |
auth.access | OpenFGA authorization check | user, resource, action, decision, policy_version |
ai.decision | Any AI output | model, version, inputs, output, confidence, trace |
ai.forecast | Forecast generation | model, version, parameters, result, source_data_hash |
report.export | Data export (CSV, Excel, PDF) | user, report_type, filters, row_count |
config.change | System configuration change | setting, old_value, new_value, user |
immudb Integration Pattern:
Application → PostgreSQL (operational) → async → immudb (immutable copy)
→ pgaudit log → Vector → immudb
- Write-ahead: critical events written to immudb before PostgreSQL commit
- Async forwarding: non-critical events batched every 5 seconds
- Verification API: any record can be cryptographically verified against Merkle tree
- 7-year retention with tamper-evident verification
D3. Authentication Architecture (Zitadel)
- Multi-tenant OIDC/OAuth2 with Zitadel
- MFA enforcement: TOTP (mandatory), WebAuthn (optional), SMS (fallback)
- SSO federation: Azure AD, Okta, OneLogin, Keycloak
- Session management: 30-min idle timeout, 8-hour absolute timeout
- Device trust: registered devices only for financial operations
- Just-In-Time provisioning from SSO IdPs
- Audit engagement access: time-limited (30/60/90 day), read-only, auto-expire
D4. LGPD Compliance Framework (Brazil)
- Data mapping: Classify all PII fields (CPF, CNPJ, name, email, phone, address)
- Consent management: Record and track consent for data processing
- Right to deletion: Anonymization workflow (replace PII with hashed tokens, preserve financial aggregates)
- Data residency: Tenant-level configuration for data location (Brazil, US, EU)
- DPO dashboard: Data protection officer view of all processing activities
- Breach notification: Automated detection → 72-hour notification workflow
- Data portability: Export all tenant data in machine-readable format
D5. SOC 2 Type II Control Mapping
Map platform capabilities to SOC 2 Trust Service Criteria:
| TSC | Control | Implementation | Evidence Collection |
|---|---|---|---|
| CC6.1 | Logical access | OpenFGA + Zitadel | Automated access review reports |
| CC6.2 | Access provisioning | JIT + approval workflow | Provisioning audit trail |
| CC6.3 | Access removal | Auto-expire + offboarding | Deprovisioning log |
| CC7.1 | Change management | Git-based, PR required | Commit history + PR approvals |
| CC7.2 | System monitoring | Prometheus + Grafana | Alert history, uptime reports |
| CC8.1 | Incident management | PagerDuty integration | Incident timeline, resolution |
| A1.2 | Availability | K8s HA, multi-AZ | Uptime metrics, DR test results |
| PI1.1 | Processing integrity | dbt tests + reconciliation | Test results, recon reports |
Automated Evidence Collection:
- Cron job generates SOC 2 evidence package monthly
- Screenshots of dashboards, exports of audit logs, test results
- Stored in tamper-evident archive (immudb-backed)
D6. Encryption Architecture
- At rest: AES-256-GCM for all database files (PostgreSQL TDE or dm-crypt)
- In transit: TLS 1.3 mandatory, mTLS between services
- Key management: HashiCorp Vault with automatic rotation (90-day cycle)
- Field-level: PII fields encrypted at application layer before DB write
- Backup: Encrypted backups with separate key hierarchy
- DLP: Export controls — watermarking, row-count limits, admin approval for bulk export
CONSTRAINTS
- Every API endpoint must pass OpenFGA authorization check
- No hard deletes in any table — soft delete + audit trail only
- All PII must be identifiable and classifiable for LGPD
- Audit trail writes must not fail silently — circuit breaker with retry
- Encryption keys never stored alongside encrypted data
- Zero trust: every service-to-service call authenticated via mTLS
RESEARCH QUESTIONS
- What is the optimal OpenFGA model for financial hierarchies with cross-entity consolidation permissions?
- How should LGPD right-to-deletion work when financial records must be retained for 7 years (legal retention vs. privacy)?
- What is the best approach for SOC 2 evidence automation — commercial tool vs. custom scripts?
- How to implement field-level encryption without breaking dbt transformations and DuckDB analytics?
- What is the recommended MFA enforcement strategy for mobile expense capture (balance security vs. UX)?
ADRs TO PRODUCE
- ADR-004: OpenFGA over .NET Identity (relationship RBAC for financial hierarchies)
- ADR-008: immudb over PostgreSQL triggers (cryptographic verification for SOX/LGPD)
- ADR-SEC-001: Encryption strategy (TDE vs. application-layer vs. both)
- ADR-SEC-002: LGPD deletion vs. retention conflict resolution