Skip to content

5. Host Provisioning, Kernel Tuning, RBAC User Management, Backups & Maintenance

Repository: VPS Infrastructure (planovi-vps) • Rule Prefix: BR-OPS • Documented Rules: 8 • Open [TEAM_WHY_NEEDED] Questions: 3

Business Purpose & Actors

  • Problem solved: Bootstraps a fresh Ubuntu 24.04 Hostinger VPS with Docker/UFW/Fail2ban/TCP BBR kernel tuning, enforces least-privilege SSH/Docker access across 4 human user roles (Admin, Developer, Auditor, SFTP-Jail), executes automated PostgreSQL backups with retention pruning, monitors disk usage and Docker container health with Google Chat alerting, and reclaims dangling Docker disk space weekly.
  • Actors: Root/Admin DevOps engineers (planovi-admin), developers troubleshooting containers (planovi-dev), read-only auditors (planovi-auditor), external SFTP uploaders (sftp-only), and Linux cron daemon.

All Features & End-to-End Flows

  1. Fresh Host Provisioning (setup-vps.sh, sysctl-tuning.conf):
    • Installs curl git ufw fail2ban htop ca-certificates gnupg tar gzip unzip + official Docker Engine CE, Buildx, Compose V2 (setup-vps.sh:15-37).
    • Copies sysctl-tuning.conf -> /etc/sysctl.d/99-vps-tuning.conf and applies sysctl --system (setup-vps.sh:42-45).
    • Copies repo into /opt/vps-stack, marks scripts/*.sh executable, enables UFW (default deny incoming, allows 80/tcp, 443/tcp, 22/tcp).
    • Runs docker compose pull, build, up -d.
    • Registers 2 cron jobs: 0 2 * * * -> backup.sh (/var/log/vps-backup.log) and 0 * * * * -> check-health.sh (/var/log/vps-health.log) (setup-vps.sh:70).
  2. Interactive SSH User Provisioning (scripts/planovi-adduser.sh):
    • Prompts for USERNAME (exits 1 if id "$USERNAME" exists), ROLE_CHOICE (1–4), and public SSH_KEY (exits 1 if empty).
    • Creates account based on role:
      • 1) Admin: /bin/bash, groups planovi-admin,docker,sudo.
      • 2) Developer: /bin/bash, group planovi-dev (sudoers grants NOPASSWD: /usr/local/bin/planovi-dev-docker).
      • 3) Auditor: /bin/bash, group planovi-auditor (no sudo, no docker).
      • 4) SFTP-Jail: prompts for SFTP_DIR, sets root:root + 0755, creates $SFTP_DIR/uploads owned by $USERNAME, shell /sbin/nologin, group sftp-only.
    • Writes authorized_keys (0700 .ssh, 0600 authorized_keys) and disables password login (passwd -d + passwd -l).
  3. Safe Developer Docker Wrapper (scripts/planovi-dev-docker.sh):
    • Installed at /usr/local/bin/planovi-dev-docker and invoked via sudo planovi-dev-docker <args>.
    • Permits ONLY logs, restart, ps, or compose (restart|logs|ps) or compose -f <file> (restart|logs|ps). Any other subcommand (e.g., exec, run, rm, cp, build) exits 1 with "Error: Not authorized to run docker <subcmd>.".
  4. PostgreSQL Backups (scripts/backup.sh & scripts/backup_databases.sh):
    • backup.sh: Sources /opt/vps-stack/.env, runs docker exec supabase-db pg_dump -U supabase_admin postgres | gzip -9 into /var/backups/vps-stack/db_backup_<TS>.sql.gz, deletes files older than 14 days (-mtime +14), logs to backup_<TS>.log, and posts Google Chat notification on both success and failure (backup.sh:9-76).
    • backup_databases.sh: Runs pg_dumpall -U supabase_admin | gzip against BOTH supabase-db (PROD) and supabase-db-dev (DEV) into /opt/vps-stack/backups/{prod,dev}/db_{PROD,DEV}_<TS>.sql.gz, deletes backups older than 30 days (-mtime +30). Sends no Chat notification (backup_databases.sh:4-26).
  5. Hourly Health Monitoring (scripts/check-health.sh):
    • Checks root filesystem / usage via df -h /; if DISK_USAGE > 85%, sends Google Chat alert (check-health.sh:19,40-44).
    • Checks docker ps -a --format "{{.Names}} - {{.Status}}" for unhealthy|exited|dead; if non-empty, sends Google Chat alert (check-health.sh:47-53).
  6. Weekly Docker Prune (scripts/docker-prune.sh):
    • Sources /opt/vps-stack/.env, runs /usr/bin/docker system prune -f (intentionally -f, NOT -af, per commit 650a7dd so tagged planovi-firmware-builder:latest and planovi-flutter:* images survive). If reclaimed space is non-empty and != "0B", sends Google Chat summary (docker-prune.sh:2-11).

Hard Business Rules, Validations, Calculations & Edge Cases

  • BR-OPS-01 (Kernel Network & Swap Tuning): sysctl-tuning.conf:8-31 enforces fs.file-max = 2097152, net.core.somaxconn = 65535, net.core.netdev_max_backlog = 65535, tcp_rmem/tcp_wmem max 16777216 (16 MiB), tcp_congestion_control = bbr with default_qdisc = fq, tcp_tw_reuse = 1, tcp_fin_timeout = 15, tcp_syncookies = 1, tcp_max_syn_backlog = 8192, vm.swappiness = 10, vm.dirty_ratio = 15, vm.dirty_background_ratio = 5.
  • BR-OPS-02 (Key-Only SSH Enforcement): Every account created by scripts/planovi-adduser.sh:123-124 has its Linux password deleted and locked (passwd -d + passwd -l), forcing SSH public-key authentication.
  • BR-OPS-03 (SFTP Chroot Ownership Requirement): scripts/planovi-adduser.sh:90-97 enforces chown root:root and chmod 755 on SFTP_DIR to satisfy OpenSSH ChrootDirectory requirements, granting write access solely to $SFTP_DIR/uploads.
  • BR-OPS-04 (Developer Docker Command Allowlist): scripts/planovi-dev-docker.sh:15-28 allows only logs, restart, ps, and compose [ -f <file> ] (restart|logs|ps). Note: $3 after -f is not restricted to /opt/vps-stack/docker-compose.yml.
  • BR-OPS-05 (Disk Usage Alert Threshold): scripts/check-health.sh:19,42 alerts strictly when / usage is > 85% (not >=). Note: despite comment on line 3 mentioning RAM, the script does NOT check RAM usage.
  • BR-OPS-06 (Docker Prune Image Preservation): scripts/docker-prune.sh:5 MUST use docker system prune -f (never -af) so tagged builder images (planovi-firmware-builder:latest, planovi-flutter:*) are retained across weekly cleanups.
  • BR-OPS-07 (Dual Backup Inconsistency): backup.sh dumps PROD only (pg_dump, /var/backups/vps-stack, 14d retention, Google Chat alerts) while backup_databases.sh dumps PROD + DEV (pg_dumpall, /opt/vps-stack/backups/{prod,dev}, 30d retention, no alerts). setup-vps.sh:70 registers only backup.sh in cron.
  • BR-OPS-08 (Host Logging Rotation Cap): Every service in docker-compose.yml configures json-file logging with max-size: "20m" and max-file: "3" (max 60 MB per container, ~1.3 GB ceiling across 22 containers).

State Machines & Data Lifecycle

  • User Account Provisioning States (planovi-adduser.sh): Input validation -> Role group assignment (planovi-admin | planovi-dev | planovi-auditor | sftp-only) -> SSH key injection -> Password lock (L).
  • Backup Artifact Lifecycle: Created daily -> Compressed (gzip) -> Retained locally for 14 days (backup.sh) or 30 days (backup_databases.sh) -> Deleted by find -mtime. No automated off-site cloud replication exists in code.

Technical Contract

  • Cron Entries (per setup-vps.sh:70):
    • 0 2 * * * -> /opt/vps-stack/scripts/backup.sh > /var/log/vps-backup.log 2>&1
    • 0 * * * * -> /opt/vps-stack/scripts/check-health.sh > /var/log/vps-health.log 2>&1
  • External Calls: POST to GOOGLE_CHAT_WEBHOOK_URL from backup.sh, check-health.sh, docker-prune.sh.

Cross-Repository Dependencies

  • planovi-adduser.sh & planovi-dev-docker.sh depend on host-level /etc/sudoers.d/planovi-roles and /etc/ssh/sshd_config (Match Group sftp-only), neither of which is stored in Git or provisioned by setup-vps.sh.
  • backup.sh & backup_databases.sh depend on Docker containers supabase-db / supabase-db-dev with role supabase_admin.

Why It Works This Way

  • Separate planovi-dev-docker.sh wrapper: Avoids adding developers to the docker group (which equals full root escalation on Linux) while still letting them read logs and restart stuck containers.
  • prune -f instead of prune -af: Explicitly documented in scripts/docker-prune.sh:3-4 and commit 650a7dd to stop weekly cron from wiping multi-gigabyte Flutter and ARM firmware builder images.
  • [TEAM_WHY_NEEDED: Which backup script is authoritative on the live VPS crontab — backup.sh or backup_databases.sh — and should the unused one be retired and off-site replication (e.g. Google Drive / GCS) added?]
  • [TEAM_WHY_NEEDED: Should /etc/sudoers.d/planovi-roles, group creation (planovi-admin, planovi-dev, planovi-auditor, sftp-only), and sshd_config SFTP-Jail blocks be versioned in planovi-vps and automated in setup-vps.sh?]
  • [TEAM_WHY_NEEDED: Should setup-vps.sh and update-allowed-ip.sh also open UFW port 8883/tcp for MQTT TLS, or is 8883 intentionally blocked at UFW on host level?]

Debugging, Logs & Common Failure Modes

  • Symptom: planovi-adduser.sh fails with useradd: group 'planovi-dev' does not exist -> Root Cause: Groups not yet created on host -> Verify: getent group planovi-admin planovi-dev planovi-auditor sftp-only -> Fix: Create missing Linux groups and /etc/sudoers.d/planovi-roles before running wizard.
  • Symptom: backup_databases.sh fails or uses wrong password -> Root Cause: grep POSTGRES_PASSWORD /opt/vps-stack/.env | cut -d= -f2 breaks if .env contains quotes or multiple lines matching POSTGRES_PASSWORD, falling back to hardcoded legacy password -> Verify: tail -n 50 /var/log/vps-backup.log -> Fix: Source .env safely (set -a; source /opt/vps-stack/.env; set +a) and remove hardcoded fallback password.
  • Symptom: check-health.sh sends false alert after one-off exited container -> Root Cause: docker ps -a matches ANY exited container (including manually stopped containers without --rm) -> Verify: docker ps -a --filter status=exited -> Fix: Remove stopped one-off containers (docker rm <id>).