Files
warmbly/internal/app/worker_orchestrator/ssh_client.go
T
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

181 lines
4.2 KiB
Go

package worker_orchestrator
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
// dialer wraps an *ssh.Client with helpers tailored for what the orchestrator
// actually needs: run commands, upload small files, with TOFU host-key pinning.
type dialer struct {
client *ssh.Client
// fingerprint observed during this connect. Caller stores it back into the
// workers row on first connect for future verification.
observedFingerprint string
}
type dialOptions struct {
host string
port int
user string
signer ssh.Signer
password string // optional; used only when signer is nil
expectedFingerprint string // empty on first connect (TOFU)
timeout time.Duration
}
func dial(ctx context.Context, opts dialOptions) (*dialer, error) {
if opts.port == 0 {
opts.port = 22
}
if opts.user == "" {
opts.user = "root"
}
if opts.timeout == 0 {
opts.timeout = 15 * time.Second
}
var auths []ssh.AuthMethod
if opts.signer != nil {
auths = append(auths, ssh.PublicKeys(opts.signer))
}
if opts.password != "" {
auths = append(auths, ssh.Password(opts.password))
}
if len(auths) == 0 {
return nil, errors.New("no SSH auth method configured")
}
d := &dialer{}
hostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
fp := FingerprintSHA256(key)
d.observedFingerprint = fp
if opts.expectedFingerprint == "" {
return nil // TOFU: accept and pin
}
if fp != opts.expectedFingerprint {
return fmt.Errorf("host key mismatch: pinned %s, got %s", opts.expectedFingerprint, fp)
}
return nil
}
cfg := &ssh.ClientConfig{
User: opts.user,
Auth: auths,
HostKeyCallback: hostKeyCallback,
Timeout: opts.timeout,
}
addr := net.JoinHostPort(opts.host, strconv.Itoa(opts.port))
// Honour context cancellation while net dial would otherwise block.
type dialResult struct {
conn net.Conn
err error
}
resCh := make(chan dialResult, 1)
go func() {
c, err := (&net.Dialer{Timeout: opts.timeout}).DialContext(ctx, "tcp", addr)
resCh <- dialResult{c, err}
}()
var rawConn net.Conn
select {
case <-ctx.Done():
return nil, ctx.Err()
case r := <-resCh:
if r.err != nil {
return nil, fmt.Errorf("dial %s: %w", addr, r.err)
}
rawConn = r.conn
}
c, chans, reqs, err := ssh.NewClientConn(rawConn, addr, cfg)
if err != nil {
_ = rawConn.Close()
return nil, fmt.Errorf("ssh handshake: %w", err)
}
d.client = ssh.NewClient(c, chans, reqs)
return d, nil
}
func (d *dialer) Close() error {
if d.client == nil {
return nil
}
return d.client.Close()
}
// Run executes a command, returning combined stdout/stderr. Stderr is appended
// to stdout because most of what we run is `set -e` shell that interleaves.
func (d *dialer) Run(ctx context.Context, cmd string) (string, error) {
sess, err := d.client.NewSession()
if err != nil {
return "", fmt.Errorf("new session: %w", err)
}
defer sess.Close()
var out bytes.Buffer
sess.Stdout = &out
sess.Stderr = &out
done := make(chan error, 1)
go func() { done <- sess.Run(cmd) }()
select {
case <-ctx.Done():
_ = sess.Signal(ssh.SIGINT)
return out.String(), ctx.Err()
case err := <-done:
return out.String(), err
}
}
// Upload writes content to a remote path via stdin to `tee`. Avoids requiring
// an scp/sftp subsystem on the target.
func (d *dialer) Upload(ctx context.Context, remotePath, content string, mode string) error {
sess, err := d.client.NewSession()
if err != nil {
return fmt.Errorf("new session: %w", err)
}
defer sess.Close()
stdin, err := sess.StdinPipe()
if err != nil {
return err
}
cmd := fmt.Sprintf("install -D -m %s /dev/stdin %s", mode, shellQuote(remotePath))
if err := sess.Start(cmd); err != nil {
return fmt.Errorf("start tee: %w", err)
}
if _, err := io.WriteString(stdin, content); err != nil {
return err
}
if err := stdin.Close(); err != nil {
return err
}
done := make(chan error, 1)
go func() { done <- sess.Wait() }()
select {
case <-ctx.Done():
_ = sess.Signal(ssh.SIGINT)
return ctx.Err()
case err := <-done:
return err
}
}
func shellQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}