Skip to main content

Code Analysis

FieldValue
Document IDASCEND-SEC-004
Version1.0.0
Last UpdatedDecember 19, 2025
AuthorAscend Engineering Team
PublisherOW-KAI Technologies Inc.
ClassificationEnterprise Client Documentation
ComplianceSOC 2 CC6.1/CC6.2, PCI-DSS 7.1/8.3, HIPAA 164.312, NIST 800-53 AC-2/SI-4

Enterprise-grade code pattern detection for AI agent actions.

Overview

ASCEND provides real-time detection of dangerous code patterns in AI agent actions. The service analyzes SQL queries, shell commands, Python scripts, and JavaScript code for security vulnerabilities with compliance mappings to CWE, MITRE ATT&CK, and CVSS.

Architecture

Action Submission


┌─────────────────────────┐
│ CodeAnalysisService │
├─────────────────────────┤
│ 1. Extract code │ ← query, script, command params
│ 2. Detect language │ ← SQL, Python, Shell, JS
│ 3. Load patterns │ ← global + org custom
│ 4. Match patterns │ ← regex analysis
│ 5. Calculate risk │ ← severity_scores from config
│ 6. Block/allow │ ← block_threshold from config
└─────────────────────────┘


Governance Decision

Supported Languages

LanguageDetectionExample Patterns
SQLSELECT, INSERT, DROP, WHERESQL injection, destructive DDL
Pythondef, class, importeval/exec, subprocess, file access
Shellecho, rm, cat, pipesCommand injection, privilege escalation
JavaScriptfunction, const, arrow functionseval, DOM manipulation

Global Patterns (20 patterns)

ASCEND ships with 20 vendor-managed patterns stored in global_code_patterns. Categories:

CategoryDescriptionSeverity Range
injectionSQL injection, command injectionCritical-High
code_executionDynamic code execution (eval, exec)Critical
code_injectionScript injection attemptsCritical
file_accessUnauthorized file operationsHigh-Medium
network_accessOutbound connections, data exfilHigh
data_destructionDROP TABLE, rm -rf, etc.Critical
data_exfiltrationData export, external transmissionHigh
credential_exposurePassword/key/token patternsCritical-High
privilege_escalationsudo, chmod, chown operationsHigh
sandbox_escapeBreakout attempts, dunder accessCritical

Key Patterns

Pattern IDLanguageCategorySeverityCVSS
SQL-001sqlinjectioncritical9.8
SQL-002sqldata_destructioncritical9.1
PY-001pythoncode_executioncritical9.8
PY-002pythoncode_executioncritical9.1
PY-004pythoncode_injectioncritical9.5
SHELL-001shellcode_injectioncritical9.8
SHELL-002shelldata_destructioncritical9.5

Configuration

All configuration is stored in org_code_analysis_config. No hardcoded values.

Default Settings

-- Default configuration created per-organization
enabled = true
mode = 'monitor' -- 'enforce', 'monitor', 'off'
block_threshold = 90 -- Block if risk >= 90
alert_threshold = 50 -- Alert if risk >= 50
escalate_threshold = 70 -- Escalate if risk >= 70

-- Severity scores (configurable per-org)
severity_scores = {
"critical": 95,
"high": 75,
"medium": 50,
"low": 25,
"info": 10
}

-- Language/category filters (empty = all enabled)
enabled_languages = []
enabled_categories = []
disabled_pattern_ids = []

Modes

ModeBehavior
enforceDetect AND block when critical findings exceed threshold
monitorDetect and log, but never block
offDisabled - no analysis performed

Pipeline Integration

Code analysis runs at Step 1.5 in the action submission pipeline:

POST /api/v1/actions/submit
├── Step 1: Risk Enrichment
├── Step 1.5: CODE ANALYSIS ← Here
├── Step 1.6: Prompt Security (Phase 10)
├── Step 2: CVSS Calculation
├── Step 3: Policy Evaluation
└── ...

Usage

Direct Service Usage

from services.code_analysis_service import CodeAnalysisService

service = CodeAnalysisService(db, org_id=1)
result = service.analyze_for_action(
action_type="execute_sql",
parameters={"query": "SELECT * FROM users WHERE id = 1; DROP TABLE users;"},
agent_id="agent-123" # Optional: for agent-specific thresholds
)

if result.blocked:
print(f"Blocked: {result.block_reason}")
else:
print(f"Risk score: {result.max_risk_score}")
for finding in result.findings:
print(f" - {finding.pattern_id}: {finding.description}")

Response Format

{
"code_analysis": {
"analyzed": true,
"language": "sql",
"findings_count": 2,
"max_severity": "critical",
"max_risk_score": 98,
"patterns_matched": ["SQL-001", "SQL-002"],
"blocked": true,
"block_reason": "Critical code pattern detected: SQL-001 - SQL injection vulnerability",
"config_mode": "enforce",
"scan_duration_ms": 12,
"findings": [
{
"pattern_id": "SQL-001",
"severity": "critical",
"category": "injection",
"description": "SQL injection vulnerability",
"matched_text": "'; DROP TABLE users;--",
"line_number": 1,
"cwe_ids": ["CWE-89"],
"mitre_techniques": ["T1190"],
"cvss_base_score": 9.8,
"risk_score": 98
}
]
}
}

Code Parameter Detection

The service automatically extracts code from these parameter names:

ParameterDescription
querySQL queries
sqlSQL statements
codeGeneric code
scriptScript content
commandShell commands
cmdCommand aliases
statementSQL/code statements
expressionExpressions to evaluate
sourceSource code
shellShell scripts
bashBash commands
descriptionMay contain code snippets

Custom Patterns

Organizations can add custom patterns with IDs prefixed CUSTOM-:

# Create custom pattern
pattern = OrgCustomPattern(
organization_id=1,
pattern_id="CUSTOM-PII-001",
language="any",
category="data_exfiltration",
severity="high",
pattern_type="regex",
pattern_value=r"\b\d{3}-\d{2}-\d{4}\b", # SSN pattern
pattern_flags="IGNORECASE",
description="Social Security Number detected",
cwe_ids=["CWE-200"],
mitre_techniques=["T1530"],
cvss_base_score=7.5
)

Pattern Overrides

Disable or adjust global patterns for your organization:

# Create override
override = OrgPatternOverride(
organization_id=1,
pattern_id="SQL-003",
is_disabled=False,
severity_override="medium",
risk_score_override=50,
modified_by=user_id,
modification_reason="False positives for our ORM-generated queries"
)

Agent-Specific Thresholds

Registered agents can have their own risk thresholds via RegisteredAgent.max_risk_threshold. The service uses the minimum of:

  1. org_code_analysis_config.block_threshold
  2. RegisteredAgent.max_risk_threshold

This allows restricting high-risk agents more than the org default.

Compliance

  • CWE-78: OS Command Injection
  • CWE-89: SQL Injection
  • CWE-94: Code Injection
  • CWE-95: Eval Injection
  • CWE-200: Information Exposure
  • MITRE ATT&CK: T1059, T1190, T1071, T1530
  • NIST 800-53: SI-10 (Information Input Validation)
  • SOC 2: CC6.1 (Access Control)

Troubleshooting

Code Not Being Analyzed

-- Check org config
SELECT enabled, mode
FROM org_code_analysis_config
WHERE organization_id = X;

Pattern Not Matching

-- Check if pattern is disabled
SELECT is_disabled
FROM org_pattern_overrides
WHERE organization_id = X AND pattern_id = 'SQL-001';

-- Check language filtering
SELECT enabled_languages
FROM org_code_analysis_config
WHERE organization_id = X;

Performance Issues

  • Normal scan duration: less than 50ms
  • If greater than 100ms, check pattern count and complexity
  • Consider disabling unused languages/categories