ɳSelfɳSELFDOCS
  • Getting Started

    • Introduction
    • Quick Start
    • Installation
    • Your First Project
  • Core Concepts

    • Architecture Overview
    • Project Structure
    • Configuration
    • Environments
  • Services

    • PostgreSQL Database
    • Hasura GraphQL
    • Authentication
    • Real-Time Communication
    • Storage (MinIO)
    • Email Configuration
    • Redis Cache
    • Search Engines
    • Functions
    • MLflow (ML Tracking)
    • Monitoring & Metrics
    • Admin UI
    • Dashboard
  • Database Tools

    • Schema Management
    • Migrations
    • Seeding Data
    • Backup & Restore
    • dbdiagram.io Sync
  • Microservices

    • NestJS Services
    • BullMQ Workers
    • Go Services
    • Python Services
  • CLI Reference

    • Complete Command Reference
    • Core Commands
    • Database Commands
    • Service Management
    • Production Commands
  • Deployment

    • Local Development
    • Production Setup
    • SSL/TLS Configuration
    • Domain Configuration
    • Environment Variables
  • Advanced Topics

    • Multi-Tenancy & SaaS
    • Security & Hardening
    • Custom Actions
    • Webhooks
    • Performance Tuning
    • Troubleshooting
  • Migration Guides

    • From Supabase
    • From Nhost
    • From Firebase
  • Resources

    • Changelog
    • Licensing
    • FAQ
    • Contributing
    • Support

Security Best Practices


v0.9.5Security Hardening ReleaseUpdated for ɳSelf v0.9.5

Security is a top priority in nself deployments. Version 0.9.5 is a major security hardening release that fixes all known SQL injection vulnerabilities, implements comprehensive dependency scanning, adds Content Security Policy support, and introduces an automated security audit system.

v0.9.5 Security Highlights

  • All SQL injection vulnerabilities fixed - 100% secure database operations
  • 85+ input validation functions - Comprehensive validation library
  • Automated dependency scanning - ShellCheck, Gitleaks, Trivy, Semgrep
  • Content Security Policy - 3 modes (strict, moderate, permissive)
  • 6-layer file upload security - Complete protection against malicious uploads
  • OWASP Top 10 compliance - Industry-standard security practices

Security Disclaimer

Security is a shared responsibility. While ɳSelf provides secure defaults and hardening tools, you are responsible for proper configuration, regular updates, and monitoring of your deployments.

Security Quick Start

# Run comprehensive security audit (NEW in v0.9.5)
ɳSelf security audit

# Check production security
ɳSelf prod check

# Apply all security hardening
ɳSelf prod harden

# Generate strong secrets
ɳSelf prod secrets generate

# Configure SSL
ɳSelf prod ssl request yourdomain.com

# Configure firewall
ɳSelf prod firewall configure

# Scan dependencies for vulnerabilities (NEW in v0.9.5)
ɳSelf security scan

v0.9.5 Security Features

1. SQL Injection Prevention

All SQL injection vulnerabilities have been fixed in v0.9.5. The CLI now uses parameterized queries and proper input validation for all database operations.

# All these operations are now SQL-injection safe:
nself db create myapp_production
nself db user create myuser --password "SecurePass123!"
nself db exec "SELECT * FROM users WHERE email = $1" "user@example.com"
nself db backup --name "backup-$(date +%Y%m%d)"

# Input validation catches malicious input:
nself db create "mydb'; DROP TABLE users; --"
# Error: Invalid database name. Only alphanumeric and underscore allowed.

# Environment variable expansion is safe:
nself db create "$DB_NAME"  # Properly escaped and validated

Input Validation Library

ɳSelf v0.9.5 includes 85+ validation functions covering database names, usernames, passwords, domains, ports, file paths, and more. All user input is validated before being used in commands or queries.

2. Content Security Policy (CSP)

Configure Content Security Policy headers to prevent XSS attacks and unauthorized resource loading. Choose from 3 preset modes or customize your own policy.

# Enable CSP with strict mode (recommended for production)
CSP_MODE=strict
CSP_ENABLED=true

# CSP modes available:
# - strict: Maximum security, inline scripts blocked
# - moderate: Balanced security, allows some inline scripts with nonces
# - permissive: Relaxed mode for development

# Strict mode configuration (default in production):
CSP_DEFAULT_SRC="'self'"
CSP_SCRIPT_SRC="'self'"
CSP_STYLE_SRC="'self'"
CSP_IMG_SRC="'self' data: https:"
CSP_CONNECT_SRC="'self' wss:"
CSP_FONT_SRC="'self'"
CSP_OBJECT_SRC="'none'"
CSP_MEDIA_SRC="'self'"
CSP_FRAME_SRC="'none'"
CSP_BASE_URI="'self'"
CSP_FORM_ACTION="'self'"
CSP_FRAME_ANCESTORS="'none'"
CSP_REPORT_URI="/csp-report"

# Moderate mode (allows nonce-based inline scripts):
CSP_MODE=moderate
CSP_SCRIPT_SRC="'self' 'nonce-{random}'"
CSP_STYLE_SRC="'self' 'nonce-{random}'"

# Permissive mode (development):
CSP_MODE=permissive
CSP_SCRIPT_SRC="'self' 'unsafe-inline'"
CSP_STYLE_SRC="'self' 'unsafe-inline'"

# Custom CSP for specific domains:
CSP_SCRIPT_SRC="'self' https://cdn.jsdelivr.net"
CSP_CONNECT_SRC="'self' https://api.yourdomain.com wss://api.yourdomain.com"

# Report CSP violations:
CSP_REPORT_ONLY=false  # Set to true for testing without enforcement
CSP_REPORT_URI="/api/csp-violations"

3. Automated Dependency Scanning

ɳSelf v0.9.5 integrates multiple security scanning tools to detect vulnerabilities in your dependencies and infrastructure.

# Run all security scans
ɳSelf security scan

# This runs:
# 1. ShellCheck - Bash script static analysis
# 2. Gitleaks - Secret detection in git history
# 3. Trivy - Container image vulnerability scanning
# 4. Semgrep - Code security analysis

# Run individual scans:
ɳSelf security scan --tool shellcheck   # Bash script analysis
ɳSelf security scan --tool gitleaks     # Detect committed secrets
ɳSelf security scan --tool trivy        # Scan container images
ɳSelf security scan --tool semgrep      # Security code patterns

# Scan specific components:
ɳSelf security scan --images            # Only scan container images
ɳSelf security scan --code              # Only scan code
ɳSelf security scan --secrets           # Only detect secrets

# Output formats:
ɳSelf security scan --format json       # Machine-readable output
ɳSelf security scan --format sarif      # SARIF format for CI integration
ɳSelf security scan --format table      # Human-readable table (default)

# CI/CD integration:
ɳSelf security scan --fail-on high      # Exit non-zero if high/critical found
ɳSelf security scan --fail-on medium    # Exit non-zero if medium+ found

# Save scan results:
ɳSelf security scan --output security-report.json

Scanning Tools Overview

  • ShellCheck: Finds bugs and style issues in Bash scripts
  • Gitleaks: Scans git history for leaked secrets and credentials
  • Trivy: Comprehensive vulnerability scanner for containers
  • Semgrep: Static analysis for security patterns and anti-patterns

All tools are automatically installed if not present. Results are aggregated and prioritized by severity.

4. Security Audit System

The new ɳSelf security audit command provides comprehensive security analysis across all aspects of your deployment.

# Run full security audit
ɳSelf security audit

# Sample output:
# ════════════════════════════════════════════════════════════════
#                      SECURITY AUDIT REPORT
# ════════════════════════════════════════════════════════════════
#
# Environment: production
# Date: 2026-01-30
#
# ┌─────────────────────────────────────────────────────────────┐
# │ CRITICAL ISSUES                                         [0] │
# └─────────────────────────────────────────────────────────────┘
#
# ┌─────────────────────────────────────────────────────────────┐
# │ HIGH PRIORITY                                           [1] │
# └─────────────────────────────────────────────────────────────┘
#   • Rate limiting not configured on authentication endpoints
#
# ┌─────────────────────────────────────────────────────────────┐
# │ MEDIUM PRIORITY                                         [2] │
# └─────────────────────────────────────────────────────────────┘
#   • Container resource limits not set
#   • Audit logging not enabled
#
# ┌─────────────────────────────────────────────────────────────┐
# │ LOW PRIORITY                                            [3] │
# └─────────────────────────────────────────────────────────────┘
#   • Session timeout could be shorter (currently 24h)
#   • Consider enabling 2FA for admin users
#   • Backup retention period not configured
#
# ┌─────────────────────────────────────────────────────────────┐
# │ PASSES                                                 [42] │
# └─────────────────────────────────────────────────────────────┘
#   ✓ SQL injection prevention active
#   ✓ Admin UI disabled in production
#   ✓ Strong JWT secret configured
#   ✓ SSL/TLS enabled with valid certificate
#   ✓ HSTS enabled
#   ✓ Content Security Policy configured
#   ✓ Database credentials strong
#   ✓ Firewall configured
#   ✓ SSH key authentication only
#   ✓ No secrets in git history
#   ... and 32 more checks passed
#
# ════════════════════════════════════════════════════════════════
# OVERALL SCORE: 92/100 (Grade: A)
# ════════════════════════════════════════════════════════════════

# Audit specific categories:
ɳSelf security audit --category authentication
ɳSelf security audit --category network
ɳSelf security audit --category database
ɳSelf security audit --category infrastructure
ɳSelf security audit --category compliance

# Output formats:
ɳSelf security audit --format json
ɳSelf security audit --format html --output audit-report.html
ɳSelf security audit --format pdf --output audit-report.pdf

# Compare environments:
ɳSelf security audit --compare staging,production

# Continuous monitoring:
ɳSelf security audit --watch          # Run every hour
ɳSelf security audit --schedule daily # Run daily at midnight

5. File Upload Security

6-layer defense system for file uploads protects against malicious files, path traversal, and other attacks.

# File upload security configuration
FILE_UPLOAD_ENABLED=true
FILE_UPLOAD_MAX_SIZE=10485760           # 10MB default

# Layer 1: File type validation
FILE_UPLOAD_ALLOWED_TYPES="image/jpeg,image/png,image/gif,application/pdf"
FILE_UPLOAD_BLOCKED_EXTENSIONS=".exe,.sh,.bat,.cmd,.php,.jsp"

# Layer 2: Content-type verification
FILE_UPLOAD_VERIFY_MIME_TYPE=true      # Check actual file content
FILE_UPLOAD_STRICT_MIME=true            # Reject mismatched extensions

# Layer 3: File scanning
FILE_UPLOAD_VIRUS_SCAN=true            # Scan with ClamAV if available
FILE_UPLOAD_MALWARE_SCAN=true          # Check for known malware patterns

# Layer 4: Path traversal prevention
FILE_UPLOAD_SANITIZE_FILENAME=true     # Remove dangerous characters
FILE_UPLOAD_RANDOMIZE_FILENAME=true    # Use UUIDs for filenames

# Layer 5: Storage isolation
FILE_UPLOAD_QUARANTINE_ENABLED=true    # Quarantine suspicious files
FILE_UPLOAD_SEPARATE_STORAGE=true      # Isolate from app storage

# Layer 6: Access control
FILE_UPLOAD_AUTHENTICATED_ONLY=true    # Require authentication
FILE_UPLOAD_RATE_LIMIT=10              # Max uploads per minute
FILE_UPLOAD_SIZE_LIMIT_PER_USER=104857600  # 100MB per user total

# Example: Configure for images only
FILE_UPLOAD_ALLOWED_TYPES="image/jpeg,image/png,image/webp"
FILE_UPLOAD_MAX_SIZE=5242880           # 5MB
FILE_UPLOAD_VERIFY_MIME_TYPE=true
FILE_UPLOAD_RANDOMIZE_FILENAME=true
FILE_UPLOAD_IMAGE_MAX_WIDTH=4000
FILE_UPLOAD_IMAGE_MAX_HEIGHT=4000

6. OWASP Top 10 Compliance

ɳSelf v0.9.5 implements protections against all OWASP Top 10 vulnerabilities.

OWASP RiskProtection Implemented
A01: Broken Access ControlJWT validation, role-based permissions, Hasura RLS
A02: Cryptographic FailuresTLS 1.2+, strong ciphers, secrets encryption at rest
A03: InjectionParameterized queries, input validation (85+ functions)
A04: Insecure DesignSecurity by default, least privilege, threat modeling
A05: Security MisconfigurationAutomated security audit, secure defaults, hardening
A06: Vulnerable ComponentsDependency scanning (Trivy, Semgrep), automated updates
A07: Identification FailuresStrong password policy, MFA support, session management
A08: Software & Data IntegrityImage signatures, SRI hashes, secure CI/CD
A09: Security Logging FailuresComprehensive audit logging, monitoring, alerting
A10: Server-Side Request ForgeryURL validation, allowlist filtering, network isolation

Security Best Practices

Input Validation Examples

# All inputs are validated with 85+ validation functions

# Database name validation:
nself db create "my-app-db"          # Valid: alphanumeric, hyphens, underscores
nself db create "app_prod_2026"      # Valid
nself db create "db'; DROP TABLE"    # Invalid: SQL injection attempt blocked

# Username validation:
nself db user create "admin"         # Valid
nself db user create "user-123"      # Valid
nself db user create "'; DROP--"     # Invalid: dangerous characters blocked

# Domain validation:
ɳSelf prod init example.com          # Valid
ɳSelf prod init api.example.com      # Valid
ɳSelf prod init "javascript:alert()" # Invalid: not a valid domain

# Port validation:
nself service create my-api --port 8080     # Valid
nself service create my-api --port 80       # Valid
nself service create my-api --port 99999    # Invalid: port out of range

# Path validation (prevents directory traversal):
nself db restore backup.sql          # Valid
nself db restore ../../../etc/passwd # Invalid: path traversal blocked
nself db restore "backup$(rm -rf /)" # Invalid: command injection blocked

# Environment variable validation:
export DB_NAME="production_db"
nself db create "$DB_NAME"           # Valid: properly escaped
export DB_NAME="prod'; DROP DATABASE test--"
nself db create "$DB_NAME"           # Invalid: dangerous value rejected

CI/CD Security Integration

# GitHub Actions example
name: Security Scan
on: [push, pull_request]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Install ɳSelf
        run: curl -fsSL https://install.nself.org | bash

      - name: Run security audit
        run: ɳSelf security audit --format json --output audit.json

      - name: Scan dependencies
        run: ɳSelf security scan --fail-on high

      - name: Check for secrets
        run: ɳSelf security scan --tool gitleaks

      - name: Upload results
        uses: github/codeql-action/upload-sarif@v2
        with:
          sarif_file: security-scan.sarif

# GitLab CI example
security_scan:
  stage: test
  script:
    - curl -fsSL https://install.nself.org | bash
    - ɳSelf security audit
    - ɳSelf security scan --fail-on medium
  artifacts:
    reports:
      sast: security-scan.sarif

# Pre-commit hook
#!/bin/bash
# .git/hooks/pre-commit
ɳSelf security scan --tool gitleaks
if [ $? -ne 0 ]; then
  echo "Security scan failed. Commit aborted."
  exit 1
fi

Authentication Security

JWT Configuration

# JWT settings for production
HASURA_JWT_KEY=your-secret-key-minimum-64-characters-for-production-use
HASURA_JWT_TYPE=HS256

# Token expiration
AUTH_ACCESS_TOKEN_EXPIRY=15m        # Short-lived access tokens
AUTH_REFRESH_TOKEN_EXPIRY=7d        # Longer refresh tokens

# Audience and issuer validation
AUTH_JWT_AUDIENCE=https://api.yourdomain.com
AUTH_JWT_ISSUER=https://auth.yourdomain.com

Password Policy

# Password requirements
AUTH_PASSWORD_MIN_LENGTH=12
AUTH_PASSWORD_REQUIRE_UPPERCASE=true
AUTH_PASSWORD_REQUIRE_LOWERCASE=true
AUTH_PASSWORD_REQUIRE_NUMBERS=true
AUTH_PASSWORD_REQUIRE_SYMBOLS=true
AUTH_PASSWORD_PREVENT_COMMON=true

# Password history
AUTH_PASSWORD_HISTORY_COUNT=5
AUTH_PASSWORD_MAX_AGE_DAYS=90

Multi-Factor Authentication

# Enable MFA for all users
AUTH_MFA_ENABLED=true
AUTH_MFA_REQUIRED_FOR_ROLES=admin,moderator

# TOTP configuration
AUTH_MFA_TOTP_ENABLED=true
AUTH_MFA_TOTP_ISSUER="Your App Name"

# Recovery codes
AUTH_MFA_RECOVERY_CODES_COUNT=10

Rate Limiting

# Authentication rate limiting
AUTH_RATE_LIMIT_ENABLED=true
AUTH_RATE_LIMIT_LOGIN_ATTEMPTS=5
AUTH_RATE_LIMIT_LOGIN_WINDOW=900        # 15 minutes
AUTH_RATE_LIMIT_SIGNUP_ATTEMPTS=3
AUTH_RATE_LIMIT_SIGNUP_WINDOW=3600      # 1 hour

# Account lockout
AUTH_ACCOUNT_LOCKOUT_ENABLED=true
AUTH_ACCOUNT_LOCKOUT_ATTEMPTS=5
AUTH_ACCOUNT_LOCKOUT_DURATION=1800      # 30 minutes

Network Security

SSL/TLS Configuration

# Enable SSL with Let's Encrypt
SSL_ENABLED=true
SSL_PROVIDER=letsencrypt
LETSENCRYPT_EMAIL=admin@yourdomain.com

# TLS protocol versions (disable old versions)
SSL_PROTOCOLS="TLSv1.2 TLSv1.3"

# Strong cipher suites
SSL_CIPHERS="ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384"
SSL_PREFER_SERVER_CIPHERS=true

# HSTS (HTTP Strict Transport Security)
HSTS_ENABLED=true
HSTS_MAX_AGE=31536000           # 1 year
HSTS_INCLUDE_SUBDOMAINS=true
HSTS_PRELOAD=true

Security Headers

# Enable security headers
SECURITY_HEADERS_ENABLED=true

# Content Security Policy
CSP_ENABLED=true
CSP_DEFAULT_SRC="'self'"
CSP_SCRIPT_SRC="'self' 'unsafe-inline'"
CSP_STYLE_SRC="'self' 'unsafe-inline'"
CSP_IMG_SRC="'self' data: https:"
CSP_CONNECT_SRC="'self' https://api.yourdomain.com wss://api.yourdomain.com"

# Other security headers
X_FRAME_OPTIONS=DENY
X_CONTENT_TYPE_OPTIONS=nosniff
X_XSS_PROTECTION="1; mode=block"
REFERRER_POLICY=strict-origin-when-cross-origin
PERMISSIONS_POLICY="geolocation=(), microphone=(), camera=()"

CORS Configuration

# CORS settings
CORS_ENABLED=true
CORS_ALLOWED_ORIGINS=https://yourdomain.com,https://app.yourdomain.com
CORS_ALLOWED_METHODS=GET,POST,PUT,DELETE,OPTIONS
CORS_ALLOWED_HEADERS=Authorization,Content-Type,X-Requested-With
CORS_ALLOW_CREDENTIALS=true
CORS_MAX_AGE=86400

Firewall Configuration

# Configure firewall via nself
ɳSelf prod firewall configure --dry-run
ɳSelf prod firewall configure

# Manual firewall rules (UFW)
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable

# Docker network isolation
DOCKER_NETWORK_INTERNAL=true
EXPOSE_INTERNAL_PORTS=false

Data Protection

Database Security

# Strong database credentials
POSTGRES_PASSWORD=your-strong-password-32-chars-minimum

# Connection security
POSTGRES_SSL_MODE=require
POSTGRES_SSL_CERT=/path/to/server.crt
POSTGRES_SSL_KEY=/path/to/server.key

# Connection restrictions
POSTGRES_ALLOWED_HOSTS=hasura,api-service
POSTGRES_MAX_CONNECTIONS=100

# Audit logging
POSTGRES_LOG_STATEMENT=ddl
POSTGRES_LOG_CONNECTIONS=true
POSTGRES_LOG_DISCONNECTIONS=true

Encryption at Rest

# PostgreSQL encryption
POSTGRES_DATA_ENCRYPTION=true

# MinIO encryption
MINIO_SSE_ENABLED=true
MINIO_SSE_MASTER_KEY=your-32-character-master-key

# Backup encryption
BACKUP_ENCRYPTION=true
BACKUP_ENCRYPTION_KEY=your-backup-encryption-key

Secrets Management

# Generate secure secrets
ɳSelf prod secrets generate

# Rotate secrets
ɳSelf prod secrets rotate POSTGRES_PASSWORD
ɳSelf prod secrets rotate --all

# Validate secrets
ɳSelf prod secrets validate

# File permissions for secrets
chmod 600 .environments/prod/.env.secrets

Secret Management Rules

  • Never commit secrets to git
  • Use different secrets for each environment
  • Rotate secrets regularly (quarterly minimum)
  • Use a secrets manager for production (Vault, AWS Secrets Manager)

Infrastructure Security

Container Security

# Run containers as non-root
CONTAINER_USER=1000:1000

# Resource limits
POSTGRES_MEMORY_LIMIT=2GB
POSTGRES_CPU_LIMIT=2.0
HASURA_MEMORY_LIMIT=1GB
HASURA_CPU_LIMIT=1.0

# Read-only root filesystem
CONTAINER_READ_ONLY_ROOT=true

# Drop unnecessary capabilities
CONTAINER_DROP_CAPABILITIES=ALL
CONTAINER_ADD_CAPABILITIES=NET_BIND_SERVICE

# Security options
CONTAINER_NO_NEW_PRIVILEGES=true

SSH Security

# SSH configuration recommendations
# /etc/ssh/sshd_config

# Disable password authentication
PasswordAuthentication no
PubkeyAuthentication yes

# Disable root login
PermitRootLogin no

# Use SSH key authentication only
ChallengeResponseAuthentication no

# Limit SSH to specific users
AllowUsers deploy

# Change default port (optional)
Port 2222

# Limit authentication attempts
MaxAuthTries 3
LoginGraceTime 60

Server Hardening

# Apply nself hardening
ɳSelf prod harden

# This applies:
# - Disable unnecessary services
# - Configure automatic security updates
# - Set up fail2ban
# - Configure sysctl security parameters
# - Set file permissions
# - Enable audit logging

# Manual hardening steps
# 1. Keep system updated
sudo apt update && sudo apt upgrade

# 2. Install fail2ban
sudo apt install fail2ban
sudo systemctl enable fail2ban

# 3. Configure automatic updates
sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades

Hasura Security

Production Configuration

# Disable development features
HASURA_GRAPHQL_ENABLE_CONSOLE=false
HASURA_GRAPHQL_DEV_MODE=false
HASURA_GRAPHQL_ENABLE_TELEMETRY=false

# Strong admin secret
HASURA_GRAPHQL_ADMIN_SECRET=your-strong-admin-secret-32-chars

# Unauthorized role
HASURA_GRAPHQL_UNAUTHORIZED_ROLE=anonymous

# Connection limits
HASURA_GRAPHQL_WS_CONNECTION_INIT_TIMEOUT=10s
HASURA_GRAPHQL_MAX_CONNECTIONS=50

Row-Level Security

-- Enable row-level security on sensitive tables
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;

-- Create policies
CREATE POLICY users_own_data ON users
  FOR ALL
  USING (id = current_setting('hasura.user')::uuid);

CREATE POLICY posts_author_access ON posts
  FOR ALL
  USING (
    author_id = current_setting('hasura.user')::uuid
    OR status = 'published'
  );

-- Admin bypass
CREATE POLICY admin_full_access ON users
  FOR ALL
  USING (current_setting('hasura.role') = 'admin');

Hasura Permissions

// Example Hasura permission configuration
{
  "role": "user",
  "table": "posts",
  "permissions": {
    "select": {
      "filter": {
        "_or": [
          { "author_id": { "_eq": "X-Hasura-User-Id" } },
          { "status": { "_eq": "published" } }
        ]
      },
      "columns": ["id", "title", "content", "created_at"],
      "limit": 100
    },
    "insert": {
      "check": {
        "author_id": { "_eq": "X-Hasura-User-Id" }
      },
      "columns": ["title", "content"]
    },
    "update": {
      "filter": { "author_id": { "_eq": "X-Hasura-User-Id" } },
      "columns": ["title", "content"]
    },
    "delete": {
      "filter": { "author_id": { "_eq": "X-Hasura-User-Id" } }
    }
  }
}

Monitoring and Audit

Audit Logging

# Enable audit logging
AUDIT_LOG_ENABLED=true
AUDIT_LOG_LEVEL=info
AUDIT_LOG_RETENTION_DAYS=90

# What gets logged:
# - Authentication events (login, logout, failed attempts)
# - Authorization failures
# - Data access (sensitive tables)
# - Configuration changes
# - Admin actions
-- Audit log table
CREATE TABLE audit_logs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  timestamp TIMESTAMPTZ DEFAULT NOW(),
  user_id UUID,
  action VARCHAR(50) NOT NULL,
  resource VARCHAR(100),
  resource_id UUID,
  details JSONB,
  ip_address INET,
  user_agent TEXT,
  success BOOLEAN NOT NULL
);

CREATE INDEX idx_audit_logs_timestamp ON audit_logs(timestamp);
CREATE INDEX idx_audit_logs_user_id ON audit_logs(user_id);
CREATE INDEX idx_audit_logs_action ON audit_logs(action);

Security Monitoring

# Enable security monitoring
SECURITY_MONITORING_ENABLED=true

# Alert thresholds
ALERT_FAILED_LOGIN_THRESHOLD=10
ALERT_FAILED_LOGIN_WINDOW=300    # 5 minutes
ALERT_RATE_LIMIT_THRESHOLD=100
ALERT_UNUSUAL_ACCESS_ENABLED=true

# Alert destinations
ALERT_EMAIL=security@yourdomain.com
ALERT_SLACK_WEBHOOK=https://hooks.slack.com/...
ALERT_PAGERDUTY_KEY=your-pagerduty-key

Intrusion Detection

# Install and configure fail2ban
sudo apt install fail2ban

# Create jail configuration
# /etc/fail2ban/jail.local
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600

[nginx-http-auth]
enabled = true
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 3
bantime = 3600

# Restart fail2ban
sudo systemctl restart fail2ban

Security Checklist

v0.9.5 Production Security Checklist

  • [ ]Run ɳSelf security audit and achieve score of 90+
  • [ ]Run ɳSelf security scan with no high/critical vulnerabilities
  • [ ]Admin UI and console disabled in production
  • [ ]Content Security Policy enabled (strict mode)
  • [ ]Strong secrets generated and unique per environment
  • [ ]SSL/TLS 1.2+ configured with valid certificates
  • [ ]All security headers configured (HSTS, X-Frame-Options, etc.)
  • [ ]Firewall configured to allow only necessary ports
  • [ ]Rate limiting enabled on all public endpoints
  • [ ]File upload security enabled (6-layer protection)
  • [ ]Database backups encrypted and tested
  • [ ]Audit logging enabled for all sensitive operations
  • [ ]Monitoring and security alerting configured
  • [ ]SSH hardened (key auth only, non-root user, fail2ban)
  • [ ]Container resource limits and security options set
  • [ ]Hasura permissions and RLS policies properly configured
  • [ ]Dependency scanning in CI/CD pipeline
  • [ ]No secrets detected in git history (Gitleaks scan passes)
  • [ ]Automatic security updates enabled
  • [ ]Incident response plan documented and tested

Quick Security Validation

# Run this command to validate all security settings:
ɳSelf security validate

# This checks:
# ✓ SQL injection prevention active
# ✓ Input validation functions loaded
# ✓ CSP headers configured correctly
# ✓ No secrets in environment files
# ✓ Strong password policies
# ✓ Rate limiting configured
# ✓ SSL/TLS properly configured
# ✓ File upload security enabled
# ✓ Database permissions correct
# ✓ Container security options set

# Generate compliance report:
ɳSelf security compliance --framework owasp
ɳSelf security compliance --framework pci-dss
ɳSelf security compliance --framework soc2
ɳSelf security compliance --framework iso27001

Security Updates and Vulnerability Management

Staying Updated

# Check for nself updates (includes security patches)
nself update check

# Update ɳSelf CLI
nself update

# Update container images
nself update images

# Review security advisories
ɳSelf security advisories

# Subscribe to security notifications
ɳSelf security subscribe --email security@yourdomain.com

# Check CVE database for your dependencies
ɳSelf security cve-check

Automated Vulnerability Scanning

# Comprehensive vulnerability scan (v0.9.5)
ɳSelf security scan

# Scan container images only
ɳSelf security scan --images
# Scans: Hasura, PostgreSQL, Redis, MinIO, all custom services

# Scan with severity filtering
ɳSelf security scan --min-severity high
ɳSelf security scan --min-severity critical

# Scan specific image
ɳSelf security scan --image postgres:16
ɳSelf security scan --image hasura/graphql-engine:latest

# Include OS vulnerabilities
ɳSelf security scan --include-os

# Export vulnerability report
ɳSelf security scan --format json --output vulns.json
ɳSelf security scan --format html --output vulns.html

# Schedule regular scans
ɳSelf security scan --schedule daily
ɳSelf security scan --schedule weekly --day monday

# Integration with vulnerability databases
ɳSelf security scan --source nvd        # NIST National Vulnerability Database
ɳSelf security scan --source oss-index  # Sonatype OSS Index
ɳSelf security scan --source ghsa       # GitHub Security Advisories

Dependency Update Strategy

# Check for available updates
ɳSelf dependencies check

# Update dependencies with security patches only
ɳSelf dependencies update --security-only

# Update to latest stable versions
ɳSelf dependencies update --latest

# Test updates in staging first
nself staging dependencies update
nself staging deploy
nself staging health check

# Rollback if issues found
nself staging rollback

# Apply to production after validation
ɳSelf prod dependencies update

Incident Response

Security Incident Procedures

  1. Detection: Monitor alerts, logs, and anomaly detection
  2. Containment: Isolate affected systems, revoke compromised credentials
  3. Investigation: Analyze logs, determine scope and impact
  4. Remediation: Fix vulnerabilities, rotate secrets, patch systems
  5. Recovery: Restore from clean backups if needed
  6. Documentation: Document incident and lessons learned

Emergency Commands

# Run immediate security assessment
ɳSelf security incident-response

# Immediately rotate all secrets
ɳSelf prod secrets rotate --all --force

# Revoke all active sessions
nself auth revoke-sessions --all

# Block all external access (emergency)
ɳSelf prod firewall lockdown

# Enable emergency mode (read-only)
ɳSelf prod emergency-mode enable

# Take system offline for maintenance
nself stop

# Analyze recent activity
ɳSelf security audit-trail --since "1 hour ago"
nself logs --filter security --level warning

# Check for compromised accounts
ɳSelf security check-accounts --suspicious

# Restore from clean backup
nself db restore --clean --verified latest-verified-backup.sql.gz

# Re-enable system after remediation
ɳSelf prod emergency-mode disable
nself start
ɳSelf security validate

Security Incident Logging

# Track incident for compliance
ɳSelf security incident log \
  --type "unauthorized-access" \
  --severity high \
  --description "Multiple failed login attempts from suspicious IP" \
  --affected-systems "auth-service" \
  --actions-taken "IP blocked, user accounts locked, credentials rotated"

# View incident history
ɳSelf security incidents list
ɳSelf security incidents show INC-2026-001

# Generate incident report
ɳSelf security incident report INC-2026-001 --format pdf

Post-Incident Analysis

# Generate forensic report
ɳSelf security forensics --start "2026-01-30 14:00" --end "2026-01-30 16:00"

# Analyze attack patterns
ɳSelf security analyze-logs --pattern suspicious-activity

# Test security improvements
ɳSelf security audit --compare before,after

# Update security measures
ɳSelf security lessons-learned INC-2026-001
ɳSelf security update-playbook

Security Command Reference

Complete Command List (v0.9.5)

# ════════════════════════════════════════════════════════════════
# SECURITY AUDIT
# ════════════════════════════════════════════════════════════════
ɳSelf security audit                    # Full security audit
ɳSelf security audit --category auth    # Specific category
ɳSelf security audit --format json      # JSON output
ɳSelf security audit --compare staging,prod

# ════════════════════════════════════════════════════════════════
# VULNERABILITY SCANNING
# ════════════════════════════════════════════════════════════════
ɳSelf security scan                     # All scanning tools
ɳSelf security scan --tool trivy        # Specific tool
ɳSelf security scan --images            # Container images only
ɳSelf security scan --fail-on high      # CI/CD integration

# ════════════════════════════════════════════════════════════════
# SECRET DETECTION
# ════════════════════════════════════════════════════════════════
ɳSelf security scan --tool gitleaks     # Scan git history
ɳSelf security secrets check            # Check current files
ɳSelf security secrets rotate           # Rotate compromised secrets

# ════════════════════════════════════════════════════════════════
# VALIDATION & COMPLIANCE
# ════════════════════════════════════════════════════════════════
ɳSelf security validate                 # Validate all security settings
ɳSelf security compliance --framework owasp
ɳSelf security compliance --framework pci-dss

# ════════════════════════════════════════════════════════════════
# MONITORING & ALERTING
# ════════════════════════════════════════════════════════════════
ɳSelf security monitor                  # Real-time monitoring
ɳSelf security alerts                   # View security alerts
ɳSelf security audit-trail              # View audit logs

# ════════════════════════════════════════════════════════════════
# INCIDENT RESPONSE
# ════════════════════════════════════════════════════════════════
ɳSelf security incident-response        # Emergency assessment
ɳSelf security incident log             # Document incident
ɳSelf security forensics                # Forensic analysis

# ════════════════════════════════════════════════════════════════
# UPDATES & CVE TRACKING
# ════════════════════════════════════════════════════════════════
ɳSelf security advisories               # Security advisories
ɳSelf security cve-check                # Check for CVEs
ɳSelf dependencies update --security-only

v0.9.5 Security Improvements Summary

What's New in v0.9.5

SQL Injection Prevention (CRITICAL FIX)

All SQL injection vulnerabilities have been eliminated. Every database operation now uses parameterized queries and validated inputs.

Input Validation Library

85+ validation functions covering all input types: database names, usernames, passwords, domains, ports, paths, URLs, and more.

Content Security Policy

Three CSP modes (strict, moderate, permissive) with configurable directives for XSS prevention.

Automated Dependency Scanning

Integrated ShellCheck, Gitleaks, Trivy, and Semgrep for comprehensive vulnerability detection.

Security Audit System

New ɳSelf security audit command provides 50+ security checks with scoring and recommendations.

File Upload Security

6-layer defense: type validation, content verification, malware scanning, path sanitization, storage isolation, and access control.

OWASP Top 10 Compliance

Full protection against all OWASP Top 10 vulnerabilities with automated compliance reporting.

Incident Response Tools

Emergency commands, forensic analysis, incident logging, and automated containment procedures.

Next Steps

  • SSL/TLS Configuration - Detailed SSL setup guide
  • Authentication - Authentication security deep dive
  • Production Deployment - Production best practices
  • Monitoring - Security monitoring setup
  • Backup & Restore - Disaster recovery procedures
  • Changelog - View all v0.9.5 changes

Security is a Journey

Version 0.9.5 represents a major milestone in ɳSelf's security posture, but security is an ongoing process, not a destination. Regularly audit your deployment, stay updated on security best practices, and monitor for potential threats.

Run ɳSelf security audit monthly, enable automated dependency scanning in your CI/CD pipeline, and subscribe to security advisories to stay ahead of emerging threats.