HeliosDB v3.0 Security Best Practices
HeliosDB v3.0 Security Best Practices
Comprehensive Security Guide for Production Deployments
Table of Contents
- Security Architecture Overview
- Authentication and Authorization
- Data Encryption
- Row-Level Security
- Data Masking
- Audit Logging
- Network Security
- Compliance
Security Architecture Overview
HeliosDB v3.0 implements defense in depth with multiple security layers:
┌─────────────────────────────────────────────┐│ Application Layer ││ - JWT Authentication ││ - Rate Limiting │└─────────────────────────────────────────────┘ ↓┌─────────────────────────────────────────────┐│ Access Control Layer ││ - Row-Level Security (RLS) ││ - Data Masking ││ - Role-Based Access Control (RBAC) │└─────────────────────────────────────────────┘ ↓┌─────────────────────────────────────────────┐│ Data Layer ││ - Column Encryption ││ - Encryption at Rest (AES-256) ││ - Tamper-Proof Audit Logging │└─────────────────────────────────────────────┘ ↓┌─────────────────────────────────────────────┐│ Network Layer ││ - TLS 1.3 ││ - mTLS (mutual TLS) ││ - Network Isolation │└─────────────────────────────────────────────┘Authentication and Authorization
1. User Authentication
JWT Authentication (Recommended)
use heliosdb::auth::{JwtAuth, JwtConfig};
let jwt_config = JwtConfig { secret: std::env::var("JWT_SECRET")?, algorithm: "HS256", expiration: Duration::from_secs(3600), // 1 hour};
let auth = JwtAuth::new(jwt_config)?;
// Generate tokenlet token = auth.generate_token(user_id, roles).await?;
// Verify tokenlet claims = auth.verify_token(&token).await?;Best Practices
DO:
- Use strong secrets (min 32 bytes, cryptographically random)
- Set short token expiration (1-24 hours)
- Implement token refresh mechanism
- Store secrets in environment variables or secret managers
- Rotate JWT secrets regularly (every 90 days)
❌ DON’T:
- Hardcode secrets in code
- Use weak secrets (dictionary words, predictable patterns)
- Set long expiration times (>24 hours)
- Store tokens in localStorage (use httpOnly cookies)
2. Role-Based Access Control (RBAC)
-- Create rolesCREATE ROLE admin;CREATE ROLE analyst;CREATE ROLE viewer;
-- Grant permissionsGRANT ALL ON DATABASE heliosdb TO admin;GRANT SELECT ON ALL TABLES TO analyst;GRANT SELECT ON public_tables TO viewer;
-- Assign roles to usersGRANT admin TO alice;GRANT analyst TO bob;GRANT viewer TO charlie;
-- Revoke permissionsREVOKE SELECT ON sensitive_data FROM analyst;Role Hierarchy
admin (superuser) ├── data_engineer (full data access) │ ├── analyst (read + limited write) │ └── viewer (read-only) └── developer (schema changes) └── tester (test data only)3. Multi-Factor Authentication (MFA)
use heliosdb::auth::MfaProvider;
// Enable MFAlet mfa = MfaProvider::new()?;let secret = mfa.generate_secret(user_id).await?;
// Verify MFA tokenlet is_valid = mfa.verify_token(user_id, token).await?;Data Encryption
1. Encryption at Rest
Automatic - All data encrypted at rest with AES-256-GCM.
[encryption]at_rest = truealgorithm = "AES-256-GCM"key_rotation_days = 90Key Management
# Generate master keyheliosdb-cli keygen --output master.key
# Rotate encryption keyheliosdb-cli rotate-key --key-id master_key_12. Column-Level Encryption
Encrypt sensitive columns (SSN, credit cards, passwords):
-- Create table with encrypted columnsCREATE TABLE users ( id INTEGER PRIMARY KEY, name VARCHAR(100), email VARCHAR(255) ENCRYPTED, ssn CHAR(11) ENCRYPTED SEARCHABLE, credit_card VARCHAR(19) ENCRYPTED DETERMINISTIC);
-- Query encrypted columns (transparent decryption)SELECT name, email FROM users WHERE email = 'alice@example.com';
-- Rotate encryption keyALTER TABLE users ROTATE KEY FOR COLUMN ssn TO 'new_key_id';Encryption Modes
| Mode | Use Case | Searchable | Order-Preserving |
|---|---|---|---|
| Standard | Maximum security | ❌ | ❌ |
| Deterministic | Equality queries | (exact match) | ❌ |
| Order-Preserving | Range queries | ||
| Searchable | Pattern matching | (LIKE queries) | ❌ |
Recommendations:
- Use Standard for passwords, API keys
- Use Deterministic for SSN, email (equality lookup)
- Use Order-Preserving for dates, amounts (range queries)
- Use Searchable for names, addresses (pattern matching)
3. Encryption in Transit (TLS)
Mandatory TLS 1.3 for all connections:
[network]tls_enabled = truetls_version = "1.3"tls_cert = "/etc/heliosdb/server.crt"tls_key = "/etc/heliosdb/server.key"mtls_enabled = true # Mutual TLS for client authenticationGenerate TLS Certificates
# Self-signed certificate (development)openssl req -x509 -newkey rsa:4096 -keyout server.key -out server.crt -days 365
# Production: Use Let's Encrypt or corporate CAcertbot certonly --standalone -d heliosdb.example.com4. FIPS 140-2 Compliance (Government/Defense)
use heliosdb_security::fips::FipsManager;
// Enable FIPS modelet fips = FipsManager::new(FipsConfig { enabled: true, self_tests: true,}).await?;
// Run power-on self-testsfips.run_power_on_self_tests().await?;
// All crypto operations now FIPS-certifiedfips.encrypt(data, key, FipsAlgorithm::Aes256Gcm).await?;FIPS-certified algorithms:
- AES-256-GCM, AES-256-CBC
- SHA-256, SHA-384, SHA-512
- RSA-2048, RSA-4096
- ECDSA P-256, P-384
Row-Level Security
1. Enable RLS
-- Create tableCREATE TABLE user_data ( id INTEGER PRIMARY KEY, user_id INTEGER, content TEXT);
-- Create policy (users see only their data)CREATE POLICY user_isolation ON user_dataFOR SELECTUSING (user_id = current_user_id());
-- Enable RLSALTER TABLE user_data ENABLE ROW LEVEL SECURITY;2. Multi-Tenant Isolation
-- Tenant isolation policyCREATE POLICY tenant_isolation ON tenant_dataFOR ALLUSING (tenant_id = current_tenant_id());
-- Department isolationCREATE POLICY dept_isolation ON employee_dataFOR SELECTUSING (department = current_user_department());
-- Manager accessCREATE POLICY manager_access ON employee_dataFOR SELECTUSING ( employee_id = current_user_id() OR manager_id = current_user_id());3. Complex Policies
-- Time-based accessCREATE POLICY business_hours ON sensitive_dataFOR SELECTUSING ( EXTRACT(HOUR FROM CURRENT_TIMESTAMP) BETWEEN 9 AND 17 AND EXTRACT(DOW FROM CURRENT_TIMESTAMP) BETWEEN 1 AND 5);
-- IP-based accessCREATE POLICY ip_whitelist ON admin_dataFOR ALLUSING ( current_client_ip() = ANY(ARRAY['10.0.0.0/8', '192.168.1.0/24']));
-- Role-based with data ownershipCREATE POLICY admin_or_owner ON documentsFOR ALLUSING ( current_user_role() = 'admin' OR owner_id = current_user_id());4. RLS Performance Optimization
-- Create index on policy columnsCREATE INDEX idx_user_data_user_id ON user_data(user_id);
-- Use materialized context (avoid repeated function calls)SET heliosdb.current_user_id = 123;Data Masking
1. Dynamic Masking (Per-Query)
-- Create masking ruleCREATE MASKING RULE mask_ssnON users.ssnALGORITHM partial(show_last => 4)FOR ROLE analyst;
-- Analysts see: ***-**-1234SELECT ssn FROM users WHERE id = 1;
-- Admins see: 123-45-1234 (unmasked)2. Masking Algorithms
| Algorithm | Example | Use Case |
|---|---|---|
| Redact | *** | Hide entirely |
| Partial | ***-**-1234 | Show last N chars |
| Hash | a3f5b2c1... | Consistent anonymization |
| Random | 847-29-3851 | Random replacement |
| Shuffle | 214-53-8967 | Scramble digits |
| Tokenize | TOKEN_12345 | Reversible mapping |
| Nullify | NULL | Replace with NULL |
| Pattern | 555-555-5555 | Fixed pattern |
3. PII Auto-Detection
use heliosdb_security::masking::PiiDetector;
let detector = PiiDetector::new();
// Detect PII in textlet pii_types = detector.detect_pii("Email: alice@example.com, SSN: 123-45-6789")?;// Returns: [Email, SSN]
// Auto-mask detected PIIlet masked = detector.auto_mask("SSN: 123-45-6789", MaskingAlgorithm::Partial { show_last: 4 })?;// Returns: "SSN: ***-**-6789"4. Static Masking (Permanent)
-- Permanently mask production data for testingBEGIN;UPDATE users SET email = mask_email(email), ssn = mask_ssn(ssn), phone = mask_phone(phone);COMMIT;Audit Logging
1. Enable Tamper-Proof Audit Logging
use heliosdb_audit::{AuditLogger, AuditConfig};
let config = AuditConfig { log_directory: "/var/log/heliosdb/audit".into(), retention_days: 365, compression: true, encryption: true, blockchain_style_hashing: true,};
let logger = AuditLogger::new(config).await?;2. What Gets Logged
Automatically logged events:
- Authentication (login, logout, failed attempts)
- Authorization (permission checks, role changes)
- Data access (SELECT, INSERT, UPDATE, DELETE)
- Schema changes (CREATE, ALTER, DROP)
- Configuration changes
- Security events (policy violations, encryption key usage)
3. Query Audit Trail
-- View audit logsSELECT timestamp, user_id, operation, table_name, query_text, rows_affectedFROM heliosdb_audit_logWHERE user_id = 123ORDER BY timestamp DESCLIMIT 100;
-- Detect suspicious activitySELECT user_id, COUNT(*) as failed_loginsFROM heliosdb_audit_logWHERE operation = 'LOGIN_FAILED' AND timestamp > NOW() - INTERVAL '1 hour'GROUP BY user_idHAVING COUNT(*) > 5;4. Tamper-Proof Chain Verification
// Verify audit log integritylet is_valid = audit_logger.verify_chain().await?;
if !is_valid { alert!("AUDIT LOG TAMPERING DETECTED");}Network Security
1. Firewall Rules
# Allow only specific IPsiptables -A INPUT -p tcp --dport 5432 -s 10.0.0.0/8 -j ACCEPTiptables -A INPUT -p tcp --dport 5432 -j DROP
# Rate limiting (prevent DDoS)iptables -A INPUT -p tcp --dport 5432 -m limit --limit 100/s -j ACCEPT2. Network Isolation
[network]bind_address = "10.0.1.100" # Internal network onlypublic_access = false
# Multi-region with VPC peering[multi_region]regions = [ { name = "us-east", vpc = "vpc-123", cidr = "10.0.0.0/16" }, { name = "eu-west", vpc = "vpc-456", cidr = "10.1.0.0/16" },]3. Rate Limiting
-- API rate limitingALTER USER analyst SET connection_limit = 10;ALTER USER analyst SET statement_timeout = '30s';ALTER USER analyst SET idle_in_transaction_session_timeout = '60s';
-- Query complexity limitsSET max_parallel_workers_per_gather = 2;SET work_mem = '64MB';Compliance
1. GDPR Compliance
Right to Access:
-- Export all user dataSELECT * FROM users WHERE user_id = 123UNION ALLSELECT * FROM orders WHERE user_id = 123UNION ALLSELECT * FROM preferences WHERE user_id = 123;Right to Erasure (Right to be Forgotten):
-- Permanently delete user dataBEGIN;DELETE FROM users WHERE user_id = 123;DELETE FROM orders WHERE user_id = 123;DELETE FROM audit_log WHERE user_id = 123;COMMIT;Data Minimization:
-- Enable data masking for unnecessary PIICREATE MASKING RULE gdpr_email_maskON users.emailALGORITHM hashFOR ROLE analyst;2. HIPAA Compliance
Required Controls:
- Encryption at rest (AES-256)
- Encryption in transit (TLS 1.3)
- Access control (RLS)
- Audit logging (tamper-proof)
- Data masking (de-identification)
Configuration:
[hipaa]encryption_at_rest = trueaudit_logging = trueaccess_control = "strict"data_retention_days = 2555 # 7 years3. PCI-DSS Compliance
Cardholder Data Protection:
-- Encrypt credit card dataCREATE TABLE payments ( id INTEGER PRIMARY KEY, card_number VARCHAR(19) ENCRYPTED DETERMINISTIC, cvv CHAR(3) ENCRYPTED, expiry_date DATE ENCRYPTED);
-- Mask for non-privileged usersCREATE MASKING RULE pci_card_maskON payments.card_numberALGORITHM partial(show_last => 4)FOR ROLE developer;4. SOC 2 Compliance
Key Controls:
- Access control (RBAC, RLS)
- Audit logging (comprehensive)
- Encryption (at rest, in transit)
- Change management (schema versioning)
- Incident response (alerting, monitoring)
-- View compliance dashboardSELECT control_name, status, last_audit_date, compliance_percentageFROM heliosdb_compliance_dashboardWHERE framework = 'SOC2';Security Checklist
Deployment Checklist
- Enable TLS 1.3 for all connections
- Use strong JWT secrets (>32 bytes)
- Enable encryption at rest (AES-256)
- Configure column encryption for sensitive data
- Enable row-level security (RLS)
- Configure data masking rules
- Enable tamper-proof audit logging
- Set up firewall rules (IP whitelist)
- Enable rate limiting
- Configure secure backup encryption
- Set up monitoring and alerting
- Rotate encryption keys every 90 days
- Review and update access policies monthly
Development Checklist
- Never hardcode secrets in code
- Use environment variables for configuration
- Implement least privilege access
- Validate all user inputs
- Use parameterized queries (prevent SQL injection)
- Log security events
- Implement MFA for admin accounts
- Regular security audits
- Penetration testing before production
- Security training for team
Monitoring Checklist
- Monitor failed login attempts
- Alert on privilege escalation
- Track data access patterns
- Monitor encryption key usage
- Alert on policy violations
- Track audit log integrity
- Monitor for SQL injection attempts
- Alert on anomalous queries
Incident Response
1. Detect Security Incidents
-- Failed login attemptsSELECT user_id, COUNT(*) as attemptsFROM heliosdb_audit_logWHERE operation = 'LOGIN_FAILED' AND timestamp > NOW() - INTERVAL '1 hour'GROUP BY user_idHAVING COUNT(*) > 5;
-- Privilege escalationSELECT * FROM heliosdb_audit_logWHERE operation = 'GRANT_ROLE' AND new_role IN ('admin', 'superuser');
-- Suspicious queriesSELECT * FROM heliosdb_slow_queriesWHERE query_text LIKE '%DROP%' OR query_text LIKE '%DELETE FROM%'ORDER BY execution_count DESC;2. Respond to Incidents
# Revoke access immediatelyheliosdb-cli revoke-user --user compromised_user
# Rotate encryption keysheliosdb-cli rotate-key --all
# Export audit logs for forensicsheliosdb-cli export-audit-logs --start "2025-01-01" --end "2025-01-31"
# Lock database (emergency)heliosdb-cli lock-database --reason "Security incident"3. Recovery Procedures
# Restore from backup (encrypted)heliosdb-cli restore --backup /backups/20250112.tar.gz.enc --decrypt
# Verify data integrityheliosdb-cli verify --full
# Re-enable accessheliosdb-cli unlock-databaseSecurity Resources
Documentation
Tools
External Resources
- OWASP Database Security Cheat Sheet
- NIST Cybersecurity Framework
- CIS Benchmarks for Databases
Support
Security Issues: security@heliosdb.com (PGP key: [link]) Enterprise Support: enterprise@heliosdb.com Bug Bounty Program: https://heliosdb.com/security/bounty