mirror of
https://github.com/profullstack/agentbbs.git
synced 2026-11-29 15:31:53 +00:00
feat: add isolated operational-status pilot (#177)
* feat: add isolated operational-status pilot * fix: allow tailnet peers through loopback sidecar * build: add pinned non-root pilot container
This commit is contained in:
parent
5f1c3f4985
commit
8a6e2f905f
9 changed files with 1509 additions and 0 deletions
269
internal/pilot/pilot_test.go
Normal file
269
internal/pilot/pilot_test.go
Normal file
|
|
@ -0,0 +1,269 @@
|
|||
package pilot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const fpAlice = "SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
const fpBob = "SHA256:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
|
||||
|
||||
func writeRegistry(t *testing.T, entries []KeyEntry) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "keys.json")
|
||||
b, err := json.Marshal(registryFile{Keys: entries})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, b, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func testRegistry() Registry {
|
||||
alice := KeyEntry{Name: "alice", Fingerprint: fpAlice, PublishAudiences: []string{"helsinki"}, QueryAudiences: []string{"helsinki"}}
|
||||
bob := KeyEntry{Name: "bob", Fingerprint: fpBob, QueryAudiences: []string{"helsinki"}}
|
||||
return Registry{byName: map[string]KeyEntry{"alice": alice, "bob": bob}, byFP: map[string]KeyEntry{fpAlice: alice, fpBob: bob}}
|
||||
}
|
||||
|
||||
func TestRegistryRejectsDuplicateAndRevokedKeys(t *testing.T) {
|
||||
path := writeRegistry(t, []KeyEntry{{Name: "alice", Fingerprint: fpAlice}, {Name: "bob", Fingerprint: fpAlice, Revoked: true}})
|
||||
if _, err := LoadRegistry(path); err == nil || !strings.Contains(err.Error(), "duplicate pilot key fingerprint") {
|
||||
t.Fatalf("duplicate fingerprint error = %v", err)
|
||||
}
|
||||
path = writeRegistry(t, []KeyEntry{{Name: "alice", Fingerprint: fpAlice, Revoked: true}})
|
||||
r, err := LoadRegistry(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := r.Authorize("alice", fpAlice); ok {
|
||||
t.Fatal("revoked key authorized")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryAudienceMatrix(t *testing.T) {
|
||||
r := testRegistry()
|
||||
cases := []struct {
|
||||
name, fp, audience string
|
||||
publish, query bool
|
||||
}{
|
||||
{"alice", fpAlice, "helsinki", true, true},
|
||||
{"alice", fpAlice, "other", false, false},
|
||||
{"bob", fpBob, "helsinki", false, true},
|
||||
{"bob", fpBob, "other", false, false},
|
||||
{"bob", fpAlice, "helsinki", false, false},
|
||||
{"unknown", fpAlice, "helsinki", false, false},
|
||||
{"alice", fpBob, "helsinki", false, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := r.canPublish(tc.name, tc.fp, tc.audience); got != tc.publish {
|
||||
t.Errorf("publish(%q,%q,%q) = %v, want %v", tc.name, tc.fp, tc.audience, got, tc.publish)
|
||||
}
|
||||
if got := r.canQuery(tc.name, tc.fp, tc.audience); got != tc.query {
|
||||
t.Errorf("query(%q,%q,%q) = %v, want %v", tc.name, tc.fp, tc.audience, got, tc.query)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadJSONRequestRejectsMalformedCRLFSizeAndDuplicateFields(t *testing.T) {
|
||||
for name, input := range map[string]string{
|
||||
"malformed": `{"subject":`,
|
||||
"crlf": "{\"subject\":\"alice\"}\r\n",
|
||||
"duplicate": `{"subject":"alice","subject":"bob"}`,
|
||||
"multiple": `{"subject":"alice"}{"subject":"bob"}`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
var dst map[string]any
|
||||
if err := readJSONRequest(strings.NewReader(input), 256, &dst); err == nil {
|
||||
t.Fatal("request unexpectedly accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
var dst map[string]any
|
||||
if err := readJSONRequest(strings.NewReader(`{"subject":"`+strings.Repeat("x", 300)+`"}`), 64, &dst); err == nil {
|
||||
t.Fatal("oversized request unexpectedly accepted")
|
||||
}
|
||||
if err := readJSONRequest(strings.NewReader(`{"subject":"alice"}`+"\n"), 256, &dst); err != nil {
|
||||
t.Fatalf("single LF should be accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func testConfig() Config {
|
||||
return Config{MaxRequestBytes: 16 * 1024, MaxResponseBytes: 32 * 1024, MaxStatuses: 100, MaxAge: 15 * time.Minute, MaxTTL: time.Hour, MaxFutureSkew: 5 * time.Minute, RateWindow: time.Minute, RequestsPerWindow: 30}
|
||||
}
|
||||
|
||||
func validPublish(now time.Time) publishRequest {
|
||||
return publishRequest{Subject: "alice", Audience: "helsinki", State: "healthy", Summary: "ready", ObservedAt: now.Add(-time.Minute).Format(time.RFC3339), ExpiresAt: now.Add(10 * time.Minute).Format(time.RFC3339), Revision: 1}
|
||||
}
|
||||
|
||||
func TestFreshnessAndStatusValidation(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
cfg := testConfig()
|
||||
entry := testRegistry().byName["alice"]
|
||||
status, err := parseAndValidatePublish(validPublish(now), entry, now, cfg)
|
||||
if err != nil || status.Subject != "alice" {
|
||||
t.Fatalf("valid status: %v %+v", err, status)
|
||||
}
|
||||
for name, mutate := range map[string]func(*publishRequest){
|
||||
"stale": func(r *publishRequest) { r.ObservedAt = now.Add(-16 * time.Minute).Format(time.RFC3339) },
|
||||
"future": func(r *publishRequest) { r.ObservedAt = now.Add(6 * time.Minute).Format(time.RFC3339) },
|
||||
"expired": func(r *publishRequest) { r.ExpiresAt = now.Add(-time.Second).Format(time.RFC3339) },
|
||||
"long ttl": func(r *publishRequest) { r.ExpiresAt = now.Add(2 * time.Hour).Format(time.RFC3339) },
|
||||
"wrong owner": func(r *publishRequest) { r.Subject = "bob" },
|
||||
"bad state": func(r *publishRequest) { r.State = "green" },
|
||||
"long summary": func(r *publishRequest) { r.Summary = strings.Repeat("x", 1025) },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
req := validPublish(now)
|
||||
mutate(&req)
|
||||
if _, err := parseAndValidatePublish(req, entry, now, cfg); err == nil {
|
||||
t.Fatal("invalid status unexpectedly accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreRestartPersistenceAndRevisionConflicts(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "pilot.db")
|
||||
st, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC().Truncate(time.Second)
|
||||
status := Status{Subject: "alice", Audience: "helsinki", State: "healthy", Summary: "ready", ObservedAt: now.Add(-time.Minute), ExpiresAt: now.Add(time.Minute), Revision: 1}
|
||||
if err := st.Publish(status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := st.Publish(status); err != nil {
|
||||
t.Fatalf("idempotent replay: %v", err)
|
||||
}
|
||||
conflict := status
|
||||
conflict.Summary = "different"
|
||||
if err := st.Publish(conflict); err == nil || !strings.Contains(err.Error(), "conflicts") {
|
||||
t.Fatalf("conflict error = %v", err)
|
||||
}
|
||||
backup := filepath.Join(t.TempDir(), "backup.db")
|
||||
if err := st.Backup(backup); err != nil {
|
||||
t.Fatalf("backup: %v", err)
|
||||
}
|
||||
if info, err := os.Stat(backup); err != nil || info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("backup permissions: info=%v err=%v", info, err)
|
||||
}
|
||||
if err := st.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Rename(path, path+".old"); err != nil {
|
||||
t.Fatalf("retain old database: %v", err)
|
||||
}
|
||||
if err := Restore(backup, path); err != nil {
|
||||
t.Fatalf("restore backup: %v", err)
|
||||
}
|
||||
if info, err := os.Stat(path); err != nil || info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("restored permissions: info=%v err=%v", info, err)
|
||||
}
|
||||
st, err = Open(path)
|
||||
if err != nil {
|
||||
t.Fatalf("open restored backup: %v", err)
|
||||
}
|
||||
defer st.Close()
|
||||
rows, err := st.Query("helsinki", "alice", now, 10)
|
||||
if err != nil || len(rows) != 1 || rows[0].Summary != "ready" {
|
||||
t.Fatalf("restored query: err=%v rows=%+v", err, rows)
|
||||
}
|
||||
if rows[0].Stale {
|
||||
t.Fatal("restored status should be fresh")
|
||||
}
|
||||
if err := st.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err = Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer st.Close()
|
||||
rows, err = st.Query("helsinki", "alice", now, 10)
|
||||
if err != nil || len(rows) != 1 || rows[0].Summary != "ready" {
|
||||
t.Fatalf("restart query: err=%v rows=%+v", err, rows)
|
||||
}
|
||||
if rows[0].Stale {
|
||||
t.Fatal("status should be fresh")
|
||||
}
|
||||
rows, err = st.Query("helsinki", "alice", now.Add(2*time.Minute), 10)
|
||||
if err != nil || len(rows) != 1 || !rows[0].Stale {
|
||||
t.Fatalf("stale derivation: err=%v rows=%+v", err, rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateConfigRejectsPublicBind(t *testing.T) {
|
||||
cfg := testConfig()
|
||||
cfg.Address = "0.0.0.0:2223"
|
||||
if err := validateConfig(cfg); err == nil {
|
||||
t.Fatal("wildcard bind unexpectedly accepted")
|
||||
}
|
||||
cfg.Address = "192.168.1.2:2223"
|
||||
if err := validateConfig(cfg); err == nil {
|
||||
t.Fatal("RFC1918 bind unexpectedly accepted")
|
||||
}
|
||||
cfg.Address = "100.100.10.2:2223"
|
||||
if err := validateConfig(cfg); err != nil {
|
||||
t.Fatalf("tailnet bind rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllowedPeerMatchesBindScope(t *testing.T) {
|
||||
loop, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:5000")
|
||||
tail, _ := net.ResolveTCPAddr("tcp", "100.100.10.5:5000")
|
||||
lan, _ := net.ResolveTCPAddr("tcp", "192.168.1.5:5000")
|
||||
if !allowedPeer("127.0.0.1:2223", loop) || !allowedPeer("127.0.0.1:2223", tail) || allowedPeer("127.0.0.1:2223", lan) {
|
||||
t.Fatal("loopback-bind peer scope incorrect")
|
||||
}
|
||||
if !allowedPeer("100.100.10.2:2223", tail) || allowedPeer("100.100.10.2:2223", lan) {
|
||||
t.Fatal("tailnet peer scope incorrect")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimiter(t *testing.T) {
|
||||
l := newRateLimiter(time.Minute, 2)
|
||||
now := time.Unix(100, 0)
|
||||
if !l.allow("alice", now) || !l.allow("alice", now.Add(time.Second)) || l.allow("alice", now.Add(2*time.Second)) {
|
||||
t.Fatal("rate limit did not cap requests")
|
||||
}
|
||||
if !l.allow("alice", now.Add(61*time.Second)) {
|
||||
t.Fatal("rate limit did not expire")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRequiresRegistryAndDoesNotUseNormalStore(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
cfg := testConfig()
|
||||
cfg.Address = "127.0.0.1:2223"
|
||||
cfg.RegistryPath = filepath.Join(root, "missing-registry")
|
||||
cfg.DatabasePath = filepath.Join(root, "pilot.db")
|
||||
cfg.HostKeyPath = filepath.Join(root, "host")
|
||||
if err := Run(context.Background(), cfg); err == nil {
|
||||
t.Fatal("missing registry unexpectedly accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDoesNotGenerateHostKey(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
registryPath := writeRegistry(t, []KeyEntry{{Name: "alice", Fingerprint: fpAlice, QueryAudiences: []string{"helsinki"}}})
|
||||
cfg := testConfig()
|
||||
cfg.Address = "127.0.0.1:2223"
|
||||
cfg.RegistryPath = registryPath
|
||||
cfg.DatabasePath = filepath.Join(root, "pilot.db")
|
||||
cfg.HostKeyPath = filepath.Join(root, "missing-host-key")
|
||||
if err := Run(context.Background(), cfg); err == nil {
|
||||
t.Fatal("startup without host key unexpectedly succeeded")
|
||||
}
|
||||
if _, err := os.Lstat(cfg.HostKeyPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("startup created host key: err=%v", err)
|
||||
}
|
||||
}
|
||||
241
internal/pilot/protocol.go
Normal file
241
internal/pilot/protocol.go
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
package pilot
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultMaxRequestBytes = 16 * 1024
|
||||
defaultMaxResponseBytes = 32 * 1024
|
||||
defaultMaxStatuses = 100
|
||||
)
|
||||
|
||||
var validStates = map[string]bool{"healthy": true, "degraded": true, "outage": true, "unknown": true}
|
||||
|
||||
type publishRequest struct {
|
||||
Subject string `json:"subject"`
|
||||
Audience string `json:"audience"`
|
||||
State string `json:"state"`
|
||||
Summary string `json:"summary"`
|
||||
ObservedAt string `json:"observed_at"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
Revision int64 `json:"revision"`
|
||||
}
|
||||
|
||||
type queryRequest struct {
|
||||
Audience string `json:"audience"`
|
||||
Subject string `json:"subject,omitempty"`
|
||||
Limit int `json:"limit,omitempty"`
|
||||
}
|
||||
|
||||
func readJSONRequest(r io.Reader, maxBytes int, dst any) error {
|
||||
if maxBytes <= 0 {
|
||||
return errors.New("request size limit is invalid")
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(r, int64(maxBytes)+1))
|
||||
if err != nil {
|
||||
return fmt.Errorf("read request: %w", err)
|
||||
}
|
||||
if len(b) > maxBytes {
|
||||
return errors.New("request exceeds size limit")
|
||||
}
|
||||
if bytes.Contains(b, []byte{'\r'}) {
|
||||
return errors.New("CRLF is not accepted")
|
||||
}
|
||||
if n := bytes.Count(b, []byte{'\n'}); n > 1 || (n == 1 && b[len(b)-1] != '\n') {
|
||||
return errors.New("request must be one JSON object")
|
||||
}
|
||||
b = bytes.TrimSuffix(b, []byte{'\n'})
|
||||
if len(bytes.TrimSpace(b)) == 0 {
|
||||
return errors.New("request is empty")
|
||||
}
|
||||
if err := rejectDuplicateKeys(b); err != nil {
|
||||
return err
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(b))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return fmt.Errorf("invalid JSON request: %w", err)
|
||||
}
|
||||
var extra any
|
||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
if err == nil {
|
||||
return errors.New("request must contain one JSON object")
|
||||
}
|
||||
return fmt.Errorf("trailing request data: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rejectDuplicateKeys walks the bounded JSON value before unmarshalling. The
|
||||
// standard library accepts duplicate object keys, which is unsafe for a policy
|
||||
// request because different consumers can choose different winners.
|
||||
func rejectDuplicateKeys(b []byte) error {
|
||||
dec := json.NewDecoder(bytes.NewReader(b))
|
||||
if err := scanJSONValue(dec, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
var extra any
|
||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
if err == nil {
|
||||
return errors.New("request contains multiple JSON values")
|
||||
}
|
||||
return fmt.Errorf("invalid JSON request: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanJSONValue(dec *json.Decoder, depth int) error {
|
||||
if depth > 32 {
|
||||
return errors.New("JSON nesting exceeds limit")
|
||||
}
|
||||
tok, err := dec.Token()
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid JSON request: %w", err)
|
||||
}
|
||||
if delim, ok := tok.(json.Delim); ok {
|
||||
switch delim {
|
||||
case '{':
|
||||
seen := map[string]bool{}
|
||||
for dec.More() {
|
||||
key, err := dec.Token()
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid JSON object: %w", err)
|
||||
}
|
||||
name, ok := key.(string)
|
||||
if !ok {
|
||||
return errors.New("invalid JSON object key")
|
||||
}
|
||||
if seen[name] {
|
||||
return fmt.Errorf("duplicate JSON field %q", name)
|
||||
}
|
||||
seen[name] = true
|
||||
if err := scanJSONValue(dec, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = dec.Token()
|
||||
case '[':
|
||||
for dec.More() {
|
||||
if err := scanJSONValue(dec, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = dec.Token()
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid JSON container: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateString(name, value string, max int) error {
|
||||
if value == "" {
|
||||
return fmt.Errorf("%s is required", name)
|
||||
}
|
||||
if len(value) > max {
|
||||
return fmt.Errorf("%s exceeds %d bytes", name, max)
|
||||
}
|
||||
if strings.IndexByte(value, '\r') >= 0 || strings.IndexByte(value, '\n') >= 0 {
|
||||
return fmt.Errorf("%s contains a line break", name)
|
||||
}
|
||||
for _, r := range value {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return fmt.Errorf("%s contains a control character", name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseAndValidatePublish(req publishRequest, identity KeyEntry, now time.Time, cfg Config) (Status, error) {
|
||||
if req.Subject != identity.Name {
|
||||
return Status{}, errors.New("subject must match the authenticated identity")
|
||||
}
|
||||
if err := validateString("subject", req.Subject, 32); err != nil {
|
||||
return Status{}, err
|
||||
}
|
||||
if err := validateString("audience", req.Audience, 32); err != nil {
|
||||
return Status{}, err
|
||||
}
|
||||
if err := validateString("state", req.State, 16); err != nil {
|
||||
return Status{}, err
|
||||
}
|
||||
if !validStates[req.State] {
|
||||
return Status{}, fmt.Errorf("invalid state %q", req.State)
|
||||
}
|
||||
if req.Summary != "" {
|
||||
if err := validateString("summary", req.Summary, 1024); err != nil {
|
||||
return Status{}, err
|
||||
}
|
||||
}
|
||||
if req.Revision <= 0 {
|
||||
return Status{}, errors.New("revision must be positive")
|
||||
}
|
||||
observed, err := time.Parse(time.RFC3339, req.ObservedAt)
|
||||
if err != nil {
|
||||
return Status{}, errors.New("observed_at must be RFC3339")
|
||||
}
|
||||
expires, err := time.Parse(time.RFC3339, req.ExpiresAt)
|
||||
if err != nil {
|
||||
return Status{}, errors.New("expires_at must be RFC3339")
|
||||
}
|
||||
observed = observed.UTC()
|
||||
expires = expires.UTC()
|
||||
if observed.After(now.Add(cfg.MaxFutureSkew)) {
|
||||
return Status{}, errors.New("observed_at is too far in the future")
|
||||
}
|
||||
if now.Sub(observed) > cfg.MaxAge {
|
||||
return Status{}, errors.New("observed_at is stale")
|
||||
}
|
||||
if !expires.After(now) {
|
||||
return Status{}, errors.New("expires_at must be in the future")
|
||||
}
|
||||
if !expires.After(observed) || expires.Sub(observed) > cfg.MaxTTL {
|
||||
return Status{}, errors.New("expires_at is outside the allowed freshness window")
|
||||
}
|
||||
return Status{Subject: req.Subject, Audience: req.Audience, State: req.State, Summary: req.Summary, ObservedAt: observed, ExpiresAt: expires, Revision: req.Revision}, nil
|
||||
}
|
||||
|
||||
func validateQuery(req queryRequest, cfg Config) error {
|
||||
if err := validateString("audience", req.Audience, 32); err != nil {
|
||||
return err
|
||||
}
|
||||
if req.Subject != "" {
|
||||
if err := validateString("subject", req.Subject, 32); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
limit := req.Limit
|
||||
if limit == 0 {
|
||||
limit = min(cfg.MaxStatuses, defaultMaxStatuses)
|
||||
}
|
||||
if limit < 1 || limit > cfg.MaxStatuses || limit > defaultMaxStatuses {
|
||||
return fmt.Errorf("limit must be between 1 and %d", min(cfg.MaxStatuses, defaultMaxStatuses))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func responseWithinLimit(v any, maxBytes int) ([]byte, error) {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(b) > maxBytes {
|
||||
return nil, errors.New("response exceeds size limit")
|
||||
}
|
||||
return append(b, '\n'), nil
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
206
internal/pilot/registry.go
Normal file
206
internal/pilot/registry.go
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
// Package pilot contains the isolated, internal-only operational-status pilot.
|
||||
// It deliberately does not share the normal AgentBBS account or feature paths.
|
||||
package pilot
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const maxRegistryBytes = 64 * 1024
|
||||
|
||||
var (
|
||||
namePattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
|
||||
audiencePattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
|
||||
fingerprintPattern = regexp.MustCompile(`^SHA256:[A-Za-z0-9+/]{43}$`)
|
||||
)
|
||||
|
||||
// KeyEntry is one pre-approved identity. A key is unique across the entire
|
||||
// registry, including revoked entries, so reusing a fingerprint is rejected.
|
||||
type KeyEntry struct {
|
||||
Name string `json:"name"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
PublishAudiences []string `json:"publish_audiences"`
|
||||
QueryAudiences []string `json:"query_audiences"`
|
||||
Revoked bool `json:"revoked"`
|
||||
}
|
||||
|
||||
type registryFile struct {
|
||||
Keys []KeyEntry `json:"keys"`
|
||||
}
|
||||
|
||||
// Registry is an immutable validated snapshot of the approved key registry.
|
||||
type Registry struct {
|
||||
byName map[string]KeyEntry
|
||||
byFP map[string]KeyEntry
|
||||
}
|
||||
|
||||
// LoadRegistry reads and validates a registry file. Unknown JSON fields are
|
||||
// rejected so an operator typo cannot silently widen or change policy.
|
||||
func LoadRegistry(path string) (Registry, error) {
|
||||
if err := validatePrivateFile(path); err != nil {
|
||||
return Registry{}, fmt.Errorf("pilot key registry: %w", err)
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return Registry{}, fmt.Errorf("read pilot key registry: %w", err)
|
||||
}
|
||||
b, readErr := io.ReadAll(io.LimitReader(file, int64(maxRegistryBytes)+1))
|
||||
closeErr := file.Close()
|
||||
if readErr != nil {
|
||||
return Registry{}, fmt.Errorf("read pilot key registry: %w", readErr)
|
||||
}
|
||||
if closeErr != nil {
|
||||
return Registry{}, fmt.Errorf("close pilot key registry: %w", closeErr)
|
||||
}
|
||||
if len(b) > maxRegistryBytes {
|
||||
return Registry{}, errors.New("pilot key registry exceeds size limit")
|
||||
}
|
||||
if err := rejectDuplicateKeys(b); err != nil {
|
||||
return Registry{}, fmt.Errorf("decode pilot key registry: %w", err)
|
||||
}
|
||||
var f registryFile
|
||||
dec := json.NewDecoder(strings.NewReader(string(b)))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&f); err != nil {
|
||||
return Registry{}, fmt.Errorf("decode pilot key registry: %w", err)
|
||||
}
|
||||
var extra any
|
||||
if err := dec.Decode(&extra); err == nil {
|
||||
return Registry{}, errors.New("pilot key registry must contain one JSON object")
|
||||
} else if !errors.Is(err, io.EOF) {
|
||||
return Registry{}, fmt.Errorf("decode pilot key registry: %w", err)
|
||||
}
|
||||
if len(f.Keys) == 0 {
|
||||
return Registry{}, errors.New("pilot key registry must contain at least one key")
|
||||
}
|
||||
r := Registry{byName: make(map[string]KeyEntry, len(f.Keys)), byFP: make(map[string]KeyEntry, len(f.Keys))}
|
||||
for i, entry := range f.Keys {
|
||||
if err := validateEntry(entry); err != nil {
|
||||
return Registry{}, fmt.Errorf("pilot key registry entry %d: %w", i, err)
|
||||
}
|
||||
if _, exists := r.byName[entry.Name]; exists {
|
||||
return Registry{}, fmt.Errorf("duplicate pilot identity name %q", entry.Name)
|
||||
}
|
||||
if _, exists := r.byFP[entry.Fingerprint]; exists {
|
||||
return Registry{}, fmt.Errorf("duplicate pilot key fingerprint %q", entry.Fingerprint)
|
||||
}
|
||||
r.byName[entry.Name] = entry
|
||||
r.byFP[entry.Fingerprint] = entry
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func validateEntry(entry KeyEntry) error {
|
||||
if !namePattern.MatchString(entry.Name) {
|
||||
return fmt.Errorf("invalid name %q", entry.Name)
|
||||
}
|
||||
if !fingerprintPattern.MatchString(entry.Fingerprint) {
|
||||
return fmt.Errorf("invalid SHA256 fingerprint %q", entry.Fingerprint)
|
||||
}
|
||||
decoded, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(entry.Fingerprint, "SHA256:"))
|
||||
if err != nil || len(decoded) != 32 {
|
||||
return fmt.Errorf("invalid SHA256 fingerprint %q", entry.Fingerprint)
|
||||
}
|
||||
if err := validateAudiences(entry.PublishAudiences); err != nil {
|
||||
return fmt.Errorf("publish audiences: %w", err)
|
||||
}
|
||||
if err := validateAudiences(entry.QueryAudiences); err != nil {
|
||||
return fmt.Errorf("query audiences: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validatePrivateFile(path string) error {
|
||||
if path == "" {
|
||||
return errors.New("path is empty")
|
||||
}
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return errors.New("path is not a regular file")
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
return errors.New("symlink is not allowed")
|
||||
}
|
||||
if info.Mode().Perm()&0o077 != 0 {
|
||||
return fmt.Errorf("file permissions %04o are too broad", info.Mode().Perm())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAudiences(audiences []string) error {
|
||||
seen := make(map[string]bool, len(audiences))
|
||||
for _, audience := range audiences {
|
||||
if !audiencePattern.MatchString(audience) {
|
||||
return fmt.Errorf("invalid audience %q", audience)
|
||||
}
|
||||
if seen[audience] {
|
||||
return fmt.Errorf("duplicate audience %q", audience)
|
||||
}
|
||||
seen[audience] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Authorize returns the non-revoked identity for an exact username/fingerprint
|
||||
// pair. The username is never inferred from caller input after this check.
|
||||
func (r Registry) Authorize(name, fingerprint string) (KeyEntry, bool) {
|
||||
entry, ok := r.byName[name]
|
||||
if !ok || entry.Revoked || entry.Fingerprint != fingerprint {
|
||||
return KeyEntry{}, false
|
||||
}
|
||||
return entry, true
|
||||
}
|
||||
|
||||
func (r Registry) entryByFingerprint(fingerprint string) (KeyEntry, bool) {
|
||||
entry, ok := r.byFP[fingerprint]
|
||||
if !ok || entry.Revoked {
|
||||
return KeyEntry{}, false
|
||||
}
|
||||
return entry, true
|
||||
}
|
||||
|
||||
func containsAudience(audiences []string, audience string) bool {
|
||||
for _, candidate := range audiences {
|
||||
if candidate == audience {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (r Registry) canPublish(name, fingerprint, audience string) bool {
|
||||
entry, ok := r.Authorize(name, fingerprint)
|
||||
return ok && containsAudience(entry.PublishAudiences, audience)
|
||||
}
|
||||
|
||||
func (r Registry) canQuery(name, fingerprint, audience string) bool {
|
||||
entry, ok := r.Authorize(name, fingerprint)
|
||||
return ok && containsAudience(entry.QueryAudiences, audience)
|
||||
}
|
||||
|
||||
// Audiences returns all audiences present in the registry in stable order.
|
||||
func (r Registry) Audiences() []string {
|
||||
seen := map[string]bool{}
|
||||
for _, entry := range r.byName {
|
||||
for _, audience := range append(append([]string{}, entry.PublishAudiences...), entry.QueryAudiences...) {
|
||||
seen[audience] = true
|
||||
}
|
||||
}
|
||||
out := make([]string, 0, len(seen))
|
||||
for audience := range seen {
|
||||
out = append(out, audience)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
331
internal/pilot/server.go
Normal file
331
internal/pilot/server.go
Normal file
|
|
@ -0,0 +1,331 @@
|
|||
package pilot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/ssh"
|
||||
"github.com/charmbracelet/wish"
|
||||
gossh "golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
const (
|
||||
maxPilotRequestBytes = 64 * 1024
|
||||
maxPilotResponseBytes = 256 * 1024
|
||||
maxPilotAge = 24 * time.Hour
|
||||
maxPilotTTL = 7 * 24 * time.Hour
|
||||
maxPilotFutureSkew = time.Hour
|
||||
)
|
||||
|
||||
// Config controls the deliberately narrow pilot server.
|
||||
type Config struct {
|
||||
Address string
|
||||
HostKeyPath string
|
||||
RegistryPath string
|
||||
DatabasePath string
|
||||
MaxRequestBytes int
|
||||
MaxResponseBytes int
|
||||
MaxStatuses int
|
||||
MaxAge time.Duration
|
||||
MaxTTL time.Duration
|
||||
MaxFutureSkew time.Duration
|
||||
RateWindow time.Duration
|
||||
RequestsPerWindow int
|
||||
}
|
||||
|
||||
// ConfigFromEnv keeps pilot activation explicit and safe by default. The
|
||||
// default address is loopback; a non-loopback address must be a literal
|
||||
// 100.64.0.0/10 tailnet address, and peer connections are checked against the
|
||||
// same range. Live firewall evidence is still required before deployment.
|
||||
func ConfigFromEnv(dataDir string) Config {
|
||||
return Config{
|
||||
Address: env("AGENTBBS_PILOT_ADDR", "127.0.0.1:2223"),
|
||||
HostKeyPath: env("AGENTBBS_PILOT_HOST_KEY", filepath.Join(dataDir, "pilot", "host_ed25519")),
|
||||
RegistryPath: env("AGENTBBS_PILOT_KEYS", filepath.Join(dataDir, "pilot", "keys.json")),
|
||||
DatabasePath: env("AGENTBBS_PILOT_DB", filepath.Join(dataDir, "pilot", "status.db")),
|
||||
MaxRequestBytes: envInt("AGENTBBS_PILOT_MAX_REQUEST_BYTES", defaultMaxRequestBytes),
|
||||
MaxResponseBytes: envInt("AGENTBBS_PILOT_MAX_RESPONSE_BYTES", defaultMaxResponseBytes),
|
||||
MaxStatuses: envInt("AGENTBBS_PILOT_MAX_STATUSES", defaultMaxStatuses),
|
||||
MaxAge: envDuration("AGENTBBS_PILOT_MAX_AGE", 15*time.Minute),
|
||||
MaxTTL: envDuration("AGENTBBS_PILOT_MAX_TTL", time.Hour),
|
||||
MaxFutureSkew: envDuration("AGENTBBS_PILOT_MAX_FUTURE_SKEW", 5*time.Minute),
|
||||
RateWindow: envDuration("AGENTBBS_PILOT_RATE_WINDOW", time.Minute),
|
||||
RequestsPerWindow: envInt("AGENTBBS_PILOT_REQUESTS_PER_WINDOW", 30),
|
||||
}
|
||||
}
|
||||
|
||||
func env(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt(key string, fallback int) int {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
var n int
|
||||
if _, err := fmt.Sscan(value, &n); err == nil && n > 0 {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envDuration(key string, fallback time.Duration) time.Duration {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
if d, err := time.ParseDuration(value); err == nil && d > 0 {
|
||||
return d
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func validateConfig(cfg Config) error {
|
||||
if cfg.MaxRequestBytes <= 0 || cfg.MaxRequestBytes > maxPilotRequestBytes || cfg.MaxResponseBytes < 64 || cfg.MaxResponseBytes > maxPilotResponseBytes || cfg.MaxStatuses <= 0 || cfg.MaxStatuses > defaultMaxStatuses {
|
||||
return errors.New("pilot size limits are invalid")
|
||||
}
|
||||
if cfg.MaxAge <= 0 || cfg.MaxAge > maxPilotAge || cfg.MaxTTL <= 0 || cfg.MaxTTL > maxPilotTTL || cfg.MaxFutureSkew < 0 || cfg.MaxFutureSkew > maxPilotFutureSkew || cfg.RateWindow <= 0 || cfg.RequestsPerWindow <= 0 {
|
||||
return errors.New("pilot time or rate limits are invalid")
|
||||
}
|
||||
host, _, err := net.SplitHostPort(cfg.Address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("pilot address must be host:port: %w", err)
|
||||
}
|
||||
host = strings.Trim(host, "[]")
|
||||
ip := net.ParseIP(host)
|
||||
if ip == nil {
|
||||
return errors.New("pilot address must use a literal loopback or 100.64.0.0/10 tailnet IP")
|
||||
}
|
||||
if !ip.IsLoopback() && !inTailnetRange(ip) {
|
||||
return errors.New("pilot address must be loopback or tailnet CGNAT (100.64.0.0/10)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func inTailnetRange(ip net.IP) bool {
|
||||
_, network, _ := net.ParseCIDR("100.64.0.0/10")
|
||||
return ip != nil && network.Contains(ip)
|
||||
}
|
||||
|
||||
func allowedPeer(bindAddress string, remote net.Addr) bool {
|
||||
if remote == nil {
|
||||
return false
|
||||
}
|
||||
host, _, err := net.SplitHostPort(remote.String())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
peer := net.ParseIP(strings.Trim(host, "[]"))
|
||||
if peer == nil {
|
||||
return false
|
||||
}
|
||||
bindHost, _, err := net.SplitHostPort(bindAddress)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
bind := net.ParseIP(strings.Trim(bindHost, "[]"))
|
||||
if bind == nil {
|
||||
return false
|
||||
}
|
||||
if bind.IsLoopback() {
|
||||
return peer.IsLoopback() || inTailnetRange(peer)
|
||||
}
|
||||
return inTailnetRange(peer)
|
||||
}
|
||||
|
||||
type rateLimiter struct {
|
||||
mu sync.Mutex
|
||||
seen map[string][]time.Time
|
||||
window time.Duration
|
||||
max int
|
||||
}
|
||||
|
||||
func newRateLimiter(window time.Duration, max int) *rateLimiter {
|
||||
return &rateLimiter{seen: map[string][]time.Time{}, window: window, max: max}
|
||||
}
|
||||
|
||||
func (l *rateLimiter) allow(key string, now time.Time) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
cutoff := now.Add(-l.window)
|
||||
items := l.seen[key]
|
||||
kept := items[:0]
|
||||
for _, at := range items {
|
||||
if at.After(cutoff) {
|
||||
kept = append(kept, at)
|
||||
}
|
||||
}
|
||||
if len(kept) >= l.max {
|
||||
l.seen[key] = kept
|
||||
return false
|
||||
}
|
||||
l.seen[key] = append(kept, now)
|
||||
return true
|
||||
}
|
||||
|
||||
// Run starts the pilot SSH service and returns when ctx is canceled or the
|
||||
// server fails. No normal AgentBBS listeners, plugins, web routes, or join
|
||||
// flows are initialized by this path.
|
||||
func Run(ctx context.Context, cfg Config) error {
|
||||
if err := validateConfig(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
registry, err := LoadRegistry(cfg.RegistryPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
st, err := Open(cfg.DatabasePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer st.Close()
|
||||
if err := ensurePrivateDir(filepath.Dir(cfg.HostKeyPath)); err != nil {
|
||||
return fmt.Errorf("pilot host-key directory: %w", err)
|
||||
}
|
||||
if _, err := os.Lstat(cfg.HostKeyPath); err == nil {
|
||||
if err := validatePrivateFile(cfg.HostKeyPath); err != nil {
|
||||
return fmt.Errorf("pilot host key: %w", err)
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return fmt.Errorf("inspect pilot host key: %w", err)
|
||||
}
|
||||
limiter := newRateLimiter(cfg.RateWindow, cfg.RequestsPerWindow)
|
||||
server, err := wish.NewServer(
|
||||
wish.WithAddress(cfg.Address),
|
||||
ssh.HostKeyFile(cfg.HostKeyPath),
|
||||
ssh.NoPty(),
|
||||
wish.WithPublicKeyAuth(func(ctx ssh.Context, key ssh.PublicKey) bool {
|
||||
_, ok := registry.Authorize(ctx.User(), fingerprint(key))
|
||||
return ok
|
||||
}),
|
||||
wish.WithPasswordAuth(func(ssh.Context, string) bool { return false }),
|
||||
wish.WithKeyboardInteractiveAuth(func(ssh.Context, gossh.KeyboardInteractiveChallenge) bool { return false }),
|
||||
wish.WithIdleTimeout(30*time.Second),
|
||||
wish.WithMiddleware(pilotMiddleware(registry, st, cfg, limiter)),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create pilot SSH server: %w", err)
|
||||
}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = server.Shutdown(shutdownCtx)
|
||||
}()
|
||||
err = server.ListenAndServe()
|
||||
if errors.Is(err, ssh.ErrServerClosed) && ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func fingerprint(key ssh.PublicKey) string {
|
||||
if key == nil {
|
||||
return ""
|
||||
}
|
||||
return gossh.FingerprintSHA256(key)
|
||||
}
|
||||
|
||||
func pilotMiddleware(registry Registry, st *Store, cfg Config, limiter *rateLimiter) wish.Middleware {
|
||||
return func(next ssh.Handler) ssh.Handler {
|
||||
return func(s ssh.Session) {
|
||||
if !allowedPeer(cfg.Address, s.RemoteAddr()) {
|
||||
_ = s.Exit(1)
|
||||
return
|
||||
}
|
||||
fp := fingerprint(s.PublicKey())
|
||||
entry, ok := registry.Authorize(s.User(), fp)
|
||||
if !ok || !limiter.allow(fp, time.Now()) {
|
||||
_ = s.Exit(1)
|
||||
return
|
||||
}
|
||||
args := s.Command()
|
||||
if len(args) != 1 || (args[0] != "publish" && args[0] != "query") {
|
||||
writeError(s, "command must be exactly publish or query", cfg.MaxResponseBytes)
|
||||
return
|
||||
}
|
||||
switch args[0] {
|
||||
case "publish":
|
||||
handlePublish(s, entry, st, cfg)
|
||||
case "query":
|
||||
handleQuery(s, entry, st, cfg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handlePublish(s ssh.Session, identity KeyEntry, st *Store, cfg Config) {
|
||||
var req publishRequest
|
||||
if err := readJSONRequest(s, cfg.MaxRequestBytes, &req); err != nil {
|
||||
writeError(s, err.Error(), cfg.MaxResponseBytes)
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if !containsAudience(identity.PublishAudiences, req.Audience) {
|
||||
writeError(s, "publish audience is not authorized", cfg.MaxResponseBytes)
|
||||
return
|
||||
}
|
||||
status, err := parseAndValidatePublish(req, identity, now, cfg)
|
||||
if err != nil {
|
||||
writeError(s, err.Error(), cfg.MaxResponseBytes)
|
||||
return
|
||||
}
|
||||
if err := st.Publish(status); err != nil {
|
||||
writeError(s, err.Error(), cfg.MaxResponseBytes)
|
||||
return
|
||||
}
|
||||
writeJSON(s, map[string]any{"ok": true, "subject": status.Subject, "audience": status.Audience, "revision": status.Revision}, cfg.MaxResponseBytes)
|
||||
}
|
||||
|
||||
func handleQuery(s ssh.Session, identity KeyEntry, st *Store, cfg Config) {
|
||||
var req queryRequest
|
||||
if err := readJSONRequest(s, cfg.MaxRequestBytes, &req); err != nil {
|
||||
writeError(s, err.Error(), cfg.MaxResponseBytes)
|
||||
return
|
||||
}
|
||||
if !containsAudience(identity.QueryAudiences, req.Audience) {
|
||||
writeError(s, "query audience is not authorized", cfg.MaxResponseBytes)
|
||||
return
|
||||
}
|
||||
if err := validateQuery(req, cfg); err != nil {
|
||||
writeError(s, err.Error(), cfg.MaxResponseBytes)
|
||||
return
|
||||
}
|
||||
limit := req.Limit
|
||||
if limit == 0 {
|
||||
limit = min(cfg.MaxStatuses, defaultMaxStatuses)
|
||||
}
|
||||
rows, err := st.Query(req.Audience, req.Subject, time.Now().UTC(), limit)
|
||||
if err != nil {
|
||||
writeError(s, err.Error(), cfg.MaxResponseBytes)
|
||||
return
|
||||
}
|
||||
writeJSON(s, map[string]any{"ok": true, "audience": req.Audience, "statuses": rows}, cfg.MaxResponseBytes)
|
||||
}
|
||||
|
||||
func writeError(s ssh.Session, message string, maxBytes int) {
|
||||
writeJSONWithExit(s, map[string]any{"ok": false, "error": message}, maxBytes, 1)
|
||||
}
|
||||
|
||||
func writeJSON(s ssh.Session, value any, maxBytes int) {
|
||||
writeJSONWithExit(s, value, maxBytes, 0)
|
||||
}
|
||||
|
||||
func writeJSONWithExit(s ssh.Session, value any, maxBytes, exitCode int) {
|
||||
b, err := responseWithinLimit(value, maxBytes)
|
||||
if err != nil {
|
||||
b = []byte("{\"ok\":false,\"error\":\"response exceeds size limit\"}\n")
|
||||
exitCode = 1
|
||||
}
|
||||
_, _ = s.Write(b)
|
||||
_ = s.Exit(exitCode)
|
||||
}
|
||||
|
||||
var _ = gossh.FingerprintSHA256
|
||||
311
internal/pilot/store.go
Normal file
311
internal/pilot/store.go
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
package pilot
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
var (
|
||||
errRevisionConflict = errors.New("status revision conflicts with stored data")
|
||||
errRevisionStale = errors.New("status revision is older than stored data")
|
||||
)
|
||||
|
||||
// Status is the only persisted operational object in pilot mode.
|
||||
type Status struct {
|
||||
Subject string `json:"subject"`
|
||||
Audience string `json:"audience"`
|
||||
State string `json:"state"`
|
||||
Summary string `json:"summary"`
|
||||
ObservedAt time.Time `json:"observed_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
Revision int64 `json:"revision"`
|
||||
}
|
||||
|
||||
// StatusView adds the derived freshness value returned to a query caller.
|
||||
type StatusView struct {
|
||||
Status
|
||||
Stale bool `json:"stale"`
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func ensurePrivateDir(path string) error {
|
||||
if path == "" || filepath.Clean(path) == "." {
|
||||
return errors.New("refusing to use the current directory")
|
||||
}
|
||||
if err := os.MkdirAll(path, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
return errors.New("path is a symlink")
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return errors.New("path is not a real directory")
|
||||
}
|
||||
if err := os.Chmod(path, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
info, err = os.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Mode().Perm()&0o077 != 0 {
|
||||
return fmt.Errorf("directory permissions %04o are too broad", info.Mode().Perm())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Backup creates a consistent SQLite snapshot using SQLite's backup-capable
|
||||
// VACUUM INTO operation. The source stays open; the destination must be a new,
|
||||
// private regular file path.
|
||||
func (s *Store) Backup(path string) error {
|
||||
if err := ensurePrivateDir(filepath.Dir(path)); err != nil {
|
||||
return fmt.Errorf("backup directory: %w", err)
|
||||
}
|
||||
if _, err := os.Lstat(path); err == nil {
|
||||
return errors.New("backup destination already exists")
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
if _, err := s.db.Exec(`VACUUM INTO ?`, path); err != nil {
|
||||
return fmt.Errorf("backup pilot database: %w", err)
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
return fmt.Errorf("protect pilot backup: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Restore verifies a stopped pilot database snapshot before copying it over
|
||||
// the configured path. Callers must stop the pilot first; this function refuses
|
||||
// to operate on an open Store and keeps replacement atomic with a same-directory
|
||||
// temporary file.
|
||||
func Restore(source, destination string) error {
|
||||
if os.Geteuid() == 0 {
|
||||
return errors.New("pilot refuses to restore as root")
|
||||
}
|
||||
if err := validatePrivateFile(source); err != nil {
|
||||
return fmt.Errorf("restore source: %w", err)
|
||||
}
|
||||
if err := ensurePrivateDir(filepath.Dir(destination)); err != nil {
|
||||
return fmt.Errorf("restore destination directory: %w", err)
|
||||
}
|
||||
if _, err := os.Lstat(destination); err == nil {
|
||||
return errors.New("restore destination must be absent; retain the old database and move it aside first")
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
src, err := os.Open(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer src.Close()
|
||||
var header [16]byte
|
||||
if _, err := io.ReadFull(src, header[:]); err != nil {
|
||||
return fmt.Errorf("read restore source: %w", err)
|
||||
}
|
||||
if string(header[:6]) != "SQLite" {
|
||||
return errors.New("restore source is not SQLite")
|
||||
}
|
||||
checkDB, err := sql.Open("sqlite", source+"?mode=ro")
|
||||
if err != nil {
|
||||
return fmt.Errorf("open restore source: %w", err)
|
||||
}
|
||||
var integrity string
|
||||
err = checkDB.QueryRow(`PRAGMA integrity_check`).Scan(&integrity)
|
||||
closeErr := checkDB.Close()
|
||||
if err != nil {
|
||||
return fmt.Errorf("check restore source integrity: %w", err)
|
||||
}
|
||||
if closeErr != nil {
|
||||
return fmt.Errorf("close restore source: %w", closeErr)
|
||||
}
|
||||
if integrity != "ok" {
|
||||
return fmt.Errorf("restore source integrity check: %s", integrity)
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(destination), ".pilot-restore-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer os.Remove(tmpName)
|
||||
if err := tmp.Chmod(0o600); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := src.Seek(0, io.SeekStart); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := io.Copy(tmp, src); err != nil {
|
||||
tmp.Close()
|
||||
return fmt.Errorf("copy restore source: %w", err)
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmpName, destination)
|
||||
}
|
||||
|
||||
const pilotSchema = `
|
||||
CREATE TABLE IF NOT EXISTS statuses (
|
||||
audience TEXT NOT NULL,
|
||||
subject TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
summary TEXT NOT NULL,
|
||||
observed_at TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
revision INTEGER NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
|
||||
PRIMARY KEY (audience, subject)
|
||||
);
|
||||
`
|
||||
|
||||
// Open opens a dedicated pilot database. It intentionally does not use the
|
||||
// normal AgentBBS store or schema. The database and parent directory are
|
||||
// private to the process; deployment still must prove the process is non-root
|
||||
// and the volume is isolated/read-only except for this database.
|
||||
func Open(path string) (*Store, error) {
|
||||
if os.Geteuid() == 0 {
|
||||
return nil, errors.New("pilot refuses to run as root")
|
||||
}
|
||||
if path == "" {
|
||||
return nil, errors.New("pilot database path is empty")
|
||||
}
|
||||
if err := ensurePrivateDir(filepath.Dir(path)); err != nil {
|
||||
return nil, fmt.Errorf("pilot database directory: %w", err)
|
||||
}
|
||||
if info, err := os.Lstat(path); err == nil {
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
|
||||
return nil, errors.New("pilot database must be a regular file")
|
||||
}
|
||||
if info.Mode().Perm()&0o077 != 0 {
|
||||
return nil, fmt.Errorf("pilot database permissions %04o are too broad", info.Mode().Perm())
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, fmt.Errorf("inspect pilot database: %w", err)
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pilot database: %w", err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return nil, fmt.Errorf("close pilot database handle: %w", err)
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
return nil, fmt.Errorf("protect pilot database: %w", err)
|
||||
}
|
||||
db, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(5000)")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open pilot database: %w", err)
|
||||
}
|
||||
// One writer connection keeps revision comparison and update atomic for the
|
||||
// small pilot and avoids an application-level lock around SQLite state.
|
||||
db.SetMaxOpenConns(1)
|
||||
if _, err := db.Exec(pilotSchema); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("initialize pilot database: %w", err)
|
||||
}
|
||||
return &Store{db: db}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() error { return s.db.Close() }
|
||||
|
||||
// Publish stores a status only if its revision is newer, or if the exact same
|
||||
// revision/payload is replayed. A same-revision different payload is a hard
|
||||
// conflict; this prevents two writers from silently forking state.
|
||||
func (s *Store) Publish(status Status) error {
|
||||
payload, err := json.Marshal(status)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal status: %w", err)
|
||||
}
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var revision int64
|
||||
var storedPayload string
|
||||
err = tx.QueryRow(`SELECT revision, payload FROM statuses WHERE audience=? AND subject=?`, status.Audience, status.Subject).Scan(&revision, &storedPayload)
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
_, err = tx.Exec(`INSERT INTO statuses (audience, subject, state, summary, observed_at, expires_at, revision, payload) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
status.Audience, status.Subject, status.State, status.Summary, status.ObservedAt.UTC().Format(time.RFC3339Nano), status.ExpiresAt.UTC().Format(time.RFC3339Nano), status.Revision, string(payload))
|
||||
case err != nil:
|
||||
return err
|
||||
case status.Revision < revision:
|
||||
return errRevisionStale
|
||||
case status.Revision == revision && string(payload) != storedPayload:
|
||||
return errRevisionConflict
|
||||
case status.Revision == revision:
|
||||
return tx.Commit()
|
||||
default:
|
||||
_, err = tx.Exec(`UPDATE statuses SET state=?, summary=?, observed_at=?, expires_at=?, revision=?, payload=?, updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE audience=? AND subject=?`,
|
||||
status.State, status.Summary, status.ObservedAt.UTC().Format(time.RFC3339Nano), status.ExpiresAt.UTC().Format(time.RFC3339Nano), status.Revision, string(payload), status.Audience, status.Subject)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// Query returns the selected audience only. Stale is derived at read time from
|
||||
// expires_at and is never persisted as authoritative state.
|
||||
func (s *Store) Query(audience, subject string, now time.Time, limit int) ([]StatusView, error) {
|
||||
if limit <= 0 {
|
||||
return nil, errors.New("query limit must be positive")
|
||||
}
|
||||
q := `SELECT subject, audience, state, summary, observed_at, expires_at, revision FROM statuses WHERE audience=?`
|
||||
args := []any{audience}
|
||||
if subject != "" {
|
||||
q += ` AND subject=?`
|
||||
args = append(args, subject)
|
||||
}
|
||||
q += ` ORDER BY subject LIMIT ?`
|
||||
args = append(args, limit)
|
||||
rows, err := s.db.Query(q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []StatusView
|
||||
for rows.Next() {
|
||||
var status Status
|
||||
var observed, expires string
|
||||
if err := rows.Scan(&status.Subject, &status.Audience, &status.State, &status.Summary, &observed, &expires, &status.Revision); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
status.ObservedAt, err = time.Parse(time.RFC3339Nano, observed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
status.ExpiresAt, err = time.Parse(time.RFC3339Nano, expires)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, StatusView{Status: status, Stale: !now.Before(status.ExpiresAt)})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue