Skip to main content

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

PrincipleImplementation
Never trust, always verifyEvery API call requires valid JWT + tenant context, even internal service-to-service
Least privilegeRBAC with granular permissions; users get minimum access needed for their role
Assume breachNetwork segmentation, encrypted communications everywhere, immutable audit log
Verify explicitlyMulti-factor authentication, device fingerprinting, behavioral analysis
Limit blast radiusTenant 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

MethodUse CaseImplementation
Email + PasswordPrimary login for partners and clientsArgon2id hashing, minimum 12 chars, breach database check
MFA (TOTP)Required for partners, optional for clientsGoogle Authenticator / Authy compatible, TOTP RFC 6238
MFA (WebAuthn/FIDO2)Hardware key supportPasskey support, YubiKey compatible
SSO (SAML 2.0 / OIDC)Enterprise partnersIntegration with Azure AD, Google Workspace, Okta
API KeysSystem-to-system integrationScoped API keys with rotation policy (90 days)
OAuth 2.0 Client CredentialsService-to-serviceShort-lived tokens (15 min), automatic rotation
Digital CertificateSPED/NF-e signing operationsICP-Brasil A1/A3 certificate-based authentication

3.2 Session Management

ParameterValueRationale
Access token lifetime15 minutesShort-lived to limit exposure
Refresh token lifetime7 days (sliding)Convenience without permanent access
Idle timeout30 minutes (configurable per tenant)Prevent unattended access
Maximum sessions5 per user (configurable)Limit concurrent access
Session bindingIP + User-Agent fingerprintDetect session hijacking
Token storageHttpOnly, Secure, SameSite=Strict cookiesPrevent XSS token theft

3.3 Role-Based Access Control (RBAC)

RoleScopePermissions
Platform AdminGlobalAll operations across all tenants (AZ1.AI staff only)
Partner OwnerTenant (firm)Full access to firm + all client entities
Partner AdminTenant (firm)Firm management, user management, billing
Partner StaffAssigned entitiesAccess limited to assigned client entities
Client AdminEntityFull access to own entity data
Client UserEntityRead access + limited write (e.g., upload documents, approve invoices)
Client ViewerEntityRead-only access to reports and dashboards
AuditorEntity/FirmRead-only access to all data + audit trail
API ServiceScopedProgrammatic access limited to defined API scopes

3.4 Permission Granularity

ResourceAvailable Permissions
Chart of Accountsview, create, edit, delete, export, import
Journal Entriesview, create, edit, reverse, post, approve, export
Bank Reconciliationview, match, unmatch, create-adjustment, approve
AP/ARview, create, edit, approve, pay, void
Reportsview, generate, export, schedule
Tax Filingview, prepare, review, submit
User Managementview, invite, edit-role, deactivate, delete
System Settingsview, edit-entity, edit-firm, edit-billing
Audit Trailview, export (never edit or delete)
AI Settingsview, 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 LayerMechanismBypass Protection
TenantRLS on tenant_id (every table)Cannot query across tenants even with SQL injection
EntityRLS on entity_id (within tenant)Staff only see assigned entities
UserApplication-level permission checksRole-based access enforcement
ConnectionSET app.current_tenant on every connectionMiddleware sets before any query; unset = no access

4.2 Cross-Tenant Protection

VectorProtection
SQL injectionParameterized queries everywhere + RLS backup layer
API enumerationUUIDs (not sequential IDs), authorization check on every endpoint
Bulk operationsAll bulk operations scoped to current tenant, server-side pagination
Search/aggregationSearch indexes partitioned by tenant, cross-tenant aggregation prohibited
ReportingReports generated within tenant context, RLS prevents data leakage
AI/MLModels trained per-tenant or on anonymized aggregate data only
BackupsLogical backups per-tenant, encryption per-tenant key
LogsTenant_id in every log entry, log access restricted by tenant

5. Encryption Architecture

5.1 Encryption Matrix

Data StateMethodKey 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 keyGoogle Cloud KMS (tenant-specific key ring)
BackupsAES-256-GCMSeparate backup encryption key
Digital signaturesRSA-2048 / ECDSA P-256HSM-backed (Cloud KMS)

5.2 Field-Level Encryption (PII)

Data CategoryFieldsEncryptionSearchable
Tax identifiersCNPJ, EIN, VAT number, SSNAES-256-GCM per-tenantDeterministic encryption for exact match
Bank detailsAccount number, routing number, IBANAES-256-GCM per-tenantEncrypted search via blind index
Contact PIIEmail, phone, addressAES-256-GCM per-tenantEncrypted search via blind index
Financial amountsNot encrypted (needed for aggregation)RLS provides access controlN/A
Document contentOCR extracted text, uploaded filesAES-256-GCM per-tenantFull-text search on encrypted index

5.3 Key Rotation

Key TypeRotation PeriodProcess
Database encryption keyAnnualGoogle-managed automatic rotation
Per-tenant field encryption keyAnnualAutomated re-encryption during maintenance window
TLS certificates90 daysAutomated via cert-manager
mTLS certificates24 hoursIstio automatic rotation
API keys90 days (enforced)User-initiated with grace period
JWT signing key30 daysAutomated, old key valid for token lifetime

6. Infrastructure Security

6.1 GKE Cluster Security

ControlConfiguration
Private clusterNo public IP on nodes, private endpoint for API server
Network policiesCalico policies: deny-all default, explicit allow per service
Pod securityPod Security Standards (Restricted), no privileged containers
Node securityCOS (Container-Optimized OS), auto-update enabled, Shielded VMs
RBACKubernetes RBAC aligned with GCP IAM, least privilege
SecretsExternal Secrets Operator + Google Secret Manager (not K8s secrets)
Image securityBinary Authorization, only signed images from private Artifact Registry
Workload IdentityGKE Workload Identity for GCP service access (no service account keys)

6.2 Network Architecture

ZoneComponentsAccess
PublicCloudflare CDN/WAF, Load BalancerInternet-facing, DDoS protected
DMZAPI Gateway (Envoy/Istio ingress)Authenticated requests only
ApplicationBackend services, worker podsInternal only, mTLS required
DataPostgreSQL, Redis, NATSApplication zone only, encrypted connections
AI/MLGPU nodes, model servingApplication zone only, no external access
ManagementMonitoring, logging, CI/CD agentsRestricted admin access

6.3 Container Security

ControlToolAction
Image scanningGoogle Artifact Analysis + TrivyScan on push, block critical CVEs
Runtime securityFalcoDetect anomalous container behavior
Network segmentationCalicoPer-namespace network policies
Resource limitsK8s resource quotasPrevent resource exhaustion attacks
Read-only filesystemSecurityContextContainers run with readOnlyRootFilesystem
Non-root executionSecurityContextAll containers run as non-root user

7. Application Security

7.1 OWASP Top 10 Mitigations

VulnerabilityMitigation
InjectionParameterized queries (SQLAlchemy ORM), RLS backup layer, input validation
Broken AuthenticationArgon2id, MFA, session binding, account lockout, breach password check
Sensitive Data ExposureField-level encryption, TLS everywhere, minimal data in logs, PII masking
XML External EntitiesXML parsing with entity expansion disabled, schema validation
Broken Access ControlRBAC + RLS, authorization check on every endpoint, UUID identifiers
Security MisconfigurationInfrastructure as Code, CIS benchmarks, automated compliance scanning
Cross-Site ScriptingContent Security Policy, React auto-escaping, DOMPurify for rich content
Insecure DeserializationJSON-only APIs, schema validation (Pydantic), no pickle/yaml deserialization
Using Components with Known VulnerabilitiesDependabot, Snyk, automated CVE patching pipeline
Insufficient Logging & MonitoringComprehensive audit trail, SIEM, anomaly detection, alerting

7.2 API Security

ControlImplementation
Rate limitingPer-user, per-endpoint, per-tenant (configurable)
Request size limits10MB default, 50MB for file uploads
Input validationPydantic models with strict type checking on all endpoints
Output filteringResponse serializers exclude internal fields
CORSStrict origin whitelist per tenant
Content-Type enforcementReject requests with unexpected content types
Request loggingFull request/response logging (PII masked) for audit
IdempotencyIdempotency keys for all mutating operations

8. AI/ML Security

8.1 AI-Specific Security Controls

ThreatControl
Prompt injectionInput sanitization before LLM calls, output validation, sandboxed execution
Data poisoningTraining data validation, anomaly detection on correction patterns, human review for model updates
Model extractionAPI rate limiting, no direct model access, watermarked outputs
Adversarial inputsDocument validation before OCR, confidence thresholds, human fallback
Privacy leakage via AIPII stripping before cloud API calls, local models for sensitive data, differential privacy
BiasMonthly bias audits on auto-categorization, demographic-aware testing

8.2 LLM Security Architecture

ControlImplementation
Prompt sanitizationStrip all PII (CNPJ, bank accounts, names) before sending to Claude API
Response validationValidate LLM output format, check for hallucinated data, SQL safety checks
Sandboxed executionNLQ-generated SQL runs on read-only replica with row limits and timeouts
Token budgetsPer-tenant monthly token limits, cost monitoring, abuse detection
Model versioningAll AI decisions logged with model version, reproducible
Fallback policyIf 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

CertificationTimelineScopeStatus
SOC 2 Type IMonth 6Security, Availability, ConfidentialityPhase 1 target
SOC 2 Type IIMonth 12Security, Availability, Confidentiality, Processing IntegrityPhase 2 target
ISO 27001Month 18Information Security Management SystemPhase 3 target
LGPD ComplianceMonth 3Brazil data protectionPhase 1 target
GDPR ComplianceMonth 12EU data protectionPhase 2 target
PCI DSS (if payment processing)Month 18Payment card dataPhase 3 (if applicable)
CSA STARMonth 24Cloud securityPhase 4 target

9.2 Compliance Controls Matrix

Control DomainControlsEvidence
Access ManagementMFA, RBAC, least privilege, access reviews (quarterly)Access logs, role assignments, review records
Data ProtectionEncryption, classification, retention, disposalEncryption configs, classification tags, disposal logs
Change ManagementCI/CD with approvals, code review, staging testingGit history, PR reviews, deployment logs
Incident ResponseIR plan, tabletop exercises, breach notificationIR runbooks, exercise records, notification templates
Business ContinuityDR plan, backup testing, RTO/RPO targetsDR test results, backup logs, recovery metrics
Vendor ManagementThird-party security reviews, SLA monitoringVendor assessments, SLA reports
Employee SecurityBackground checks, security training, acceptable useTraining records, policy acknowledgments
Physical SecurityCloud provider (Google) physical controlsGoogle SOC 2 report inheritance

10. Incident Response

10.1 Incident Severity Levels

LevelDefinitionResponse TimeEscalation
P1 CriticalActive data breach, service outage, ransomware15 minutesCEO + CTO + Legal immediately
P2 HighSuspected breach, significant vulnerability, degraded service1 hourCTO + Engineering Lead
P3 MediumMinor vulnerability, suspicious activity, non-critical bug4 hoursEngineering Lead
P4 LowMinor security finding, hardening opportunity24 hoursSecurity team

10.2 Incident Response Phases

PhaseActivitiesTimeline
DetectionAutomated monitoring alerts, user reports, vulnerability scansContinuous
TriageSeverity assessment, scope determination, containment decision15 min (P1), 1 hr (P2)
ContainmentIsolate affected systems, block attack vectors, preserve evidence1 hr (P1), 4 hr (P2)
EradicationRemove threat, patch vulnerabilities, rotate credentials4 hr (P1), 24 hr (P2)
RecoveryRestore services, verify integrity, monitor for recurrence8 hr (P1), 48 hr (P2)
Lessons LearnedPost-incident review, update controls, improve detection72 hr after resolution

10.3 Breach Notification

JurisdictionAuthorityTimelineMethod
Brazil (LGPD)ANPD + Data subjects"Reasonable time" (practice: 72 hrs)Written notification
EU (GDPR)Supervisory Authority + Data subjects72 hours (authority), "without undue delay" (subjects)DPA notification form
US (varies by state)State AG + Affected individuals30-60 days (varies)Written notification
UK (UK GDPR)ICO + Data subjects72 hoursICO notification form
AustraliaOAIC + Affected individuals30 daysNDB statement

11. Security Monitoring & Logging

11.1 Logging Architecture

Log CategoryContentRetentionStorage
Audit trailAll data CRUD operations, user actions, AI decisions7 years (regulatory minimum)Immutable append-only (Cloud Logging + BigQuery)
AuthenticationLogin attempts, MFA events, session management2 yearsCloud Logging
API accessAll API calls with tenant, user, endpoint, status1 yearCloud Logging
InfrastructureK8s events, node metrics, network flows90 daysCloud Logging + Prometheus
Security eventsWAF blocks, IDS alerts, anomaly detections2 yearsSIEM (Chronicle)
AI operationsModel invocations, confidence scores, corrections2 yearsApplication database + Cloud Logging

11.2 Monitoring & Alerting

MonitorToolAlert Threshold
Authentication anomaliesCloud Armor + custom5 failed logins/5min, impossible travel
API abuseRate limiting + anomaly detection10x normal volume, unusual endpoints
Data exfiltrationDLP + query monitoringBulk exports, unusual query patterns
Privilege escalationAudit log analysisRole changes, permission grants
Infrastructure threatsFalco + GKE securityContainer escape, privilege escalation, crypto mining
Vulnerability scanningTrivy + Artifact AnalysisNew critical CVE in deployed images
Certificate monitoringcert-manager + customExpiry within 14 days
Compliance driftOPA/Gatekeeper + customPolicy violation in deployment

12. Security Development Lifecycle

12.1 Secure SDLC Practices

PhaseSecurity Activities
DesignThreat modeling (STRIDE), security architecture review, privacy impact assessment
DevelopmentSecure coding guidelines, pre-commit hooks (secrets detection), IDE security plugins
ReviewMandatory security review for auth/crypto/data changes, automated SAST (Semgrep)
TestingDAST (ZAP), dependency scanning (Snyk), container scanning (Trivy), penetration testing
DeploymentBinary authorization, canary with security monitoring, rollback capability
OperationsRuntime security (Falco), continuous compliance, regular penetration testing

12.2 Security Testing Calendar

ActivityFrequencyScope
Automated SAST/DASTEvery CI runFull codebase
Dependency vulnerability scanDailyAll dependencies
Container image scanEvery buildAll container images
Internal penetration testQuarterlyFull application + infrastructure
External penetration testAnnuallyFull attack surface
Red team exerciseAnnuallySocial engineering + technical
Tabletop exercise (IR)Semi-annuallyIncident response process
Disaster recovery testSemi-annuallyFull DR procedure

Hal Casteel CEO/CTO, AZ1.AI Inc.

Copyright © 2026 AZ1.AI Inc. All rights reserved. Unauthorized distribution or reproduction is strictly prohibited.