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
- Webhook Ingestion & HMAC-SHA256 Verification (
deployer/deployer.py:405-470):- Trigger:
POSTto port9000(proxied fromhttps://api.planovi.app/deploy-webhook). - Validation: Reads
Content-Lengthbytes. RequiresX-Hub-Signature-256matchingsha256=+hmac.new(WEBHOOK_SECRET, body, sha256).hexdigest()usinghmac.compare_digest(deployer.py:430-437). - Rejection Path: Missing or invalid signature returns
HTTP 403 "Invalid signature"and spawns a background thread callingsend_reject_alert()(rate-limited to 1 Google Chat alert per600svia_reject_alert_lock,deployer.py:35-37,124-142,411-420). - Ping Event:
X-GitHub-Event: ping-> returnsHTTP 200 "pong"(deployer.py:439-441). - Push Event: Parses JSON
repository.name,ref,head_commit. If(repo_name, ref)exists inREPO_MAPPING, immediately returnsHTTP 200 "Deploy started asynchronously"and spawns daemon threadprocess_deploy(); otherwise returnsHTTP 200 "Ignored branch or repo"(deployer.py:443-463). Malformed JSON returnsHTTP 500 "Internal Server Error".
- Trigger:
- Serialized Git Checkout & Post-Deploy Pipeline (
deployer/deployer.py:352-404):- Acquires global
_deploy_lockso concurrent pushes never corrupt shared Docker builds or container recreates (deployer.py:32,353, commit047e20f). - Records
old_commit = git rev-parse HEADfor rollback. - Runs
GIT_SSH_COMMAND='ssh -i /root/.ssh/id_ed25519_deploy -o StrictHostKeyChecking=no' git fetch originandgit reset --hard origin/<branch>. - Executes repo-specific
post_deployhook:planovi-webpage&planovi-microservices(post_deploy: None): Git checkout only (php-appserves directly).planovi-flutter-app(post_deploy: "flutter_build"):get_flutter_version(target_dir)reads.fvmrc(flutter) or.fvm/fvm_config.json(flutterSdkVersion/flutter), validates^\d+\.\d+\.\d+$(deployer.py:177-206).ensure_flutter_image(version)checks Docker cache forplanovi-flutter:<version>; if missing, queries Google’s officialreleases_linux.json, validates archive path + 64-hex SHA256, and builds image from/opt/vps-stack/flutter-builderunder_flutter_image_lock(deployer.py:208-242).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 JWTrole == "service_role", and writesassets/env(deployer.py:252-306).flutter_build()runsdocker 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"):- Runs
rsync -av --delete <target_dir>/supabase/functions/ /opt/vps-stack/supabase/functions-{dev,prod}/. - Runs
docker restart supabase-edge-runtime-{dev,prod}(warning-only on restart exception) (deployer.py:308-324).
- Runs
planovi-converter(post_deploy: "converter_build"):- Validates
admin/.fvmrcand ensuresplanovi-flutter:<version>image FIRST (fail-fast before rebuilding API,deployer.py:331-333). - Rebuilds FastAPI container:
docker compose -f /opt/vps-stack/docker-compose.yml up -d --build converters-api-{dev,prod}. - If
<target_dir>/deploy/docker-compose.public-ingress.ymlAND<target_dir>/deploy/.envboth exist, rebuilds mTLS public ingress (deployer.py:337-339). - Builds Flutter admin web panel (
flutter_build(admin_dir, image)) and setschown -R 33:33 <target_dir>/admin/build/web. - Ensures
planovi-firmware-builder:latestimage exists (building fromdeploy/Dockerfile.firmware-builderif absent), compiles ARM firmware mountingplanovi-device-ca.pemandota-signing-key.pemread-only into/certs/, outputs to<target_dir>/firmware, and setschown -R 33:33 <target_dir>/firmware(deployer.py:346-350).
- Validates
- 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).
- Acquires global
- Failure Handling & Auto-Rollback (
deployer/deployer.py:390-403):- Any raised exception triggers
git reset --hard <old_commit>intarget_dir. - Extracts compiler error summary via
_log_tail()(up to 10 lines containingError:/error:with preceding.dart:/.py:/.ts:file context + last 8 tail lines, capped at1500chars, escaping backticks```->''') and posts failure + rollback alert to Google Chat (deployer.py:115-122,144-163,402-403).
- Any raised exception triggers
- Legacy GitHub Actions Workflow (
.github/workflows/deploy.yml):- Triggers on push to
planovi-vpsmain. Attempts to build./fastapi-appand./php-app, push toghcr.io, and SSH toVPS_HOSTtodocker compose pull fastapi-app php-app. Currently broken because./fastapi-appdoes not exist inplanovi-vpsandphp-app/index.phpis gitignored.
- Triggers on push to
Hard Business Rules, Validations, Calculations & Edge Cases
- BR-DEP-01 (Mandatory Startup Secret):
deployer.py:472-474aborts startup withsys.exit(1)and stderr"FATAL: zmienna WEBHOOK_SECRET jest pusta lub nieustawiona. Deployer nie wystartuje."ifWEBHOOK_SECRETis empty (no default fallback). - BR-DEP-02 (Mandatory Signature Enforcement): Unsigned requests (missing
X-Hub-Signature-256) are rejected withHTTP 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 = 600seconds (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.zchannel names (e.g."stable") matchingFLUTTER_VERSION_RE = ^\d+\.\d+\.\d+$(deployer.py:28,177-206). Release archive metadata must passFLUTTER_ARCHIVE_RE(no..) and 64-hexSHA256_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 inFLUTTER_TEMP_ALLOWED = {"DEALFLOW_API_SECRET", "SCHEDULER_API_SECRET"}, and base64-decodes any JWT value (3dot-parts starting witheyJ) to rejectrole == "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>intarget_dir(deployer.py:396-401); it does NOT re-runflutter_build, revertrsync-ed Edge Functions, or roll back rebuiltconverters-api-*Docker containers. - BR-DEP-09 (Live Script Execution):
deployer/Dockerfile:14executes/opt/vps-stack/deployer/deployer.pyfrom the bind-mounted/opt/vps-stackvolume rather than/app/deployer.pycopied at line 10. - BR-DEP-10 (Log Tail Truncation & Error Extraction):
_log_tail()scans lines prior to the last15lines forError:/error:, attaches the preceding line if it references.dart:,.py:, or.ts:, shows max10error snippets +---+ last8lines, and truncates tomax_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(publiclyhttps://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, writesassets/env, buildsbuild/web.vps-deployer -> planovi-backend| Syncssupabase/functions/->/opt/vps-stack/supabase/functions-{dev,prod}/and restartssupabase-edge-runtime-{dev,prod}.vps-deployer -> planovi-converter| Readsadmin/.fvmrc, rebuildsconverters-api-*, optionaldeploy/docker-compose.public-ingress.yml, buildsadmin/build/web, builds ARM firmware viadeploy/Dockerfile.firmware-builderwith/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 indeployer.py:21-22explains third-party Flutter Docker images lag behind or stop publishing; building directly from Google’s official SHA256-verified archive ensures exact.fvmrcparity. FLUTTER_TEMP_ALLOWEDexception: Comment indeployer.py:258-259explicitly marksDEALFLOW_API_SECRETandSCHEDULER_API_SECRETas temporary until an Edge Function proxy replaces direct browser calls to PHP microservices.- No
git cleanduring deploy: Preserves untracked runtime.envfiles anddealflow/data/*.jsonfiles 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.envcontaining 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.envand keep it only in server-side/opt/vps-stack/.env. - Symptom:
HTTP 403 Invalid signatureon GitHub webhook delivery -> Root Cause: Mismatch between GitHub repo webhook secret andWEBHOOK_SECRETin/opt/vps-stack/.env-> Verify:docker logs --tail 30 vps-deployer-> Fix: Synchronize webhook secret and restartvps-deployer. - Symptom:
planovi-flutter:<version>build fails with missing directory -> Root Cause:/opt/vps-stack/flutter-buildermissing on host -> Verify:ls -la /opt/vps-stack/flutter-builder-> Fix: Restoreflutter-builder/Dockerfileon VPS (and commit to repo).