---
title: "HeliosDB WASM Security Model"
---

# HeliosDB WASM Security Model

:::caution[Planned design: not yet available in the server]
The current `heliosdb-full` server does not run WASM or polyglot (JavaScript,
Python, Rust) stored procedures: the WASM runtime is not wired into the server.
This page describes the design for this upcoming feature, and its SQL (for
example `LANGUAGE wasm`, security profiles and syscall filters) is not accepted
by the current server. Only the
[Go SDK](/docs/full/guides/features/wasm_procedures_language_sdks/#go-sdk) is
published. See the
[WASM Procedures Quick Start](/docs/full/guides/features/wasm_procedures_quick_start/)
for what works today.
:::

## Overview

The planned security model for stored procedures combines several layers:
- 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:

```sql
-- Planned syntax for the upcoming WASM procedures feature; the current server does not accept it.
-- Minimal permissions (default)
CREATE FUNCTION read_only_function(id INTEGER)
RETURNS JSON
LANGUAGE javascript
AS $$
    function read_only_function(id) {
        // Can only perform computations
        // No database, file, or network access
        return { id: id, processed: true };
    }
$$;

-- With database read permission
ALTER FUNCTION user_lookup
GRANT CAPABILITY DATABASE_READ('users');

-- With database write permission
ALTER FUNCTION update_user
GRANT 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 time
- `random_get` - Generate random bytes
- `proc_exit` - Exit process
- `environ_get` - Get environment variables
- `environ_sizes_get` - Get environment sizes

Additional syscalls require explicit permissions.

### Layer 5: Audit Logging

All security-relevant operations are logged:

```sql
-- View audit log
SELECT * FROM heliosdb.audit_log
WHERE 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

```sql
-- Read from all tables
GRANT CAPABILITY DATABASE_READ('*');

-- Read from specific table
GRANT CAPABILITY DATABASE_READ('users');

-- Read from tables matching pattern
GRANT CAPABILITY DATABASE_READ('user_*');

-- Write to specific table
GRANT CAPABILITY DATABASE_WRITE('audit_log');

-- Execute DDL operations
GRANT CAPABILITY DATABASE_EXECUTE;
```

### File System Capabilities

```sql
-- Read files in specific directory
GRANT CAPABILITY FILE_READ('/tmp/uploads/*');

-- Write to specific directory
GRANT CAPABILITY FILE_WRITE('/var/log/app/*');

-- No recursive access by default
-- /tmp/uploads/* allows /tmp/uploads/file.txt
-- but NOT /tmp/uploads/subdir/file.txt
```

### Network Capabilities

```sql
-- Access specific host
GRANT CAPABILITY NETWORK_ACCESS('api.example.com');

-- Access hosts matching pattern
GRANT CAPABILITY NETWORK_ACCESS('*.example.com');

-- Access any host (not recommended)
GRANT CAPABILITY NETWORK_ACCESS('*');
```

### System Capabilities

```sql
-- Access environment variables
GRANT CAPABILITY ENV_ACCESS;

-- Access system time
GRANT CAPABILITY TIME_ACCESS;

-- Generate random numbers
GRANT CAPABILITY RANDOM_ACCESS;

-- Perform cryptographic operations
GRANT CAPABILITY CRYPTO_ACCESS;

-- Make HTTP requests
GRANT CAPABILITY HTTP_CLIENT;
```

### Function Call Capabilities

```sql
-- Call specific function
GRANT CAPABILITY CALL_FUNCTION('helper_function');

-- Call functions matching pattern
GRANT CAPABILITY CALL_FUNCTION('util_*');
```

## Security Policies

### Predefined Policies

```sql
-- Minimal policy (no capabilities)
ALTER FUNCTION my_function
SET SECURITY POLICY MINIMAL;

-- Default policy (basic capabilities)
ALTER FUNCTION my_function
SET SECURITY POLICY DEFAULT;

-- Permissive policy (most capabilities, higher limits)
ALTER FUNCTION my_function
SET SECURITY POLICY PERMISSIVE;
```

### Custom Policies

```sql
-- Planned syntax for the upcoming WASM procedures feature; the current server does not accept it.
-- Create custom security policy
CREATE 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 function
ALTER FUNCTION public_query
SET SECURITY POLICY strict_read_only;
```

## Security Best Practices

### 1. Principle of Least Privilege

Grant only the minimum capabilities required:

```sql
-- BAD: Overly permissive
ALTER FUNCTION process_data
GRANT CAPABILITY DATABASE_READ('*');
GRANT CAPABILITY DATABASE_WRITE('*');
GRANT CAPABILITY NETWORK_ACCESS('*');

-- GOOD: Specific permissions
ALTER FUNCTION process_data
GRANT CAPABILITY DATABASE_READ('input_data');
GRANT CAPABILITY DATABASE_WRITE('processed_data');
```

### 2. Input Validation

Always validate inputs in functions:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
// BAD: Hardcoded secret
function api_call() {
    const api_key = 'sk_live_abc123...';  // Don't do this!
}

// GOOD: Use environment variables
function api_call() {
    const api_key = heliosdb.env.get('API_KEY');
    if (!api_key) {
        throw new Error('API_KEY not configured');
    }
}
```

## Threat Model

### Prevented Threats

1. **Memory Corruption** - WASM sandbox prevents buffer overflows
2. **Arbitrary Code Execution** - Sandboxing prevents unsafe operations
3. **Resource Exhaustion** - Resource limits prevent DoS
4. **Data Exfiltration** - Capability system controls data access
5. **Privilege Escalation** - Capability-based permissions
6. **SQL Injection** - Parameterized query enforcement

### Mitigation Strategies

#### Sandbox Escape Attempts

All syscalls are filtered and logged:

```
[AUDIT] Syscall attempted: open
Function: untrusted_function
Allowed: false
Action: Blocked, logged, incremented violation counter
```

After 5 violations, function is automatically disabled.

#### Resource Exhaustion

```javascript
// This will be terminated after hitting CPU time limit
function infinite_loop() {
    while (true) {
        // CPU time limit (5s default) will kill this
    }
}
```

Memory allocations are tracked:

```javascript
// This will be terminated after hitting memory limit
function 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:

```javascript
function check_and_execute() {
    // Capabilities checked here (atomic)
    heliosdb.query('SELECT * FROM users');
}
```

## Security Monitoring

### Audit Log Analysis

```sql
-- Find denied capability checks
SELECT *
FROM heliosdb.audit_log
WHERE event_type = 'CapabilityCheck'
  AND allowed = false
ORDER BY timestamp DESC
LIMIT 100;

-- Find resource limit violations
SELECT *
FROM heliosdb.audit_log
WHERE event_type = 'ResourceLimitExceeded'
ORDER BY timestamp DESC;

-- Function execution failures
SELECT
    function_name,
    COUNT(*) as failure_count,
    MIN(timestamp) as first_failure,
    MAX(timestamp) as last_failure
FROM heliosdb.audit_log
WHERE event_type = 'ExecutionFailed'
GROUP BY function_name
ORDER BY failure_count DESC;
```

### Security Alerts

Configure alerts for security events:

```sql
-- Alert on repeated capability denials
CREATE TRIGGER security_alert_capability_denial
AFTER INSERT ON heliosdb.audit_log
FOR EACH ROW
WHEN (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

1. **Detect**: Monitor audit logs for anomalies
2. **Contain**: Disable affected functions immediately
3. **Investigate**: Analyze audit logs and execution traces
4. **Remediate**: Fix vulnerabilities, update functions
5. **Review**: Update security policies and procedures

### Disabling Compromised Functions

```sql
-- Immediately disable function
ALTER FUNCTION compromised_function
SET ENABLED = false;

-- Review audit log
SELECT * FROM heliosdb.audit_log
WHERE function_name = 'compromised_function'
ORDER BY timestamp DESC;

-- After fixing, re-enable with stricter policy
ALTER FUNCTION compromised_function
SET SECURITY POLICY MINIMAL;

ALTER FUNCTION compromised_function
SET 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.
