Skip to main content

ASCEND 12-Layer Security Architecture

Executive Summary

ASCEND implements a defense-in-depth security model with 12 distinct security layers. Every layer is designed with FAIL SECURE behavior, meaning any error condition defaults to DENY. This architecture ensures that even if multiple layers fail, remaining layers continue to protect the system.

Key Security Properties

  • All layers fail secure - Default to DENY on any error
  • Defense in depth - Each layer operates independently
  • Zero trust - Every request verified at multiple checkpoints
  • Immutable audit trail - All decisions logged with hash-chaining
  • Multi-tenant isolation - Complete data segregation between organizations

Architecture Overview

                              ASCEND 12-LAYER SECURITY ARCHITECTURE
══════════════════════════════════════

┌─────────────────────────────────────────────────────────────────────────────┐
│ INCOMING REQUEST │
└─────────────────────────────────────┬───────────────────────────────────────┘

┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 1: RATE LIMITING [FAIL → DENY] │
│ Redis-backed sliding window • Per-org/agent/endpoint limits │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 2: PROMPT SECURITY [FAIL → BLOCK] │
│ 20 detection patterns • Injection/jailbreak/encoding attacks │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 3: CODE ANALYSIS [FAIL → BLOCK] │
│ 20 patterns • CWE mappings • Secrets detection │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 4: ACTION GOVERNANCE [FAIL → DENY] │
│ 7-step pipeline • CVSS v3.1 scoring • Policy evaluation │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 5: AUTHENTICATION [FAIL → DENY] │
│ JWT (RS256) • API Keys • AWS Cognito MFA │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 6: AUTHORIZATION (RBAC) [FAIL → DENY] │
│ 6-level role hierarchy • Separation of Duties │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 7: MULTI-TENANT ISOLATION [FAIL → DENY] │
│ PostgreSQL RLS • Per-org Cognito pools • organization_id enforcement │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 8: APPROVAL WORKFLOWS [FAIL → BLOCK] │
│ Multi-stage approval • SLA tracking • Risk-based escalation │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 9: KILL SWITCH [FAIL → BLOCK] │
│ Circuit breaker • Sub-100ms termination • SNS/SQS messaging │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 10: AUDIT TRAIL [FAIL → BLOCK] │
│ WORM design • SHA-256 hash-chaining • 7-year retention │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 11: BYOK ENCRYPTION [FAIL → BLOCK] │
│ Envelope encryption • AWS KMS • Customer-managed keys │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ LAYER 12: INPUT VALIDATION [FAIL → REJECT] │
│ Pydantic schemas • Type enforcement • Sanitization │
└─────────────────────────────────────┬───────────────────────────────────────┘
│ PASS
┌─────────────────────────────────────▼───────────────────────────────────────┐
│ BUSINESS LOGIC │
└─────────────────────────────────────────────────────────────────────────────┘

Layer 1: Rate Limiting

Purpose: DDoS protection, abuse prevention, resource management

Implementation

AspectDetails
TechnologyRedis-backed with ElastiCache
AlgorithmSliding window (O(log N) Redis sorted sets)
GranularityPer-organization, per-agent, per-endpoint

Code Locations

ComponentFile Path
IP-based limitersecurity/rate_limiter.py
Agent-based limiterservices/agent_rate_limiter.py
Data modelsmodels_rate_limits.py
Migrationalembic/versions/20251218_behav001_rate_limits.py

Configuration

# Default rate limits (configurable per-organization)
RATE_LIMITS = {
"auth_login": "5/minute",
"auth_refresh": "10/minute",
"auth_password_change": "3/minute",
"api_read": "100/minute",
"api_write": "30/minute",
"default": "60/minute"
}

# Per-agent limits
agent_actions_per_minute: 100 # Default
agent_actions_per_hour: 5000

# Priority tier multipliers
priority_tiers = {
"standard": 1.0,
"elevated": 2.0,
"critical": 5.0
}

FAIL SECURE Behavior

# services/agent_rate_limiter.py:148-158
if self.redis is None:
logger.error("BEHAV-001: Redis unavailable, DENYING action (fail-closed)")
return RateLimitResult(
allowed=False,
reason="Rate limiting service unavailable",
retry_after=60
)

Test Evidence

  • tests/e2e/test_05_rate_limiting.py - Rate limiting behavior verification
  • tests/e2e/test_21_fail_secure.py - Fail-secure layer verification

Compliance Mapping

FrameworkControl
NIST 800-53SC-5 (Denial of Service Protection)
PCI-DSS6.5.10
SOC 2A1.1 (Availability)

Layer 2: Prompt Security

Purpose: Detect and block prompt injection attacks against AI agents

Implementation

AspectDetails
Patterns20 global detection patterns
CategoriesInjection, jailbreak, encoding, role manipulation, data exfiltration
ArchitectureDatabase-driven (no hardcoded values)

Code Locations

ComponentFile Path
Detection serviceservices/prompt_security_service.py
Data modelsmodels_prompt_security.py
Pattern seedalembic/versions/20251218_phase10_002_seed_prompt_patterns.py
Routesroutes/prompt_security_routes.py

Detection Patterns

Pattern IDCategorySeverityDescription
PROMPT-001prompt_injectionCRITICALDirect instruction override ("ignore previous instructions")
PROMPT-002prompt_injectionCRITICALNew instruction injection ("from now on")
PROMPT-004jailbreakCRITICALKnown jailbreak modes (DAN, STAN)
PROMPT-008role_manipulationCRITICALEvil AI roleplay attempts
PROMPT-011encoding_attackHIGHBase64 encoded payloads
PROMPT-012encoding_attackHIGHUnicode smuggling
PROMPT-016prompt_injectionCRITICALFake system/admin tags
PROMPT-018data_exfiltrationCRITICALSystem prompt extraction
PROMPT-020chain_attackCRITICALLLM chain injection

FAIL SECURE Behavior

# services/prompt_security_service.py - Enforce mode
if mode == "enforce" and risk_score >= block_threshold:
return PromptAnalysisResult(
blocked=True,
reason=f"Blocked: {pattern.description}",
risk_score=risk_score
)

Test Evidence

  • tests/e2e/test_06_prompt_security.py - Detection verification
  • tests/validation/test_prompt_injection.py - Attack payload testing

Compliance Mapping

FrameworkControl
MITRE ATT&CKT1059 (Command and Scripting Interpreter)
CWECWE-77, CWE-94 (Code Injection)
OWASP LLMLLM01 (Prompt Injection)

Layer 3: Code Analysis

Purpose: Detect dangerous code patterns before execution

Implementation

AspectDetails
Patterns20 detection patterns
LanguagesSQL, Python, Shell, JavaScript
CWE Coverage16 unique CWE identifiers

Code Locations

ComponentFile Path
Analysis serviceservices/code_analysis_service.py
Pattern seedalembic/versions/20251217_phase9_002_seed_global_patterns.py
Security mappingssecurity_mappings.py

Detection Patterns

Pattern IDCategorySeverityCWE
SQL-001data_destructionCRITICALCWE-89, CWE-1321
SQL-006injectionCRITICALCWE-89, CWE-943
PY-001code_executionCRITICALCWE-94, CWE-95
PY-002code_executionCRITICALCWE-78, CWE-77
PY-005sandbox_escapeCRITICALCWE-94
SH-001data_destructionCRITICALCWE-73
SH-002code_executionCRITICALCWE-94, CWE-829
CRED-001credential_exposureCRITICALCWE-798, CWE-259

FAIL SECURE Behavior

# services/code_analysis_service.py
# Critical patterns blocked automatically in enforce mode
if max_risk_score >= effective_threshold:
return CodeAnalysisResult(
blocked=True,
reason="Critical code pattern detected"
)

Test Evidence

  • tests/e2e/test_07_code_analysis.py - Pattern detection verification

Compliance Mapping

FrameworkControl
NIST 800-53SI-10 (Information Input Validation)
PCI-DSS6.5.1 (Injection Flaws)
OWASPA03:2021 (Injection)

Layer 4: Action Governance

Purpose: Risk-based decision making for AI agent actions

Implementation

AspectDetails
Pipeline7-step governance pipeline
Risk FrameworkCVSS v3.1 with 50+ action type mappings
DecisionsALLOW, DENY, REQUIRE_APPROVAL

Code Locations

ComponentFile Path
Action routesroutes/actions_v1_routes.py
Policy evaluationservices/unified_policy_evaluation_service.py
CVSS mappingservices/cvss_auto_mapper.py
Risk assessmentservices/enterprise_risk_calculator_v2.py

7-Step Governance Pipeline

1. ENRICHMENT       → Add context and detect patterns
2. CVSS CALCULATION → Risk score (0.0-10.0)
3. POLICY EVALUATION → ALLOW/DENY/REQUIRE_APPROVAL
4. SMART RULES → Custom rule evaluation
5. ALERT GENERATION → Create alerts for high-risk actions
6. WORKFLOW ROUTING → Route to approval workflows
7. AUDIT LOGGING → Immutable audit trail

Risk Categories

Risk LevelCVSS RangeExample Actions
LOW0.0-3.9Read operations, analytics queries
MEDIUM4.0-6.9Database writes, file writes
HIGH7.0-8.9Delete operations, data export
CRITICAL9.0-10.0Privilege escalation, code execution

FAIL SECURE Behavior

# services/unified_policy_evaluation_service.py:796-805
except Exception as e:
logger.error(f"Failed to evaluate action: {e}")
# Fail-closed: deny by default on error
return {
'decision': 'DENY',
'status': 'FAILED',
'risk_score': 100,
'risk_level': 'CRITICAL',
'reason': f'Governance evaluation failed: {str(e)}'
}

# services/cvss_auto_mapper.py:1036-1037
# Unknown actions default to HIGH risk
logger.warning(f"Unknown action type '{action_type}' - defaulting to HIGH risk")
return "unknown_action" # Maps to CVSS 7.5

Test Evidence

  • tests/e2e/test_04_action_evaluation.py - Governance pipeline verification

Compliance Mapping

FrameworkControl
NIST AI RMFGOVERN, MAP, MEASURE, MANAGE
SOC 2CC6.1 (Access Control)
ISO 27001A.9 (Access Control)

Layer 5: Authentication

Purpose: Verify identity of users and agents

Implementation

AspectDetails
MethodsJWT (RS256), API Keys, AWS Cognito
Token Lifetime60 minutes (access), 30 days (refresh)
MFASupported via Cognito

Code Locations

ComponentFile Path
JWT managerjwt_manager.py
Cognito integrationdependencies_cognito.py
API key validationdependencies_api_keys.py
Multi-pool validatorservices/multi_pool_jwt_validator.py

Authentication Flow

1. Extract token from Authorization header or cookie
2. Validate JWT signature (RS256)
3. Verify claims (iss, aud, exp, nbf)
4. Check token revocation status
5. Set RLS context with organization_id
6. Return authenticated user context

Security Features

FeatureImplementation
AlgorithmRS256 (asymmetric)
Key storageAWS Secrets Manager
API key hashingSHA-256 + salt
Timing attacksConstant-time comparison
Brute force5 attempts/15 min (IP), 10/15 min (email)

FAIL SECURE Behavior

# jwt_manager.py - SEC-079: FAIL-FAST in production
if not self.private_key or not self.public_key:
if environment == "production":
raise ValueError("JWT keys not configured in production!")

# dependencies_cognito.py - Strict validation
options = {
"verify_signature": True, # ALWAYS verify
"verify_exp": True, # Check expiration
"require_exp": True, # Must have exp
"verify_aud": True, # Check audience
}

Test Evidence

  • tests/e2e/test_01_authentication.py - Authentication verification

Compliance Mapping

FrameworkControl
NIST 800-53IA-2 (Identification and Authentication)
NIST 800-63BAuthentication Assurance
PCI-DSS8.1, 8.2 (User Identification)

Layer 6: Authorization (RBAC)

Purpose: Enforce role-based access control

Implementation

AspectDetails
Hierarchy6-level role system
ScopesPlatform tier + Tenant tier
SoDSeparation of Duties enforcement

Code Locations

ComponentFile Path
RBAC managerrbac_manager.py
Permission serviceservices/permission_service.py
RBAC dependenciesdependencies_rbac.py

Role Hierarchy

LevelRolePermissions
5EXECUTIVEAll + emergency override
4ADMINFull access except override
3MANAGERApproval (low/medium risk)
2POWERAnalytics + acknowledgement
1BASICDashboard view
0RESTRICTEDNone (suspended)

Tenant Roles

RoleAccess Level
OwnerFull organization access
AdminFull (no billing)
ApproverApproval workflows
OperatorCreate/manage resources
ViewerRead-only

FAIL SECURE Behavior

# services/permission_service.py
async def has_permission(...):
try:
# permission check logic
except Exception as e:
# FAIL SECURE - Deny on any error
logger.error(f"Permission check error: {e}")
return False

Test Evidence

  • tests/e2e/test_02_authorization.py - RBAC verification

Compliance Mapping

FrameworkControl
NIST 800-53AC-2, AC-3, AC-5
SOC 2CC6.2, CC6.3
PCI-DSS7.1 (Access Control)

Layer 7: Multi-Tenant Isolation

Purpose: Ensure complete data segregation between organizations

Implementation

AspectDetails
DatabasePostgreSQL Row-Level Security (RLS)
AuthenticationPer-organization Cognito user pools
Enforcementorganization_id on all tenant tables

Code Locations

ComponentFile Path
RLS activationdependencies.py
Tenant contextservices/unified_auth/tenant_context.py
RLS migrationalembic/versions/20251205_sec082_multi_tenant_isolation.py
Auth lookupalembic/versions/20251209_sec_rls_002_auth_lookup_function.py

Isolation Mechanisms

LayerImplementation
DatabaseRLS policies, organization_id FK
ApplicationTenantContext (frozen dataclass)
APIAll endpoints scoped to organization
AuthenticationPer-org Cognito pools
EncryptionPer-org BYOK keys

RLS Activation

# dependencies.py
def get_db_with_rls(current_user: dict) -> Session:
"""SEC-082: Activate Row-Level Security context"""
db.execute(
text("SET LOCAL app.current_organization_id = :org_id"),
{"org_id": str(org_id)}
)
# All subsequent queries are tenant-isolated

FAIL SECURE Behavior

# TenantContext is immutable (frozen=True)
@dataclass(frozen=True)
class TenantContext:
org_id: UUID
tenant_id: str
user_id: UUID
# ... prevents tampering after establishment

Test Evidence

  • tests/e2e/test_18_multi_tenant.py - Isolation verification

Compliance Mapping

FrameworkControl
NIST 800-53AC-4 (Information Flow Enforcement)
SOC 2CC6.1, CC6.3
PCI-DSS7.1

Layer 8: Approval Workflows

Purpose: Human-in-the-loop for high-risk actions

Implementation

AspectDetails
StagesMulti-stage with SLA tracking
EscalationAutomatic backup assignment
Levels5 approval levels based on risk

Code Locations

ComponentFile Path
Workflow serviceservices/workflow_approver_service.py
Approval routesroutes/approval_routes.py

Approval Levels

LevelRisk RangeApproverSLA
10-30No approval-
230-50Peer review10 min
350-70Department head15 min
470-80Senior management30 min
580+Executive60 min

FAIL SECURE Behavior

  • Missing approver → DENY
  • Expired SLA → Escalate to backup
  • Invalid workflow → DENY

Test Evidence

  • tests/e2e/test_09_approval_workflows.py - Workflow verification

Compliance Mapping

FrameworkControl
NIST 800-53AC-3 (Access Enforcement)
SOC 2CC5.2

Layer 9: Kill Switch

Purpose: Emergency termination of AI agent activity

Implementation

AspectDetails
PatternCircuit breaker state machine
LatencySub-100ms termination
MessagingSNS/SQS infrastructure

Code Locations

ComponentFile Path
Circuit breakerservices/circuit_breaker_service.py
Kill switch routesroutes/kill_switch_routes.py

State Machine

CLOSED (healthy) ─failure_threshold─→ OPEN (blocked)
↑ │
│ timeout
│ │
└─────── recovery ─────────── HALF_OPEN (testing)
failure│

OPEN (blocked)

Capabilities

FeatureDetails
Block individual agentImmediate effect
Block all org agentsOrganization-wide
Manual overrideForce open/close with audit
PropagationSNS/SQS messaging

FAIL SECURE Behavior

# When circuit is OPEN, all requests denied
if state == CircuitState.OPEN:
return CircuitResult(allowed=False, reason="Circuit breaker OPEN")

Test Evidence

  • tests/e2e/test_12_kill_switch.py - Kill switch verification

Compliance Mapping

FrameworkControl
NIST 800-53IR-4 (Incident Handling)
SOC 2CC7.3 (Incident Response)
NIST AI RMFMANAGE

Layer 10: Audit Trail

Purpose: Immutable logging for compliance and forensics

Implementation

AspectDetails
DesignWORM (Write-Once-Read-Many)
IntegritySHA-256 hash-chaining
Retention7 years (configurable per framework)

Code Locations

ComponentFile Path
Audit serviceservices/immutable_audit_service.py
Audit modelsmodels_audit.py
Audit routesroutes/audit_routes.py

Hash-Chaining

Log Entry N:
content_hash = SHA-256(event_content)
previous_hash = Log Entry N-1.chain_hash
chain_hash = SHA-256(content_hash + previous_hash)

Retention Periods

FrameworkRetention
SOX7 years
HIPAA6 years
PCI-DSS1 year
GDPR6 years
CCPA3 years

FAIL SECURE Behavior

# If audit write fails, block the action
try:
await audit_service.log_event(event)
except Exception:
raise HTTPException(status_code=500, detail="Audit logging failed")

Test Evidence

  • tests/e2e/test_17_audit_trail.py - Audit verification

Compliance Mapping

FrameworkControl
NIST 800-53AU-2, AU-3, AU-9
PCI-DSS10.1, 10.2, 10.3, 10.5
HIPAA164.312(b)
SOC 2CC7.2

Layer 11: BYOK Encryption

Purpose: Customer-controlled encryption keys

Implementation

AspectDetails
PatternEnvelope encryption
KMSAWS KMS integration
AlgorithmAES-256-GCM

Code Locations

ComponentFile Path
BYOK serviceservices/encryption/byok_service.py
BYOK routesroutes/byok_routes.py
BYOK healthservices/encryption/byok_health.py
Exceptionsservices/encryption/byok_exceptions.py

Envelope Encryption

Customer's CMK (AWS KMS Account)

Encrypts DEK (Data Encryption Key)

DEK encrypts actual data (AES-256-GCM)

If customer revokes CMK → Data becomes unreadable (by design)

Features

FeatureDetails
Customer-managed keysFull customer control
Key rotationAutomatic detection (BYOK-011)
Health monitoring15-minute validation cycles
Encryption contextPer-tenant binding

FAIL SECURE Behavior

# services/encryption/byok_service.py
if byok_config["status"] != "active":
raise DataAccessBlocked(
f"Encryption key is not active (status: {byok_config['status']})"
)

# CMK revocation = immediate data inaccessibility
except KeyAccessDenied:
raise KeyAccessDenied(f"Encryption key access revoked")

Test Evidence

  • tests/e2e/test_13_byok_encryption.py - BYOK verification

Compliance Mapping

FrameworkControl
NIST 800-53SC-12, SC-13
PCI-DSS3.5, 3.6
HIPAA164.312(a)(2)(iv)
FedRAMPSC-12, SC-13

Layer 12: Input Validation

Purpose: Ensure data integrity and prevent malformed input

Implementation

AspectDetails
FrameworkPydantic v2
ValidationType, format, size, content
SanitizationHTML, SQL, command injection

Code Locations

ComponentFile Path
Request schemasschemas/*.py
Validation middleware(integrated in FastAPI)

Validation Types

TypeDescription
Type enforcementStrong typing via Pydantic
Required fieldsNon-nullable validation
Format validationEmail, UUID, URL, etc.
Size limitsMax length, max items
Pattern matchingRegex validation
SanitizationXSS, injection prevention

FAIL SECURE Behavior

# Pydantic automatically rejects invalid input
class ActionRequest(BaseModel):
action_type: str = Field(..., min_length=1, max_length=100)
agent_id: UUID

@field_validator("action_type")
def validate_action_type(cls, v):
if not v or not v.strip():
raise ValueError("action_type cannot be empty")
return v.strip()

Test Evidence

  • Covered across all test suites via Pydantic validation

Compliance Mapping

FrameworkControl
NIST 800-53SI-10
CWECWE-20 (Improper Input Validation)
OWASPA03:2021 (Injection)

Defense-in-Depth Verification

Each layer operates independently. Failure of one layer does not compromise others:

Failure ScenarioLayers Still Protecting
Redis downLayers 2-12 (Layer 1 fails secure)
Auth bypass attemptLayers 1, 6-12
Injection attackLayers 1, 4-12
Code execution attemptLayers 1-2, 4-12
Tenant escape attemptLayers 1-6, 8-12
Key compromiseLayers 1-10, 12

Test Coverage Summary

LayerTest SuiteTestsPass Rate
1test_05_rate_limiting15100%
2test_06_prompt_security30100%
3test_07_code_analysis20100%
4test_04_action_evaluation23100%
5test_01_authentication16100%
6test_02_authorization21100%
7test_18_multi_tenant29100%
8test_09_approval_workflows18100%
9test_12_kill_switch32100%
10test_17_audit_trail28100%
11test_13_byok_encryption12100%
12(integrated)-100%
TOTALtest_21_fail_secure36100%

Compliance Framework Summary

FrameworkLayers Covered
SOC 2 Type IIAll 12 layers
PCI-DSS v4.0Layers 1, 3, 5-7, 10-12
HIPAALayers 5-7, 10-11
FedRAMPLayers 1, 5-7, 10-11
NIST 800-53All 12 layers
NIST AI RMFLayers 2-4, 8-10
OWASP LLM Top 10Layers 2-3

Document ID: ASCEND-SECURITY-ARCH-2024-001 Classification: Enterprise Confidential