Home · Developers · Guides · Security

Security

Security

Security subsystem overview

Nova Coder's security subsystem provides a comprehensive security platform with 24 security rules and 34 complete security subsystems covering authentication, authorization, audit logging, secret management, input validation, monitoring, encryption, permissions, rate limiting, testing, policies, incident response, compliance, permission management, dependency scanning, IaC security scanning, container security scanning, SAST/DAST integration, security dashboard, AST-based analysis, dedicated secret scanning, rule validation, data privacy controls, rule sandboxing, AI provider security, scanning cache, pattern cache, AI batch processing, zero trust architecture, ML-based threat detection, behavioral analysis, supply chain security, and ML training data generation.

Overview

The security system has evolved from a basic foundation with static security rule scanning and permission checking to a production-ready security platform. All 15 identified security gaps have been successfully implemented and integrated into the Nova Coder platform.

Security Subsystems

0. Advanced Security System

  • File: novacoder/security/advanced.py
  • Features: Runtime security monitoring, threat detection with multiple types, policy enforcement with rules, compliance reporting for GDPR, HIPAA, PCI DSS, SOC2, ISO27001, threat history tracking, event callbacks for custom handling
  • Components: AdvancedSecurity, Threat, ThreatLevel, ThreatType, SecurityPolicy, PolicyType, PolicyViolation, ComplianceReport, ComplianceStandard
  • Threat Types: ANOMALY, MALWARE, PHISHING, DDOS, INJECTION, XSS, CSRF, BRUTE_FORCE, DATA_EXFILTRATION, PRIVILEGE_ESCALATION
  • Policy Types: ACCESS_CONTROL, DATA_PROTECTION, NETWORK_SECURITY, COMPLIANCE, CUSTOM
  • Compliance Standards: GDPR, HIPAA, PCI_DSS, SOC2, ISO27001

1. Enhanced Security Rules

  • File: novacoder/security/enhanced_rules.py
  • Features: 19 enhanced security rules covering XSS, CSRF, command injection, path traversal, XXE, SSRF, dependency vulnerabilities
  • Custom Rule Language: Define custom security patterns with variable substitution
  • Total Rules: 30 (11 default + 19 enhanced)

2. Dynamic Security Analysis

  • File: novacoder/security/dynamic_analysis.py
  • Features: Runtime vulnerability detection, taint analysis, data flow tracking, runtime security monitoring
  • Components: TaintAnalyzer, DataFlowTracker, RuntimeSecurityMonitor, RuntimeVulnerabilityDetector

3. Authentication and Authorization

  • File: novacoder/security/auth.py
  • Features: User authentication with PBKDF2 password hashing, RBAC with predefined roles, session management with expiration, multi-factor authentication support, user management
  • Components: AuthenticationManager, AuthorizationManager, SessionManager, User, Role

4. Comprehensive Audit Logging

  • File: novacoder/security/audit_logging.py
  • Features: Security event tracking with multiple event types, log aggregation from multiple sources, security analytics for pattern detection, audit trail management with archival capabilities
  • Components: AuditLogger, LogAggregator, SecurityAnalytics, AuditTrailManager

5. Secret Management

  • File: novacoder/security/secret_management.py
  • Features: Secret storage with encryption, secret rotation with configurable intervals, secret encryption with master key, secret access logging for audit trail, API key generation
  • Components: SecretManager, SecretRotationScheduler, Secret, SecretType

6. Input Validation Framework

  • File: novacoder/security/input_validation.py
  • Features: Input validation with multiple rule types, output encoding for HTML/JavaScript/URLs/CSS, input sanitization for various contexts, SQL injection prevention, validation rule library
  • Components: InputValidator, OutputEncoder, Sanitizer, ValidationRule, ValidationResult

7. Security Monitoring

  • File: novacoder/security/monitoring.py
  • Features: Real-time security monitoring, security alerting with threat levels, threat detection (brute force, suspicious IPs, data exfiltration), security dashboards with metrics, security analytics and anomaly detection
  • Components: SecurityMonitor, ThreatDetector, AlertManager, SecurityDashboard, SecurityAlert

8. Encryption Capabilities

  • File: novacoder/security/encryption.py
  • Features: Data encryption at rest, data encryption in transit, key management with rotation, certificate management for SSL/TLS, encryption policies with algorithm selection
  • Components: EncryptionManager, KeyManager, CertificateManager, EncryptionPolicy

9. Enhanced Permission Granularity

  • File: novacoder/security/permissions.py
  • Features: Resource-level permissions, action-specific permissions (READ, WRITE, DELETE, EXECUTE, etc.), time-based permissions with scheduling, context-aware permissions based on conditions, permission inheritance
  • Components: EnhancedPermissionManager, ResourcePermission, TimeBasedPermission, ContextPermission, PermissionAction

10. Rate Limiting

  • File: novacoder/security/rate_limiting.py
  • Features: API rate limiting with token bucket algorithm, authentication rate limiting, operation rate limiting, adaptive rate limiting based on system load, rate limiting configuration
  • Components: RateLimiter, AdaptiveRateLimiter, RateLimitManager, RateLimitConfig

11. Security Testing Framework

  • File: novacoder/security/testing.py
  • Features: Penetration testing tools, vulnerability scanning for code and dependencies, security regression testing, extensible security test suite
  • Components: SecurityTestFramework, VulnerabilityScanner, SecurityTest, SecurityTestResult

12. Security Policy Framework

  • File: novacoder/security/policies.py
  • Features: Security policy enforcement, policy compliance checking, policy violation detection, policy management with default policies
  • Components: PolicyManager, PolicyEnforcement, Policy, PolicyViolation

13. Incident Response System

  • File: novacoder/security/incident_response.py
  • Features: Incident response workflow, automated incident handling, security incident tracking, incident reporting with statistics, response playbooks for common incident types
  • Components: IncidentManager, ResponsePlaybook, Incident, IncidentStatus

14. Security Compliance

  • File: novacoder/security/compliance.py
  • Features: Compliance frameworks (SOC2, HIPAA, GDPR, PCI-DSS, ISO-27001), compliance reporting with scoring, compliance monitoring, compliance automation and dashboards
  • Components: ComplianceManager, ComplianceReport, ComplianceFramework, ComplianceStatus

15. Enhanced Permission Management

  • File: novacoder/security/permission_management.py
  • Features: Permission management UI components, permission templates for common roles, permission auditing with change tracking, permission request workflow with approval, permission analytics with anomaly detection
  • Components: EnhancedPermissionManagementSystem, PermissionTemplateManager, PermissionRequestWorkflow, PermissionAuditor, PermissionAnalytics

16. Dependency Scanning

  • File: novacoder/security/dependency_scanning.py
  • Features: Dependency vulnerability detection for CVEs, outdated package checking, multiple scan sources (requirements.txt, pyproject.toml, pip list), policy compliance validation, comprehensive reporting and JSON export
  • Components: DependencyScanner, DependencyPolicy, DependencyInfo, ScanResult, Vulnerability, SeverityLevel

17. IaC Security Scanning

  • File: novacoder/security/iac_scanning.py
  • Features: Multi-platform IaC scanning for Terraform, Kubernetes, Docker Compose, and CloudFormation, comprehensive security checks, severity classification, remediation recommendations
  • Components: IaCScanner, IaCFinding, IaCScanResult, IaCPlatform, SeverityLevel, CheckCategory

18. Container Security Scanning

  • File: novacoder/security/container_scanning.py
  • Features: Docker image vulnerability scanning, Dockerfile security analysis, compliance scoring, secret detection, layer analysis
  • Components: ContainerScanner, ContainerVulnerability, ContainerImage, ContainerScanResult, VulnerabilityType

19. SAST/DAST Integration

  • File: novacoder/security/sast_dast.py
  • Features: Static application security testing (Bandit, SonarQube), dynamic application security testing (OWASP ZAP, Burp Suite), OWASP Top 10 categorization, compliance scoring
  • Components: SASTScanner, DASTScanner, SASTDASTManager, SecurityFinding, SecurityTestResult, TestType

20. Security Dashboard

  • File: novacoder/security/dashboard.py
  • Features: Real-time security metrics, customizable widgets (overview cards, charts, gauges, tables, alerts), trend analysis, overall compliance score calculation, JSON export/import
  • Components: SecurityDashboardManager, SecurityDashboard, DashboardWidget, SecurityMetric, SecurityTrend

21. AST-Based Security Analysis

  • File: novacoder/security/ast_analysis.py
  • Features: Context-aware security analysis using Python AST, accurate line and column information, detection of code injection, SQL injection, XSS, path traversal, insecure deserialization, weak cryptography, hardcoded credentials, insecure random, SSRF, and XXE
  • Components: ASTSecurityAnalyzer, ASTAnalysisManager, ASTFinding, ASTAnalysisResult, VulnerabilityType, SeverityLevel

22. Dedicated Secret Scanning

  • File: novacoder/security/secret_scanning.py
  • Features: Specialized secret detection for AWS keys, API keys, passwords, tokens, database URLs, JWT tokens, Slack tokens, GitHub tokens, Google API keys, Stripe keys, SendGrid keys, Twitter keys, SSH keys, and private keys, compliance checking, secret masking
  • Components: SecretScanner, SecretFinding, SecretScanResult, SecretScanPolicy, SecretPattern, SecretType

23. Rule Validation System

  • File: novacoder/security/rule_validation.py
  • Features: Comprehensive validation for security rules including syntax validation, security checking, performance analysis, and best practice enforcement. Validates rule ID format, regex pattern syntax, severity levels, and dangerous pattern detection.
  • Components: RuleValidator, RuleValidationManager, ValidationIssue, ValidationResult, ValidationSeverity, ValidationCategory

24. Data Privacy Controls

  • File: novacoder/security/data_privacy.py
  • Features: Data privacy controls with masking and redaction for emails, IP addresses, API keys, and AWS keys. Privacy policy management with multiple privacy levels (public, internal, confidential, restricted), data category classification, and compliance checking.
  • Components: DataPrivacyManager, PrivacyPolicy, DataMaskingRule, PrivacyLevel, DataCategory

25. Rule Sandbox

  • File: novacoder/security/rule_sandbox.py
  • Features: Security sandboxing for custom rules with configurable sandboxing levels (none, basic, strict). Validates custom rules for dangerous modules, functions, and AST constructs. Provides violation tracking and sandbox validation reports.
  • Components: RuleSandbox, RuleSandboxManager, SandboxViolation, SandboxResult, SandboxLevel, RuleOperation

26. AI Provider Security

  • File: novacoder/security/ai_provider_security.py
  • Features: AI provider validation and rate limiting with trusted provider checking, suspicious pattern detection, and configurable validation levels (none, basic, strict). Rate limiting with configurable limits per minute/hour/day, usage statistics, and provider blocking/suspension capabilities.
  • Components: AIProviderValidator, RateLimiter, AIProviderSecurityManager, ProviderStatus, ValidationLevel, RateLimitConfig, ProviderValidation, RateLimitInfo

27. Scanning Cache

  • File: novacoder/security/scanning_cache.py
  • Features: Incremental scanning and caching with file hash-based change detection, configurable caching strategies (none, memory, disk, hybrid), LRU cache eviction, and scan metadata tracking. Supports incremental scanning to only re-scan changed files.
  • Components: ScanningCache, IncrementalScanner, ScanningCacheManager, CacheStrategy, CacheEntry, ScanMetadata

28. Pattern Cache

  • File: novacoder/security/pattern_cache.py
  • Features: Pattern caching and optimization with compiled pattern caching with LRU eviction, pattern optimization (greedy to non-greedy, character class shorthands, redundant escaping), configurable optimization levels (none, basic, aggressive), and batch pattern compilation.
  • Components: PatternCache, PatternOptimizer, PatternCacheManager, OptimizationLevel, CompiledPattern, PatternOptimization

29. AI Batch Processing

  • File: novacoder/security/ai_batch_processor.py
  • Features: Async processing and batching with configurable batching strategies (size-based, time-based, hybrid), priority-based task queuing, concurrent scan limiting, and async directory scanning. Includes batch processing statistics and performance monitoring.
  • Components: BatchProcessor, AsyncAIScanner, AIBatchProcessingManager, BatchStrategy, ProcessingPriority, BatchTask, BatchResult

30. Zero Trust Architecture

  • File: novacoder/security/zero_trust.py
  • Features: Identity and access management with trust levels, device trust verification, mutual TLS for secure communication, continuous verification and monitoring, access request workflow, session management
  • Components: IdentityAccessManager, DeviceTrustManager, MutualTLSManager, ContinuousVerification, Identity, Device, AccessRequest, TrustLevel, DeviceStatus

31. ML Threat Detection

  • File: novacoder/security/ml_threats.py
  • Features: Machine learning-based threat detection with multiple model types (anomaly detection, behavioral analysis, pattern recognition, sequence analysis, classification), model training and prediction, threat scoring, model performance tracking
  • Components: MLThreatDetector, ThreatModel, ModelType, ModelStatus, PredictionResult, ThreatScore

32. Behavioral Analysis

  • File: novacoder/security/behavioral_analysis.py
  • Features: User behavior profiling and anomaly detection, event recording and analysis, alert generation based on behavioral patterns, risk scoring, user profile management
  • Components: BehavioralAnalyzer, UserProfile, EventRecord, Alert, RiskLevel, AlertType

33. Security Automation

  • File: novacoder/security/automation.py
  • Features: Automated security response with rule-based triggers, action execution, event processing, rule management, execution tracking, success rate monitoring
  • Components: SecurityAutomation, AutomationRule, AutomationAction, AutomationTrigger, ActionExecution, ActionType, TriggerType, ActionStatus

34. Supply Chain Security

  • File: novacoder/security/supply_chain.py
  • Features: Software Bill of Materials (SBOM) generation, dependency analysis for security issues, package verification with hash and signature checking, attack path analysis through dependency graph, vulnerability tracking
  • Components: SupplyChainSecurity, SBOM, SBOMComponent, Vulnerability, VulnerabilitySeverity, PackageStatus, AttackPath

35. Compliance Automation

  • File: novacoder/security/compliance_automation.py
  • Features: Compliance rule management for multiple standards (GDPR, HIPAA, PCI DSS, SOC2, ISO27001, NIST, CIS), automated compliance checks, report generation, remediation action management, check function registration
  • Components: ComplianceAutomation, ComplianceRule, ComplianceCheck, ComplianceReport, ComplianceStandard, ComplianceStatus, RemediationAction, RemediationStatus

Components

  • novacoder/security/service.py, SecurityService with regex-based static rules and scan_with_ai() for AI-assisted analysis
  • novacoder/security/agent.py, SecurityAgent that uses AI first and falls back to SecurityService
  • novacoder/security/enhanced_rules.py, Enhanced security rules and custom rule language
  • novacoder/security/dynamic_analysis.py, Runtime vulnerability detection and taint analysis
  • novacoder/security/auth.py, Authentication, authorization, and session management
  • novacoder/security/audit_logging.py, Comprehensive audit logging and analytics
  • novacoder/security/secret_management.py, Secret storage, rotation, and encryption
  • novacoder/security/input_validation.py, Input validation, sanitization, and output encoding
  • novacoder/security/monitoring.py, Real-time security monitoring and alerting
  • novacoder/security/encryption.py, Data encryption, key management, and certificates
  • novacoder/security/permissions.py, Enhanced permission granularity
  • novacoder/security/rate_limiting.py, Rate limiting with adaptive capabilities
  • novacoder/security/testing.py, Security testing framework and vulnerability scanning
  • novacoder/security/policies.py, Security policy framework
  • novacoder/security/incident_response.py, Incident response system
  • novacoder/security/compliance.py, Compliance frameworks (SOC2, HIPAA, GDPR)
  • novacoder/security/permission_management.py, Permission templates, auditing, and analytics
  • novacoder/security/dependency_scanning.py, Dependency vulnerability detection and supply chain security
  • novacoder/security/iac_scanning.py, Infrastructure-as-Code security misconfiguration detection
  • novacoder/security/container_scanning.py, Docker image and Dockerfile security scanning
  • novacoder/security/sast_dast.py, Static and dynamic application security testing
  • novacoder/security/dashboard.py, Security visualization and metrics dashboard
  • novacoder/security/ast_analysis.py, Context-aware security analysis using Python AST
  • novacoder/security/secret_scanning.py, Dedicated secret detection for credentials and sensitive data
  • novacoder/security/rule_validation.py, Security rule validation system for syntax, security, performance, and best practice checking
  • novacoder/security/data_privacy.py, Data privacy controls with masking, redaction, and privacy policy enforcement
  • novacoder/security/rule_sandbox.py, Security sandboxing for custom rules with configurable sandboxing levels
  • novacoder/security/ai_provider_security.py, AI provider validation and rate limiting with trusted provider checking
  • novacoder/security/scanning_cache.py, Incremental scanning and caching with file hash-based change detection
  • novacoder/security/pattern_cache.py, Pattern caching and optimization with compiled pattern caching
  • novacoder/security/ai_batch_processor.py, Async processing and batching for AI security scanning
  • novacoder/security/zero_trust.py, Zero trust architecture with identity management, device trust, and mutual TLS
  • novacoder/security/ml_threats.py, ML-based threat detection with multiple model types
  • novacoder/security/behavioral_analysis.py, User behavior profiling and anomaly detection
  • novacoder/security/automation.py, Automated security response with rule-based triggers
  • novacoder/security/supply_chain.py, Supply chain security with SBOM generation and attack path analysis
  • novacoder/security/compliance_automation.py, Compliance automation for multiple security standards
  • novacoder/security/ml_training_data.py, ML training data generation and management for threat detection models

SecurityService

SecurityService scans source code for known security issues. It is language-agnostic and operates line-by-line with a configurable rule set.

from novacoder.security.service import SecurityService

service = SecurityService()
findings = service.scan_code("import os; os.system('rm -rf /')", language="python")
report = service.aggregate(findings)
print(report["risk_level"], report["recommendations"])

Advanced Security System

The Advanced Security System provides runtime security monitoring, threat detection, policy enforcement, and compliance reporting.

from novacoder.security import AdvancedSecurity, ThreatType, ThreatLevel, PolicyType, ComplianceStandard

# Create advanced security manager
security = AdvancedSecurity()
security.start()

# Threat detection
threat = security.detect_threat(
    threat_type=ThreatType.ANOMALY,
    source='source-1',
    target='target-1',
    description='Unusual activity detected',
    level=ThreatLevel.MEDIUM
)
print(f"Threat ID: {threat.threat_id}")

# Policy management
from novacoder.security.advanced import SecurityPolicy
policy = SecurityPolicy(
    name='Access Control Policy',
    policy_type=PolicyType.ACCESS_CONTROL,
    description='Enforce access control rules'
)
security.add_policy(policy)

# Policy enforcement
context = {'user': 'test', 'action': 'read', 'resource': 'data'}
enforced = security.enforce_policy(policy.policy_id, context)
print(f"Policy enforced: {enforced}")

# Compliance reporting
report = security.generate_compliance_report(ComplianceStandard.GDPR)
print(f"Compliance score: {report.compliance_score}")

# Get security statistics
stats = security.get_security_stats()
print(f"Total threats: {stats['total_threats']}")
print(f"Total policies: {stats['total_policies']}")

security.stop()

Default Rules

Rule ID Severity Issue
DANGEROUS_EVAL high Use of eval()
DANGEROUS_EXEC high Use of exec()
OS_SYSTEM high os.system, os.popen, os.spawn, os.exec
SHELL_TRUE high subprocess.*(..., shell=True)
PICKLE_LOAD high pickle.loads() / pickle.load()
UNSAFE_YAML high yaml.load() without a safe loader
DYNAMIC_IMPORT medium __import__ / importlib.import_module
HARDCODED_SECRET medium Possible hardcoded password / secret / token
SQL_FORMAT medium SQL string formatting (%s, f"...", .format)
INSECURE_TEMP medium tempfile.mktemp()
DEBUG_TRUE low app.run(..., debug=True)

Enhanced Rules

Rule ID Severity Issue
XSS_REFLECTED high Reflected XSS vulnerabilities
XSS_DOM high DOM-based XSS vulnerabilities
CSRF_MISSING_TOKEN high Disabled CSRF protection
CSRF_STATE_CHANGE high State-changing operations without CSRF
COMMAND_INJECTION high Command injection patterns
COMMAND_INJECTION_PIPE high Command chaining
PATH_TRAVERSAL high Path traversal patterns
PATH_TRAVERSAL_USER_INPUT high User-controlled file paths
XXE_VULNERABILITY high XML External Entity vulnerabilities
SSRF_URL_USER_INPUT high SSRF via user input
SSRF_INTERNAL_IP high Internal IP addresses in URLs
OUTDATED_DEPENDENCY medium Potentially outdated dependencies
INSECURE_PROTOCOL medium Insecure HTTP usage
HARDCODED_API_KEY medium Hardcoded API keys
WEAK_CRYPTO medium Weak cryptographic algorithms
RANDOM_NOT_SECURE medium Non-cryptographically secure random
SSL_VERIFICATION_DISABLED medium Disabled SSL verification
INSECURE_COOKIE medium Insecure cookie configuration
INFORMATION_DISCLOSURE low Potential information disclosure

SecurityAgent

SecurityAgent is a built-in agent that scans files from the workspace or from task.context["files"].

Enabling

agents:
  security: true

Or via environment variable:

NOVACODER_AGENTS__SECURITY=true

Usage

from novacoder.agents.agent import AgentTask
from novacoder.agents.service import AgentService

service = AgentService(config)
service.initialize()

task = AgentTask(
    id="scan-1",
    description="Scan for security issues",
    goal="Review project files",
    context={"files": ["app.py"]},
)
result = service.manager.run("security", task)
print(result.output)

AI vs Static Analysis

The agent first delegates to SecurityService.scan_with_ai(), which augments static rule findings with the configured AI provider. If the AI is unavailable or the response is not valid JSON, the agent falls back to SecurityService static scanning. This makes the agent safe to use even when no AI provider is reachable.

Output Format

The agent output follows the same shape whether from AI or static rules:

{
  "risk_level": "high|medium|low",
  "findings": [
    {
      "rule_id": "SHELL_TRUE",
      "file": "app.py",
      "line": 42,
      "severity": "high",
      "issue": "Passing shell=True to subprocess can enable shell injection.",
      "recommendation": "Set shell=False and pass the command as a list of arguments.",
      "match": "subprocess.run('ls', shell=True)",
      "language": "python"
    }
  ],
  "recommendations": [
    "Set shell=False and pass the command as a list of arguments."
  ]
}

Integration

  • The security agent now appears in novacoder agents and the TUI Agents page by default.
  • AgentService.initialize() registers SecurityAgent by default and honors the agents.security flag.
  • AgentManager._register_defaults() also registers security so it is available outside the full service lifecycle.
  • The TUI Chat page loads the agent list dynamically, so security is available when enabled.

Recent Security Improvements (v0.1.0)

API Token Security

  • Token Exposure Resolution: API tokens are no longer exposed in frontend JavaScript
  • Secure Authentication: Token removed from page source to prevent XSS and browser extension access
  • Future Enhancement: HTTP-only cookies recommended for production deployments

Shell Command Hardening

  • Expanded Command Blocking: Additional dangerous commands blocked including process control, user management, and system commands
  • Shell Operator Blocking: Pipes, redirects, and command chaining operators blocked (|, &, ;, $(), `, >, <)
  • Argument Validation: Comprehensive validation for command type, timeout ranges, and working directories
  • Security Logging: All shell commands logged with security context for audit trails
  • Specific Exception Handling: Proper error handling with security-specific error messages

API Protection

  • Rate Limiting: Implemented using slowapi with IP-based client identification
  • Request Validation: Comprehensive Pydantic models with field validators and length constraints
  • Input Sanitization: All API endpoints now validate input against strict schemas
  • Abuse Prevention: Rate limits protect against DoS attacks and API abuse

Database Security

  • WAL Mode: SQLite Write-Ahead Logging enabled for better concurrency and thread safety
  • Busy Timeout: Configured busy timeout for concurrent access handling
  • Comprehensive Logging: All database operations logged for security auditing
  • Thread Safety: Enhanced synchronization with improved locking mechanisms

Security Best Practices

For Users

  • Use the comprehensive security scanning for all code changes
  • Leverage authentication and authorization for access control
  • Monitor security dashboards for threat detection
  • Review audit logs regularly for security events
  • Use secret management for storing sensitive data
  • Implement input validation for all user inputs
  • Enable rate limiting to prevent abuse
  • Use encryption for sensitive data at rest and in transit

For Developers

  • Use the security testing framework for automated security testing
  • Implement security policies for code review
  • Follow incident response playbooks for security incidents
  • Ensure compliance with relevant frameworks (SOC2, HIPAA, GDPR)
  • Use permission templates for consistent access control
  • Monitor compliance dashboards for regulatory requirements
  • Use the dynamic analysis for runtime security testing
  • Implement proper secret rotation policies

Usage Examples

Authentication and Authorization

from novacoder.security.auth import AuthenticationManager, AuthorizationManager

# Create user
auth_manager = AuthenticationManager()
user = auth_manager.create_user("username", "email@example.com", "password")

# Authenticate
authenticated = auth_manager.authenticate("username", "password")

# Check permissions
authz_manager = AuthorizationManager()
has_permission = authz_manager.has_permission(user, "read_files")

Secret Management

from novacoder.security.secret_management import SecretManager

secret_manager = SecretManager()
secret_manager.store_secret("api_key", "secret_value", SecretType.API_KEY)
api_key = secret_manager.get_secret("api_key")

Input Validation

from novacoder.security.input_validation import InputValidator, ValidationRule, ValidationRuleType

validator = InputValidator()
validator.add_rule("email", ValidationRule(
    rule_type=ValidationRuleType.EMAIL,
    error_message="Invalid email"
))
result = validator.validate({"email": "user@example.com"})

Rate Limiting

from novacoder.security.rate_limiting import RateLimitConfig, RateLimitType, RateLimiter

config = RateLimitConfig(
    limit_type=RateLimitType.API,
    max_requests=100,
    window_seconds=60
)
limiter = RateLimiter(config)
result = limiter.check_rate_limit("user_id")

Security Monitoring

from novacoder.security.monitoring import SecurityMonitor, ThreatDetector

monitor = SecurityMonitor()
detector = ThreatDetector()
monitor.get_threat_detector(detector)
monitor.start_monitoring()

Compliance Checking

from novacoder.security.compliance import ComplianceManager, ComplianceFramework

compliance_manager = ComplianceManager()
report = compliance_manager.check_compliance(ComplianceFramework.SOC2)
print(f"Compliance score: {report.compliance_score}")

Integration

  • Service Integration: SecurityService registered in app.py service container
  • UI Integration: SecurityPage in TUI displays all 15 security systems
  • API Integration: Security rules and scanning available via REST API
  • Package Exports: 88 components exported from security package for easy access

TUI Integration

The security system is integrated into the Terminal User Interface (TUI) through the SecurityPage.

SecurityPage Features

The TUI security page provides:

  • Security Systems Overview: Table view of all security subsystems with status and descriptions
  • Security Rules Management: Table view of security rules with rule ID, severity, issue, and pattern
  • Code Scanning: Text area for pasting code to scan for vulnerabilities
  • Language Selection: Input field for specifying programming language for scanning
  • Background Loading: Asynchronous loading of security systems and rules
  • Scan Results: Display of security scan results
  • Refresh Capability: Manual refresh to update security data

Access security in the TUI:

  • Keyboard Shortcut: Shift+F1
  • Sidebar: Click "Security" in the ADVANCED section

Usage Example

# In the TUI, navigate to Security page
# View security systems overview in the systems table
# View security rules in the rules table
# Paste code to scan in the code text area
# Optionally specify the programming language
# Click Scan to perform security analysis
# View scan results in the result box

Service Integration

The SecurityPage integrates with the SecurityService:

from novacoder.security.service import SecurityService

# Security service is accessed via service integration
service = SecurityService(config)
service.initialize()

# Access security rules
rules = service._rules

# Scan code for vulnerabilities
results = service.scan_code(code, language)

Web UI Integration

The security system also provides web interface integration:

  • Security Dashboard: Comprehensive security overview with metrics and alerts
  • Rule Management: Interface for managing security rules and policies
  • Scan Results: Detailed vulnerability reports with remediation suggestions
  • Compliance Dashboard: Compliance status and reporting interface
  • Incident Response: Security incident management interface
  • Audit Logs: Security event log viewer with filtering

API Endpoints

The security system provides REST API endpoints:

  • GET /api/security/rules - List all security rules
  • POST /api/security/scan - Scan code for vulnerabilities
  • GET /api/security/components - Get security systems/component status
  • GET /api/security/compliance/{standard} - Get compliance status for a standard (also /api/security/compliance/reports, /api/security/compliance/statistics)
  • GET /api/security/incidents - List security incidents
  • POST /api/security/incidents - Report security incident
  • GET /api/security/audit - Get security audit logs

Zero Trust Architecture API Endpoints

GET /api/security/threats

List all detected security threats with optional filtering.

Query Parameters: threat_type (optional), level (optional), resolved (optional)

Response:

{
  "threats": [
    {
      "id": "threat-1",
      "type": "MALWARE",
      "level": "HIGH",
      "description": "Malware detected",
      "resolved": false
    }
  ]
}

POST /api/security/threats/{threat_id}/resolve

Resolve a security threat.

Response:

{
  "success": true,
  "resolved": true
}

GET /api/security/policies

List all configured security policies.

Response:

{
  "policies": [
    {
      "policy_id": "policy-1",
      "policy_type": "ACCESS_CONTROL",
      "name": "Access Control Policy",
      "enabled": true
    }
  ]
}

POST /api/security/policies

Add a new security policy.

Response:

{
  "success": true,
  "policy_id": "policy-1"
}

DELETE /api/security/policies/{policy_id}

Remove a security policy.

Response:

{
  "success": true
}

GET /api/security/violations

List policy violations with optional filtering.

Response:

{
  "violations": [
    {
      "violation_id": "violation-1",
      "policy_id": "policy-1",
      "description": "Policy violated",
      "resolved": false
    }
  ]
}

POST /api/security/violations/{violation_id}/resolve

Resolve a policy violation.

Response:

{
  "success": true,
  "resolved": true
}

GET /api/security/compliance/{standard}

Generate a compliance report for a standard (gdpr, hipaa, pci_dss, soc2, iso27001).

Response:

{
  "standard": "GDPR",
  "compliance_score": 85,
  "findings": [ /* compliance findings */ ]
}

GET /api/security/statistics

Get overall security statistics.

Response:

{
  "total_threats": 10,
  "resolved_threats": 8,
  "total_policies": 5,
  "total_violations": 3
}

Web UI Integration

The Security Scan system is fully integrated into the Nova Coder Web UI with a dedicated "Security Scan" navigation item under the Administration section.

Security Scan UI Features

The Security Scan UI provides:

  • Security Rules Display: View all configured security scanning rules with patterns, severity levels, and issue descriptions
  • Code Scanning Interface: Submit code for security vulnerability analysis using configured security rules
  • Dependency Vulnerability Scanning: Scan project dependencies for known vulnerabilities and outdated packages
  • IaC Security Scanning: Scan infrastructure-as-code files (Terraform, Kubernetes) for security misconfigurations
  • Container Security Scanning: Scan Docker images and Dockerfiles for security vulnerabilities
  • SAST Scanning: Run static application security testing on source code using Bandit
  • AST Security Analysis: Run AST-based security analysis on Python files
  • Secret Scanning: Scan for hardcoded secrets and credentials in the project

API Endpoints Used

The Security Scan UI integrates with the following API endpoints:

  • GET /api/security/rules - List all configured security scanning rules
  • POST /api/security/scan - Scan code for security issues
  • GET /api/security/dependency/scan - Scan dependencies for vulnerabilities
  • GET /api/security/iac/scan - Scan IaC files for security issues
  • GET /api/security/container/scan - Scan containers for security issues
  • GET /api/security/sast/scan - Run SAST scan
  • GET /api/security/ast/scan - Run AST security analysis
  • GET /api/security/secret/scan - Scan for hardcoded secrets

UI Navigation

Access the Security Scan UI by:

  1. Navigate to the Administration section in the sidebar
  2. Click on "Security Scan"
  3. The UI displays all security scanning options in a grid layout

JavaScript Integration

The Security Scan UI is implemented in novacoder/web/react/src/pages/Security.tsx with the following functions:

  • renderScan() - Main render function for the Security Scan page
  • loadSecurityRules() - Load and display security rules
  • runSecurityScan() - Execute code security scan
  • runDependencyScan() - Execute dependency vulnerability scan
  • runIaCScan() - Execute IaC security scan
  • runContainerScan() - Execute container security scan
  • runSASTScan() - Execute SAST scan
  • runASTAnalysis() - Execute AST security analysis
  • runSecretScan() - Execute secret scan

Response Handling

The UI handles API responses according to the actual response structure from each endpoint:

  • Security Rules: Expects r.rules array with pattern, severity, issue, and recommendation fields
  • Code Scan: Expects r.findings array with rule, severity, and issue fields
  • Dependency Scan: Expects scan_id, total_dependencies, vulnerable_dependencies, and severity counts
  • IaC Scan: Expects scan_id, platform, files_scanned, total_findings, and severity counts
  • Container Scan: Expects scan_id, image_name, total_vulnerabilities, secrets_found, and severity counts
  • SAST Scan: Expects execution_id, test_type, target, total_findings, and severity counts
  • AST Scan: Expects files_analyzed, total_findings, and severity counts
  • Secret Scan: Expects files_scanned, total_secrets, and severity counts
  • Agents
  • Tools
  • Configuration
  • REST API
  • Memory
  • Security Rules
  • Authentication
  • Audit Logging
  • Secret Management
  • Input Validation
  • Security Monitoring
  • Encryption
  • Permissions
  • Rate Limiting
  • Security Testing
  • Security Policies
  • Incident Response
  • Compliance
  • Permission Management
  • Dependency Scanning
  • IaC Scanning
  • Container Scanning
  • SAST/DAST
  • Security Dashboard
  • AST Analysis
  • Secret Scanning
  • Rule Validation
  • Data Privacy
  • Rule Sandbox
  • AI Provider Security
  • Scanning Cache
  • Pattern Cache
  • AI Batch Processing
  • TUI

Source: wiki/security.md · rendered 2026-11-10