HeliosDB WASM Security Model
HeliosDB WASM Security Model
Overview
HeliosDB implements a multi-layered security model for stored procedures combining:
- Capability-based security
- Resource isolation
- Syscall filtering
- Audit logging
- WASM sandboxing
Security Layers
Layer 1: WASM Sandbox
All non-native code runs in WebAssembly sandboxes providing:
- Memory isolation
- No direct system access
- Controlled host function access
- Stack overflow protection
Layer 2: Capability-Based Access Control
Functions must explicitly request capabilities to perform operations:
-- Minimal permissions (default)CREATE FUNCTION read_only_function(id INTEGER)RETURNS JSONLANGUAGE javascriptAS $$ function read_only_function(id) { // Can only perform computations // No database, file, or network access return { id: id, processed: true }; }$$;
-- With database read permissionALTER FUNCTION user_lookupGRANT CAPABILITY DATABASE_READ('users');
-- With database write permissionALTER FUNCTION update_userGRANT CAPABILITY DATABASE_WRITE('users');Layer 3: Resource Limits
Every function execution is bounded by:
| Resource | Default Limit | Max Limit |
|---|---|---|
| Memory | 16MB (JS), 32MB (Python) | 128MB |
| CPU Time | 5 seconds | 60 seconds |
| Wall Time | 10 seconds | 120 seconds |
| Instructions | 10 billion | 100 billion |
| Stack Size | 2MB | 8MB |
| File Handles | 10 | 100 |
| Network Connections | 5 | 50 |
Layer 4: Syscall Filtering
Functions can only call allowed system calls:
Default allowed syscalls:
clock_time_get- Get current timerandom_get- Generate random bytesproc_exit- Exit processenviron_get- Get environment variablesenviron_sizes_get- Get environment sizes
Additional syscalls require explicit permissions.
Layer 5: Audit Logging
All security-relevant operations are logged:
-- View audit logSELECT * FROM heliosdb.audit_logWHERE function_name = 'sensitive_function'ORDER BY timestamp DESC;Logged events:
- Function execution (start/complete/fail)
- Capability checks (granted/denied)
- Resource limit violations
- Database operations
- File system operations
- Network operations
- Syscall attempts
Capability Reference
Database Capabilities
-- Read from all tablesGRANT CAPABILITY DATABASE_READ('*');
-- Read from specific tableGRANT CAPABILITY DATABASE_READ('users');
-- Read from tables matching patternGRANT CAPABILITY DATABASE_READ('user_*');
-- Write to specific tableGRANT CAPABILITY DATABASE_WRITE('audit_log');
-- Execute DDL operationsGRANT CAPABILITY DATABASE_EXECUTE;File System Capabilities
-- Read files in specific directoryGRANT CAPABILITY FILE_READ('/tmp/uploads/*');
-- Write to specific directoryGRANT CAPABILITY FILE_WRITE('/var/log/app/*');
-- No recursive access by default-- /tmp/uploads/* allows /tmp/uploads/file.txt-- but NOT /tmp/uploads/subdir/file.txtNetwork Capabilities
-- Access specific hostGRANT CAPABILITY NETWORK_ACCESS('api.example.com');
-- Access hosts matching patternGRANT CAPABILITY NETWORK_ACCESS('*.example.com');
-- Access any host (not recommended)GRANT CAPABILITY NETWORK_ACCESS('*');System Capabilities
-- Access environment variablesGRANT CAPABILITY ENV_ACCESS;
-- Access system timeGRANT CAPABILITY TIME_ACCESS;
-- Generate random numbersGRANT CAPABILITY RANDOM_ACCESS;
-- Perform cryptographic operationsGRANT CAPABILITY CRYPTO_ACCESS;
-- Make HTTP requestsGRANT CAPABILITY HTTP_CLIENT;Function Call Capabilities
-- Call specific functionGRANT CAPABILITY CALL_FUNCTION('helper_function');
-- Call functions matching patternGRANT CAPABILITY CALL_FUNCTION('util_*');Security Policies
Predefined Policies
-- Minimal policy (no capabilities)ALTER FUNCTION my_functionSET SECURITY POLICY MINIMAL;
-- Default policy (basic capabilities)ALTER FUNCTION my_functionSET SECURITY POLICY DEFAULT;
-- Permissive policy (most capabilities, higher limits)ALTER FUNCTION my_functionSET SECURITY POLICY PERMISSIVE;Custom Policies
-- Create custom security policyCREATE SECURITY POLICY strict_read_only AS ( capabilities: [DATABASE_READ('public_*'), TIME_ACCESS], max_memory_bytes: 4194304, -- 4MB max_cpu_time_ms: 1000, max_wall_time_ms: 2000, audit_logging: true, allowed_syscalls: ['clock_time_get']);
-- Apply to functionALTER FUNCTION public_querySET SECURITY POLICY strict_read_only;Security Best Practices
1. Principle of Least Privilege
Grant only the minimum capabilities required:
-- BAD: Overly permissiveALTER FUNCTION process_dataGRANT CAPABILITY DATABASE_READ('*');GRANT CAPABILITY DATABASE_WRITE('*');GRANT CAPABILITY NETWORK_ACCESS('*');
-- GOOD: Specific permissionsALTER FUNCTION process_dataGRANT CAPABILITY DATABASE_READ('input_data');GRANT CAPABILITY DATABASE_WRITE('processed_data');2. Input Validation
Always validate inputs in functions:
function update_user_email(user_id, email) { // Validate user_id if (typeof user_id !== 'number' || user_id < 1) { throw new Error('Invalid user ID'); }
// Validate email if (typeof email !== 'string' || !email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) { throw new Error('Invalid email format'); }
// Prevent SQL injection by using parameterized queries heliosdb.execute( 'UPDATE users SET email = ? WHERE id = ?', [email, user_id] );}3. Output Sanitization
Sanitize data before returning:
function get_user_info(user_id) { const user = heliosdb.query( 'SELECT * FROM users WHERE id = ?', [user_id] ).rows[0];
// Don't expose sensitive fields return { id: user.id, name: user.name, email: user.email, // Exclude: password_hash, ssn, etc. };}4. Rate Limiting
Implement rate limiting for resource-intensive functions:
function expensive_analysis(data) { // Check rate limit using heliosdb.storage const last_call = heliosdb.storage.get('last_expensive_call'); const now = Date.now();
if (last_call && (now - last_call) < 60000) { throw new Error('Rate limit: wait 60 seconds between calls'); }
heliosdb.storage.set('last_expensive_call', now);
// Perform analysis...}5. Secure Secrets Management
Never hardcode secrets:
// BAD: Hardcoded secretfunction api_call() { const api_key = 'sk_live_abc123...'; // Don't do this!}
// GOOD: Use environment variablesfunction api_call() { const api_key = heliosdb.env.get('API_KEY'); if (!api_key) { throw new Error('API_KEY not configured'); }}Threat Model
Prevented Threats
- Memory Corruption - WASM sandbox prevents buffer overflows
- Arbitrary Code Execution - Sandboxing prevents unsafe operations
- Resource Exhaustion - Resource limits prevent DoS
- Data Exfiltration - Capability system controls data access
- Privilege Escalation - Capability-based permissions
- SQL Injection - Parameterized query enforcement
Mitigation Strategies
Sandbox Escape Attempts
All syscalls are filtered and logged:
[AUDIT] Syscall attempted: openFunction: untrusted_functionAllowed: falseAction: Blocked, logged, incremented violation counterAfter 5 violations, function is automatically disabled.
Resource Exhaustion
// This will be terminated after hitting CPU time limitfunction infinite_loop() { while (true) { // CPU time limit (5s default) will kill this }}Memory allocations are tracked:
// This will be terminated after hitting memory limitfunction memory_bomb() { const huge_array = new Array(100000000); // Memory limit (16MB default) will kill this}Time-of-Check to Time-of-Use (TOCTOU)
Capabilities are checked at execution time:
function check_and_execute() { // Capabilities checked here (atomic) heliosdb.query('SELECT * FROM users');}Security Monitoring
Audit Log Analysis
-- Find denied capability checksSELECT *FROM heliosdb.audit_logWHERE event_type = 'CapabilityCheck' AND allowed = falseORDER BY timestamp DESCLIMIT 100;
-- Find resource limit violationsSELECT *FROM heliosdb.audit_logWHERE event_type = 'ResourceLimitExceeded'ORDER BY timestamp DESC;
-- Function execution failuresSELECT function_name, COUNT(*) as failure_count, MIN(timestamp) as first_failure, MAX(timestamp) as last_failureFROM heliosdb.audit_logWHERE event_type = 'ExecutionFailed'GROUP BY function_nameORDER BY failure_count DESC;Security Alerts
Configure alerts for security events:
-- Alert on repeated capability denialsCREATE TRIGGER security_alert_capability_denialAFTER INSERT ON heliosdb.audit_logFOR EACH ROWWHEN (NEW.event_type = 'CapabilityCheck' AND NEW.allowed = false)BEGIN SELECT heliosdb.alert( 'security', 'Capability denied for function: ' || NEW.function_name );END;Compliance
GDPR Compliance
- Right to Access: Audit logs track data access
- Right to Erasure: Functions cannot cache user data without consent
- Data Minimization: Capability system enforces minimum data access
- Purpose Limitation: Functions declared with specific purposes
SOC 2 Compliance
- Access Control: Capability-based permissions
- Audit Logging: Comprehensive event logging
- Monitoring: Real-time security event detection
- Encryption: Data encrypted in transit and at rest
Security Checklist
Before deploying a function to production:
- Minimum required capabilities granted
- Input validation implemented
- Output sanitization implemented
- Resource limits configured appropriately
- Audit logging enabled
- Security policy reviewed
- Code reviewed for vulnerabilities
- Tested with malicious inputs
- Rate limiting implemented (if applicable)
- Error messages don’t leak sensitive info
- Dependencies vetted for security issues
- Compliance requirements met
Incident Response
Security Incident Procedure
- Detect: Monitor audit logs for anomalies
- Contain: Disable affected functions immediately
- Investigate: Analyze audit logs and execution traces
- Remediate: Fix vulnerabilities, update functions
- Review: Update security policies and procedures
Disabling Compromised Functions
-- Immediately disable functionALTER FUNCTION compromised_functionSET ENABLED = false;
-- Review audit logSELECT * FROM heliosdb.audit_logWHERE function_name = 'compromised_function'ORDER BY timestamp DESC;
-- After fixing, re-enable with stricter policyALTER FUNCTION compromised_functionSET SECURITY POLICY MINIMAL;
ALTER FUNCTION compromised_functionSET ENABLED = true;Conclusion
HeliosDB’s multi-layered security model provides defense-in-depth protection for stored procedures. By combining WASM sandboxing, capability-based access control, resource limits, and comprehensive audit logging, it ensures that user-defined functions cannot compromise system security or data integrity.
Always follow the principle of least privilege and regularly review audit logs to maintain a secure system.