carlos / platform Public

region HA P1a Task 11: one mint gate before every producer; secrets published and acknowledged before every HA launch

- haMintGate before EnsureAdminToken(Beneath) and the instance key on every
  launch path (prepare, seedChild, spawnChildFrom), the backfill and the
  claim launch source: an HA host whose manifest exists never mints.
- haSecretsReady after the ensure calls: the env's SHA-256 must be the
  committed manifest's env item, else publish through the wake's or the
  entry's publisher (a publisher of its own only when there is neither)
  and wait for the commit. Any failure fails the launch.
- ServeScheduled fills an HA tick's bearer from the restored env after the
  wake (fillScheduledToken). Service.IsHA for internal/host.
- harelease_test: failAfterReplicate drops the store at the spawn, after
  the launch's publish; the first wake's request count includes it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 6bc9e06666d584a4a56dbe122b7cabd11850e014 parent 1236ad9
8 files changed, +777 −6
  • internal/activator/activator.go +18 −0
  • internal/activator/backend_exec.go +15 −0
  • internal/activator/claim_snapshot.go +4 −0
  • internal/activator/harelease_test.go +14 −6
  • internal/activator/hasecrets.go +292 −0
  • internal/activator/hasecrets_test.go +419 −0
  • internal/activator/instancekey.go +5 −0
  • internal/activator/prepare.go +10 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 7e0571bdf..36245f6c4 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -1474,6 +1474,11 @@ func New(cfg Config, backend Backend, due DueStore) *Service {
} else {
a.liveVer = func(string) (string, error) { return "", nil }
}
+ // An HA launch while the host is awake publishes its secrets through
+ // the entry's own files publisher (hasecrets.go).
+ if u, ok := backend.(entryFilesUser); ok {
+ u.useEntryFiles(a.entryFilesFor)
+ }
return a
}
@@ -5499,6 +5504,19 @@ func (a *Service) ServeScheduled(w http.ResponseWriter, r *http.Request, rt regi
maintenanceResponse(w, r) // turned off by its plan (plans 4d)
return true
}
+ // After the wake, an HA host's tick carries the token its restored env
+ // holds (fillScheduledToken): the runner never mints one for it.
+ next := proxy
+ proxy = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := a.fillScheduledToken(r, rt); err != nil {
+ log.Printf("activator: %s: scheduled tick: %v", rt.Host, err)
+ edge.MarkAnswered(r)
+ w.Header().Set("Retry-After", "5")
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
return a.serve(w, r, rt, proxy, false)
}
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 1b75808ba..f051c3b03 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -341,6 +341,9 @@ type ExecBackend struct {
sameBoxProof func(ctx context.Context, rt registry.Route) func() (bool, error)
// haWakes is each host's last Acquire classification (hawake.go).
haWakes haWakes
+ // entryFiles is the Service's lookup of an awake entry's files
+ // publisher (hasecrets.go), installed by New. Nil: none.
+ entryFiles func(host string) *hostFiles
}
// hostGate serialises everything that touches one host's group once Strict
@@ -1060,6 +1063,9 @@ func (b *ExecBackend) seedChild(ctx context.Context, rt registry.Route, exe stri
// thing a fresh instance runs, so this is usually where the token comes
// into existence, and instanceEnv's contract is that a seed sees the same
// environment the instance will.
+ if err := b.haMintGate(ctx, rt); err != nil {
+ return fmt.Errorf("secrets for %s: %w", host, err)
+ }
if err := EnsureAdminToken(paths.envFile); err != nil {
return fmt.Errorf("admin token for %s: %w", host, err)
}
@@ -1068,6 +1074,9 @@ func (b *ExecBackend) seedChild(ctx context.Context, rt registry.Route, exe stri
if _, err := b.ensureInstanceKeyFor(ctx, rt, paths); err != nil {
return fmt.Errorf("instance key for %s: %w", host, err)
}
+ if err := b.haSecretsReady(ctx, rt); err != nil {
+ return fmt.Errorf("secrets for %s: %w", host, err)
+ }
fileEnv, keyLayer, err := b.instanceEnvLayer(rt)
if err != nil {
return err
@@ -2165,6 +2174,9 @@ func (b *ExecBackend) spawnChildFrom(ctx context.Context, rt registry.Route, soc
// instance with no token can neither answer /api/next-due nor accept a
// tick, and a wake that quietly skipped it would report a healthy instance
// that silently never runs its scheduled work — the #110 kind of lie.
+ if err := b.haMintGate(ctx, rt); err != nil {
+ return nil, "", fmt.Errorf("secrets for %s: %w", host, err)
+ }
if err := EnsureAdminToken(paths.envFile); err != nil {
return nil, "", fmt.Errorf("admin token for %s: %w", host, err)
}
@@ -2175,6 +2187,9 @@ func (b *ExecBackend) spawnChildFrom(ctx context.Context, rt registry.Route, soc
if _, err := b.ensureInstanceKeyFor(ctx, rt, paths); err != nil {
return nil, "", fmt.Errorf("instance key for %s: %w", host, err)
}
+ if err := b.haSecretsReady(ctx, rt); err != nil {
+ return nil, "", fmt.Errorf("secrets for %s: %w", host, err)
+ }
// One read gives the env and the layer its CARLOS_INSTANCE_KEY came
// from, for the replica gate below (ruling 29).
diff --git a/internal/activator/claim_snapshot.go b/internal/activator/claim_snapshot.go
index d643a4c4c..74373737f 100644
--- a/internal/activator/claim_snapshot.go
+++ b/internal/activator/claim_snapshot.go
@@ -104,6 +104,10 @@ func (b *ExecBackend) EnsureClaimAdminToken(ctx context.Context, rt registry.Rou
if authorize == nil {
return hostwrite.ErrUnavailable
}
+ // The one mint gate for an HA host's secrets (hasecrets.go).
+ if err := b.haMintGate(ctx, rt); err != nil {
+ return err
+ }
paths := b.pathsFor(rt)
return authorize(ctx, func() error {
// Only a missing token is minted: one the rendered configuration
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go
index 4c40e67f5..82939e671 100644
--- a/internal/activator/harelease_test.go
+++ b/internal/activator/harelease_test.go
@@ -350,11 +350,15 @@ func (s *haSvc) failMarkerPuts(n int) {
}
}
-// failAfterReplicate makes the wake fail once its replica runs: with no
-// files store, the files publisher cannot open (a first wake's restore
-// needs none, so the wake gets that far).
+// failAfterReplicate makes the wake fail once its replica runs: the files
+// store goes once the app is spawned (its launch has published its
+// secrets by then, Task 11), so the files publisher cannot open.
func (s *haSvc) failAfterReplicate() {
- s.b.FilesStore = nil
+ start := s.ctl.onStart
+ s.ctl.onStart = func() {
+ start()
+ s.b.FilesStore = nil
+ }
}
func isMarker(w lockWrite) bool {
@@ -780,8 +784,12 @@ func TestHAWakeRequestCounts(t *testing.T) {
return e, s.fx.Requests()[n:]
}
e, reqs := wake()
- if want := []string{"GET " + lock, "LIST " + s.b.Cfg.hibernatePrefix(s.rt.Host) + "/", "PUT " + lock}; strings.Join(reqs, ",") != strings.Join(want, ",") {
- t.Fatalf("a first wake made %v, want %v", reqs, want)
+ // A first wake: the lock's three, then the launch's publish of its
+ // minted secrets (Task 11): the env and wake state objects and the
+ // first manifest, a create, with no read of it.
+ if want := []string{"GET " + lock, "LIST " + s.b.Cfg.hibernatePrefix(s.rt.Host) + "/", "PUT " + lock}; len(reqs) != 6 || strings.Join(reqs[:3], ",") != strings.Join(want, ",") ||
+ !strings.HasPrefix(reqs[3], "PUT "+s.b.filesPrefix(s.rt.Host)+"objects/") || !strings.HasPrefix(reqs[4], "PUT "+s.b.filesPrefix(s.rt.Host)+"objects/") || reqs[5] != "PUT "+manifest {
+ t.Fatalf("a first wake made %v, want %v, two objects and the manifest", reqs, want)
}
writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "app"})
s.stopForTest(e)
diff --git a/internal/activator/hasecrets.go b/internal/activator/hasecrets.go
new file mode 100644
index 000000000..b9d054216
--- /dev/null
+++ b/internal/activator/hasecrets.go
@@ -0,0 +1,292 @@
+package activator
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/instancefs"
+ "github.com/carlosframework/platform/internal/instancekey"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// Region HA P1a, the instance's secrets (spec §8.2, r2.3, r3.8). An HA
+// host's CARLOS_ADMIN_TOKEN and CARLOS_INSTANCE_KEY travel in its env file,
+// which publishes as the files manifest's env item, so any box that wakes
+// the host next restores the same pair. Two rules keep them one pair:
+//
+// - one mint gate (haMintGate) runs before every producer of either
+// secret: once the host's files manifest exists, nothing is minted.
+// A manifest is written only with the env acknowledged (below), so an
+// env without the pair beside one is a lost or damaged env, and a new
+// pair minted there would fork the instance's secrets. The launch is
+// deferred instead (ErrInstanceKeyDeferred).
+// - before every launch of an HA host, retries included, the env file
+// the launch reads is the one the manifest names (haSecretsReady): its
+// SHA-256 is the committed env item's, or the env is published and the
+// commit acknowledged first. A launch whose publish fails fails; the
+// app never starts with a secret no other box could restore.
+//
+// On a first wake no manifest exists, so the launch's own ensure calls
+// mint both, and haSecretsReady's publish (the env, the empty files tree
+// and the wake state) writes the first manifest. A crash between the two
+// leaves an unpublished pair on disk and no manifest: the restore that
+// follows sets the env aside, and the next launch mints a new pair.
+
+// haSecretsBudget bounds the gate's manifest read and the publish, on a
+// launch path that has no context of its own (prepare).
+const haSecretsBudget = 30 * time.Second
+
+// haHostNow is the HA classification a launch acts on: the one this
+// backend's Acquire recorded for the host's current wake, else the record
+// facts (isHA).
+func (b *ExecBackend) haHostNow(ctx context.Context, rt registry.Route) (bool, error) {
+ if s, ok := b.haWakes.get(rt.Host); ok {
+ return s.ha, nil
+ }
+ _, ha, err := b.isHA(ctx, rt)
+ return ha, err
+}
+
+// haMintGate is the one gate before every producer of an HA host's
+// secrets: nil for a host that is not HA, or whose env file holds both
+// (nothing will be minted), or whose files manifest does not exist yet.
+// An HA host whose env lacks either beside an existing manifest is
+// ErrInstanceKeyDeferred, and nothing is minted. A replica row is minted
+// no key, so only its token counts.
+func (b *ExecBackend) haMintGate(ctx context.Context, rt registry.Route) error {
+ ha, err := b.haHostNow(ctx, rt)
+ if err != nil {
+ return fmt.Errorf("refusing to mint: %w", err)
+ }
+ if !ha {
+ return nil
+ }
+ p := b.pathsFor(rt)
+ raw, cfg, _, err := readInstanceEnvPair(p.dataDir, rt.Host+".env", p.layout == LayoutNested)
+ if err != nil {
+ return err
+ }
+ own := parseEnvBytes(raw)
+ _, layer := instancekey.Effective(parseEnvBytes(cfg), own)
+ if own["CARLOS_ADMIN_TOKEN"] != "" && (rt.Replica || layer != instancekey.LayerNone) {
+ return nil
+ }
+ found, err := b.haManifestFound(ctx, rt)
+ if err != nil {
+ return fmt.Errorf("refusing to mint: read the files manifest: %w", err)
+ }
+ if found {
+ return fmt.Errorf("%w: the host's files manifest exists and its env file lacks CARLOS_ADMIN_TOKEN or %s, so nothing is minted beside it", ErrInstanceKeyDeferred, InstanceKeyVar)
+ }
+ return nil
+}
+
+// haPublisherNow is the files publisher a launch of rt publishes through:
+// the one this wake's restore opened for the entry (wakeFiles), else the
+// awake entry's own (a generation start). Nil when there is neither.
+func (b *ExecBackend) haPublisherNow(host string) *hostFiles {
+ if f, ok := b.wakeFiles(host); ok {
+ return f
+ }
+ if b.entryFiles != nil {
+ return b.entryFiles(host)
+ }
+ return nil
+}
+
+// haManifestFound reports whether rt's files manifest exists: from the
+// publisher this wake already holds, else by one read.
+func (b *ExecBackend) haManifestFound(ctx context.Context, rt registry.Route) (bool, error) {
+ if f := b.haPublisherNow(rt.Host); f != nil {
+ return f.pub.Baseline().Found, nil
+ }
+ if b.FilesStore == nil {
+ return false, errors.New("no files store configured")
+ }
+ _, found, err := hostfiles.Load(ctx, b.FilesStore, b.filesPrefix(rt.Host))
+ return found, err
+}
+
+// haSecretsReady is the step between an HA host's ensure calls and its
+// launch: nil once the env file's SHA-256 is the env item of the manifest
+// last committed. Otherwise it publishes the platform items (the env, the
+// trio and the wake state) through the wake's or the entry's publisher, or
+// a publisher of its own when there is neither (one read), waits for the
+// commit, and checks again. Every error fails the launch. Not HA: nil.
+func (b *ExecBackend) haSecretsReady(ctx context.Context, rt registry.Route) error {
+ ha, err := b.haHostNow(ctx, rt)
+ if err != nil || !ha {
+ return err
+ }
+ f := b.haPublisherNow(rt.Host)
+ own := false
+ if f == nil {
+ if b.FilesStore == nil {
+ return errors.New("publish the host's secrets: no files store configured")
+ }
+ pub, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host))
+ if err != nil {
+ return fmt.Errorf("publish the host's secrets: %w", err)
+ }
+ f, own = b.newHostFiles(rt, pub), true
+ }
+ ok, err := f.envAcknowledged()
+ if err != nil {
+ return err
+ }
+ if !ok {
+ if err := f.PublishPlatformNow(ctx); err != nil {
+ return fmt.Errorf("publish the host's secrets: %w", err)
+ }
+ if ok, err = f.envAcknowledged(); err != nil {
+ return err
+ }
+ if !ok {
+ return errors.New("publish the host's secrets: the env file changed while it was published")
+ }
+ }
+ if own {
+ // The wake's entry continues from the manifest this read or
+ // committed (openHostFiles), with no second read.
+ b.haWakes.setFiles(rt.Host, f)
+ }
+ return nil
+}
+
+// envAcknowledged reports whether the env file's bytes are the env item of
+// the manifest f last committed. An env file that is absent is an error:
+// a launch's ensure calls have just written it.
+func (f *hostFiles) envAcknowledged() (bool, error) {
+ dir, name := filepath.Dir(f.paths.envFile), filepath.Base(f.paths.envFile)
+ env, absent, err := instancefs.ReadBeneathLimitOrAbsent(dir, name, haEnvReadLimit)
+ switch {
+ case err != nil && !errors.Is(err, os.ErrNotExist):
+ return false, fmt.Errorf("read %s: %w", name, err)
+ case absent || err != nil:
+ return false, fmt.Errorf("%s is absent", name)
+ }
+ base := f.pub.Baseline()
+ if !base.Found {
+ return false, nil
+ }
+ var m hostfiles.Manifest
+ if err := json.Unmarshal(base.Body, &m); err != nil {
+ return false, fmt.Errorf("the committed files manifest: %w", err)
+ }
+ item, ok := m.Platform[hostfiles.EnvItem]
+ sum := sha256.Sum256(env)
+ return ok && !item.Deleted && item.SHA256 == hex.EncodeToString(sum[:]), nil
+}
+
+// entryFilesUser is the Backend capability New hands the service's entry
+// lookup to, so a launch while the host is awake publishes through the
+// entry's own publisher: a second publisher on the prefix would supersede
+// it.
+type entryFilesUser interface {
+ useEntryFiles(func(host string) *hostFiles)
+}
+
+func (b *ExecBackend) useEntryFiles(f func(host string) *hostFiles) { b.entryFiles = f }
+
+func (b *SplitBackend) useEntryFiles(f func(host string) *hostFiles) {
+ for _, half := range []Backend{b.Exec, b.Unit} {
+ if u, ok := half.(entryFilesUser); ok {
+ u.useEntryFiles(f)
+ }
+ }
+}
+
+// entryFilesFor is the awake (or waking) entry's files publisher for host,
+// nil when it has none.
+func (a *Service) entryFilesFor(host string) *hostFiles {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if e := a.entries[host]; e != nil {
+ return e.files
+ }
+ return nil
+}
+
+// haScheduledTokener is the Backend capability ServeScheduled asks after a
+// tick's wake (ExecBackend's; SplitBackend dispatches it).
+type haScheduledTokener interface {
+ haScheduledToken(ctx context.Context, rt registry.Route) (token string, ha bool, err error)
+}
+
+// haScheduledToken is an HA host's CARLOS_ADMIN_TOKEN as its env file holds
+// it now, after the wake that restored it. ha is false, and nothing is
+// read, for a host that is not HA.
+func (b *ExecBackend) haScheduledToken(ctx context.Context, rt registry.Route) (string, bool, error) {
+ ha, err := b.haHostNow(ctx, rt)
+ if err != nil || !ha {
+ return "", ha, err
+ }
+ p := b.pathsFor(rt)
+ raw, err := instancefs.ReadBeneathLimit(filepath.Dir(p.envFile), filepath.Base(p.envFile), haEnvReadLimit)
+ if err != nil {
+ return "", true, fmt.Errorf("read the instance token: %w", err)
+ }
+ tok := parseEnvBytes(raw)["CARLOS_ADMIN_TOKEN"]
+ if tok == "" {
+ return "", true, errors.New("no CARLOS_ADMIN_TOKEN after the wake")
+ }
+ return tok, true, nil
+}
+
+func (b *SplitBackend) haScheduledToken(ctx context.Context, rt registry.Route) (string, bool, error) {
+ if t, ok := b.pick(rt).(haScheduledTokener); ok {
+ return t.haScheduledToken(ctx, rt)
+ }
+ return "", false, nil
+}
+
+// fillScheduledToken sets a scheduled tick's bearer token for an HA host
+// from the env file its wake restored: the runner's own read ran before
+// the wake and never mints for an HA host (internal/host scheduleToken),
+// so it may have found none, or a stale one. Any other host's tick is left
+// as the runner built it.
+func (a *Service) fillScheduledToken(r *http.Request, rt registry.Route) error {
+ t, ok := a.backend.(haScheduledTokener)
+ if !ok {
+ return nil
+ }
+ tok, ha, err := t.haScheduledToken(r.Context(), rt)
+ if err != nil || !ha {
+ return err
+ }
+ r.Header.Set("Authorization", "Bearer "+tok)
+ return nil
+}
+
+// haClassifier is the Backend capability IsHA asks.
+type haClassifier interface {
+ IsHA(ctx context.Context, rt registry.Route) (bool, error)
+}
+
+func (b *SplitBackend) IsHA(ctx context.Context, rt registry.Route) (bool, error) {
+ if c, ok := b.Exec.(haClassifier); ok {
+ return c.IsHA(ctx, rt)
+ }
+ return rt.HA, nil
+}
+
+// IsHA is the box's HA classification of rt (ExecBackend.IsHA) for the
+// rest of the box (internal/host): the row's sticky mark alone on a
+// Service whose backend cannot classify.
+func (a *Service) IsHA(ctx context.Context, rt registry.Route) (bool, error) {
+ if a != nil {
+ if c, ok := a.backend.(haClassifier); ok {
+ return c.IsHA(ctx, rt)
+ }
+ }
+ return rt.HA, nil
+}
diff --git a/internal/activator/hasecrets_test.go b/internal/activator/hasecrets_test.go
new file mode 100644
index 000000000..191f6bd84
--- /dev/null
+++ b/internal/activator/hasecrets_test.go
@@ -0,0 +1,419 @@
+package activator
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// haLaunchBackend is haBackend with a short run directory, so the launch
+// path's unix sockets fit whatever the test's name.
+func haLaunchBackend(t *testing.T, host string) (*ExecBackend, registry.Route) {
+ t.Helper()
+ b, rt := haBackend(t, host)
+ run, err := os.MkdirTemp("", "ha")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(run) })
+ b.RunDirOverride = run
+ rt.Socket = nestedRoute(b, host).Socket
+ if err := b.Registry.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ return b, rt
+}
+
+// launchForTest is the nested launch path's preparation for the run role,
+// the step every nested start takes before root starts the unit: the mint
+// gate, the admin token, the instance key and the secrets' publish.
+func (b *ExecBackend) launchForTest(rt registry.Route) error {
+ _, ctl, logs, _, _, err := b.prepareKeyedAt(rt, instancectl.RoleRun, rt.Socket, 0, nil)
+ if ctl != nil {
+ ctl.Close()
+ }
+ if logs != nil {
+ logs.Close()
+ }
+ return err
+}
+
+func writeEnv(t *testing.T, b *ExecBackend, rt registry.Route, body string) {
+ t.Helper()
+ p := b.pathsFor(rt)
+ if err := os.MkdirAll(filepath.Dir(p.envFile), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p.envFile, []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func envFileHas(t *testing.T, b *ExecBackend, rt registry.Route, name string) bool {
+ t.Helper()
+ raw, err := os.ReadFile(b.pathsFor(rt).envFile)
+ if errors.Is(err, os.ErrNotExist) {
+ return false
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return parseEnvBytes(raw)[name] != ""
+}
+
+func envValues(t *testing.T, b *ExecBackend, rt registry.Route, names ...string) []string {
+ t.Helper()
+ raw, err := os.ReadFile(b.pathsFor(rt).envFile)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ env := parseEnvBytes(raw)
+ out := make([]string, len(names))
+ for i, n := range names {
+ out[i] = env[n]
+ }
+ return out
+}
+
+// platformEnv is the env item of the host's files manifest as stored now,
+// "" when there is none.
+func platformEnv(t *testing.T, b *ExecBackend, rt registry.Route) string {
+ t.Helper()
+ ctx := context.Background()
+ prefix := b.filesPrefix(rt.Host)
+ m, found, err := hostfiles.Load(ctx, b.FilesStore, prefix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !found {
+ return ""
+ }
+ if _, ok := m.Platform[hostfiles.EnvItem]; !ok {
+ return ""
+ }
+ env, err := hostfiles.ReadPlatform(ctx, b.FilesStore, prefix, m, hostfiles.EnvItem, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(env)
+}
+
+// failingCommits is a files store whose next n manifest writes fail.
+type failingCommits struct {
+ release.Store
+ mu sync.Mutex
+ n int
+}
+
+func (s *failingCommits) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if strings.HasSuffix(key, "manifest.json") {
+ s.mu.Lock()
+ fail := s.n > 0
+ if fail {
+ s.n--
+ }
+ s.mu.Unlock()
+ if fail {
+ return "", errors.New("store unavailable")
+ }
+ }
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+func failFilesCommitOnce(t *testing.T, b *ExecBackend) {
+ t.Helper()
+ b.FilesStore = &failingCommits{Store: b.FilesStore, n: 1}
+}
+
+// r2.3: beside an existing manifest, an env missing a secret is a lost env,
+// and nothing is minted into it.
+func TestHATokenNotMintedBesideAManifest(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ publishManifest(t, b, rt, nil, "CARLOS_INSTANCE_KEY=k1\n")
+ writeEnv(t, b, rt, "CARLOS_INSTANCE_KEY=k1\n")
+ if err := b.launchForTest(rt); !errors.Is(err, ErrInstanceKeyDeferred) || envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN") {
+ t.Fatalf("launch: %v; token minted: %v", err, envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN"))
+ }
+ // The key alone missing defers the same way.
+ writeEnv(t, b, rt, "CARLOS_ADMIN_TOKEN=t1\n")
+ if err := b.launchForTest(rt); !errors.Is(err, ErrInstanceKeyDeferred) || envFileHas(t, b, rt, InstanceKeyVar) {
+ t.Fatalf("launch: %v; key minted: %v", err, envFileHas(t, b, rt, InstanceKeyVar))
+ }
+}
+
+// Every other instance-key producer goes through the same gate: the
+// backfill defers beside a manifest and writes nothing.
+func TestHABackfillNotMintedBesideAManifest(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ publishManifest(t, b, rt, nil, "CARLOS_ADMIN_TOKEN=t1\n")
+ writeEnv(t, b, rt, "CARLOS_ADMIN_TOKEN=t1\n")
+ if _, err := b.BackfillInstanceKey(context.Background(), rt); !errors.Is(err, ErrInstanceKeyDeferred) || envFileHas(t, b, rt, InstanceKeyVar) {
+ t.Fatalf("backfill: %v; key minted: %v", err, envFileHas(t, b, rt, InstanceKeyVar))
+ }
+}
+
+// The first launch's publish fails: the launch fails, and its retry
+// publishes the secrets it minted before it succeeds.
+func TestHALaunchRetryPublishesPendingSecretFirst(t *testing.T) {
+ b, rt := haLaunchBackend(t, "fresh.example.com")
+ failFilesCommitOnce(t, b)
+ if err := b.launchForTest(rt); err == nil {
+ t.Fatal("launched without an acknowledged publish")
+ }
+ minted := envValues(t, b, rt, "CARLOS_ADMIN_TOKEN", InstanceKeyVar)
+ if minted[0] == "" || minted[1] == "" {
+ t.Fatalf("the first launch minted %v", minted)
+ }
+ if err := b.launchForTest(rt); err != nil {
+ t.Fatal(err)
+ }
+ pub := platformEnv(t, b, rt)
+ if !strings.Contains(pub, "CARLOS_ADMIN_TOKEN="+minted[0]) || !strings.Contains(pub, InstanceKeyVar+"="+minted[1]) {
+ t.Fatalf("published env %q, want the pair the first launch minted", pub)
+ }
+}
+
+// A launch whose env already matches the manifest publishes nothing: a
+// restore wake costs no manifest write.
+func TestHALaunchAcknowledgedEnvWritesNothing(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ env := "CARLOS_ADMIN_TOKEN=t1\n" + InstanceKeyVar + "=k1\n"
+ publishManifest(t, b, rt, nil, env)
+ writeEnv(t, b, rt, env)
+ failFilesCommitOnce(t, b) // a write would fail the launch
+ if err := b.launchForTest(rt); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// A launch while the host is awake publishes through the entry's own
+// publisher, never a second one (which would supersede it).
+func TestHALaunchUsesTheEntryPublisher(t *testing.T) {
+ ctx := context.Background()
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ pub, err := hostfiles.Open(ctx, b.FilesStore, b.filesPrefix(rt.Host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ entry := b.newHostFiles(rt, pub)
+ asked := 0
+ b.useEntryFiles(func(host string) *hostFiles { asked++; return entry })
+ if err := b.launchForTest(rt); err != nil {
+ t.Fatal(err)
+ }
+ if asked == 0 || !strings.Contains(platformEnv(t, b, rt), "CARLOS_ADMIN_TOKEN=") {
+ t.Fatalf("asked %d; published %q", asked, platformEnv(t, b, rt))
+ }
+ // The entry's publisher is still the manifest's writer: it commits on.
+ writeEnv(t, b, rt, "CARLOS_ADMIN_TOKEN=t2\n"+InstanceKeyVar+"=k2\n")
+ if err := entry.PublishPlatformNow(ctx); err != nil {
+ t.Fatalf("the entry's publisher was superseded: %v", err)
+ }
+}
+
+// Not HA: no gate, no publish, nothing read from the files store.
+func TestLegacyLaunchPublishesNothing(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ h := haFixOf(b)
+ h.mu.Lock()
+ h.records[rt.Host] = haRecord(rt.Host, false)
+ h.mu.Unlock()
+ b.Lifetimes = nil
+ publishManifest(t, b, rt, nil, "CARLOS_INSTANCE_KEY=k1\n")
+ writeEnv(t, b, rt, "CARLOS_INSTANCE_KEY=k1\n")
+ if err := b.launchForTest(rt); err != nil || !envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN") {
+ t.Fatalf("launch: %v", err)
+ }
+ if strings.Contains(platformEnv(t, b, rt), "CARLOS_ADMIN_TOKEN") {
+ t.Fatal("a legacy host's env was published")
+ }
+}
+
+// G7: a tick for an HA host carries the token of the env its wake
+// restored, whatever the runner read before the wake; any other host's
+// tick is left alone.
+func TestFillScheduledToken(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ a := New(Config{Bucket: b.Cfg.Bucket, Idle: time.Hour}, b, b.Registry)
+ writeEnv(t, b, rt, "CARLOS_ADMIN_TOKEN=restored\n")
+ r := httptest.NewRequest(http.MethodPost, "http://shop.example.com/tick", nil)
+ r.Header.Set("Authorization", "Bearer ")
+ if err := a.fillScheduledToken(r, rt); err != nil || r.Header.Get("Authorization") != "Bearer restored" {
+ t.Fatalf("fill: %v, header %q", err, r.Header.Get("Authorization"))
+ }
+ writeEnv(t, b, rt, "OTHER=1\n")
+ if err := a.fillScheduledToken(r, rt); err == nil {
+ t.Fatal("no token after the wake should fail the tick")
+ }
+ h := haFixOf(b)
+ h.mu.Lock()
+ h.records[rt.Host] = haRecord(rt.Host, false)
+ h.mu.Unlock()
+ b.Lifetimes = nil
+ r.Header.Set("Authorization", "Bearer runner")
+ if err := a.fillScheduledToken(r, rt); err != nil || r.Header.Get("Authorization") != "Bearer runner" {
+ t.Fatalf("legacy: %v, header %q", err, r.Header.Get("Authorization"))
+ }
+}
+
+// G7, through ServeScheduled: the tick the app receives carries the
+// restored token.
+func TestServeScheduledFillsTheTokenAfterTheWake(t *testing.T) {
+ s, _ := haServiceEntry(t, "shop.example.com")
+ tok := envValues(t, s.b, s.rt, "CARLOS_ADMIN_TOKEN")[0]
+ if tok == "" {
+ t.Fatal("the wake minted no token")
+ }
+ var got string
+ proxy := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { got = r.Header.Get("Authorization") })
+ r := httptest.NewRequest(http.MethodPost, "http://shop.example.com/tick", nil)
+ r.Header.Set("Authorization", "Bearer ")
+ if !s.a.ServeScheduled(httptest.NewRecorder(), r, s.rt, proxy) || got != "Bearer "+tok {
+ t.Fatalf("the app got %q, want the restored token", got)
+ }
+}
+
+// Review Focus 4, r3.8: the first wake mints, and the agent dies before
+// the files commit lands. The same box, restarted, takes its own expired
+// lock on the startup sweep's proof; the unpublished pair is set aside,
+// a new one is minted, and the app starts only once the manifest holds it.
+// Another box stays refused throughout.
+func TestFirstWakeCrashBeforePublishRemints(t *testing.T) {
+ s := haService(t, "fresh.example.com")
+ manifestKey := hostfiles.ManifestKey(s.b.filesPrefix(s.rt.Host))
+ // The crash: the first manifest write never lands, and the agent that
+ // sent it never runs again.
+ stuck, release := make(chan struct{}), make(chan struct{})
+ var once sync.Once
+ s.fx.BeforeWrite(func(method, key string) {
+ if key != manifestKey {
+ return
+ }
+ blocked := false
+ once.Do(func() { blocked = true })
+ if blocked {
+ close(stuck)
+ <-release
+ }
+ })
+ dead := make(chan struct{})
+ go func() {
+ defer close(dead)
+ _, _ = s.wakeForTest(context.Background())
+ }()
+ t.Cleanup(func() {
+ close(release)
+ select {
+ case <-dead:
+ case <-time.After(time.Minute):
+ t.Error("the dead agent's wake never returned")
+ }
+ })
+ select {
+ case <-stuck:
+ case <-time.After(30 * time.Second):
+ t.Fatal("crash not simulated: the wake never reached its publish")
+ }
+ lost := envValues(t, s.b, s.rt, "CARLOS_ADMIN_TOKEN", InstanceKeyVar)
+ if lost[0] == "" || lost[1] == "" {
+ t.Fatalf("the first wake minted %v", lost)
+ }
+ if platformEnv(t, s.b, s.rt) != "" {
+ t.Fatal("the pair was published before the crash")
+ }
+ // Its TTL passes: the dead agent's HA lock, expired.
+ v := s.lockView(t)
+ if v.Absent || v.Lock.Release != nil || !v.HAOn() {
+ t.Fatalf("the dead agent left %+v", v)
+ }
+ expired := v.Lock
+ expired.ExpiresAt = time.Now().Add(-time.Minute).UTC()
+ body, err := json.Marshal(expired)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.fx.PutLock(s.b.Cfg.hibernatePrefix(s.rt.Host), body)
+
+ // Another box is refused the expired lease.
+ other := s.restart(t)
+ lease.SetSelf(hafresh.Self{Ref: "b", IID: "i-b"})
+ _, err = other.wakeForTest(context.Background())
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"})
+ var refused *errLeaseRefused
+ if !errors.As(err, &refused) || !strings.Contains(refused.reason, hafresh.ReasonOtherExpired) {
+ t.Fatalf("another box took it: %v", err)
+ }
+
+ // The same box restarts; its startup sweep proved every unit stopped.
+ a2 := s.restart(t)
+ a2.b.SetSameBoxProof(func(context.Context, registry.Route) func() (bool, error) {
+ return func() (bool, error) { return true, nil }
+ })
+ var atSpawn string
+ start := s.ctl.onStart
+ s.ctl.onStart = func() {
+ atSpawn = platformEnv(t, a2.b, a2.rt) // read from the manifest at the spawn
+ start()
+ }
+ if _, err := a2.wakeForTest(context.Background()); err != nil {
+ t.Fatalf("the same box could not wake its own host: %v", err)
+ }
+ got := envValues(t, a2.b, a2.rt, "CARLOS_ADMIN_TOKEN", InstanceKeyVar)
+ if got[0] == "" || got[1] == "" || got[0] == lost[0] || got[1] == lost[1] {
+ t.Fatalf("secrets not reminted: %v after %v", got, lost)
+ }
+ if !strings.Contains(atSpawn, "CARLOS_ADMIN_TOKEN="+got[0]) || !strings.Contains(atSpawn, InstanceKeyVar+"="+got[1]) {
+ t.Fatalf("the app started before its secrets were acknowledged: the manifest held %q", atSpawn)
+ }
+ // Another box is still refused: the host is held.
+ lease.SetSelf(hafresh.Self{Ref: "b", IID: "i-b"})
+ _, err = other.b.Acquire(context.Background(), other.rt)
+ lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a"})
+ var held *errLeaseHeld
+ if !errors.As(err, &held) {
+ t.Fatalf("another box acquired the woken host: %v", err)
+ }
+}
+
+// The claim launch source's mint goes through the same gate.
+func TestHAClaimTokenNotMintedBesideAManifest(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ publishManifest(t, b, rt, nil, "CARLOS_INSTANCE_KEY=k1\n")
+ writeEnv(t, b, rt, "CARLOS_INSTANCE_KEY=k1\n")
+ authorize := func(ctx context.Context, write func() error) error { return write() }
+ if err := b.EnsureClaimAdminToken(context.Background(), rt, authorize); !errors.Is(err, ErrInstanceKeyDeferred) || envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN") {
+ t.Fatalf("claim ensure: %v; token minted: %v", err, envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN"))
+ }
+}
+
+// The flat launch path's producers go through the gate too (an HA host
+// never launches flat: haSpawnGate refuses one acquired HA first).
+func TestHAFlatLaunchNotMintedBesideAManifest(t *testing.T) {
+ b, rt := haLaunchBackend(t, "shop.example.com")
+ flattenRoute(t, b, &rt)
+ stageLive(t, b, rt.Host, "v1")
+ publishManifest(t, b, rt, nil, "CARLOS_INSTANCE_KEY=k1\n")
+ writeEnv(t, b, rt, "CARLOS_INSTANCE_KEY=k1\n")
+ if _, _, err := b.Start(context.Background(), rt); !errors.Is(err, ErrInstanceKeyDeferred) || envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN") {
+ t.Fatalf("start: %v; token minted: %v", err, envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN"))
+ }
+ rt.Seed = `["seed"]`
+ if err := b.Seed(context.Background(), rt); !errors.Is(err, ErrInstanceKeyDeferred) || envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN") {
+ t.Fatalf("seed: %v; token minted: %v", err, envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN"))
+ }
+}
diff --git a/internal/activator/instancekey.go b/internal/activator/instancekey.go
index ad10821ec..9dd17dd1b 100644
--- a/internal/activator/instancekey.go
+++ b/internal/activator/instancekey.go
@@ -264,6 +264,11 @@ func (b *ExecBackend) ensureInstanceKeyFor(ctx context.Context, rt registry.Rout
// The agent's backfill names the host when it logs the error, so the
// refusal does not.
func (b *ExecBackend) BackfillInstanceKey(ctx context.Context, rt registry.Route) (InstanceKeyOutcome, error) {
+ // An HA host's secrets are minted only before its manifest exists
+ // (haMintGate); the agent's backfill skips HA hosts before this.
+ if err := b.haMintGate(ctx, rt); err != nil {
+ return InstanceKeyFailed, err
+ }
return b.ensureInstanceKeyAt(ctx, rt, b.pathsFor(rt), false, "backfilled")
}
diff --git a/internal/activator/prepare.go b/internal/activator/prepare.go
index 4d22604ca..0ebde4575 100644
--- a/internal/activator/prepare.go
+++ b/internal/activator/prepare.go
@@ -77,6 +77,13 @@ func (b *ExecBackend) prepareKeyedAt(rt registry.Route, role instancectl.Role, s
var keyLayer instancekey.Layer // the layer env's key came from, read with it (ruling 29)
switch role {
case instancectl.RoleRun, instancectl.RoleSeed:
+ // An HA host's secrets: the mint gate before either producer, and
+ // the env published and acknowledged after them (hasecrets.go).
+ hctx, cancel := context.WithTimeout(context.Background(), haSecretsBudget)
+ defer cancel()
+ if err := b.haMintGate(hctx, rt); err != nil {
+ return p, nil, nil, nil, instancekey.LayerNone, fmt.Errorf("secrets for %s: %w", rt.Host, err)
+ }
// p.dataDir is the instance directory here, tenant-writable ground
// (design §3.2), so the token file is minted and read through
// instancefs rather than a plain path-based open.
@@ -87,6 +94,9 @@ func (b *ExecBackend) prepareKeyedAt(rt registry.Route, role instancectl.Role, s
if _, err := b.ensureInstanceKeyFor(context.Background(), rt, p); err != nil { // prepareAt has no ctx to bound the mint's bucket read; configReadTimeout does
return p, nil, nil, nil, instancekey.LayerNone, fmt.Errorf("instance key for %s: %w", rt.Host, err)
}
+ if err := b.haSecretsReady(hctx, rt); err != nil {
+ return p, nil, nil, nil, instancekey.LayerNone, fmt.Errorf("secrets for %s: %w", rt.Host, err)
+ }
steps.mark(time.Now(), "instance key")
var err error
env, keyLayer, err = b.instanceEnvLayer(rt)