---
title: "HeliosDB Nano Security Hardening Guide"
---

# HeliosDB Nano Security Hardening Guide

---

## Table of Contents

1. [Overview](#overview)
2. [Network Security](#network-security)
3. [Authentication & Authorization](#authentication--authorization)
4. [Data Encryption](#data-encryption)
5. [Access Control](#access-control)
6. [Error Handling & Logging](#error-handling--logging)
7. [Deployment Security](#deployment-security)
8. [Monitoring & Alerting](#monitoring--alerting)
9. [Security Checklist](#security-checklist)
10. [Known Limitations](#known-limitations)

---

## Overview

HeliosDB Nano is a high-performance embedded database optimized for AI workloads. This guide covers security hardening practices for production deployments.

### Security Architecture

- **Embedded Model:** Runs within your application process (shared memory space)
- **No Network Protocol:** Direct in-process API calls
- **PostgreSQL Compatible:** SQL interface using PostgreSQL protocol compliance
- **Rate Limiting:** Built-in rate limiting middleware for API protection

### Threat Model

**Protected Against:**
- External network attacks (no network interface)
- Rate-based attacks (rate limiting enabled)
- Concurrent access issues (MVCC transaction isolation)
- Data corruption (WAL and crash recovery)
- Unauthorized table access (access control)

**Design Assumptions:**
- Application layer provides authentication
- Network layer is protected (firewall/VPC)
- Host access is controlled
- Operating system is patched

---

## Network Security

### 1. Embedded Deployment (Default)

HeliosDB Nano runs embedded within your application:

```rust
use heliosdb_nano::HeliosDB;

// In-process only - no network exposure
let db = HeliosDB::new("./data")?;
let result = db.query("SELECT * FROM users")?;
```

**Security:**
- No external network attack surface
- Direct memory access only
- Isolation through process boundaries

### 2. REST API Protection

When exposing via REST API, implement these controls:

```rust
use heliosdb_nano::api::RateLimitConfig;

// Configure rate limiting
let rate_config = RateLimitConfig {
    max_requests: 1000,      // requests per window
    window_duration: Duration::from_secs(60),
    burst_capacity: 100,
    key_extractor: "client_ip", // rate limit by IP
};
```

**Implementation:**
- Place behind API gateway with authentication
- Enable HTTPS/TLS for all connections
- Implement rate limiting (enabled by default)
- Use VPC/network isolation
- Enable CORS restrictions

---

## Authentication & Authorization

### 1. Application-Level Authentication

HeliosDB Nano does not provide authentication. Implement at application layer:

```rust
// Example: Verify user token before database access
async fn get_user_data(auth_header: &str, db: &HeliosDB) -> Result<Vec<Row>> {
    let user_id = verify_jwt_token(auth_header)?;

    // Query data for authenticated user only
    db.query(&format!("SELECT * FROM users WHERE id = {}", user_id))
}
```

**Best Practices:**
- Use JWT or OAuth2 tokens
- Validate all requests
- Implement request signing
- Rotate credentials regularly

### 2. Data-Level Access Control

Implement row-level security (RLS) in application:

```sql
-- Application enforces user_id filter
SELECT * FROM documents WHERE user_id = $1 AND deleted_at IS NULL;
```

### 3. Administrative Access

Restrict administrative operations:

```rust
// Only allow admin role to execute DDL
if !user.has_role("admin") {
    return Err("Unauthorized: DDL requires admin role");
}

db.execute("CREATE TABLE audit_log (...)")?;
```

---

## Data Encryption

### 1. At-Rest Encryption

HeliosDB Nano stores data in data files. Implement encryption:

```yaml
# Container/VM encryption options:
# - EBS encryption (AWS)
# - Azure Disk Encryption
# - Linux LUKS encryption
# - Filesystem-level encryption (ext4, XFS)
```

**Implementation:**
- Enable full-disk encryption on deployment infrastructure
- Use encrypted volumes for data directory
- Encrypt backups separately
- Maintain separate encryption keys for backups

### 2. In-Transit Encryption

Protect data in transit:

```rust
// HTTPS configuration (when using REST API)
let https_config = HttpsConfig {
    tls_version: "1.3",
    cipher_suites: vec![
        "TLS_AES_256_GCM_SHA384",
        "TLS_CHACHA20_POLY1305_SHA256",
    ],
    certificate: "/path/to/cert.pem",
    private_key: "/path/to/key.pem",
};
```

**Best Practices:**
- Use TLS 1.3 minimum
- Use strong cipher suites
- Implement certificate pinning in SDKs
- Rotate certificates before expiration

### 3. Backup Encryption

```bash
# Encrypt backups with GPG
tar czf database_backup.tar.gz ./data/
gpg --cipher-algo AES256 --symmetric database_backup.tar.gz

# Securely store encryption key separately
```

---

## Access Control

### 1. File System Permissions

```bash
# Restrict data directory permissions
chmod 700 ./data/
chown database_user:database_group ./data/

# Restrict configuration files
chmod 600 ./config.yaml
chown database_user:database_group ./config.yaml
```

### 2. Process-Level Isolation

```dockerfile
# Docker: Run as non-root user
FROM rust:latest
RUN useradd -m -u 1000 heliosdb
USER heliosdb:heliosdb

# Limit capabilities
RUN setcap -r /usr/local/bin/heliosdb-nano
```

### 3. Kubernetes RBAC

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: heliosdb-reader
rules:
- apiGroups: [""]
  resources: ["configmaps"]
  verbs: ["get", "list"]
- apiGroups: [""]
  resources: ["secrets"]
  resourceNames: ["db-encryption-key"]
  verbs: ["get"]
```

---

## Error Handling & Logging

### 1. Secure Error Messages

```rust
// GOOD: Generic error to clients
if database_error {
    return Err("Query execution failed");  // No details
}

// BAD: Detailed errors exposed
return Err(format!("SQL syntax error: {}", sql_error));  // Information leak
```

### 2. Audit Logging

```rust
// Log all administrative operations
audit_log::log_event(AuditEvent {
    timestamp: now(),
    user_id: user.id,
    action: "DROP TABLE users",
    table: "users",
    status: "success",
    source_ip: request.remote_addr(),
});
```

### 3. Security Event Logging

```rust
// Log security-relevant events
log::warn!("Failed authentication attempt from {}", client_ip);
log::error!("Unauthorized access attempt to table {}", table_name);
log::info!("User {} password changed", user_id);
```

---

## Deployment Security

### 1. Environment Configuration

```bash
# Use environment variables for sensitive config
export HELIOSDB_DATA_DIR=/data
export HELIOSDB_ENCRYPTION_KEY=$(cat /run/secrets/db_key)
export HELIOSDB_LOG_LEVEL=info

# Never log sensitive values
LOG_LEVEL=info  # Not: LOG_SECRETS=true
```

### 2. Secrets Management

```yaml
# Use secret management system
apiVersion: v1
kind: Secret
metadata:
  name: heliosdb-secrets
type: Opaque
data:
  encryption-key: base64_encoded_key
  backup-password: base64_encoded_password
```

### 3. Network Isolation

```yaml
# Kubernetes: Restrict network access
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: heliosdb-network-policy
spec:
  podSelector:
    matchLabels:
      app: heliosdb
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: application-tier
    ports:
    - protocol: TCP
      port: 5432
```

---

## Monitoring & Alerting

### 1. Security Metrics

```rust
// Track security-relevant metrics
metrics::counter!("auth_failures", 1);
metrics::gauge!("active_connections", active_count);
metrics::histogram!("query_execution_time", elapsed);
```

### 2. Alert Thresholds

Set up alerts for:
- Authentication failures > 10/minute
- Rate limit exceeded > 5 times/hour
- Unusual query patterns
- Error rate > 1%
- Disk space < 10%

### 3. Log Aggregation

```yaml
# Example: ELK Stack configuration
filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /var/log/heliosdb/security.log
    - /var/log/heliosdb/audit.log

output.elasticsearch:
  hosts: ["elasticsearch:9200"]
```

---

## Security Checklist

### Pre-Deployment

- [ ] Enable HTTPS/TLS for all network endpoints
- [ ] Configure authentication at application layer
- [ ] Implement rate limiting (enabled by default)
- [ ] Enable full-disk encryption
- [ ] Restrict file system permissions (700 on data dir)
- [ ] Configure audit logging
- [ ] Set up security event alerting
- [ ] Review and approve data access patterns
- [ ] Document data sensitivity levels
- [ ] Implement data retention policies

### During Deployment

- [ ] Use encrypted secrets management
- [ ] Deploy behind API gateway with authentication
- [ ] Isolate database service in VPC/network
- [ ] Enable network policies (if using Kubernetes)
- [ ] Verify TLS certificate validity
- [ ] Test rate limiting functionality
- [ ] Verify audit logging works
- [ ] Set up monitoring and alerting
- [ ] Document security configuration
- [ ] Perform security testing

### Post-Deployment

- [ ] Monitor authentication logs for anomalies
- [ ] Review rate limit metrics
- [ ] Audit access patterns regularly
- [ ] Rotate credentials on schedule
- [ ] Test backup and recovery procedures
- [ ] Keep logs for compliance period
- [ ] Review security alerts
- [ ] Update security patches promptly
- [ ] Conduct periodic security audits
- [ ] Train team on security procedures

---

## Known Limitations

In the current release (see [Known Limitations](https://www.heliosdb.com/docs/nano/reference/compatibility/known-limitations/)
for the full list with issue links):

### 1. Authentication is per listener
The PostgreSQL listener supports SCRAM-SHA-256 and password authentication
(`--auth scram-sha-256 --password …`), and trust auth is refused on non-loopback
binds. The MySQL listener is trust-only — the user name is asserted by the
client — so keep `--mysql` on loopback or a trusted network. Roles created with
`CREATE ROLE … LOGIN` cannot yet authenticate with SCRAM
([#49](https://github.com/HeliosDatabase/HeliosDB-Nano/issues/49)), and
`--password` is visible in the process list
([#38](https://github.com/HeliosDatabase/HeliosDB-Nano/issues/38)).

### 2. TLS is offered, not required
`--tls-cert`/`--tls-key` enable TLS, but there is no switch that rejects
plaintext clients ([#53](https://github.com/HeliosDatabase/HeliosDB-Nano/issues/53)).
Require `sslmode=verify-full` on clients or keep the listener on a private
network.

### 3. Encryption at rest has no key rotation
AES-256-GCM encryption at rest is available, under a single static key. Key
rotation is not implemented, and offline tools cannot open an encrypted data
directory ([#45](https://github.com/HeliosDatabase/HeliosDB-Nano/issues/45)).

### 4. Session identity is reported, not enforced
`current_user` reports the authenticated login, but `SET ROLE` /
`SET SESSION AUTHORIZATION` are refused and no privilege decision is made from
the role. Row-Level Security policies are enforced only on the embedded API and
the REPL — not over the PostgreSQL or MySQL wire protocols or REST — so enforce
per-user access control in the application for server deployments.

### 5. Triggers cannot implement audit trails
Trigger bodies do not execute (beyond simple `BEFORE INSERT` row rewrites). Use
the built-in [audit logging](https://www.heliosdb.com/docs/nano/guides/audit_logging/) or write audit rows explicitly in
the same transaction.

### 6. No data masking
Implement data masking at the application layer for sensitive fields.

---

## Compliance

### GDPR Compliance

- Right to be forgotten: Delete row data
- Data portability: Export data as SQL
- Data minimization: Only store necessary data
- Partial: audit trail (implement at the application layer)
- Encryption: AES-256-GCM at rest (no key rotation yet)

### HIPAA Compliance

- Encryption at rest: AES-256-GCM (single static key)
- Encryption in transit: Use HTTPS/TLS
- Partial: access control (implement at the application layer)
- Partial: audit logging (implement at the application layer)
- Not applicable: business associate agreement (embedded)

### SOC 2 Type II

- Availability: MVCC and crash recovery
- Processing integrity: Transaction support
- Partial: confidentiality (AES-256-GCM at rest; TLS offered but not enforceable server-side)
- Partial: privacy (access control at the application level)

---

## Incident Response

### Security Incident Procedure

1. **Detect:** Monitor security alerts and logs
2. **Assess:** Determine scope and impact
3. **Contain:** Limit access to affected data
4. **Investigate:** Review audit logs and metrics
5. **Remediate:** Apply fixes and patches
6. **Recover:** Restore from clean backup if needed
7. **Document:** Record incident details for analysis
8. **Communicate:** Notify affected parties per policy

### Backup Recovery for Compromised Data

```bash
# 1. Stop application
systemctl stop application

# 2. Restore from clean backup
cp /backups/clean-database-20250101.backup ./data/

# 3. Verify integrity (for .heliodump backups, restore with --verify instead of copying)
heliosdb-nano restore --input /backups/clean-database-20250101.heliodump --target ./data --verify

# 4. Restart application
systemctl start application
```

---

## Resources

- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [CWE/SANS Top 25](https://cwe.mitre.org/top25/)
- [PostgreSQL Security](https://www.postgresql.org/docs/current/sql-syntax.html)
- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework)

---

## Support

For security issues, please follow responsible disclosure:

1. Do NOT open public issues for security vulnerabilities
2. Email security@heliosdb.com with details
3. Allow 90 days for response and patching
4. Coordinate disclosure timeline
