Commit Graph

115 Commits

Author SHA1 Message Date
Matthew Meszaros 126114b34f feat(admin): audit-log every mutating worker / credentials / release action
The new admin endpoints for SSH worker management, AWS credentials,
worker profiles, releases, and system operations bypassed the existing
audit-logging pattern. Now every mutating action records a row in the
audit log with adminID, IP, user-agent, and operation-specific metadata
(never secret values — for credential updates we record which fields
were rotated, not what they became).

New action constants:
  test, install, restart, upgrade, uninstall, rotate_keys, apply,
  assign, system_update, reboot, check_releases

New entity types:
  worker, aws_credentials, worker_profile, release

Read-only endpoints (list/get/status/logs) intentionally not audited —
they don't change state and would flood the log.

Each handler calls a small h.audit(c, action, entity, &id, metadata)
helper that pulls adminID from the admin middleware and fires the
existing AuditService.LogAction (fire-and-forget, never blocks the
response).
2026-05-18 14:55:44 +00:00
Matthew Meszaros 8ae7759964 feat(consumer): sync worker heartbeats from Redis to workers.last_seen_at
Workers heartbeat into Redis every 90s as RFC3339 timestamp values with a
3-min TTL. The dashboard surfaces liveness based on workers.last_seen_at,
but until now nothing populated that column — the "Live" badge was always
red.

New 60s job in the consumer reads each active worker's Redis heartbeat
value, parses the timestamp, and writes it to workers.last_seen_at. Runs
on its own interval (separate from the 5-min dead-worker detection job,
which does heavier reassignment work) so the UI sees fresh data within a
minute.
2026-05-18 14:55:34 +00:00
Matthew Meszaros 261cc439ad feat(admin): manage worker fleet from dashboard with encrypted credentials and GitHub release auto-update
Workers are no longer curl|sh-only. Admins add and manage them from the
dashboard over SSH, with all runtime config (Kafka, Schema Registry,
Redis, AWS keys) stored encrypted via the existing KMS-envelope cipher
service.

Worker lifecycle:
  1. Admin POSTs host/port/user. Backend generates an ed25519 keypair,
     encrypts the private key under uuid.Nil (platform identity), and
     stores the row in 'pending' state.
  2. Admin pastes the returned public key into the VPS's authorized_keys.
  3. Test connection — runs `true` over SSH, pins the host SHA256
     fingerprint on first success (TOFU).
  4. Install — backend scp's install-worker.sh + a per-worker env file
     and runs it. State moves pending → provisioning → installed.
  5. From then on: restart, update image, apply config, uninstall,
     rotate keys, tail logs, live status, OS package update, reboot —
     all dashboard buttons backed by SSH operations.

Credentials are reusable entities:
  - aws_credentials: named keypair, secret encrypted at rest
  - worker_profiles: bundles Kafka + Schema Registry + Redis + image +
    release channel, references one AWS credentials row
  - workers.profile_id links a worker to a profile; many workers can
    share one profile

Saving a profile doesn't restart anything. The dashboard compares
profile.updated_at to each worker's config_applied_at and shows a
"stale config" badge; Apply rewrites /etc/warmbly/worker.env over SSH
and restarts the unit.

Auto-update on GitHub release:
  - profile.release_channel ∈ {pinned, stable, dev}
  - profile.auto_update toggles automatic rollout
  - Trigger model is push, not poll: one check on backend boot, then
    the /webhooks/github/releases endpoint (HMAC-validated with
    RELEASES_WEBHOOK_SECRET) on every release event. Manual "Check now"
    button as fallback.
  - When a new tag resolves, the orchestrator SSHes into each assigned
    worker, runs install-worker.sh --update --image <new>, which now
    rewrites the systemd unit (not just `docker pull`) so the image
    actually changes. workers.image_version captures the running tag
    for the UI's "v1.2.3 → v1.2.4" diff.

Self-hostable: every release knob is env-driven —
RELEASES_GITHUB_REPO, RELEASES_WORKER_IMAGE_REPO,
RELEASES_WEBHOOK_SECRET, RELEASES_GITHUB_TOKEN, RELEASES_ENABLED. Set
RELEASES_ENABLED=false to disable the feature entirely.

OS-level updates and reboot are also exposed: detect apt / dnf / yum /
pacman / apk, run the right upgrade noninteractively, return the full
output and a reboot-required flag. Reboots are never automatic.

Migrations:
  000028_worker_ssh        — ssh fields, install_state enum, last_seen,
                              host fingerprint
  000029_worker_credentials — aws_credentials + worker_profiles +
                              workers.profile_id + workers.config_applied_at
  000030_worker_releases   — release_channel enum, auto_update,
                              resolved_image_tag, workers.image_version

Endpoints added:
  POST   /admin/workers                        (create + keypair)
  GET    /admin/workers/managed
  GET    /admin/workers/:id/managed
  POST   /admin/workers/:id/{test,install,restart,upgrade,uninstall,rotate-keys,apply,system-update,reboot}
  PUT    /admin/workers/:id/profile
  GET    /admin/workers/:id/{live-status,logs}
  DELETE /admin/workers/:id
  GET    /admin/aws-credentials                CRUD
  GET    /admin/worker-profiles                CRUD + /workers + /apply + /release
  GET    /admin/releases/state
  POST   /admin/releases/check
  POST   /webhooks/github/releases             public, HMAC-validated

Admin UI:
  /app/admin/workers           list with status + version columns
  /app/admin/workers/new       add form with profile dropdown
  /app/admin/workers/:id       detail with all actions + logs + system update
  /app/admin/credentials       tabs: AWS credentials + worker profiles,
                                Releases panel, channel selector +
                                auto-update toggle in profile form
2026-05-18 13:09:11 +00:00
Matthew Meszaros 1ad8e7e995 feat: implement dead worker detection with heartbeat TTL and auto-reassignment 2026-04-12 11:14:24 +00:00
Matthew Meszaros 2f2ccb41dd feat: add exponential backoff retry for transient email send failures 2026-04-12 11:10:28 +00:00
Matthew Meszaros 3e556825d8 fix: add org scoping to contact notes and activities to prevent IDOR 2026-04-12 11:09:40 +00:00
Matthew Meszaros 562752d20e feat: skip bounced and suppressed contacts in campaign scheduling 2026-04-12 11:06:04 +00:00
Matthew Meszaros 0f883e38ac fix: record bounces in campaign progress so analytics and auto-pause work 2026-04-12 11:05:10 +00:00
Matthew Meszaros e7933ab6c5 feat: publish auth error events on critical mail errors and register token update handler 2026-04-10 07:05:39 +00:00
Matthew Meszaros f9d9ed6dc0 feat: implement IMAP sync worker and unified mail sync loop for all providers 2026-04-10 07:02:25 +00:00
Matthew Meszaros 00dac953ae fix: add nil checks on SmtpImapData and avoid slice modification during iteration 2026-04-10 06:58:41 +00:00
Matthew Meszaros 6766696ac4 fix: add 2-minute timeout context to task handlers to prevent hangs 2026-04-10 06:57:17 +00:00
Matthew Meszaros a741b4939a feat: implement worker HandleAddEmail and HandleRemoveEmail handlers 2026-04-10 06:56:35 +00:00
Matthew Meszaros fbd62ea20c fix: invert nil checks in dynamo email message Del so non-nil keys are added 2026-04-10 06:54:58 +00:00
Matthew Meszaros 58d41f3668 fix: store correct email account ID and message ID in dynamo email map 2026-04-10 06:54:31 +00:00
Matthew Meszaros 7f90323d55 chore: remove metrics endpoint, prometheus instrumentation, and IP rate limiter 2026-04-10 06:32:30 +00:00
Matthew Meszaros 7e123a2dac fix: remove deep health endpoint and add IP rate limiting to public endpoints 2026-04-09 16:03:37 +00:00
Matthew Meszaros 80358168ae test: add unit tests for warmup health evaluation, campaign state machine, and templates 2026-04-09 15:59:27 +00:00
Matthew Meszaros 23b5c925e4 feat: add scheduled warmup health sweep, pool health summary endpoint, and admin overview 2026-04-09 15:57:04 +00:00
Matthew Meszaros 65641ec1f2 feat: add send test email endpoint for campaign preview before launch 2026-04-09 15:52:59 +00:00
Matthew Meszaros 33092fa56e fix: add 10MB request body size limit to prevent OOM from large payloads 2026-04-09 15:50:08 +00:00
Matthew Meszaros 816c432e71 feat: add deep health check endpoint with PostgreSQL connectivity check 2026-04-09 15:49:28 +00:00
Matthew Meszaros dd1fc3d41d feat: generate List-Unsubscribe URL for campaign emails when unsubscribe header is enabled 2026-04-09 15:17:39 +00:00
Matthew Meszaros ffe6bd31ca fix: sanitize Stripe error messages to prevent leaking internal details to clients 2026-04-09 15:15:18 +00:00
Matthew Meszaros 3699774f7d fix: use timeout context for Stripe webhook migration goroutines to prevent leaks 2026-04-09 15:13:47 +00:00
Matthew Meszaros 9c4b6d21fd fix: add contact email deduplication with unique index and upsert on conflict 2026-04-09 15:12:41 +00:00
Matthew Meszaros 41aa183be2 fix: add campaign state machine to prevent invalid status transitions 2026-04-09 15:11:58 +00:00
Matthew Meszaros 36f4a94814 fix: prevent race condition in dedicated worker assignment with atomic insert 2026-04-09 14:54:22 +00:00
Matthew Meszaros 306690db0a feat: add explicit position column to sequences for deterministic ordering 2026-04-09 14:52:17 +00:00
Matthew Meszaros 421a3fb3dc fix: add campaign ownership validation to prevent IDOR in bulk campaign operations 2026-04-09 14:48:29 +00:00
Matthew Meszaros c2948d464b fix: add hard limit to pipeline list query to prevent unbounded results 2026-04-09 14:47:14 +00:00
Matthew Meszaros d903c26255 fix: add hard limit of 500 to template list query to prevent unbounded results 2026-04-09 14:46:20 +00:00
Matthew Meszaros 4f16944ff8 fix: add size limits to bulk contact operations to prevent resource exhaustion 2026-04-09 14:45:10 +00:00
Matthew Meszaros d417b1f0a4 perf: add missing index on campaign_leads(contact_id) for reverse lookups 2026-04-09 14:43:40 +00:00
Matthew Meszaros 4b8ff94201 fix: use correct column names contact_id and campaign_id in campaign_leads queries 2026-04-09 14:43:10 +00:00
Matthew Meszaros 0799020dac feat: add metrics, warmup content variety, tz-aware scheduling, org budget, admin stubs, and bug fixes 2026-04-09 14:33:45 +00:00
Matthew Meszaros 19d20e72b4 feat: add warmup health throttled state, complaint/bounce metrics, A/B analysis, and rate limiting 2026-04-09 12:51:30 +00:00
Matthew Meszaros ba9e3c096a fix: replace context.TODO with proper context in cipher and Google client
- cipher: use the already-available ctx parameter for DynamoDB Put
- goog: use context.Background for OAuth token refresh callback since
  it runs asynchronously outside any request lifecycle
2026-04-09 12:10:42 +00:00
Matthew Meszaros 91ec703093 fix: increment verification code tries on failed attempts
The Tries counter on login and registration sessions was checked but
never incremented, making the brute-force protection dead code. An
attacker could retry verification codes indefinitely within the session
TTL. Now each failed attempt increments and persists the counter.
2026-04-09 12:10:26 +00:00
Matthew Meszaros 4ec7e65896 fix: prevent nil deref on Stripe Customer and use background ctx for goroutines
- Guard checkoutSession.Customer access with nil checks to prevent panic
  when Stripe sends incomplete checkout session data
- Switch worker migration goroutines from request ctx to context.Background()
  since these operations outlive the webhook HTTP request and would be
  cancelled prematurely when the response completes
2026-04-09 12:09:07 +00:00
Matthew Meszaros 7fe8e663d5 fix: propagate parent context instead of context.TODO in cipher service
The ctx parameter was already available from the Cipher method but
wasn't being passed to the DynamoDB Put call for new DEK storage.
2026-04-09 12:06:54 +00:00
Matthew Meszaros 6517b06893 feat: expand warmup subject lines and conversation templates
Increase warmup subjects from 5 to 20 and conversations from 3 to 12
to reduce repetition patterns that spam filters can detect. New themes
cover industry, tools, networking, feedback, planning, reading, travel,
wellness, and events.
2026-04-09 12:06:30 +00:00
Matthew Meszaros 3edf6b1d22 refactor: remove redundant min/max helpers shadowing Go builtins
Go 1.21+ provides builtin min/max for all ordered types. Remove the
custom int helpers and replace math.Max with builtin max for floats.
2026-04-09 12:06:25 +00:00
Matthew Meszaros 57644d752d refactor: replace fmt.Printf with structured zerolog logging and fix weak URL hash
- Replace all fmt.Printf calls in Kafka consumer/producer, tracking consumer,
  and user email task with structured zerolog (log.Warn/Error/Info)
- Fix hashURL using SHA-256 instead of naive first-8-chars+length approach
  which was collision-prone for deduplication
2026-04-09 12:06:20 +00:00
Matthew Meszaros 9dbd25b24b feat: delete S3 email body after successful send 2026-04-03 06:25:44 +00:00
Matthew Meszaros 308f72b874 feat: add CORS origin config, encrypt email bodies in S3, replace printfs with structured logging 2026-04-03 06:24:20 +00:00
Matthew Meszaros d8d88c7f69 feat: add warmup health tracking, migrate repos to postgres, and overhaul web UI 2026-04-03 06:08:52 +00:00
Matthew Meszaros 21ffb6a748 feat: add advanced outreach controls with A/B testing, deliverability dashboard, and DLQ 2026-02-20 08:59:17 +00:00
Matthew Meszaros c564b3ac95 feat: implement unibox replies, warmup conversations, and daily email limits 2026-02-20 04:54:46 +00:00
Matthew Meszaros fbb55379c5 fix: propagate captcha errors and fix JWT signing
- Return actual captcha verification errors instead of generic
  internal errors in login, registration, and reset password flows
- Fix Sentry capturing wrong variable (err -> xerr) in
  RegistrationConfirm
- Pass AuthSecret as []byte to JWT SignedString/keyfunc
- Send form data in request body instead of PostForm for Turnstile
- Improve Turnstile non-200 error handling with response body logging

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 06:30:50 +01:00