CONFIDENTIAL -- AZ1.AI Inc. -- Internal Use Only
CFS-010: Security & Privacy Architecture
1. Executive Summary
Financial software requires the highest tier of security architecture. CODITECT handles the most sensitive data a business produces: bank transactions, tax filings, employee compensation, client financials, and regulatory documents. A single breach doesn't just expose data -- it can destroy an accounting firm's reputation and the trust of hundreds of their clients.
Security posture: Zero-trust architecture with defense-in-depth. Every request is authenticated, every action is authorized, every data access is logged, and every component assumes the network is compromised.
2. Security Architecture Overview
2.1 Zero-Trust Model
| Principle | Implementation |
|---|---|
| Never trust, always verify | Every API call requires valid JWT + tenant context, even internal service-to-service |
| Least privilege | RBAC with granular permissions; users get minimum access needed for their role |
| Assume breach | Network segmentation, encrypted communications everywhere, immutable audit log |
| Verify explicitly | Multi-factor authentication, device fingerprinting, behavioral analysis |
| Limit blast radius | Tenant isolation via RLS, service isolation via K8s namespaces, data encryption per tenant |
2.2 Architecture Layers
┌─────────────────────────────────────────────────────────────┐
│ Layer 1: Edge Security │
│ CDN (Cloudflare) + WAF + DDoS protection + Rate limiting │
├─────────────────────────────────────────────────────────────┤
│ Layer 2: Authentication & Authorization │
│ OAuth 2.0 / OIDC + JWT + RBAC + MFA + Session management │
├─────────────────────────────────────────────────────────────┤
│ Layer 3: Application Security │
│ Input validation + CSRF + XSS prevention + SQL injection │
│ protection + API rate limiting + request sanitization │
├─────────────────────────────────────────────────────────────┤
│ Layer 4: Data Security │
│ RLS tenant isolation + AES-256 encryption at rest + │
│ TLS 1.3 in transit + field-level encryption for PII │
├─────────────────────────────────────────────────────────────┤
│ Layer 5: Infrastructure Security │
│ GKE private cluster + VPC isolation + IAM + Secret │
│ management + Container scanning + Network policies │
├─────────────────────────────────────────────────────────────┤
│ Layer 6: Monitoring & Response │
│ SIEM + IDS/IPS + Anomaly detection + Audit logging + │
│ Incident response automation + Forensic capability │
└─────────────────────────────────────────────────────────────┘
3. Authentication & Authorization
3.1 Authentication Methods
| Method | Use Case | Implementation |
|---|---|---|
| Email + Password | Primary login for partners and clients | Argon2id hashing, minimum 12 chars, breach database check |
| MFA (TOTP) | Required for partners, optional for clients | Google Authenticator / Authy compatible, TOTP RFC 6238 |
| MFA (WebAuthn/FIDO2) | Hardware key support | Passkey support, YubiKey compatible |
| SSO (SAML 2.0 / OIDC) | Enterprise partners | Integration with Azure AD, Google Workspace, Okta |
| API Keys | System-to-system integration | Scoped API keys with rotation policy (90 days) |
| OAuth 2.0 Client Credentials | Service-to-service | Short-lived tokens (15 min), automatic rotation |
| Digital Certificate | SPED/NF-e signing operations | ICP-Brasil A1/A3 certificate-based authentication |
3.2 Session Management
| Parameter | Value | Rationale |
|---|---|---|
| Access token lifetime | 15 minutes | Short-lived to limit exposure |
| Refresh token lifetime | 7 days (sliding) | Convenience without permanent access |
| Idle timeout | 30 minutes (configurable per tenant) | Prevent unattended access |
| Maximum sessions | 5 per user (configurable) | Limit concurrent access |
| Session binding | IP + User-Agent fingerprint | Detect session hijacking |
| Token storage | HttpOnly, Secure, SameSite=Strict cookies | Prevent XSS token theft |
3.3 Role-Based Access Control (RBAC)
| Role | Scope | Permissions |
|---|---|---|
| Platform Admin | Global | All operations across all tenants (AZ1.AI staff only) |
| Partner Owner | Tenant (firm) | Full access to firm + all client entities |
| Partner Admin | Tenant (firm) | Firm management, user management, billing |
| Partner Staff | Assigned entities | Access limited to assigned client entities |
| Client Admin | Entity | Full access to own entity data |
| Client User | Entity | Read access + limited write (e.g., upload documents, approve invoices) |
| Client Viewer | Entity | Read-only access to reports and dashboards |
| Auditor | Entity/Firm | Read-only access to all data + audit trail |
| API Service | Scoped | Programmatic access limited to defined API scopes |
3.4 Permission Granularity
| Resource | Available Permissions |
|---|---|
| Chart of Accounts | view, create, edit, delete, export, import |
| Journal Entries | view, create, edit, reverse, post, approve, export |
| Bank Reconciliation | view, match, unmatch, create-adjustment, approve |
| AP/AR | view, create, edit, approve, pay, void |
| Reports | view, generate, export, schedule |
| Tax Filing | view, prepare, review, submit |
| User Management | view, invite, edit-role, deactivate, delete |
| System Settings | view, edit-entity, edit-firm, edit-billing |
| Audit Trail | view, export (never edit or delete) |
| AI Settings | view, configure-thresholds, retrain-request |
4. Multi-Tenant Data Isolation
4.1 PostgreSQL Row-Level Security (RLS)
-- Every table includes tenant_id
-- RLS policy enforced at database level
ALTER TABLE journal_entries ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON journal_entries
USING (tenant_id = current_setting('app.current_tenant')::uuid);
CREATE POLICY entity_isolation ON journal_entries
USING (entity_id = ANY(
string_to_array(current_setting('app.accessible_entities'), ',')::uuid[]
));
| Isolation Layer | Mechanism | Bypass Protection |
|---|---|---|
| Tenant | RLS on tenant_id (every table) | Cannot query across tenants even with SQL injection |
| Entity | RLS on entity_id (within tenant) | Staff only see assigned entities |
| User | Application-level permission checks | Role-based access enforcement |
| Connection | SET app.current_tenant on every connection | Middleware sets before any query; unset = no access |
4.2 Cross-Tenant Protection
| Vector | Protection |
|---|---|
| SQL injection | Parameterized queries everywhere + RLS backup layer |
| API enumeration | UUIDs (not sequential IDs), authorization check on every endpoint |
| Bulk operations | All bulk operations scoped to current tenant, server-side pagination |
| Search/aggregation | Search indexes partitioned by tenant, cross-tenant aggregation prohibited |
| Reporting | Reports generated within tenant context, RLS prevents data leakage |
| AI/ML | Models trained per-tenant or on anonymized aggregate data only |
| Backups | Logical backups per-tenant, encryption per-tenant key |
| Logs | Tenant_id in every log entry, log access restricted by tenant |
5. Encryption Architecture
5.1 Encryption Matrix
| Data State | Method | Key Management |
|---|---|---|
| At rest (database) | AES-256-GCM (GKE persistent disk encryption) | Google-managed keys (CMEK available) |
| At rest (file storage) | AES-256-GCM (GCS server-side encryption) | Google-managed keys (CMEK available) |
| In transit (external) | TLS 1.3 (minimum TLS 1.2) | Let's Encrypt + Google-managed certs |
| In transit (internal) | mTLS (service mesh) | Istio-managed certificates |
| Field-level (PII) | AES-256-GCM with per-tenant key | Google Cloud KMS (tenant-specific key ring) |
| Backups | AES-256-GCM | Separate backup encryption key |
| Digital signatures | RSA-2048 / ECDSA P-256 | HSM-backed (Cloud KMS) |
5.2 Field-Level Encryption (PII)
| Data Category | Fields | Encryption | Searchable |
|---|---|---|---|
| Tax identifiers | CNPJ, EIN, VAT number, SSN | AES-256-GCM per-tenant | Deterministic encryption for exact match |
| Bank details | Account number, routing number, IBAN | AES-256-GCM per-tenant | Encrypted search via blind index |
| Contact PII | Email, phone, address | AES-256-GCM per-tenant | Encrypted search via blind index |
| Financial amounts | Not encrypted (needed for aggregation) | RLS provides access control | N/A |
| Document content | OCR extracted text, uploaded files | AES-256-GCM per-tenant | Full-text search on encrypted index |
5.3 Key Rotation
| Key Type | Rotation Period | Process |
|---|---|---|
| Database encryption key | Annual | Google-managed automatic rotation |
| Per-tenant field encryption key | Annual | Automated re-encryption during maintenance window |
| TLS certificates | 90 days | Automated via cert-manager |
| mTLS certificates | 24 hours | Istio automatic rotation |
| API keys | 90 days (enforced) | User-initiated with grace period |
| JWT signing key | 30 days | Automated, old key valid for token lifetime |
6. Infrastructure Security
6.1 GKE Cluster Security
| Control | Configuration |
|---|---|
| Private cluster | No public IP on nodes, private endpoint for API server |
| Network policies | Calico policies: deny-all default, explicit allow per service |
| Pod security | Pod Security Standards (Restricted), no privileged containers |
| Node security | COS (Container-Optimized OS), auto-update enabled, Shielded VMs |
| RBAC | Kubernetes RBAC aligned with GCP IAM, least privilege |
| Secrets | External Secrets Operator + Google Secret Manager (not K8s secrets) |
| Image security | Binary Authorization, only signed images from private Artifact Registry |
| Workload Identity | GKE Workload Identity for GCP service access (no service account keys) |
6.2 Network Architecture
| Zone | Components | Access |
|---|---|---|
| Public | Cloudflare CDN/WAF, Load Balancer | Internet-facing, DDoS protected |
| DMZ | API Gateway (Envoy/Istio ingress) | Authenticated requests only |
| Application | Backend services, worker pods | Internal only, mTLS required |
| Data | PostgreSQL, Redis, NATS | Application zone only, encrypted connections |
| AI/ML | GPU nodes, model serving | Application zone only, no external access |
| Management | Monitoring, logging, CI/CD agents | Restricted admin access |
6.3 Container Security
| Control | Tool | Action |
|---|---|---|
| Image scanning | Google Artifact Analysis + Trivy | Scan on push, block critical CVEs |
| Runtime security | Falco | Detect anomalous container behavior |
| Network segmentation | Calico | Per-namespace network policies |
| Resource limits | K8s resource quotas | Prevent resource exhaustion attacks |
| Read-only filesystem | SecurityContext | Containers run with readOnlyRootFilesystem |
| Non-root execution | SecurityContext | All containers run as non-root user |
7. Application Security
7.1 OWASP Top 10 Mitigations
| Vulnerability | Mitigation |
|---|---|
| Injection | Parameterized queries (SQLAlchemy ORM), RLS backup layer, input validation |
| Broken Authentication | Argon2id, MFA, session binding, account lockout, breach password check |
| Sensitive Data Exposure | Field-level encryption, TLS everywhere, minimal data in logs, PII masking |
| XML External Entities | XML parsing with entity expansion disabled, schema validation |
| Broken Access Control | RBAC + RLS, authorization check on every endpoint, UUID identifiers |
| Security Misconfiguration | Infrastructure as Code, CIS benchmarks, automated compliance scanning |
| Cross-Site Scripting | Content Security Policy, React auto-escaping, DOMPurify for rich content |
| Insecure Deserialization | JSON-only APIs, schema validation (Pydantic), no pickle/yaml deserialization |
| Using Components with Known Vulnerabilities | Dependabot, Snyk, automated CVE patching pipeline |
| Insufficient Logging & Monitoring | Comprehensive audit trail, SIEM, anomaly detection, alerting |
7.2 API Security
| Control | Implementation |
|---|---|
| Rate limiting | Per-user, per-endpoint, per-tenant (configurable) |
| Request size limits | 10MB default, 50MB for file uploads |
| Input validation | Pydantic models with strict type checking on all endpoints |
| Output filtering | Response serializers exclude internal fields |
| CORS | Strict origin whitelist per tenant |
| Content-Type enforcement | Reject requests with unexpected content types |
| Request logging | Full request/response logging (PII masked) for audit |
| Idempotency | Idempotency keys for all mutating operations |
8. AI/ML Security
8.1 AI-Specific Security Controls
| Threat | Control |
|---|---|
| Prompt injection | Input sanitization before LLM calls, output validation, sandboxed execution |
| Data poisoning | Training data validation, anomaly detection on correction patterns, human review for model updates |
| Model extraction | API rate limiting, no direct model access, watermarked outputs |
| Adversarial inputs | Document validation before OCR, confidence thresholds, human fallback |
| Privacy leakage via AI | PII stripping before cloud API calls, local models for sensitive data, differential privacy |
| Bias | Monthly bias audits on auto-categorization, demographic-aware testing |
8.2 LLM Security Architecture
| Control | Implementation |
|---|---|
| Prompt sanitization | Strip all PII (CNPJ, bank accounts, names) before sending to Claude API |
| Response validation | Validate LLM output format, check for hallucinated data, SQL safety checks |
| Sandboxed execution | NLQ-generated SQL runs on read-only replica with row limits and timeouts |
| Token budgets | Per-tenant monthly token limits, cost monitoring, abuse detection |
| Model versioning | All AI decisions logged with model version, reproducible |
| Fallback policy | If AI confidence <threshold, route to human; never auto-post uncertain results |
8.3 Data Flow for AI
Financial Data (sensitive)
│
├── Local AI Models (on-GKE)
│ Tesseract, LayoutLM, XGBoost, Mistral
│ → Full access to financial data
│ → No data leaves the cluster
│
└── Cloud AI (Claude API)
│
├── Sanitization Layer
│ → Strip PII (CNPJ, names, account numbers)
│ → Replace with tokens: [ENTITY_1], [AMOUNT_1]
│ → Preserve structure, remove identity
│
├── API Call (TLS 1.3)
│ → Anonymized prompt sent to Claude
│ → No customer data in training (contractual)
│
└── Response Reconstruction
→ Re-inject PII tokens
→ Validate output format
→ Log for audit
9. Compliance & Certifications
9.1 Target Certifications
| Certification | Timeline | Scope | Status |
|---|---|---|---|
| SOC 2 Type I | Month 6 | Security, Availability, Confidentiality | Phase 1 target |
| SOC 2 Type II | Month 12 | Security, Availability, Confidentiality, Processing Integrity | Phase 2 target |
| ISO 27001 | Month 18 | Information Security Management System | Phase 3 target |
| LGPD Compliance | Month 3 | Brazil data protection | Phase 1 target |
| GDPR Compliance | Month 12 | EU data protection | Phase 2 target |
| PCI DSS (if payment processing) | Month 18 | Payment card data | Phase 3 (if applicable) |
| CSA STAR | Month 24 | Cloud security | Phase 4 target |
9.2 Compliance Controls Matrix
| Control Domain | Controls | Evidence |
|---|---|---|
| Access Management | MFA, RBAC, least privilege, access reviews (quarterly) | Access logs, role assignments, review records |
| Data Protection | Encryption, classification, retention, disposal | Encryption configs, classification tags, disposal logs |
| Change Management | CI/CD with approvals, code review, staging testing | Git history, PR reviews, deployment logs |
| Incident Response | IR plan, tabletop exercises, breach notification | IR runbooks, exercise records, notification templates |
| Business Continuity | DR plan, backup testing, RTO/RPO targets | DR test results, backup logs, recovery metrics |
| Vendor Management | Third-party security reviews, SLA monitoring | Vendor assessments, SLA reports |
| Employee Security | Background checks, security training, acceptable use | Training records, policy acknowledgments |
| Physical Security | Cloud provider (Google) physical controls | Google SOC 2 report inheritance |
10. Incident Response
10.1 Incident Severity Levels
| Level | Definition | Response Time | Escalation |
|---|---|---|---|
| P1 Critical | Active data breach, service outage, ransomware | 15 minutes | CEO + CTO + Legal immediately |
| P2 High | Suspected breach, significant vulnerability, degraded service | 1 hour | CTO + Engineering Lead |
| P3 Medium | Minor vulnerability, suspicious activity, non-critical bug | 4 hours | Engineering Lead |
| P4 Low | Minor security finding, hardening opportunity | 24 hours | Security team |
10.2 Incident Response Phases
| Phase | Activities | Timeline |
|---|---|---|
| Detection | Automated monitoring alerts, user reports, vulnerability scans | Continuous |
| Triage | Severity assessment, scope determination, containment decision | 15 min (P1), 1 hr (P2) |
| Containment | Isolate affected systems, block attack vectors, preserve evidence | 1 hr (P1), 4 hr (P2) |
| Eradication | Remove threat, patch vulnerabilities, rotate credentials | 4 hr (P1), 24 hr (P2) |
| Recovery | Restore services, verify integrity, monitor for recurrence | 8 hr (P1), 48 hr (P2) |
| Lessons Learned | Post-incident review, update controls, improve detection | 72 hr after resolution |
10.3 Breach Notification
| Jurisdiction | Authority | Timeline | Method |
|---|---|---|---|
| Brazil (LGPD) | ANPD + Data subjects | "Reasonable time" (practice: 72 hrs) | Written notification |
| EU (GDPR) | Supervisory Authority + Data subjects | 72 hours (authority), "without undue delay" (subjects) | DPA notification form |
| US (varies by state) | State AG + Affected individuals | 30-60 days (varies) | Written notification |
| UK (UK GDPR) | ICO + Data subjects | 72 hours | ICO notification form |
| Australia | OAIC + Affected individuals | 30 days | NDB statement |
11. Security Monitoring & Logging
11.1 Logging Architecture
| Log Category | Content | Retention | Storage |
|---|---|---|---|
| Audit trail | All data CRUD operations, user actions, AI decisions | 7 years (regulatory minimum) | Immutable append-only (Cloud Logging + BigQuery) |
| Authentication | Login attempts, MFA events, session management | 2 years | Cloud Logging |
| API access | All API calls with tenant, user, endpoint, status | 1 year | Cloud Logging |
| Infrastructure | K8s events, node metrics, network flows | 90 days | Cloud Logging + Prometheus |
| Security events | WAF blocks, IDS alerts, anomaly detections | 2 years | SIEM (Chronicle) |
| AI operations | Model invocations, confidence scores, corrections | 2 years | Application database + Cloud Logging |
11.2 Monitoring & Alerting
| Monitor | Tool | Alert Threshold |
|---|---|---|
| Authentication anomalies | Cloud Armor + custom | 5 failed logins/5min, impossible travel |
| API abuse | Rate limiting + anomaly detection | 10x normal volume, unusual endpoints |
| Data exfiltration | DLP + query monitoring | Bulk exports, unusual query patterns |
| Privilege escalation | Audit log analysis | Role changes, permission grants |
| Infrastructure threats | Falco + GKE security | Container escape, privilege escalation, crypto mining |
| Vulnerability scanning | Trivy + Artifact Analysis | New critical CVE in deployed images |
| Certificate monitoring | cert-manager + custom | Expiry within 14 days |
| Compliance drift | OPA/Gatekeeper + custom | Policy violation in deployment |
12. Security Development Lifecycle
12.1 Secure SDLC Practices
| Phase | Security Activities |
|---|---|
| Design | Threat modeling (STRIDE), security architecture review, privacy impact assessment |
| Development | Secure coding guidelines, pre-commit hooks (secrets detection), IDE security plugins |
| Review | Mandatory security review for auth/crypto/data changes, automated SAST (Semgrep) |
| Testing | DAST (ZAP), dependency scanning (Snyk), container scanning (Trivy), penetration testing |
| Deployment | Binary authorization, canary with security monitoring, rollback capability |
| Operations | Runtime security (Falco), continuous compliance, regular penetration testing |
12.2 Security Testing Calendar
| Activity | Frequency | Scope |
|---|---|---|
| Automated SAST/DAST | Every CI run | Full codebase |
| Dependency vulnerability scan | Daily | All dependencies |
| Container image scan | Every build | All container images |
| Internal penetration test | Quarterly | Full application + infrastructure |
| External penetration test | Annually | Full attack surface |
| Red team exercise | Annually | Social engineering + technical |
| Tabletop exercise (IR) | Semi-annually | Incident response process |
| Disaster recovery test | Semi-annually | Full DR procedure |
Hal Casteel CEO/CTO, AZ1.AI Inc.
Copyright © 2026 AZ1.AI Inc. All rights reserved. Unauthorized distribution or reproduction is strictly prohibited.