Skip to content

About

Continuously compares the real state of your Docker containers against the declared state in your GitHub repo, flags any divergence ("drift") within ~60 seconds, and optionally explains the fix with AI and alerts you on Discord.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

116 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DriftWatch

Detects configuration drift between what your servers are actually running (Docker Engine) and what git says they should be running (docker-compose.yml), alerts you, and suggests the fix.

Stack: Go + Gin · SvelteKit dashboard · Cloudflare Workers/Pages · Postgres (Neon) · Redis (Upstash) · Docker · optional Gemini.

 your server                        DriftWatch backend (Go + Gin)                 GitHub
┌──────────────┐  HTTPS push   ┌────────────────────────────────────┐  ETag   ┌────────┐
│ Docker       │──────────────▶│ /api/agent/state  (per-project key)│◀───────▶│compose │
│ + agent (Go) │  every change │   │                                │  fetch  │  file  │
└──────────────┘  + heartbeat  │   ▼  Redis: live state (encrypted) │         └────────┘
   no inbound ports            │ scheduler: 1 goroutine / project   │            ▲ push
                               │   diff → reconcile → Gemini* → alert           │ webhook
                               └───────────┬────────────────────────┘      ┌─────┴──────┐
                                   Postgres│  Discord alert                │ CF Worker  │
                                           ▼                               │ HMAC-SHA256│
                                      SvelteKit dashboard                  └────────────┘

* optional, gated by a SHA-256 fingerprint so the same drift set is never analyzed twice.

Drift types

Type Meaning Severity
missing_container declared service isn't running (or crashed) critical
extra_container running container not in compose info
image_stale image reference differs (registry/repo/tag/digest) warning
env_mismatch a declared env var is unset or different (one event per variable) critical for keys containing PASSWORD/SECRET/KEY/TOKEN/DATABASE/DB, else warning
port_changed a declared published port isn't bound warning

Secret values are never stored, shown, logged or sent to the LLM (<redacted>), including values that embed credentials in a URL.

What changed in this rewrite (and why the old build wasn't workable)

The previous builds compared the wrong things, so almost every real deployment looked broken. This version fixes the root causes:

Problem in the old build Now
Live containers were matched by container name (shop-web-1) against compose service names (web) → every service reported missing and extra Agent reports the com.docker.compose.service label; container_name: aliases are honored
The "dedupe hash" included captured_at, so it changed on every push and never matched → a Gemini call and a Discord alert on every scan Hash is over live + declared state only (order-independent). Unchanged state skips the scan; an identical drift set reuses the cached analysis
Drift events were never resolved; one open env_mismatch per container hid all others Each drift is tracked by (container, type, env-var); gone drifts auto-resolve; changed values update in place; a unique index prevents duplicates
Webhook-triggered scans were skipped when the live state hadn't changed A forced scan bypasses the shortcut and the fetch cache
Ports compared as 0:80 vs 127.0.0.1:8080:80 → false positives Canonical host:container/proto on both sides (IPs, ranges, long syntax)
${VAR} in compose compared literally; only docker-compose.yml was tried; exited one-shot jobs flagged critical; profiles and replicas: 0 counted as missing; the agent flagged itself as extra Interpolation (from the repo's .env; unresolvable values are skipped, not guessed), 4 filename fallbacks + compose_path, one-shot detection, profiles/replicas skipped, agent self-exclusion + driftwatch.ignore label + optional DRIFTWATCH_COMPOSE_PROJECT
Discord alert only if Gemini succeeded (contradicting "AI is optional") Rule-based analysis and fix commands when AI is off or fails
Env secrets stored in drift rows/snapshots and sent to Gemini Redacted everywhere; cached live state is AES-GCM encrypted in Redis
Arbitrary Discord webhook URL (SSRF), unvalidated repo/branch strings, no login rate limit, 24 h token only Discord host allow-list, strict validation, per-IP limiter on auth, JWT HS256-only
GitHub fetched every cycle (60 req/h unauthenticated) ETag conditional requests (304s are free); a GitHub outage falls back to the last good copy
No way to tell a dead agent from "no drift" last_agent_seen_at / agent_connected; stale state isn't diffed

Quick start (local)

Prereqs: Go 1.22+, Postgres, Redis (optional locally), Node 20 for the dashboard.

cd driftwatch/backend
cp .env.example .env            # minimum: DATABASE_URL, JWT_SECRET
go mod tidy                     # first time only — creates go.sum; commit it
go run ./cmd/server             # migrations run on boot; API on :8080

Dashboard: cd driftwatch/dashboard && npm install && npm run dev (needs GITHUB_OAUTH_* set to sign in; see SETUP.md).

Agent (on the machine with Docker; key is shown once when you create a project):

DRIFTWATCH_URL=http://localhost:8080 DRIFTWATCH_AGENT_KEY=dw_... go run ./cmd/agent
# or: docker build -f agent.Dockerfile -t driftwatch-agent . && see deploy/agent/docker-compose.agent.yml

Tests: make test (race detector on). Production deploy: see deploy/README.md (VPS + Caddy) or SETUP.md (free tier).

Configuration

Variable Required Purpose
DATABASE_URL yes Postgres (Neon works; pooled endpoints are supported)
JWT_SECRET yes signs session tokens
REDIS_URL recommended Upstash rediss://…; empty ⇒ in-memory cache (single instance only)
ENCRYPTION_KEY recommended AES-256-GCM for GitHub tokens + cached live state
GITHUB_OAUTH_CLIENT_ID/SECRET, BACKEND_URL, DASHBOARD_URL, ALLOWED_ORIGIN for sign-in OAuth callback = ${BACKEND_URL}/api/auth/github/callback
WEBHOOK_SECRET optional shared with the Cloudflare worker
GEMINI_API_KEY, GEMINI_MODEL optional AI summaries (rule-based otherwise)
SCAN_INTERVAL (60s), AGENT_STALE_AFTER (3m), LOG_LEVEL, PORT optional tuning

Agent: DRIFTWATCH_URL, DRIFTWATCH_AGENT_KEY (required); DOCKER_HOST, DRIFTWATCH_COMPOSE_PROJECT, POLL_INTERVAL (10s), HEARTBEAT_INTERVAL (45s).

API

All responses: { "data": …, "message": … } or { "error": …, "code": … }.

Method Path Auth
POST /api/auth/register, /api/auth/login – (rate limited)
GET /api/auth/github/login, /api/auth/github/callback –
GET /api/me JWT
POST/GET /api/projects JWT (create returns agent_key once)
GET/DELETE /api/projects/:id JWT, owner only
POST /api/projects/:id/rotate-agent-key JWT, owner
POST /api/projects/:id/scan JWT, owner (forces a rescan)
GET /api/projects/:id/drifts?status=open|resolved&limit&offset JWT, owner (open first)
GET /api/projects/:id/drifts/:driftId JWT, owner
POST /api/projects/:id/drifts/:driftId/resolve JWT, owner (acknowledge)
GET /api/github/repos, /api/github/repos/:owner/:repo/branches JWT (user's OAuth token)
POST /api/agent/state X-DriftWatch-Agent-Key
POST /api/webhook/github X-DriftWatch-Secret (from the worker)
GET /health, /status –

Create-project body: name, repo_owner, repo_name, optional repo_branch (default main), compose_path, github_token, discord_webhook_url.

Layout

driftwatch/
├── backend/                 Go module
│   ├── cmd/server           API + scheduler        cmd/agent   the agent
│   └── internal/
│       ├── api              Gin handlers, CORS, middleware
│       ├── scheduler        per-project goroutines, scan → diff → reconcile → analyze → alert
│       ├── diff             drift engine (+ redaction, rule-based analysis)
│       ├── compose          compose parser, ${VAR} interpolation
│       ├── ports            canonical port mappings
│       ├── store            pgx queries + embedded migrations (golang-migrate compatible)
│       ├── ghclient gemini discord cache crypto auth config model logx agent
├── dashboard/               SvelteKit (unchanged API contract)
└── webhook-worker/          Cloudflare Worker (HMAC-SHA256 verify → backend)
deploy/                      VPS compose + Caddy, agent compose

Known limits

  • Compose features not analyzed: env_file, extends/include, multiple -f files, .env values that aren't committed to the repo (those comparisons are skipped, never guessed).
  • Image drift compares references, not registry digests (a re-pushed tag with the same name is invisible).
  • The agent forwards container env to the backend (needed to compare); it is encrypted at rest in Redis and redacted in Postgres, but you should still treat the agent key as a secret (rotate it from the API if leaked).
  • Live env also contains image-baked variables; only variables declared in compose are compared.

About

Continuously compares the real state of your Docker containers against the declared state in your GitHub repo, flags any divergence ("drift") within ~60 seconds, and optionally explains the fix with AI and alerts you on Discord.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages