hub v0.127.0: off-site key registrar (box never gets the storage password), password sealed at rest, daily key check, clean-up window (shipped off) — decisions 68-69, R-820/R-821/R-822
gates / gates (push) Successful in 29s

Part A evidence (migration spike, sftp-written repo through the pinned rclone key) and the hub
red-proofs under documentation/audits/offsite-lock-build-2026-10-03/. Manifest bump follows after
the image is built and Secret/offsite-secret-key exists.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-03 16:57:04 +02:00
1 parent 5188dbdb44
commit f417cdede1
28 files changed
+2333 -44

No files matched your search

+386
View File
@@ -0,0 +1,386 @@
// Package offsitekeys is the hub's off-site KEY REGISTRAR (decision 69, R-820): the hub — never the box —
// writes the box's public key into the customer's Storage Box sub-account `.ssh/authorized_keys`, pinned
// to an append-only rclone server, and audits that file.
//
// WHY THE HUB AND NOT THE BOX (measured 2026-10-03, audits/offsite-append-only-2026-10-03/): a key pinned
// to `command="rclone serve restic --stdio --append-only <repo>",restrict` can back up and restore and is
// refused every delete (403). But the sub-account PASSWORD logs in on ports 22 and 23 and can rewrite
// `authorized_keys` — removing the pin. So the protection holds only if no box ever holds the password.
// The box sends its PUBLIC key; the hub, which keeps the password sealed (R-821), does the write.
//
// THE TRANSPORT IS THE PROVIDER'S RESTRICTED SHELL (port 23), not SFTP: measured on the provider, its
// `dd of=<file>` takes stdin, `mv` overwrites, `cat` of a missing file exits 1, and `test` does not exist.
// That needs only golang.org/x/crypto/ssh, which the hub already uses — no new dependency.
//
// THE WINDOW (decision 68, Part E): OpenSSH uses the FIRST line whose key matches. Measured on the
// provider: the same key on an append-only line first and a deleting line second → refused (403);
// deleting line first → deletes. So opening a window = PREPENDING an unpinned-delete line for the box's
// own key; closing = removing it. One key on the box.
package offsitekeys
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"golang.org/x/crypto/ssh"
)
// Shell runs one command in the sub-account's restricted shell, feeding stdin, returning stdout. A
// non-zero exit is an error (*ssh.ExitError underneath).
type Shell interface {
Run(ctx context.Context, cmd string, stdin []byte) ([]byte, error)
Close() error
}
// Target is one sub-account, from the customer's offsite descriptor.
type Target struct {
Host string
User string
Port int
RepoPath string // e.g. /home/felhom-repo — measured: an absolute path works in the forced command
Fingerprint string // the host-key fingerprint captured at provisioning (SHA256:…); REQUIRED
}
// Dialer opens a Shell to a Target with the sub-account password, verifying the host key against
// Target.Fingerprint (never TOFU).
type Dialer interface {
Dial(ctx context.Context, t Target, password string) (Shell, error)
}
// PinnedPrefix is the authorized_keys option set every box key must carry outside a window.
func PinnedPrefix(repoPath string) string {
return fmt.Sprintf(`command="rclone serve restic --stdio --append-only %s",restrict `, repoPath)
}
// WindowPrefix is the DELETING line written only while a clean-up window is open (decision 68).
func WindowPrefix(repoPath string) string {
return fmt.Sprintf(`command="rclone serve restic --stdio %s",restrict `, repoPath)
}
const authorizedKeys = ".ssh/authorized_keys"
const tmpKeys = ".ssh/authorized_keys.felhom-new"
// Line is one parsed authorized_keys line.
type Line struct {
Raw string
Fingerprint string // SHA256:… of the key, "" when the line holds no parseable key
Pinned bool // carries exactly PinnedPrefix(repo)
Window bool // carries exactly WindowPrefix(repo)
}
// ParseLines classifies every non-empty, non-comment line of an authorized_keys file.
func ParseLines(content, repoPath string) []Line {
var out []Line
pin, win := PinnedPrefix(repoPath), WindowPrefix(repoPath)
for _, raw := range strings.Split(content, "\n") {
raw = strings.TrimRight(raw, "\r")
t := strings.TrimSpace(raw)
if t == "" || strings.HasPrefix(t, "#") {
continue
}
l := Line{Raw: t, Pinned: strings.HasPrefix(t, pin), Window: strings.HasPrefix(t, win)}
if pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(t)); err == nil {
l.Fingerprint = ssh.FingerprintSHA256(pk)
}
out = append(out, l)
}
return out
}
// KeyFingerprint validates a single PUBLIC key line as a box would send it (no options) and returns its
// fingerprint and its canonical "type base64" form (the comment is dropped — it is box-supplied text).
func KeyFingerprint(pub string) (fp, canonical string, err error) {
pub = strings.TrimSpace(pub)
if pub == "" || strings.ContainsAny(pub, "\n\r\x00") {
return "", "", errors.New("offsitekeys: public key must be one line")
}
pk, _, options, _, err := ssh.ParseAuthorizedKey([]byte(pub))
if err != nil {
return "", "", fmt.Errorf("offsitekeys: not a public key: %w", err)
}
if len(options) > 0 {
return "", "", errors.New("offsitekeys: a box key must carry no options — the hub writes them")
}
switch pk.Type() {
case ssh.KeyAlgoED25519, ssh.KeyAlgoRSA, ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521:
default:
return "", "", fmt.Errorf("offsitekeys: key type %s not accepted", pk.Type())
}
canon := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pk)))
return ssh.FingerprintSHA256(pk), canon, nil
}
// Registrar performs the key-file operations. Every method opens its own Shell and closes it.
type Registrar struct {
Dialer Dialer
}
func (r *Registrar) open(ctx context.Context, t Target, password string) (Shell, error) {
if t.Fingerprint == "" {
return nil, errors.New("offsitekeys: target has no host fingerprint — refusing (no blind TOFU)")
}
if t.Host == "" || t.User == "" || t.RepoPath == "" {
return nil, errors.New("offsitekeys: target missing host/user/repo_path")
}
return r.Dialer.Dial(ctx, t, password)
}
// read returns the current authorized_keys content; a missing file is "" (cat exits 1 there).
func read(ctx context.Context, sh Shell) (string, error) {
if _, err := sh.Run(ctx, "ls -d .ssh", nil); err != nil {
if _, merr := sh.Run(ctx, "mkdir .ssh", nil); merr != nil {
return "", fmt.Errorf("offsitekeys: create .ssh: %w", merr)
}
_, _ = sh.Run(ctx, "chmod 700 .ssh", nil)
return "", nil
}
if _, err := sh.Run(ctx, "ls "+authorizedKeys, nil); err != nil {
return "", nil // no file yet
}
out, err := sh.Run(ctx, "cat "+authorizedKeys, nil)
if err != nil {
return "", fmt.Errorf("offsitekeys: read authorized_keys: %w", err)
}
return string(out), nil
}
// write replaces authorized_keys atomically (dd to a temp file, chmod, mv) and reads it back.
func write(ctx context.Context, sh Shell, content string) error {
if _, err := sh.Run(ctx, "dd of="+tmpKeys, []byte(content)); err != nil {
return fmt.Errorf("offsitekeys: write temp file: %w", err)
}
if _, err := sh.Run(ctx, "chmod 600 "+tmpKeys, nil); err != nil {
return fmt.Errorf("offsitekeys: chmod temp file: %w", err)
}
if _, err := sh.Run(ctx, "mv "+tmpKeys+" "+authorizedKeys, nil); err != nil {
return fmt.Errorf("offsitekeys: move into place: %w", err)
}
back, err := sh.Run(ctx, "cat "+authorizedKeys, nil)
if err != nil {
return fmt.Errorf("offsitekeys: read back: %w", err)
}
if strings.TrimSpace(string(back)) != strings.TrimSpace(content) {
return errors.New("offsitekeys: read-back differs from what was written")
}
return nil
}
func join(lines []string) string {
if len(lines) == 0 {
return ""
}
return strings.Join(lines, "\n") + "\n"
}
// InstallResult says what Install changed.
type InstallResult struct {
Fingerprint string
RemovedUnpinned int // unpinned lines dropped (any line without the pin is a deletion route)
}
// Install adds the box's key pinned append-only. Every UNPINNED line is dropped in the same write — an
// unpinned line is a route to deletion (this is also the migration of a box whose key predates the pin:
// the same key comes back pinned). Other PINNED lines are kept until Confirm, so a box that has not yet
// switched keeps working (rotation: write new → box confirms → remove old). Idempotent.
func (r *Registrar) Install(ctx context.Context, t Target, password, pub string) (InstallResult, error) {
fp, canon, err := KeyFingerprint(pub)
if err != nil {
return InstallResult{}, err
}
sh, err := r.open(ctx, t, password)
if err != nil {
return InstallResult{}, err
}
defer sh.Close()
cur, err := read(ctx, sh)
if err != nil {
return InstallResult{}, err
}
res := InstallResult{Fingerprint: fp}
var keep []string
for _, l := range ParseLines(cur, t.RepoPath) {
switch {
case !l.Pinned:
res.RemovedUnpinned++
case l.Fingerprint == fp:
// re-added below, once
default:
keep = append(keep, l.Raw)
}
}
keep = append(keep, PinnedPrefix(t.RepoPath)+canon+" felhom-box")
if err := write(ctx, sh, join(keep)); err != nil {
return InstallResult{}, err
}
return res, nil
}
// Confirm keeps ONLY the pinned line of the confirmed key — the rotation's last step. Returns how many
// lines it removed. Refuses when the confirmed key is not present pinned (nothing is written).
func (r *Registrar) Confirm(ctx context.Context, t Target, password, fp string) (int, error) {
sh, err := r.open(ctx, t, password)
if err != nil {
return 0, err
}
defer sh.Close()
cur, err := read(ctx, sh)
if err != nil {
return 0, err
}
var keep []string
removed := 0
for _, l := range ParseLines(cur, t.RepoPath) {
if l.Pinned && l.Fingerprint == fp {
if len(keep) == 0 {
keep = append(keep, l.Raw)
} else {
removed++
}
continue
}
removed++
}
if len(keep) == 0 {
return 0, fmt.Errorf("offsitekeys: key %s is not installed pinned — nothing confirmed", fp)
}
if removed == 0 {
return 0, nil
}
if err := write(ctx, sh, join(keep)); err != nil {
return 0, err
}
return removed, nil
}
// Finding is one problem the audit saw. It names the line by fingerprint, NEVER by key material.
type Finding struct {
Fingerprint string
Kind string // "unpinned" | "window" | "unparseable"
}
// AuditResult is the daily check's view of one sub-account.
type AuditResult struct {
Lines int
Pinned int
Findings []Finding
}
// Audit reads authorized_keys and reports every line that is not pinned append-only. A window line is
// reported only when no window is supposed to be open. Read-only.
func (r *Registrar) Audit(ctx context.Context, t Target, password string, windowOpen bool) (AuditResult, error) {
sh, err := r.open(ctx, t, password)
if err != nil {
return AuditResult{}, err
}
defer sh.Close()
cur, err := read(ctx, sh)
if err != nil {
return AuditResult{}, err
}
return audit(cur, t.RepoPath, windowOpen), nil
}
func audit(content, repo string, windowOpen bool) AuditResult {
var res AuditResult
for _, l := range ParseLines(content, repo) {
res.Lines++
switch {
case l.Pinned:
res.Pinned++
case l.Window && windowOpen:
// expected while the window is open
case l.Window:
res.Findings = append(res.Findings, Finding{Fingerprint: l.Fingerprint, Kind: "window"})
case l.Fingerprint == "":
res.Findings = append(res.Findings, Finding{Kind: "unparseable"})
default:
res.Findings = append(res.Findings, Finding{Fingerprint: l.Fingerprint, Kind: "unpinned"})
}
}
sort.Slice(res.Findings, func(i, j int) bool { return res.Findings[i].Fingerprint < res.Findings[j].Fingerprint })
return res
}
// OpenWindow PREPENDS a deleting line for the (pinned, installed) key fp — first match wins (measured).
// Refuses when fp is not installed pinned. Idempotent.
func (r *Registrar) OpenWindow(ctx context.Context, t Target, password, fp string) error {
sh, err := r.open(ctx, t, password)
if err != nil {
return err
}
defer sh.Close()
cur, err := read(ctx, sh)
if err != nil {
return err
}
var body string
var rest []string
for _, l := range ParseLines(cur, t.RepoPath) {
if l.Window {
continue // re-written below exactly once
}
if l.Pinned && l.Fingerprint == fp && body == "" {
body = strings.TrimPrefix(l.Raw, PinnedPrefix(t.RepoPath))
}
rest = append(rest, l.Raw)
}
if body == "" {
return fmt.Errorf("offsitekeys: key %s is not installed pinned — no window opened", fp)
}
return write(ctx, sh, join(append([]string{WindowPrefix(t.RepoPath) + body}, rest...)))
}
// CloseWindow removes every window line. Idempotent; a file with no window line is not rewritten.
func (r *Registrar) CloseWindow(ctx context.Context, t Target, password string) error {
sh, err := r.open(ctx, t, password)
if err != nil {
return err
}
defer sh.Close()
cur, err := read(ctx, sh)
if err != nil {
return err
}
var rest []string
found := false
for _, l := range ParseLines(cur, t.RepoPath) {
if l.Window {
found = true
continue
}
rest = append(rest, l.Raw)
}
if !found {
return nil
}
return write(ctx, sh, join(rest))
}
// MoveAside renames the repository directory to `<repo>.orphaned-<date>` (then -2, -3 …), NEVER
// deletes — the R-26/R-32 move-aside the box can no longer do itself (its key reaches only the pinned
// rclone server). Returns the new path. A missing repository is an error (nothing to set aside).
func (r *Registrar) MoveAside(ctx context.Context, t Target, password, date string) (string, error) {
sh, err := r.open(ctx, t, password)
if err != nil {
return "", err
}
defer sh.Close()
if _, err := sh.Run(ctx, "ls -d "+t.RepoPath, nil); err != nil {
return "", fmt.Errorf("offsitekeys: repository %s not found: %w", t.RepoPath, err)
}
base := t.RepoPath + ".orphaned-" + date
name := base
for i := 2; i <= 50; i++ {
if _, err := sh.Run(ctx, "ls -d "+name, nil); err != nil {
break // absent → free
}
name = fmt.Sprintf("%s-%d", base, i)
}
if _, err := sh.Run(ctx, "mv "+t.RepoPath+" "+name, nil); err != nil {
return "", fmt.Errorf("offsitekeys: move aside: %w", err)
}
return name, nil
}
@@ -0,0 +1,216 @@
package offsitekeys
import (
"context"
"crypto/ed25519"
"crypto/rand"
"errors"
"strings"
"testing"
"golang.org/x/crypto/ssh"
)
// fakeFS emulates the provider's restricted shell as MEASURED 2026-10-03: `dd of=` takes stdin, `mv`
// overwrites, `cat`/`ls` of a missing path exit non-zero, `test` does not exist.
type fakeFS struct {
files map[string]string
dirs map[string]bool
cmds []string
}
func newFS() *fakeFS { return &fakeFS{files: map[string]string{}, dirs: map[string]bool{".ssh": true}} }
func (f *fakeFS) Run(_ context.Context, cmd string, stdin []byte) ([]byte, error) {
f.cmds = append(f.cmds, cmd)
a := strings.Fields(cmd)
miss := errors.New("exit status 1")
switch {
case a[0] == "ls" && a[1] == "-d":
if f.dirs[a[2]] {
return []byte(a[2] + "\n"), nil
}
return nil, miss
case a[0] == "ls":
if _, ok := f.files[a[1]]; ok {
return []byte(a[1]), nil
}
return nil, miss
case a[0] == "cat":
if v, ok := f.files[a[1]]; ok {
return []byte(v), nil
}
return nil, miss
case a[0] == "mkdir":
f.dirs[a[1]] = true
return nil, nil
case a[0] == "chmod":
return nil, nil
case strings.HasPrefix(a[0], "dd") && strings.HasPrefix(a[1], "of="):
f.files[strings.TrimPrefix(a[1], "of=")] = string(stdin)
return nil, nil
case a[0] == "mv":
if v, ok := f.files[a[1]]; ok {
f.files[a[2]] = v
delete(f.files, a[1])
return nil, nil
}
if f.dirs[a[1]] {
f.dirs[a[2]] = true
delete(f.dirs, a[1])
return nil, nil
}
return nil, miss
case a[0] == "rm":
return nil, errors.New("the registrar must never delete")
}
return nil, errors.New("Command not found")
}
func (f *fakeFS) Close() error { return nil }
type fakeDialer struct{ fs *fakeFS }
func (d fakeDialer) Dial(context.Context, Target, string) (Shell, error) { return d.fs, nil }
var tgt = Target{Host: "u1-sub4.example", User: "u1-sub4", Port: 23, RepoPath: "/home/felhom-repo", Fingerprint: "SHA256:host"}
func newKey(t *testing.T) (pub, fp string) {
t.Helper()
k, _, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
pk, _ := ssh.NewPublicKey(k)
return strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pk))) + " box", ssh.FingerprintSHA256(pk)
}
// The MIGRATION shape: a box whose key predates the pin (an unpinned line, exactly as ssh-copy-id left
// it) registers the SAME key → it comes back pinned and the unpinned line is gone. Then the audit is clean.
func TestInstall_MigratesUnpinnedKeyAndAuditGoesClean(t *testing.T) {
fs := newFS()
pub, fp := newKey(t)
other, _ := newKey(t)
fs.files[".ssh/authorized_keys"] = pub + "\n" + other + "\n"
r := &Registrar{Dialer: fakeDialer{fs}}
before, err := r.Audit(context.Background(), tgt, "pw", false)
if err != nil || len(before.Findings) != 2 {
t.Fatalf("before: %+v %v — want 2 unpinned findings (the decoy must be seen)", before, err)
}
res, err := r.Install(context.Background(), tgt, "pw", pub)
if err != nil || res.Fingerprint != fp || res.RemovedUnpinned != 2 {
t.Fatalf("install = %+v, %v", res, err)
}
got := fs.files[".ssh/authorized_keys"]
if !strings.HasPrefix(got, PinnedPrefix(tgt.RepoPath)) || strings.Count(got, "\n") != 1 {
t.Fatalf("file after install:\n%s", got)
}
after, _ := r.Audit(context.Background(), tgt, "pw", false)
if len(after.Findings) != 0 || after.Pinned != 1 {
t.Fatalf("after: %+v", after)
}
for _, c := range fs.cmds {
if strings.HasPrefix(c, "rm") {
t.Fatalf("registrar issued a delete: %q", c)
}
}
}
// Rotation: new key installed beside the old pinned one; Confirm leaves only the new one.
func TestInstallThenConfirm_Rotation(t *testing.T) {
fs := newFS()
r := &Registrar{Dialer: fakeDialer{fs}}
oldPub, oldFP := newKey(t)
newPub, newFP := newKey(t)
if _, err := r.Install(context.Background(), tgt, "pw", oldPub); err != nil {
t.Fatal(err)
}
if _, err := r.Install(context.Background(), tgt, "pw", newPub); err != nil {
t.Fatal(err)
}
lines := ParseLines(fs.files[".ssh/authorized_keys"], tgt.RepoPath)
if len(lines) != 2 || !lines[0].Pinned || !lines[1].Pinned {
t.Fatalf("both keys must be pinned until confirm: %+v", lines)
}
if _, err := r.Confirm(context.Background(), tgt, "pw", "SHA256:not-installed"); err == nil {
t.Fatal("confirming an absent key must refuse")
}
n, err := r.Confirm(context.Background(), tgt, "pw", newFP)
if err != nil || n != 1 {
t.Fatalf("confirm = %d, %v", n, err)
}
lines = ParseLines(fs.files[".ssh/authorized_keys"], tgt.RepoPath)
if len(lines) != 1 || lines[0].Fingerprint != newFP || lines[0].Fingerprint == oldFP {
t.Fatalf("after confirm: %+v", lines)
}
}
// The window (decision 68): the deleting line goes FIRST (first match wins — measured), the audit
// tolerates it only while a window is open, and closing removes it.
func TestWindow_PrependAuditClose(t *testing.T) {
fs := newFS()
r := &Registrar{Dialer: fakeDialer{fs}}
pub, fp := newKey(t)
if err := r.OpenWindow(context.Background(), tgt, "pw", fp); err == nil {
t.Fatal("a window for a key that is not installed must refuse")
}
if _, err := r.Install(context.Background(), tgt, "pw", pub); err != nil {
t.Fatal(err)
}
if err := r.OpenWindow(context.Background(), tgt, "pw", fp); err != nil {
t.Fatal(err)
}
lines := ParseLines(fs.files[".ssh/authorized_keys"], tgt.RepoPath)
if len(lines) != 2 || !lines[0].Window || !lines[1].Pinned || lines[0].Fingerprint != fp {
t.Fatalf("window line must be first: %+v", lines)
}
if a, _ := r.Audit(context.Background(), tgt, "pw", true); len(a.Findings) != 0 {
t.Fatalf("open window flagged: %+v", a)
}
if a, _ := r.Audit(context.Background(), tgt, "pw", false); len(a.Findings) != 1 || a.Findings[0].Kind != "window" {
t.Fatalf("a window line with no open window must alarm: %+v", a)
}
if err := r.CloseWindow(context.Background(), tgt, "pw"); err != nil {
t.Fatal(err)
}
if a, _ := r.Audit(context.Background(), tgt, "pw", false); len(a.Findings) != 0 || a.Pinned != 1 {
t.Fatalf("after close: %+v", a)
}
}
// Move-aside renames, never deletes, and never reuses a name.
func TestMoveAside_RenamesNeverDeletes(t *testing.T) {
fs := newFS()
fs.dirs["/home/felhom-repo"] = true
fs.dirs["/home/felhom-repo.orphaned-20261003"] = true
r := &Registrar{Dialer: fakeDialer{fs}}
to, err := r.MoveAside(context.Background(), tgt, "pw", "20261003")
if err != nil || to != "/home/felhom-repo.orphaned-20261003-2" {
t.Fatalf("move-aside = %q, %v", to, err)
}
if fs.dirs["/home/felhom-repo"] || !fs.dirs["/home/felhom-repo.orphaned-20261003"] {
t.Fatalf("dirs after: %v", fs.dirs)
}
}
func TestTargetWithoutFingerprint_Refused(t *testing.T) {
r := &Registrar{Dialer: fakeDialer{newFS()}}
pub, _ := newKey(t)
nt := tgt
nt.Fingerprint = ""
if _, err := r.Install(context.Background(), nt, "pw", pub); err == nil {
t.Fatal("no host fingerprint must refuse (no blind TOFU)")
}
}
func TestKeyFingerprint_RefusesOptionsAndJunk(t *testing.T) {
pub, _ := newKey(t)
for _, bad := range []string{"", "not a key", `command="sh" ` + pub, pub + "\n" + pub} {
if _, _, err := KeyFingerprint(bad); err == nil {
t.Fatalf("accepted %q", bad)
}
}
if _, _, err := KeyFingerprint(pub); err != nil {
t.Fatal(err)
}
}
+335
View File
@@ -0,0 +1,335 @@
package offsitekeys
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"time"
"gitea.dooplex.hu/admin/felhom-hub/internal/offsite"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)
// Event types this package raises — all OPERATOR-ONLY (registered in notify.operatorOnlyEvents).
const (
EventKeyInstalled = "offsite_key_installed" // info: the registrar pinned a box key
EventKeyUnlocked = "offsite_key_unlocked" // error: the daily check saw a line that can delete
EventAuditFailed = "offsite_key_audit_failed" // warning: the daily check could not read the file
EventMovedAside = "offsite_repo_moved_aside" // info: the hub set an orphaned repository aside
)
// Service binds the Registrar to the hub's store: the descriptor (where), the sealed password (how),
// the key record, and the operator events.
type Service struct {
Store *store.Store
Reg *Registrar
Logger *log.Logger
// Emit routes an event to the dispatcher (operator mail). nil → events are only saved.
Emit func(customerID, eventType, severity, message, detailsJSON, source string)
Now func() time.Time
}
// ErrNotProvisioned — the customer has no provisioned off-site target (nothing to register against).
var ErrNotProvisioned = errors.New("offsitekeys: customer has no provisioned off-site target")
func (s *Service) logf(f string, a ...any) {
if s.Logger != nil {
s.Logger.Printf(f, a...)
}
}
func (s *Service) now() time.Time {
if s.Now != nil {
return s.Now()
}
return time.Now()
}
func (s *Service) event(customerID, typ, sev, msg string, details any) {
dj := ""
if details != nil {
if b, err := json.Marshal(details); err == nil {
dj = string(b)
}
}
if _, err := s.Store.SaveEvent(customerID, typ, sev, msg, dj, "hub"); err != nil {
s.logf("[WARN] offsitekeys: save event %s for %s: %v", typ, customerID, err)
}
if s.Emit != nil {
s.Emit(customerID, typ, sev, msg, dj, "hub")
}
}
// TargetFor resolves the customer's sub-account and the hub's (decrypted) password for it.
func (s *Service) TargetFor(customerID string) (Target, string, error) {
cfg, err := s.Store.GetCustomerConfig(customerID)
if err != nil || cfg == nil {
return Target{}, "", fmt.Errorf("offsitekeys: customer %s: %v", customerID, err)
}
d, err := offsite.ReadDescriptor(cfg.ConfigJSON)
if err != nil {
return Target{}, "", err
}
if d == nil || !d.Enabled || d.Host == "" || d.User == "" || d.RepoPath == "" {
return Target{}, "", ErrNotProvisioned
}
pw, err := s.Store.OffsitePassword(customerID)
if err != nil {
return Target{}, "", fmt.Errorf("offsitekeys: no usable stored credential for %s: %w", customerID, err)
}
return Target{Host: d.Host, User: d.User, Port: d.Port, RepoPath: d.RepoPath, Fingerprint: d.HostFingerprint}, pw, nil
}
// RegisterKey installs the box's public key pinned append-only (the ONLY way a box gets off-site access
// from hub v0.127.0 on — no box ever receives the password).
func (s *Service) RegisterKey(ctx context.Context, customerID, pub string) (InstallResult, error) {
t, pw, err := s.TargetFor(customerID)
if err != nil {
return InstallResult{}, err
}
start := s.now()
res, err := s.Reg.Install(ctx, t, pw, pub)
if err != nil {
s.logf("[ERROR] offsitekeys: install key for %s (%s@%s): %v", customerID, t.User, t.Host, err)
return InstallResult{}, err
}
if err := s.Store.RecordOffsiteKeyInstalled(customerID, res.Fingerprint); err != nil {
s.logf("[WARN] offsitekeys: record key for %s: %v", customerID, err)
}
if err := s.Store.MarkOffsiteSecretDelivered(customerID); err != nil {
s.logf("[WARN] offsitekeys: mark delivered for %s: %v", customerID, err)
}
s.logf("[INFO] offsitekeys: installed box key %s for %s pinned append-only (%s@%s, dropped %d unpinned line(s)) in %s",
res.Fingerprint, customerID, t.User, t.Host, res.RemovedUnpinned, s.now().Sub(start).Round(time.Millisecond))
s.event(customerID, EventKeyInstalled, "info",
fmt.Sprintf("Off-site: the box's key %s was installed append-only on %s (%d unpinned line(s) removed).", res.Fingerprint, t.User, res.RemovedUnpinned),
map[string]any{"fingerprint": res.Fingerprint, "removed_unpinned": res.RemovedUnpinned})
return res, nil
}
// ConfirmKey is the rotation's last step: only the confirmed key's pinned line stays.
func (s *Service) ConfirmKey(ctx context.Context, customerID, fp string) (int, error) {
t, pw, err := s.TargetFor(customerID)
if err != nil {
return 0, err
}
removed, err := s.Reg.Confirm(ctx, t, pw, fp)
if err != nil {
return 0, err
}
if ok, err := s.Store.RecordOffsiteKeyConfirmed(customerID, fp); err != nil || !ok {
s.logf("[WARN] offsitekeys: confirm record for %s (fp %s): matched=%v err=%v", customerID, fp, ok, err)
}
s.logf("[INFO] offsitekeys: box confirmed key %s for %s; %d other line(s) removed", fp, customerID, removed)
return removed, nil
}
// MoveAside sets the repository aside (never deletes) on the box's request.
func (s *Service) MoveAside(ctx context.Context, customerID string) (string, error) {
t, pw, err := s.TargetFor(customerID)
if err != nil {
return "", err
}
name, err := s.Reg.MoveAside(ctx, t, pw, s.now().UTC().Format("20060102"))
if err != nil {
return "", err
}
s.logf("[WARN] offsitekeys: moved %s's repository aside: %s -> %s (nothing deleted)", customerID, t.RepoPath, name)
s.event(customerID, EventMovedAside, "info",
fmt.Sprintf("Off-site: the box asked to set its orphaned repository aside; %s was moved to %s. Nothing was deleted.", t.RepoPath, name),
map[string]any{"from": t.RepoPath, "to": name})
return name, nil
}
// AuditOutcome is one customer's daily-check result.
type AuditOutcome struct {
CustomerID string
Result AuditResult
Err error
}
// WindowOpenFunc reports whether a clean-up window is open for the customer (Part E). nil → never.
type WindowOpenFunc func(customerID string) bool
// AuditAll is the DAILY CHECK (decision 69): every provisioned customer's authorized_keys is read, and
// any line that can delete outside an open window raises `offsite_key_unlocked` (error, operator-only),
// naming the line by fingerprint only. An unreadable file raises `offsite_key_audit_failed`.
func (s *Service) AuditAll(ctx context.Context, windowOpen WindowOpenFunc) []AuditOutcome {
cfgs, err := s.Store.ListCustomerConfigs()
if err != nil {
s.logf("[ERROR] offsitekeys: audit: list configs: %v", err)
return nil
}
var out []AuditOutcome
for _, c := range cfgs {
d, derr := offsite.ReadDescriptor(c.ConfigJSON)
if derr != nil || d == nil || !d.Enabled || d.Host == "" {
continue
}
o := AuditOutcome{CustomerID: c.CustomerID}
t, pw, terr := s.TargetFor(c.CustomerID)
if terr != nil {
o.Err = terr
} else {
open := windowOpen != nil && windowOpen(c.CustomerID)
o.Result, o.Err = s.Reg.Audit(ctx, t, pw, open)
}
out = append(out, o)
switch {
case o.Err != nil:
s.logf("[WARN] offsitekeys: audit %s: %v", c.CustomerID, o.Err)
s.event(c.CustomerID, EventAuditFailed, "warning",
fmt.Sprintf("Off-site key check: could not read the key file of %s: %v", c.CustomerID, o.Err), nil)
case len(o.Result.Findings) > 0:
var parts []string
for _, f := range o.Result.Findings {
parts = append(parts, f.Kind+" "+f.Fingerprint)
}
s.logf("[ERROR] offsitekeys: audit %s: %d line(s) can delete off-site history: %s", c.CustomerID, len(o.Result.Findings), strings.Join(parts, "; "))
s.event(c.CustomerID, EventKeyUnlocked, "error",
fmt.Sprintf("Off-site key check: %d key line(s) on %s are NOT append-only and can delete this household's off-site history: %s",
len(o.Result.Findings), t.User, strings.Join(parts, "; ")),
map[string]any{"findings": o.Result.Findings, "lines": o.Result.Lines, "pinned": o.Result.Pinned})
default:
s.logf("[INFO] offsitekeys: audit %s: %d line(s), all pinned append-only", c.CustomerID, o.Result.Lines)
}
}
return out
}
// ── Decision 68: the clean-up window ──────────────────────────────────────────────────────────────
const (
EventWindowDrop = "offsite_window_drop" // error: more snapshots went than a window may remove
EventWindowFailed = "offsite_window_failed" // warning: a window errored or was left open
EventGuardRefused = "offsite_prune_guard_refused" // error: the box's fake-snapshot guard refused (R-822)
windowLength = 20 * time.Minute
windowCadence = 6*24*time.Hour + 12*time.Hour // "weekly", with slack for the night chain's drift
)
// WindowGrant is the hub's answer to the box.
type WindowGrant struct {
Granted bool `json:"granted"`
WindowID int64 `json:"window_id,omitempty"`
NewestAllowed time.Time `json:"newest_allowed,omitempty"`
MaxRemove int `json:"max_remove,omitempty"`
Reason string `json:"reason,omitempty"`
}
// WindowResult is the box's report when it is done.
type WindowResult struct {
WindowID int64 `json:"window_id"`
CountBefore int `json:"count_before"`
CountAfter int `json:"count_after"`
Removed int `json:"removed"`
Outcome string `json:"outcome"`
Reason string `json:"reason"`
}
// MaxRemove is the most snapshots one window may remove: 40 % of what was there, at least 5. The ruled
// policy (7 daily + 4 weekly + 6 monthly per app) removes ~7 of ~17 per app per week (~41 %); the box
// takes the OLDEST first within this bound, so a backlog drains over several windows.
func MaxRemove(countBefore int) int {
n := countBefore * 40 / 100
if n < 5 {
n = 5
}
return n
}
// OpenWindowFor decides and, if due, opens the window: a deleting line for the box's CONFIRMED key is
// prepended (first match wins), and a ledger row bounds it to 20 minutes.
func (s *Service) OpenWindowFor(ctx context.Context, customerID string, countBefore int) (WindowGrant, error) {
oneShot := s.Store.TakeOffsiteWindowGrant(customerID)
last := s.Store.LastOffsiteWindowOpened(customerID)
due := last.IsZero() || s.now().Sub(last) >= windowCadence
if !oneShot && !(s.Store.OffsiteWindowsEnabled() && due) {
reason := "weekly windows are off"
if s.Store.OffsiteWindowsEnabled() {
reason = "not due (last window " + last.UTC().Format(time.RFC3339) + ")"
}
return WindowGrant{Reason: reason}, nil
}
k, err := s.Store.GetOffsiteKey(customerID)
if err != nil || k == nil || k.ConfirmedAt.IsZero() {
return WindowGrant{Reason: "no confirmed append-only key on record"}, nil
}
t, pw, err := s.TargetFor(customerID)
if err != nil {
return WindowGrant{}, err
}
if err := s.Reg.OpenWindow(ctx, t, pw, k.Fingerprint); err != nil {
return WindowGrant{}, err
}
now := s.now()
id, err := s.Store.OpenOffsiteWindowRow(customerID, now.Add(windowLength), countBefore)
if err != nil {
// The line is written; close it rather than leave a deleting line without a ledger row.
_ = s.Reg.CloseWindow(ctx, t, pw)
return WindowGrant{}, err
}
g := WindowGrant{Granted: true, WindowID: id, NewestAllowed: now.UTC(), MaxRemove: MaxRemove(countBefore)}
s.logf("[WARN] offsitekeys: clean-up window %d OPENED for %s (key %s, %d snapshot(s), max %d removed, closes by %s, one-shot=%v)",
id, customerID, k.Fingerprint, countBefore, g.MaxRemove, now.Add(windowLength).UTC().Format(time.RFC3339), oneShot)
return g, nil
}
// CloseWindowFor closes the window on the box's report and checks the count.
func (s *Service) CloseWindowFor(ctx context.Context, customerID string, r WindowResult) error {
w, err := s.Store.GetOffsiteWindow(r.WindowID)
if err != nil || w == nil || w.CustomerID != customerID {
return fmt.Errorf("offsitekeys: window %d is not this customer's", r.WindowID)
}
t, pw, err := s.TargetFor(customerID)
if err != nil {
return err
}
if err := s.Reg.CloseWindow(ctx, t, pw); err != nil {
return err // the sweep retries at closes_by
}
if _, err := s.Store.CloseOffsiteWindowRow(w.ID, r.CountAfter, r.Outcome, "box"); err != nil {
s.logf("[WARN] offsitekeys: ledger close %d: %v", w.ID, err)
}
drop := w.CountBefore - r.CountAfter
s.logf("[INFO] offsitekeys: clean-up window %d CLOSED for %s: outcome=%s, %d -> %d (drop %d, allowed %d)",
w.ID, customerID, r.Outcome, w.CountBefore, r.CountAfter, drop, MaxRemove(w.CountBefore))
details := map[string]any{"window_id": w.ID, "count_before": w.CountBefore, "count_after": r.CountAfter, "outcome": r.Outcome, "reason": r.Reason}
switch {
case drop > MaxRemove(w.CountBefore):
s.event(customerID, EventWindowDrop, "error",
fmt.Sprintf("Off-site clean-up window %d: the snapshot count fell %d -> %d, more than a window may remove (%d).", w.ID, w.CountBefore, r.CountAfter, MaxRemove(w.CountBefore)), details)
case r.Outcome == "guard-refused":
s.event(customerID, EventGuardRefused, "error",
fmt.Sprintf("Off-site clean-up window %d: the box's fake-snapshot guard refused to prune — nothing was deleted: %s", w.ID, r.Reason), details)
case r.Outcome == "error":
s.event(customerID, EventWindowFailed, "warning",
fmt.Sprintf("Off-site clean-up window %d: the prune failed on the box: %s", w.ID, r.Reason), details)
}
return nil
}
// SweepExpiredWindows closes every window left open past its 20 minutes (a box that crashed or lied).
func (s *Service) SweepExpiredWindows(ctx context.Context) {
ws, err := s.Store.ExpiredOffsiteWindows()
if err != nil {
s.logf("[WARN] offsitekeys: window sweep: %v", err)
return
}
for _, w := range ws {
t, pw, err := s.TargetFor(w.CustomerID)
if err == nil {
err = s.Reg.CloseWindow(ctx, t, pw)
}
if err != nil {
s.logf("[ERROR] offsitekeys: window %d for %s is past its time and could NOT be closed: %v (retrying next sweep)", w.ID, w.CustomerID, err)
continue
}
_, _ = s.Store.CloseOffsiteWindowRow(w.ID, -1, "", "timeout")
s.logf("[WARN] offsitekeys: clean-up window %d for %s was left open — closed by the hub", w.ID, w.CustomerID)
s.event(w.CustomerID, EventWindowFailed, "warning",
fmt.Sprintf("Off-site clean-up window %d was not closed by the box within %s; the hub closed it (the deleting key line is removed).", w.ID, windowLength), nil)
}
}
+94
View File
@@ -0,0 +1,94 @@
package offsitekeys
import (
"context"
"log"
"os"
"path/filepath"
"testing"
"gitea.dooplex.hu/admin/felhom-hub/internal/store"
)
func svcFixture(t *testing.T) (*Service, *fakeFS, *[]string) {
t.Helper()
st, err := store.New(filepath.Join(t.TempDir(), "hub.db"), log.New(os.Stderr, "", 0))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { st.Close() })
cfg := `{"offsite":{"enabled":true,"type":"shared","host":"u1-sub4.example","user":"u1-sub4","port":23,"repo_path":"/home/felhom-repo","host_fingerprint":"SHA256:host"}}`
if err := st.SaveCustomerConfig(&store.CustomerConfig{CustomerID: "c1", APIKey: "k", RetrievalPassword: "p", ConfigJSON: cfg}); err != nil {
t.Fatal(err)
}
if err := st.SaveOneTimeSecret("c1", "SubPw1%"); err != nil {
t.Fatal(err)
}
fs := newFS()
var events []string
s := &Service{Store: st, Reg: &Registrar{Dialer: fakeDialer{fs}},
Emit: func(_, typ, _, _, _, _ string) { events = append(events, typ) }}
return s, fs, &events
}
// Register → confirm → the window is refused while weekly windows are off; an operator one-shot opens
// it (deleting line FIRST); the box's close removes it; a drop beyond the bound alarms.
func TestWindow_GrantOpenCloseAndDropAlarm(t *testing.T) {
s, fs, events := svcFixture(t)
ctx := context.Background()
pub, fp := newKey(t)
if _, err := s.RegisterKey(ctx, "c1", pub); err != nil {
t.Fatal(err)
}
if _, err := s.ConfirmKey(ctx, "c1", fp); err != nil {
t.Fatal(err)
}
if g, err := s.OpenWindowFor(ctx, "c1", 20); err != nil || g.Granted {
t.Fatalf("windows off: granted=%v err=%v — must refuse", g.Granted, err)
}
if err := s.Store.GrantOffsiteWindowOnce("c1"); err != nil {
t.Fatal(err)
}
g, err := s.OpenWindowFor(ctx, "c1", 20)
if err != nil || !g.Granted || g.MaxRemove != 8 {
t.Fatalf("one-shot: %+v %v", g, err)
}
if lines := ParseLines(fs.files[".ssh/authorized_keys"], "/home/felhom-repo"); !lines[0].Window || lines[0].Fingerprint != fp {
t.Fatalf("window line not first: %+v", lines)
}
if !s.Store.OffsiteWindowOpen("c1") {
t.Fatal("the ledger does not show the window open — the daily check would alarm on it")
}
if g2, _ := s.OpenWindowFor(ctx, "c1", 20); g2.Granted {
t.Fatal("the one-shot grant was not consumed")
}
// The box reports a fall of 12 (allowed 8) → offsite_window_drop.
if err := s.CloseWindowFor(ctx, "c1", WindowResult{WindowID: g.WindowID, CountAfter: 8, Outcome: "pruned"}); err != nil {
t.Fatal(err)
}
if a := audit(fs.files[".ssh/authorized_keys"], "/home/felhom-repo", false); len(a.Findings) != 0 {
t.Fatalf("window line left behind: %+v", a)
}
found := false
for _, e := range *events {
if e == EventWindowDrop {
found = true
}
}
if !found {
t.Fatalf("no %s event for a fall beyond the bound: %v", EventWindowDrop, *events)
}
}
// A window for a box that never confirmed its key is refused (nothing to scope the window to).
func TestWindow_NoConfirmedKeyRefused(t *testing.T) {
s, _, _ := svcFixture(t)
_ = s.Store.GrantOffsiteWindowOnce("c1")
pub, _ := newKey(t)
if _, err := s.RegisterKey(context.Background(), "c1", pub); err != nil {
t.Fatal(err)
}
if g, _ := s.OpenWindowFor(context.Background(), "c1", 10); g.Granted {
t.Fatal("granted without a confirmed key")
}
}
+101
View File
@@ -0,0 +1,101 @@
package offsitekeys
import (
"bytes"
"context"
"fmt"
"net"
"strconv"
"time"
"golang.org/x/crypto/ssh"
)
// SSHDialer is the production Dialer: password (and keyboard-interactive) auth to the sub-account's
// restricted shell, the host key checked against the provisioning-time fingerprint. The password is
// never logged and never leaves this process.
type SSHDialer struct {
Timeout time.Duration // connect + per-command bound; 0 → 30 s
}
type sshShell struct {
c *ssh.Client
timeout time.Duration
}
func (d SSHDialer) Dial(ctx context.Context, t Target, password string) (Shell, error) {
to := d.Timeout
if to == 0 {
to = 30 * time.Second
}
port := t.Port
if port == 0 {
port = 23
}
want := t.Fingerprint
cfg := &ssh.ClientConfig{
User: t.User,
Auth: []ssh.AuthMethod{
ssh.Password(password),
ssh.KeyboardInteractive(func(_, _ string, qs []string, _ []bool) ([]string, error) {
ans := make([]string, len(qs))
for i := range ans {
ans[i] = password
}
return ans, nil
}),
},
HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
if got := ssh.FingerprintSHA256(key); got != want {
return fmt.Errorf("offsitekeys: host key MISMATCH for %s (got %s, want %s)", t.Host, got, want)
}
return nil
},
Timeout: to,
}
addr := net.JoinHostPort(t.Host, strconv.Itoa(port))
var nd net.Dialer
dctx, cancel := context.WithTimeout(ctx, to)
defer cancel()
conn, err := nd.DialContext(dctx, "tcp", addr)
if err != nil {
return nil, fmt.Errorf("offsitekeys: dial %s: %w", addr, err)
}
_ = conn.SetDeadline(time.Now().Add(to))
cc, chans, reqs, err := ssh.NewClientConn(conn, addr, cfg)
if err != nil {
conn.Close()
return nil, fmt.Errorf("offsitekeys: ssh handshake %s: %w", addr, err)
}
_ = conn.SetDeadline(time.Time{})
return &sshShell{c: ssh.NewClient(cc, chans, reqs), timeout: to}, nil
}
func (s *sshShell) Run(ctx context.Context, cmd string, stdin []byte) ([]byte, error) {
sess, err := s.c.NewSession()
if err != nil {
return nil, err
}
defer sess.Close()
if stdin != nil {
sess.Stdin = bytes.NewReader(stdin)
}
var out, errb bytes.Buffer
sess.Stdout, sess.Stderr = &out, &errb
done := make(chan error, 1)
go func() { done <- sess.Run(cmd) }()
rctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
select {
case err := <-done:
if err != nil {
return out.Bytes(), fmt.Errorf("%q: %w: %s", cmd, err, bytes.TrimSpace(errb.Bytes()))
}
return out.Bytes(), nil
case <-rctx.Done():
_ = sess.Close()
return nil, fmt.Errorf("%q: %w", cmd, rctx.Err())
}
}
func (s *sshShell) Close() error { return s.c.Close() }