Skip to content

4. GitHub Webhook Auto-Deployer & Legacy CI Workflow

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

Business Purpose & Actors

  • Problem solved: Automates continuous deployment of all 5 product repositories (planovi-webpage, planovi-microservices, planovi-flutter-app, planovi-converter, planovi-backend) onto PROD (main) and DEV (develop / dev) directly from GitHub push webhooks, with HMAC-SHA256 verification, serialized execution, secret-leak prevention on Flutter public bundles, on-demand FVM Flutter SDK image builds, ARM firmware compilation, zero-downtime Nginx reloads, automatic Git rollback on failure, and Google Chat notifications.
  • Actors: GitHub Webhooks (POST https://api.planovi.app/deploy-webhook), DevOps/Engineering team receiving Google Chat deployment & rejection alerts.

All Features & End-to-End Flows

  1. Webhook Ingestion & HMAC-SHA256 Verification (deployer/deployer.py:405-470):
    • Trigger: POST to port 9000 (proxied from https://api.planovi.app/deploy-webhook).
    • Validation: Reads Content-Length bytes. Requires X-Hub-Signature-256 matching sha256= + hmac.new(WEBHOOK_SECRET, body, sha256).hexdigest() using hmac.compare_digest (deployer.py:430-437).
    • Rejection Path: Missing or invalid signature returns HTTP 403 "Invalid signature" and spawns a background thread calling send_reject_alert() (rate-limited to 1 Google Chat alert per 600s via _reject_alert_lock, deployer.py:35-37,124-142,411-420).
    • Ping Event: X-GitHub-Event: ping -> returns HTTP 200 "pong" (deployer.py:439-441).
    • Push Event: Parses JSON repository.name, ref, head_commit. If (repo_name, ref) exists in REPO_MAPPING, immediately returns HTTP 200 "Deploy started asynchronously" and spawns daemon thread process_deploy(); otherwise returns HTTP 200 "Ignored branch or repo" (deployer.py:443-463). Malformed JSON returns HTTP 500 "Internal Server Error".
  2. Serialized Git Checkout & Post-Deploy Pipeline (deployer/deployer.py:352-404):
    • Acquires global _deploy_lock so concurrent pushes never corrupt shared Docker builds or container recreates (deployer.py:32,353, commit 047e20f).
    • Records old_commit = git rev-parse HEAD for rollback.
    • Runs GIT_SSH_COMMAND='ssh -i /root/.ssh/id_ed25519_deploy -o StrictHostKeyChecking=no' git fetch origin and git reset --hard origin/<branch>.
    • Executes repo-specific post_deploy hook:
      • planovi-webpage & planovi-microservices (post_deploy: None): Git checkout only (php-app serves directly).
      • planovi-flutter-app (post_deploy: "flutter_build"):
        1. get_flutter_version(target_dir) reads .fvmrc (flutter) or .fvm/fvm_config.json (flutterSdkVersion/flutter), validates ^\d+\.\d+\.\d+$ (deployer.py:177-206).
        2. ensure_flutter_image(version) checks Docker cache for planovi-flutter:<version>; if missing, queries Google’s official releases_linux.json, validates archive path + 64-hex SHA256, and builds image from /opt/vps-stack/flutter-builder under _flutter_image_lock (deployer.py:208-242).
        3. inject_flutter_env(target_dir, env_name) reads ONLY /opt/vps-apps/flutter-app/{dev,prod}.public.env, validates every key/value against secret regex and JWT role == "service_role", and writes assets/env (deployer.py:252-306).
        4. flutter_build() runs docker run --rm -v <dir>:/app -w /app planovi-flutter:<ver> sh -c 'flutter pub get && flutter build web --release' (deployer.py:247-248).
      • planovi-backend (post_deploy: "supabase_functions_sync"):
        1. Runs rsync -av --delete <target_dir>/supabase/functions/ /opt/vps-stack/supabase/functions-{dev,prod}/.
        2. Runs docker restart supabase-edge-runtime-{dev,prod} (warning-only on restart exception) (deployer.py:308-324).
      • planovi-converter (post_deploy: "converter_build"):
        1. Validates admin/.fvmrc and ensures planovi-flutter:<version> image FIRST (fail-fast before rebuilding API, deployer.py:331-333).
        2. Rebuilds FastAPI container: docker compose -f /opt/vps-stack/docker-compose.yml up -d --build converters-api-{dev,prod}.
        3. If <target_dir>/deploy/docker-compose.public-ingress.yml AND <target_dir>/deploy/.env both exist, rebuilds mTLS public ingress (deployer.py:337-339).
        4. Builds Flutter admin web panel (flutter_build(admin_dir, image)) and sets chown -R 33:33 <target_dir>/admin/build/web.
        5. Ensures planovi-firmware-builder:latest image exists (building from deploy/Dockerfile.firmware-builder if absent), compiles ARM firmware mounting planovi-device-ca.pem and ota-signing-key.pem read-only into /certs/, outputs to <target_dir>/firmware, and sets chown -R 33:33 <target_dir>/firmware (deployer.py:346-350).
    • Reloads Nginx (docker exec vps-proxy nginx -s reload) to refresh DNS cache (deployer.py:385-386).
    • Sends success notification to Google Chat (deployer.py:387).
  3. Failure Handling & Auto-Rollback (deployer/deployer.py:390-403):
    • Any raised exception triggers git reset --hard <old_commit> in target_dir.
    • Extracts compiler error summary via _log_tail() (up to 10 lines containing Error: / error: with preceding .dart: / .py: / .ts: file context + last 8 tail lines, capped at 1500 chars, escaping backticks ``` -> ''') and posts failure + rollback alert to Google Chat (deployer.py:115-122,144-163,402-403).
  4. Legacy GitHub Actions Workflow (.github/workflows/deploy.yml):
    • Triggers on push to planovi-vps main. Attempts to build ./fastapi-app and ./php-app, push to ghcr.io, and SSH to VPS_HOST to docker compose pull fastapi-app php-app. Currently broken because ./fastapi-app does not exist in planovi-vps and php-app/index.php is gitignored.

Hard Business Rules, Validations, Calculations & Edge Cases

  • BR-DEP-01 (Mandatory Startup Secret): deployer.py:472-474 aborts startup with sys.exit(1) and stderr "FATAL: zmienna WEBHOOK_SECRET jest pusta lub nieustawiona. Deployer nie wystartuje." if WEBHOOK_SECRET is empty (no default fallback).
  • BR-DEP-02 (Mandatory Signature Enforcement): Unsigned requests (missing X-Hub-Signature-256) are rejected with HTTP 403, never bypassed (deployer.py:430-437).
  • BR-DEP-03 (Rejection Alert Throttling): Google Chat rejection alerts are rate-limited to at most 1 message every REJECT_ALERT_WINDOW_SECONDS = 600 seconds (deployer.py:35,129-132).
  • BR-DEP-04 (Exact Repository & Branch Mapping): Only 5 repositories (planovi-webpage, planovi-microservices, planovi-flutter-app, planovi-converter, planovi-backend) and 3 refs (refs/heads/main -> PROD, refs/heads/develop & refs/heads/dev -> DEVELOP) trigger deployments (deployer.py:39-101).
  • BR-DEP-05 (Strict SemVer FVM Pinning): get_flutter_version() rejects missing .fvmrc, unparseable JSON, or non-x.y.z channel names (e.g. "stable") matching FLUTTER_VERSION_RE = ^\d+\.\d+\.\d+$ (deployer.py:28,177-206). Release archive metadata must pass FLUTTER_ARCHIVE_RE (no ..) and 64-hex SHA256_RE (deployer.py:29-30,218-219).
  • BR-DEP-06 (Flutter Public Env Secret-Leak Gate): inject_flutter_env() reads ONLY /opt/vps-apps/flutter-app/{dev,prod}.public.env (aborts if missing; never falls back to private .env), rejects malformed lines without =, rejects any key matching (SERVICE_ROLE|SECRET|TOKEN|PRIVATE|PASSWORD|API_KEY) case-insensitively UNLESS in FLUTTER_TEMP_ALLOWED = {"DEALFLOW_API_SECRET", "SCHEDULER_API_SECRET"}, and base64-decodes any JWT value (3 dot-parts starting with eyJ) to reject role == "service_role" (deployer.py:252-302).
  • BR-DEP-07 (Serialized Deployment Locking): All deployments execute sequentially under _deploy_lock, and Flutter builder image creation is guarded by _flutter_image_lock (deployer.py:31-32,227,353).
  • BR-DEP-08 (Rollback Scope Limitation): On error, auto-rollback ONLY executes git reset --hard <old_commit> in target_dir (deployer.py:396-401); it does NOT re-run flutter_build, revert rsync-ed Edge Functions, or roll back rebuilt converters-api-* Docker containers.
  • BR-DEP-09 (Live Script Execution): deployer/Dockerfile:14 executes /opt/vps-stack/deployer/deployer.py from the bind-mounted /opt/vps-stack volume rather than /app/deployer.py copied at line 10.
  • BR-DEP-10 (Log Tail Truncation & Error Extraction): _log_tail() scans lines prior to the last 15 lines for Error: / error:, attaches the preceding line if it references .dart:, .py:, or .ts:, shows max 10 error snippets + --- + last 8 lines, and truncates to max_chars=1500 (deployer.py:144-163).

State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> Received: POST /deploy-webhook
    Received --> Rejected403: Missing/Invalid HMAC-SHA256
    Rejected403 --> [*]: Rate-limited Chat Alert (10m)
    Received --> Ignored200: ping / unmapped repo or branch
    Ignored200 --> [*]
    Received --> Queued: Valid push (HTTP 200 async)
    Queued --> Fetching: Acquire _deploy_lock
    Fetching --> PostDeploy: git fetch & reset --hard
    Fetching --> Rollback: Git error
    PostDeploy --> ReloadNginx: Build/Sync succeeded
    PostDeploy --> Rollback: FVM/Env/Build/Sync error
    ReloadNginx --> Succeeded: nginx -s reload OK
    ReloadNginx --> Rollback: Reload error
    Rollback --> Failed: git reset --hard old_commit + Chat Error Alert
    Succeeded --> [*]: Chat Success Alert
    Failed --> [*]

Technical Contract

  • Endpoint: POST http://vps-deployer:9000/deploy-webhook (publicly https://api.planovi.app/deploy-webhook).
  • Headers Required: X-Hub-Signature-256, X-GitHub-Event, Content-Length.
  • Mounts & Host Privileges: /var/run/docker.sock (full host Docker daemon control), /opt/vps-apps (RW), /opt/vps-stack (RW), /root/.ssh (RO, uses /root/.ssh/id_ed25519_deploy).
  • External Network Calls: github.com (SSH git fetch), storage.googleapis.com (releases_linux.json + Flutter SDK tarballs), chat.googleapis.com (Google Chat webhook, timeout=10).

Cross-Repository Dependencies

  • GitHub (5 PA-IDEAS repos) -> vps-deployer | HTTPS Webhook + HMAC-SHA256 | Triggers deployment on push.
  • vps-deployer -> planovi-flutter-app | Reads .fvmrc, writes assets/env, builds build/web.
  • vps-deployer -> planovi-backend | Syncs supabase/functions/ -> /opt/vps-stack/supabase/functions-{dev,prod}/ and restarts supabase-edge-runtime-{dev,prod}.
  • vps-deployer -> planovi-converter | Reads admin/.fvmrc, rebuilds converters-api-*, optional deploy/docker-compose.public-ingress.yml, builds admin/build/web, builds ARM firmware via deploy/Dockerfile.firmware-builder with /opt/vps-stack/cloudflare-ssl/ota-signing-key.pem.
  • vps-deployer -> planovi-webpage & planovi-microservices | Git fetch + hard reset.

Why It Works This Way

  • Custom planovi-flutter:<version> image builder: Comment in deployer.py:21-22 explains third-party Flutter Docker images lag behind or stop publishing; building directly from Google’s official SHA256-verified archive ensures exact .fvmrc parity.
  • FLUTTER_TEMP_ALLOWED exception: Comment in deployer.py:258-259 explicitly marks DEALFLOW_API_SECRET and SCHEDULER_API_SECRET as temporary until an Edge Function proxy replaces direct browser calls to PHP microservices.
  • No git clean during deploy: Preserves untracked runtime .env files and dealflow/data/*.json files inside /opt/vps-apps/*.
  • [TEAM_WHY_NEEDED: Why is /opt/vps-stack/flutter-builder (referenced by FLUTTER_BUILDER_DIR in deployer.py:24) not tracked in PA-IDEAS/planovi-vps?]
  • [TEAM_WHY_NEEDED: Should .github/workflows/deploy.yml be removed or rewritten to sync planovi-vps configs to /opt/vps-stack instead of referencing the deleted ./fastapi-app directory?]
  • [TEAM_WHY_NEEDED: Commit 6faaa16 added automatic DB migration execution for planovi-converter, which is no longer present in build_converter() — was DB migration execution intentionally moved into converters-api startup?]

Debugging, Logs & Common Failure Modes

  • Symptom: Deploy aborted with "Brak pliku /opt/vps-apps/flutter-app/dev.public.env" -> Root Cause: Public Flutter env file missing on VPS -> Verify: ls -la /opt/vps-apps/flutter-app/*.public.env -> Fix: Create browser-safe .public.env containing only non-secret keys.
  • Symptom: Deploy aborted with "klucz ... wygląda na sekret" or "zawiera klucz service_role" -> Root Cause: Secret key accidentally placed in .public.env -> Verify: docker logs --tail 50 vps-deployer -> Fix: Remove secret from .public.env and keep it only in server-side /opt/vps-stack/.env.
  • Symptom: HTTP 403 Invalid signature on GitHub webhook delivery -> Root Cause: Mismatch between GitHub repo webhook secret and WEBHOOK_SECRET in /opt/vps-stack/.env -> Verify: docker logs --tail 30 vps-deployer -> Fix: Synchronize webhook secret and restart vps-deployer.
  • Symptom: planovi-flutter:<version> build fails with missing directory -> Root Cause: /opt/vps-stack/flutter-builder missing on host -> Verify: ls -la /opt/vps-stack/flutter-builder -> Fix: Restore flutter-builder/Dockerfile on VPS (and commit to repo).