Skip to main content

Work Order QMS Module — Security Architecture

Classification: Internal — Security Engineering Date: 2026-02-13 Artifact: 64 of WO System Series Prompt Section: v8.0 §5 — Security Architecture


1. Threat Model (STRIDE)

1.1 System Boundary

The WO system's attack surface spans six boundaries: the API Gateway (external-facing), the Agent Orchestrator (internal, trusted), the Compliance Engine (internal, trusted), Agent Workers (internal, semi-trusted), the Vendor Portal (external-facing, limited trust), and the State Store (internal, highest trust).

1.2 STRIDE Analysis

Spoofing (Identity)

Attack VectorTargetLikelihoodImpactMitigationDetectionStatus
Stolen JWT used to access APIAPI GatewayMediumHigh — attacker acts as authenticated userShort-lived JWTs (1hr), refresh token rotation, device fingerprintingFailed auth monitoring, IP anomaly detection✅ Designed
Agent token reuse across WO executionsAgent WorkersLowHigh — agent acts outside intended scopeEphemeral per-execution tokens scoped to WO ID, token invalidated on WO completionToken reuse detection in audit trail✅ Designed
Vendor impersonation via shared credentialsVendor PortalMediumMedium — unauthorized WO modificationsPer-vendor unique credentials, MFA required, IP allowlisting optionalLogin anomaly detection, geo-mismatch alerts✅ Designed
Forged e-signature (identity claim)Signature ServiceLowCritical — invalidates regulatory complianceRe-authentication at signing time (§11.100(b)), cryptographic hash binding (§11.70)Hash verification on every signature read, chain integrity audit⚠️ Partial (G02, G05)

Tampering (Integrity)

Attack VectorTargetLikelihoodImpactMitigationDetectionStatus
Direct DB modification bypassing applicationState StoreLow (requires DB admin access)Critical — violates audit trail integrityPostgreSQL triggers prevent UPDATE/DELETE on audit_trail; separate DB credentials for app vs. adminHash chain verification (nightly job), chain break = immediate P1 alert⚠️ Partial (G03)
WO field modification after approvalWO ServiceLowHigh — approved record no longer matches what was approvedOptimistic locking (version field), post-approval fields immutable (application-enforced)Version mismatch detection, audit trail diff on every mutation✅ Designed
Agent message tampering in transitEvent Bus (NATS)LowMedium — agent acts on false instructionsHMAC-SHA256 message signing, nonce-based replay preventionSignature verification on receipt, sequence gap detection⚠️ Partial (G04)
Malicious schema migrationState StoreVery LowCritical — corrupts regulated dataMigration requires approval (ADR link), pre-migration snapshot, tested rollbackSchema hash comparison, migration audit log✅ Designed

Repudiation (Non-repudiation)

Attack VectorTargetLikelihoodImpactMitigationDetectionStatus
User denies approving WOApproval/SignatureMediumHigh — regulatory compliance failureElectronicSignature with re-auth attestation, cryptographic hash binding, immutable audit trailSignature chain verification, re-auth log correlation⚠️ Partial (G02, G05)
Agent denies performing actionAgent WorkersLowMedium — audit gapAgent session ID in every audit trail entry, message signing, correlation ID chainAgent execution trace in observability stack✅ Designed
Admin denies configuration changeTenant SettingsLowMedium — accountability gapAdmin actions generate L4 audit entries with re-authenticationAdmin audit trail review (weekly)✅ Designed

Information Disclosure (Confidentiality)

Attack VectorTargetLikelihoodImpactMitigationDetectionStatus
Cross-tenant data leakageState StoreLow (RLS enforced)Critical — regulatory violation, trust destructionPostgreSQL RLS on every table, tenant_id set at connection pool level, RLS penetration tested quarterlyCross-tenant access attempt logging, automated RLS policy verification✅ Implemented
PHI exposure in WO descriptionsWO ServiceMediumHigh — HIPAA violationPHI detection scanner on WO creation/update, confidence-based response (block/flag/log)PHI scan results dashboard, false negative review⚠️ Design Only (G09)
Vendor sees non-assigned WO dataVendor PortalLowMedium — confidentiality breachVendor role scoped to assigned WOs only (RBAC + application-level filtering)Vendor access audit (monthly), access pattern anomaly✅ Implemented
Credential exposure in job planJobPlan ServiceMediumHigh — lateral movement riskVault references only (vault://path), never plaintext; PHI scanner catches credential patternsCredential pattern detection in L2+ fields⚠️ Design Only (G01)
Audit trail data exfiltrationAPI / ExportLowCritical — bulk regulated data exposureExport requires AUDITOR or ADMIN role, rate limited, logged, paginated (no bulk dump)Export volume anomaly detection✅ Designed

Denial of Service (Availability)

Attack VectorTargetLikelihoodImpactMitigationDetectionStatus
API rate abuseAPI GatewayHighMedium — service degradationPer-tenant token bucket rate limiting, burst + sustained ratesRate limit hit monitoring, auto-scaling triggers✅ Designed
Agent execution storm (infinite loop)Agent OrchestratorMediumHigh — token budget exhaustion, system overloadToken budget controller (hard stop at 95%), max iteration limits, circuit breakers per agentBudget threshold alerts (80%), iteration count monitoring✅ Implemented
Database connection exhaustionState StoreLowCritical — system-wide outageConnection pooling (PgBouncer), per-tenant connection limits, query timeout (30s)Connection pool saturation alerts, slow query logging✅ Designed
Event bus floodNATSLowMedium — message processing delayPer-agent publish rate limits, message size limits (1MB), backpressure signalingQueue depth monitoring, consumer lag alerts✅ Designed

Elevation of Privilege (Authorization)

Attack VectorTargetLikelihoodImpactMitigationDetectionStatus
Agent attempts to approve WO (self-elevation)Agent Workers → ApprovalLow (architectural constraint)Critical — bypasses human controlAgents NEVER hold SYSTEM_OWNER, QA, or ADMIN roles; approval endpoints reject agent tokensAgent-attempted-approval alert (immediate P1)✅ Implemented
ASSIGNEE approves their own WOApproval ServiceMedium (user error or intent)High — SOD violation, Part 11 breachSOD guard: ASSIGNEE ≠ APPROVER enforced in state machine guard T5SOD violation audit log, blocked transition logged✅ Implemented
Admin bypasses approval chainAdmin ConsoleLowHigh — undermines regulatory workflowADMIN role can cancel but cannot approve/reject; documented in RBAC matrixAdmin action audit (all admin operations logged at L4)✅ Implemented
Break-glass abuse (over-broad emergency access)Break-Glass SystemLowMedium — unauthorized access under emergency cover4-hour time limit, enhanced audit logging, mandatory post-incident review within 72 hours, break-glass does not bypass SODBreak-glass activation alert (immediate), usage pattern analysis⚠️ Design Only (G10)

1.3 Threat Model Summary

STRIDE CategoryTotal Vectors✅ Implemented✅ Designed⚠️ Partial/DesignCoverage
Spoofing403175%
Tampering402250%
Repudiation302167%
Information Disclosure521260%
Denial of Service4130100%
Elevation of Privilege430175%
Total24611771%

The 7 partial/design-only items map directly to gap closure prompts G01–G05, G09, G10.


2. Authentication Architecture

2.1 Authentication Flow

                    ┌──────────────────────┐
│ Identity Provider │
│ (Okta / Azure AD / │
│ Auth0 / Cognito) │
└──────────┬───────────┘
│ OIDC / SAML 2.0
┌──────────▼───────────┐
│ API Gateway │
│ ┌─────────────────┐ │
│ │ Token Validator │ │
│ │ (JWT RS256) │ │
│ └─────────────────┘ │
└──────────┬───────────┘
│ Validated Claims
┌────────────────┼────────────────┐
▼ ▼ ▼
┌───────────┐ ┌────────────┐ ┌────────────┐
│ Human │ │ Service │ │ Agent │
│ Sessions │ │ Accounts │ │ Tokens │
│ │ │ │ │ │
│ JWT + │ │ mTLS + │ │ Scoped, │
│ Refresh │ │ API Key │ │ Ephemeral │
└───────────┘ └────────────┘ └────────────┘

2.2 Authentication Types

Auth TypeMechanismLifetimeScopeRotationWO System Use
Human sessionJWT (RS256) + refresh token1hr access / 7d refresh / 30min idle timeoutTenant + rolesRefresh on useAll human API calls
E-signature re-authRe-authentication attestation5 minutesSingle signaturePer-signatureApproval signing events
Service-to-servicemTLS + API keyCertificate: 90dService identityAuto-rotate at 60dCompliance Engine ↔ State Store
Agent executionScoped ephemeral tokenWO execution durationWO ID + agent rolePer-executionAll agent API calls
Vendor portalJWT (RS256) + MFA1hr access / no refresh (re-login required)Assigned WOs onlyPer-sessionVendor interactions
Break-glassEmergency override token4 hours maxSpecified scope (not SOD bypass)Single-useEmergency access only

2.3 Session Management

ParameterValueRegulatory Requirement
Idle timeout30 minutes (configurable: 5–120 min)HIPAA §164.312(a)(2)(iii)
Absolute timeout12 hoursSecurity best practice
E-signature window5 minutesFDA §11.100(b)
Concurrent sessions3 max per userSecurity best practice
Grace warning2 minutes before idle timeoutUX requirement
Failed login lockout5 attempts → 15 minute lockoutHIPAA §164.312(a)(1)
Re-auth for signaturesEvery signature eventFDA §11.100(b), §11.200

3. Authorization Architecture

3.1 Layered Model

Layer 1: RBAC  ──→  "Does this role have this permission?"
│ 8 roles: ORIGINATOR, ASSIGNER, ASSIGNEE, SYSTEM_OWNER,
│ QA, VENDOR, ADMIN, AUDITOR
│ 6 agent roles: AGENT_ORCHESTRATOR, AGENT_ASSET_MGMT,
│ AGENT_SCHEDULER, AGENT_VENDOR_COORD, AGENT_DOCUMENTATION,
│ AGENT_QA_ASSIST

Layer 2: RLS ──→ "Can this tenant see this row?"
│ PostgreSQL RLS on all 22 tables
│ tenant_id = current_setting('app.tenant_id')

Layer 3: SOD ──→ "Does this create a conflict of interest?"
│ ASSIGNEE ≠ APPROVER
│ Both SO + QA required for regulatory WOs
│ Agents never approve

Layer 4: Scope ──→ "Can this actor access THIS specific resource?"
│ Vendors: only assigned WOs
│ Agents: only current execution scope
│ Auditors: read-only everything in tenant

Layer 5: Context ─→ "Do special conditions apply?"
Break-glass: bypasses RBAC (not SOD)
Training expiration: blocks assignment
Certification lapse: blocks execution

3.2 Policy Decision Flow

async function authorize(request: AuthzRequest): Promise<AuthzDecision> {
// Layer 1: RBAC
const rolePermission = await checkRBAC(request.actorRole, request.permission);
if (!rolePermission.allowed) {
return deny('RBAC', `Role ${request.actorRole} lacks ${request.permission}`);
}

// Layer 2: RLS (enforced at DB level, but verified here for defense-in-depth)
const tenantMatch = request.actorTenantId === request.resourceTenantId;
if (!tenantMatch) {
return deny('RLS', 'Cross-tenant access denied');
}

// Layer 3: SOD
if (request.permission === 'APPROVE_WO') {
const isAssignee = await isActorAssignee(request.actorId, request.resourceId);
if (isAssignee) {
return deny('SOD', 'Assignee cannot approve own WO (§11.10(g))');
}
}

// Layer 4: Scope
if (request.actorRole === 'VENDOR') {
const isAssignedVendor = await isVendorAssigned(request.actorId, request.resourceId);
if (!isAssignedVendor) {
return deny('SCOPE', 'Vendor not assigned to this WO');
}
}

// Layer 5: Context
if (request.contextFlags?.breakGlass) {
// Break-glass bypasses RBAC but NOT SOD
await logBreakGlassAccess(request);
// Still enforce Layer 3 SOD checks
}

return allow(request, [rolePermission]);
}

3.3 Agent Permission Boundaries

ConstraintEnforcement PointConsequence of Violation
Agents cannot hold SO, QA, or ADMIN rolesToken issuer (Orchestrator)Token rejected at API Gateway
Agents cannot approve or reject WOsState machine guard (T5)Guard violation, human checkpoint triggered
Agents cannot sign electronicallySignature serviceRequest rejected, P1 alert
Agent scope limited to current WO executionToken claims include WO IDRequests outside scope return 403
Agent actions always attributedAudit trail includes agent session IDAgent actions auditable end-to-end

4. Secrets Management

4.1 Secret Inventory

SecretClassificationStorageRotationCurrent Status
Database connection stringsL3Vault (HashiCorp / GCP Secret Manager)90 days⚠️ Gap G01 — currently env vars
AI model API keysL3VaultPer provider policy (90d default)⚠️ Gap G01
JWT signing keysL3KMS (cloud-native)Annual + on-demand✅ Designed
E-signature hash keysL4HSM / Cloud KMSVersioned (never rotated — new version created)⚠️ Gap G02
Agent execution tokensL2In-memory (ephemeral)Per-execution✅ Designed
mTLS certificatesL2Cert-manager (automated)90 days (Let's Encrypt)✅ Designed
Encryption keys (at-rest)L4KMS (cloud-native)Annual✅ Designed
NATS credentialsL2Vault90 days⚠️ Gap G01
Vendor portal OAuth client secretsL3Vault180 days⚠️ Gap G01

4.2 Vault Integration Pattern (Gap G01)

Application Code → Vault Sidecar → Vault Server → Secret Value

Job Plan credential reference:
Before (gap): { "db_password": "plaintextvalue" }
After (G01): { "db_password": "vault://secret/wo-system/db/prod#password" }

Resolution flow:
1. Agent needs credential → reads vault reference from JobPlan
2. Agent requests scoped token from Orchestrator (includes WO ID + credential path)
3. Vault sidecar resolves reference → returns value in memory
4. Value used for operation → never persisted outside vault
5. Vault audit log records: who accessed, when, which secret, from which WO

4.3 Key Management

Key TypeAlgorithmKey SizeStorageRotation Trigger
JWT signingRSA2048-bitKMSAnnual or compromise
E-signature hashSHA-256256-bitKMS/HSMVersion-based (new key per year, old keys retained for verification)
Audit trail hash chainSHA-256256-bitKMSNever rotated (chain integrity)
At-rest encryptionAES-256-GCM256-bitKMSAnnual (envelope encryption, rotate DEK)
Message signing (agent-to-agent)HMAC-SHA256256-bitVault (ephemeral per session)Per agent session

5. Network Security

5.1 Network Boundaries

┌─────────────────────────────────────────────────┐
│ PUBLIC INTERNET │
│ ┌────────────────────────────────────────────┐ │
│ │ DMZ (WAF + DDoS Protection) │ │
│ │ ┌──────────────────────────────────────┐ │ │
│ │ │ API Gateway (TLS termination) │ │ │
│ │ │ Vendor Portal (TLS termination) │ │ │
│ │ └──────────────┬───────────────────────┘ │ │
│ └─────────────────┼─────────────────────────┘ │
│ │ mTLS │
│ ┌─────────────────▼─────────────────────────┐ │
│ │ PRIVATE NETWORK (VPC) │ │
│ │ ┌──────────┐ ┌──────────┐ ┌───────────┐ │ │
│ │ │ Agent │ │Compliance│ │ Observ. │ │ │
│ │ │Orchestr. │ │ Engine │ │ Stack │ │ │
│ │ └────┬─────┘ └────┬─────┘ └───────────┘ │ │
│ │ │ mTLS │ mTLS │ │
│ │ ┌────▼─────────────▼────────────────────┐ │ │
│ │ │ DATA PLANE (most restricted) │ │ │
│ │ │ ┌───────────┐ ┌──────────┐ │ │ │
│ │ │ │PostgreSQL │ │ NATS │ │ │ │
│ │ │ │(encrypted │ │(TLS + │ │ │ │
│ │ │ │ at rest) │ │ authz) │ │ │ │
│ │ │ └───────────┘ └──────────┘ │ │ │
│ │ └───────────────────────────────────────┘ │ │
│ └────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────┘

5.2 Network Policies

RuleSourceDestinationProtocolPortJustification
Internet → API GatewayAnyAPI GatewayHTTPS443Public API access
Internet → Vendor PortalVendor IP allowlist (optional)Vendor PortalHTTPS443Vendor access
API Gateway → OrchestratorAPI GatewayAgent OrchestratorgRPC over mTLS8443Internal routing
Orchestrator → Agent WorkersAgent OrchestratorAgent WorkersgRPC over mTLS8444Agent dispatch
Any service → PostgreSQLPrivate VPC servicesPostgreSQLTLS5432Data access
Any service → NATSPrivate VPC servicesNATS clusterTLS4222Event bus
PostgreSQL → ExternalPostgreSQLNoneNo outbound (data plane isolated)
Agent Workers → AI ModelsAgent WorkersAnthropic/OpenAI APIHTTPS443Model calls (via egress proxy)

5.3 Zero Trust Principles

PrincipleWO System Implementation
Never trust, always verifyEvery request authenticated + authorized, even internal
Least privilegeTokens scoped to minimum required access; agent tokens scoped to WO
Assume breachAudit everything; hash chains detect tampering; circuit breakers limit blast radius
Explicit verificationmTLS between all services; no implicit trust based on network position
Encrypt everythingTLS 1.3 in transit; AES-256-GCM at rest; field-level for L3+

6. Supply Chain Security

6.1 Dependency Management

ControlToolFrequencyGate Type
Vulnerability scanningSnyk / TrivyEvery PR + daily scanBlock on critical/high CVEs
License complianceFOSSAEvery PRBlock copyleft in proprietary components
Dependency pinningLock files (package-lock.json, poetry.lock)AlwaysExact versions only
Controlled updatesRenovate (configured for grouped weekly PRs)WeeklyPR with changelog + test results
Transitive dependency auditSnyk deep scanMonthlyReview report, create WO for remediation

6.2 Build Artifact Security

ArtifactSigningStorageVerification
Container imagesCosign (Sigstore)Private registry (GCR/ECR)Admission controller verifies signature before deployment
Helm chartsGPG signedPrivate chart repositorySignature verified before helm install
Database migrationsSHA-256 hash in migration manifestGit (source of truth)Hash verified before execution
SBOMAuto-generated (CycloneDX format)Stored alongside build artifactIncluded in IQ evidence package

6.3 Base Image Policy

Allowed BaseUse CaseUpdate Cadence
gcr.io/distroless/cc-debian12Service containers (Go, compiled languages)Monthly rebuild
gcr.io/distroless/python3-debian12Python services (Orchestrator, Compliance Engine)Monthly rebuild
node:22-slimTypeScript services (API Gateway, IDE)Monthly rebuild
postgres:16-alpineDatabase (dev/test only; managed service in production)Quarterly

Rejected: Ubuntu/Debian full images, latest tags, unverified third-party images.


7. Incident Response Integration

7.1 Security Event Taxonomy

Event CategorySourceSeverityResponse
Authentication failure (≥5 in 5min)API GatewayP3Auto-lockout + alert to security team
Cross-tenant access attemptRLS / ApplicationP1Immediate block + forensic investigation
SOD violation attemptState machine guardP2Block + log + notify compliance officer
Hash chain integrity failureNightly verification jobP1Freeze affected records + forensic investigation
Agent attempted approvalSignature serviceP1Block + alert + review agent configuration
PHI detected in non-PHI fieldPHI scannerP2Flag record + notify data owner + quarantine
Token budget exhaustionToken Budget ControllerP3Hard stop agent execution + alert orchestrator
Circuit breaker openAgent Worker monitoringP3Route around failed worker + alert SRE
Break-glass activationBreak-glass systemP2Enhanced audit logging + mandatory 72-hour review
Credential rotation failureVault integrationP2Retry with backoff + alert security team + use cached credential

7.2 Security Event → WO Creation (Gap G14)

Critical security events auto-generate incident Work Orders:

Security Event (P1/P2)
→ Incident WO created automatically
→ Type: MANUAL (source_type override: SECURITY_INCIDENT)
→ Priority: EMERGENCY
→ Assigned to: Security Team (pre-configured)
→ Regulatory flag: true (all security incidents are regulatory-relevant)
→ JobPlan: pre-populated from incident template
→ Mandatory QA review before closure
→ Correlation: incident WO linked to triggering event via correlationId

8. Residual Risk Register

Risk IDDescriptionSTRIDE CategorySeverityProbabilityMitigation StatusAcceptance CriteriaReview Date
SR-001Plaintext credentials in JobPlan JSONBDisclosureCriticalMedium⚠️ Gap G01Resolved when vault integration completeImmediate
SR-002No cryptographic hash binding on e-signaturesRepudiationHighLow⚠️ Gap G02Resolved when hash function implementedImmediate
SR-003Audit trail hash chain not implementedTamperingHighLow⚠️ Gap G03Resolved when chain verification activeImmediate
SR-004Agent messages unsignedTamperingMediumLow⚠️ Gap G04Resolved when HMAC signing activeNext sprint
SR-005No PHI scanner on WO fieldsDisclosureHighMedium⚠️ Gap G09Resolved when scanner operationalNext sprint
SR-006Break-glass not implementedPrivilegeMediumLow⚠️ Gap G10Resolved when break-glass system liveNext quarter
SR-007AI model provider processes L4 dataDisclosureMediumLowContractual (BAA/DPA)BAA/DPA signed with all model providersAnnually
SR-008Single-region deployment (no DR)AvailabilityMediumLow⚠️ DR gapResolved when multi-region deployedNext quarter
SR-009Insider threat (malicious admin)All categoriesMediumVery LowAdmin audit trail + SOD + no admin approvalAccepted — residual risk with quarterly access reviewQuarterly

Risk review cadence: Monthly for Critical/High, quarterly for Medium, annually for Low.


Security is not a feature — it's a property of the system. Every new endpoint, every new agent capability, every new data flow must pass through this STRIDE analysis and authorization framework before deployment. The gap closure series (G01–G10) addresses the 7 partial items identified in this threat model.


Copyright 2026 AZ1.AI Inc. All rights reserved. Developer: Hal Casteel, CEO/CTO Product: CODITECT-BIO-QMS | Part of the CODITECT Product Suite Classification: Internal - Confidential