carlos / platform Public

region HA P1a final fix: F2 the mint decision lives in the producers; the launch env is captured once

For an HA host, both producers (ensureAdminToken, ensureInstanceKey) now ask
the host's mint decision (haMintGuard) in their missing-secret branch, on the
read the mint decides from: while the files manifest exists nothing is minted,
whatever an earlier read saw. The separate env-reading gate is gone.

The launch env is read once (captureLaunchEnv); haSecretsReady verifies and,
if needed, publishes against those exact bytes, and the launch is handed the
env parsed from them (launchEnvLayer). A file replaced after the read is never
launched; one replaced under the publish fails the launch.

Tests: a replacement after the gate's read mints neither secret beside a
manifest; a replacement after the publish is not what the launch is handed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 2ea08e52da335fb6e6431176d146f818ee4aaed9 parent 9c7b537
7 files changed, +262 −112
  • internal/activator/admintoken.go +17 −17
  • internal/activator/backend_exec.go +9 −18
  • internal/activator/claim_snapshot.go +3 −5
  • internal/activator/hasecrets.go +131 −52
  • internal/activator/hasecrets_test.go +67 −0
  • internal/activator/instancekey.go +25 −10
  • internal/activator/prepare.go +10 −10
diff --git a/internal/activator/admintoken.go b/internal/activator/admintoken.go
index 239632806..1b93e2c8e 100644
--- a/internal/activator/admintoken.go
+++ b/internal/activator/admintoken.go
@@ -66,17 +66,6 @@ var adminTokenLogMu sync.Mutex
// deduplicated before it is said again.
const adminTokenLogRepeat = time.Hour
-// ensureAdminTokenAt is EnsureAdminToken on p's layout: through instancefs
-// for a nested row's tenant-writable directory, by path otherwise. The
-// legacy launch bodies each know their layout and call one or the other;
-// the claim path, which serves both, calls this.
-func ensureAdminTokenAt(p instancePaths, name string) error {
- if p.layout == LayoutNested {
- return EnsureAdminTokenBeneath(p.dataDir, name)
- }
- return EnsureAdminToken(filepath.Join(p.dataDir, name))
-}
-
// logPerFile emits msg unless this (kind, path) pair has already said it
// within adminTokenLogRepeat. Keyed by kind as well as path so a file that
// is both un-tightenable AND holding a malformed token still reports both —
@@ -130,7 +119,7 @@ func wellFormedAdminToken(tok string) bool {
// shape-checked, and a value that isn't the shape this mints is reported and
// left exactly as it is.
func EnsureAdminToken(path string) error {
- return ensureAdminToken(filepath.Dir(path), filepath.Base(path), false)
+ return ensureAdminToken(filepath.Dir(path), filepath.Base(path), false, nil)
}
// EnsureAdminTokenBeneath is EnsureAdminToken for a nested row's own env
@@ -149,14 +138,17 @@ func EnsureAdminToken(path string) error {
// ordinary regular file. Splitting path into dir/name here, once, is what
// lets both callers share every line after the read.
func EnsureAdminTokenBeneath(dir, name string) error {
- return ensureAdminToken(dir, name, true)
+ return ensureAdminToken(dir, name, true, nil)
}
// ensureAdminToken is EnsureAdminToken's and EnsureAdminTokenBeneath's
-// shared body. beneath selects which pair of I/O primitives the read and
-// the append use; everything else, the parse, the mode check, the shape
-// check, the mint, is one piece of logic so the two callers cannot drift.
-func ensureAdminToken(dir, name string, beneath bool) error {
+// shared body (and ensureAdminTokenFor's). beneath selects which pair of
+// I/O primitives the read and the append use; everything else, the parse,
+// the mode check, the shape check, the mint, is one piece of logic so the
+// callers cannot drift. guard, when not nil, is asked once this read has
+// found no token, before anything is minted (an HA host's haMintGuard);
+// its refusal is returned and nothing is written.
+func ensureAdminToken(dir, name string, beneath bool, guard mintGuard) error {
path := filepath.Join(dir, name)
adminTokenMu.Lock()
defer adminTokenMu.Unlock()
@@ -219,6 +211,14 @@ func ensureAdminToken(dir, name string, beneath bool) error {
}
return nil
}
+ // The token is missing on this read, the one the mint decides from:
+ // an HA host's mint decision is asked here, never on an earlier read
+ // (final review F2).
+ if guard != nil {
+ if err := guard(); err != nil {
+ return err
+ }
+ }
secret := make([]byte, 32)
if _, err := rand.Read(secret); err != nil {
return fmt.Errorf("mint admin token for %s: %w", path, err)
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 1c9bac847..d97a017e8 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -1071,10 +1071,7 @@ 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 {
+ if err := b.ensureAdminTokenFor(ctx, rt, paths); err != nil {
return fmt.Errorf("admin token for %s: %w", host, err)
}
// The instance key, before the env is read for the same reason: a seed
@@ -1082,10 +1079,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)
+ // An HA host's env is captured once, acknowledged, and handed on as
+ // captured (launchEnvLayer); any other host's is instanceEnvLayer.
+ fileEnv, keyLayer, err := b.launchEnvLayer(ctx, rt)
if err != nil {
return err
}
@@ -2182,10 +2178,7 @@ 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 {
+ if err := b.ensureAdminTokenFor(ctx, rt, paths); err != nil {
return nil, "", fmt.Errorf("admin token for %s: %w", host, err)
}
// The instance key is minted here for the same reason and fails the
@@ -2195,13 +2188,11 @@ 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).
- fileEnv, keyLayer, err := b.instanceEnvLayer(rt)
+ // from, for the replica gate below (ruling 29). An HA host's is
+ // captured once, acknowledged, and handed on as captured
+ // (launchEnvLayer).
+ fileEnv, keyLayer, err := b.launchEnvLayer(ctx, rt)
if err != nil {
return nil, "", err
}
diff --git a/internal/activator/claim_snapshot.go b/internal/activator/claim_snapshot.go
index 74373737f..72b8735af 100644
--- a/internal/activator/claim_snapshot.go
+++ b/internal/activator/claim_snapshot.go
@@ -104,17 +104,15 @@ 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
- }
+ // An HA host's mint decision is inside both producers below
+ // (haMintGuard, hasecrets.go).
paths := b.pathsFor(rt)
return authorize(ctx, func() error {
// Only a missing token is minted: one the rendered configuration
// supplies is the one the launch delivers, and a second one in the
// own file would shadow it.
if vars["CARLOS_ADMIN_TOKEN"] == "" {
- if err := ensureAdminTokenAt(paths, rt.Host+".env"); err != nil {
+ if err := b.ensureAdminTokenFor(ctx, rt, paths); err != nil {
return err
}
}
diff --git a/internal/activator/hasecrets.go b/internal/activator/hasecrets.go
index b9d054216..cc7b06f33 100644
--- a/internal/activator/hasecrets.go
+++ b/internal/activator/hasecrets.go
@@ -10,6 +10,7 @@ import (
"net/http"
"os"
"path/filepath"
+ "sync"
"time"
"github.com/carlosframework/platform/internal/hostfiles"
@@ -23,17 +24,22 @@ import (
// 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
+// - one mint decision (haMintGuard) inside every producer of either
+// secret, asked in its missing-secret branch at the moment it would
+// mint (final review F2): once the host's files manifest exists,
+// nothing is minted, whatever an earlier read of the env saw. 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.
+// - before every launch of an HA host, retries included, the launch's
+// env is read once (captureLaunchEnv), those bytes are the env item of
+// the manifest last committed (haSecretsReady), or are published and
+// the commit acknowledged first, and the launch is handed the env
+// parsed from those same bytes, never a later read (launchEnvLayer).
+// A launch whose publish fails, or whose env changed under its
+// publish, 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
@@ -41,6 +47,13 @@ import (
// 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.
+// haLaunchHooks are an HA launch's test seams: afterGate runs before
+// either producer; afterPublish once the launch's env is acknowledged,
+// before the launch is handed it.
+var haLaunchHooks struct {
+ afterGate, afterPublish func()
+}
+
// 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
@@ -56,38 +69,114 @@ func (b *ExecBackend) haHostNow(ctx context.Context, rt registry.Route) (bool, e
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 {
+// mintGuard is a producer's last word before it mints a missing secret,
+// asked in its missing-secret branch: nil lets the mint go ahead; an error
+// refuses it, and nothing is written. A nil mintGuard always mints (a host
+// that is not HA).
+type mintGuard func() error
+
+// haMintGuard is the one mint decision for an HA host's secrets (r2.3,
+// final review F2): nil for a host that is not HA. For an HA host, a
+// guard that refuses with ErrInstanceKeyDeferred while the host's files
+// manifest exists, and lets the mint go ahead only while it does not.
+// It never reads the env: the producer asks it only once its own read
+// found the secret missing. The manifest is read at most once per guard,
+// and only when a producer would mint (from the wake's publisher when
+// there is one, no request).
+func (b *ExecBackend) haMintGuard(ctx context.Context, rt registry.Route) (mintGuard, error) {
ha, err := b.haHostNow(ctx, rt)
if err != nil {
- return fmt.Errorf("refusing to mint: %w", err)
+ return nil, fmt.Errorf("refusing to mint: %w", err)
}
if !ha {
- return nil
+ return nil, nil
}
- p := b.pathsFor(rt)
- raw, cfg, _, err := readInstanceEnvPair(p.dataDir, rt.Host+".env", p.layout == LayoutNested)
+ var (
+ once sync.Once
+ verdict error
+ )
+ return func() error {
+ once.Do(func() {
+ found, err := b.haManifestFound(ctx, rt)
+ switch {
+ case err != nil:
+ verdict = fmt.Errorf("refusing to mint: read the files manifest: %w", err)
+ case found:
+ verdict = 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 verdict
+ }, nil
+}
+
+// ensureAdminTokenFor is the launch paths' admin token producer for rt on
+// p's layout, with the host's mint decision inside it (haMintGuard).
+func (b *ExecBackend) ensureAdminTokenFor(ctx context.Context, rt registry.Route, p instancePaths) error {
+ guard, err := b.haMintGuard(ctx, rt)
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
+ return ensureAdminToken(p.dataDir, rt.Host+".env", p.layout == LayoutNested, guard)
+}
+
+// capturedEnv is a launch's env files, read once: the own file's bytes,
+// and the env and key layer parsed from that same read.
+type capturedEnv struct {
+ own []byte
+ env map[string]string
+ layer instancekey.Layer
+}
+
+// captureLaunchEnv reads rt's own env file and its rendered configuration
+// once, the way instanceEnvParts reads them (beneath on the nested
+// layout), and parses the launch's env from those bytes. An own file that
+// is absent is an error: the launch's producers have just written it.
+func (b *ExecBackend) captureLaunchEnv(rt registry.Route) (capturedEnv, error) {
+ p := b.pathsFor(rt)
+ read := func(path string) ([]byte, error) {
+ if p.layout == LayoutNested {
+ return instancefs.ReadBeneathLimit(filepath.Dir(path), filepath.Base(path), haEnvReadLimit)
+ }
+ return os.ReadFile(path)
}
- found, err := b.haManifestFound(ctx, rt)
+ own, err := read(p.envFile)
if err != nil {
- return fmt.Errorf("refusing to mint: read the files manifest: %w", err)
+ return capturedEnv{}, fmt.Errorf("read env file: %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)
+ cfg, err := read(p.configEnv)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return capturedEnv{}, fmt.Errorf("read config env file: %w", err)
}
- return nil
+ cfgEnv, ownEnv := parseEnvBytes(cfg), parseEnvBytes(own)
+ _, layer := instancekey.Effective(cfgEnv, ownEnv)
+ return capturedEnv{own: own, env: mergeEnv(cfgEnv, ownEnv), layer: layer}, nil
+}
+
+// launchEnvLayer is a launch's env and the layer its key came from
+// (instanceEnvLayer's answer). For an HA host the env is captured once,
+// those bytes are published and acknowledged (haSecretsReady), and the
+// env parsed from them is the one returned: a replacement of the file
+// after the read is never what the launch is handed. Any other host's is
+// instanceEnvLayer, unchanged.
+func (b *ExecBackend) launchEnvLayer(ctx context.Context, rt registry.Route) (map[string]string, instancekey.Layer, error) {
+ ha, err := b.haHostNow(ctx, rt)
+ if err != nil {
+ return nil, instancekey.LayerNone, fmt.Errorf("secrets for %s: %w", rt.Host, err)
+ }
+ if !ha {
+ return b.instanceEnvLayer(rt)
+ }
+ c, err := b.captureLaunchEnv(rt)
+ if err != nil {
+ return nil, instancekey.LayerNone, fmt.Errorf("secrets for %s: %w", rt.Host, err)
+ }
+ if err := b.haSecretsReady(ctx, rt, c.own); err != nil {
+ return nil, instancekey.LayerNone, fmt.Errorf("secrets for %s: %w", rt.Host, err)
+ }
+ if haLaunchHooks.afterPublish != nil {
+ haLaunchHooks.afterPublish()
+ }
+ return c.env, c.layer, nil
}
// haPublisherNow is the files publisher a launch of rt publishes through:
@@ -117,16 +206,15 @@ func (b *ExecBackend) haManifestFound(ctx context.Context, rt registry.Route) (b
}
// 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
- }
+// launch: nil once env, the bytes the launch captured, has the SHA-256 of
+// 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: an env file
+// that changed after the capture is committed as other bytes, and fails
+// the launch. Every error fails the launch. The caller has classified rt
+// HA (launchEnvLayer).
+func (b *ExecBackend) haSecretsReady(ctx context.Context, rt registry.Route, env []byte) error {
f := b.haPublisherNow(rt.Host)
own := false
if f == nil {
@@ -139,7 +227,7 @@ func (b *ExecBackend) haSecretsReady(ctx context.Context, rt registry.Route) err
}
f, own = b.newHostFiles(rt, pub), true
}
- ok, err := f.envAcknowledged()
+ ok, err := f.envAcknowledged(env)
if err != nil {
return err
}
@@ -147,7 +235,7 @@ func (b *ExecBackend) haSecretsReady(ctx context.Context, rt registry.Route) err
if err := f.PublishPlatformNow(ctx); err != nil {
return fmt.Errorf("publish the host's secrets: %w", err)
}
- if ok, err = f.envAcknowledged(); err != nil {
+ if ok, err = f.envAcknowledged(env); err != nil {
return err
}
if !ok {
@@ -162,18 +250,9 @@ func (b *ExecBackend) haSecretsReady(ctx context.Context, rt registry.Route) err
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)
- }
+// envAcknowledged reports whether env, the bytes a launch captured, are
+// the env item of the manifest f last committed. It reads no file.
+func (f *hostFiles) envAcknowledged(env []byte) (bool, error) {
base := f.pub.Baseline()
if !base.Found {
return false, nil
diff --git a/internal/activator/hasecrets_test.go b/internal/activator/hasecrets_test.go
index 11b409bf0..07fde366e 100644
--- a/internal/activator/hasecrets_test.go
+++ b/internal/activator/hasecrets_test.go
@@ -417,3 +417,70 @@ func TestHAFlatLaunchNotMintedBesideAManifest(t *testing.T) {
t.Fatalf("seed: %v; token minted: %v", err, envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN"))
}
}
+
+// setLaunchHook installs one of haLaunchHooks for the test.
+func setLaunchHook(t *testing.T, hook *func(), f func()) {
+ t.Helper()
+ *hook = f
+ t.Cleanup(func() { *hook = nil })
+}
+
+// launchEnvForTest is launchForTest returning the env the launch would
+// hand the app.
+func (b *ExecBackend) launchEnvForTest(rt registry.Route) (map[string]string, error) {
+ _, ctl, logs, env, _, err := b.prepareKeyedAt(rt, instancectl.RoleRun, rt.Socket, 0, nil)
+ if ctl != nil {
+ ctl.Close()
+ }
+ if logs != nil {
+ logs.Close()
+ }
+ return env, err
+}
+
+// F2 (spec §7.3): the env holds both secrets when the launch decides, and
+// is replaced by one without the token before the token's producer runs.
+// A manifest exists, so the producer mints nothing.
+func TestHATokenNotMintedAfterAReplacementPastTheGate(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)
+ setLaunchHook(t, &haLaunchHooks.afterGate, func() { writeEnv(t, b, rt, InstanceKeyVar+"=k1\n") })
+ err := b.launchForTest(rt)
+ if !errors.Is(err, ErrInstanceKeyDeferred) || envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN") {
+ t.Fatalf("launch: %v; token minted beside the manifest: %v", err, envFileHas(t, b, rt, "CARLOS_ADMIN_TOKEN"))
+ }
+}
+
+// F2: the same for the instance key's producer.
+func TestHAKeyNotMintedAfterAReplacementPastTheGate(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)
+ setLaunchHook(t, &haLaunchHooks.afterGate, func() { writeEnv(t, b, rt, "CARLOS_ADMIN_TOKEN=t1\n") })
+ err := b.launchForTest(rt)
+ if !errors.Is(err, ErrInstanceKeyDeferred) || envFileHas(t, b, rt, InstanceKeyVar) {
+ t.Fatalf("launch: %v; key minted beside the manifest: %v", err, envFileHas(t, b, rt, InstanceKeyVar))
+ }
+}
+
+// F2: the env is replaced after its publish was acknowledged. The launch
+// is handed the acknowledged bytes, never the replacement.
+func TestHALaunchEnvIsTheAcknowledgedOne(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)
+ setLaunchHook(t, &haLaunchHooks.afterPublish, func() {
+ writeEnv(t, b, rt, "CARLOS_ADMIN_TOKEN=t2\n"+InstanceKeyVar+"=k2\n")
+ })
+ got, err := b.launchEnvForTest(rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got["CARLOS_ADMIN_TOKEN"] != "t1" || got[InstanceKeyVar] != "k1" {
+ t.Fatalf("the launch was handed %q / %q, not the acknowledged t1 / k1", got["CARLOS_ADMIN_TOKEN"], got[InstanceKeyVar])
+ }
+}
diff --git a/internal/activator/instancekey.go b/internal/activator/instancekey.go
index 9dd17dd1b..75ada0606 100644
--- a/internal/activator/instancekey.go
+++ b/internal/activator/instancekey.go
@@ -226,14 +226,14 @@ func (b *ExecBackend) configuredKeyFor(rt registry.Route) configuredKeyReader {
// reader, so nothing is asked before the mint. Tests use it; every launch
// path goes through ensureInstanceKeyFor, which asks the bucket first.
func ensureInstanceKeyNoConfig(path string) (InstanceKeyOutcome, error) {
- return ensureInstanceKey(context.Background(), filepath.Dir(path), filepath.Base(path), false, true, nil)
+ return ensureInstanceKey(context.Background(), filepath.Dir(path), filepath.Base(path), false, true, nil, nil)
}
// ensureInstanceKeyBeneathNoConfig is ensureInstanceKeyNoConfig for a
// nested row's own env file, read and written through instancefs because
// the directory is tenant-writable (isolated-exec design §3.2).
func ensureInstanceKeyBeneathNoConfig(dir, name string) (InstanceKeyOutcome, error) {
- return ensureInstanceKey(context.Background(), dir, name, true, true, nil)
+ return ensureInstanceKey(context.Background(), dir, name, true, true, nil, nil)
}
// ensureInstanceKeyFor is the launch paths' ensure for rt: none for a
@@ -264,11 +264,9 @@ 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
- }
+ // An HA host's key is minted only before its manifest exists
+ // (haMintGuard, inside ensureInstanceKeyAt); the agent's backfill
+ // skips HA hosts before this.
return b.ensureInstanceKeyAt(ctx, rt, b.pathsFor(rt), false, "backfilled")
}
@@ -276,7 +274,8 @@ func (b *ExecBackend) BackfillInstanceKey(ctx context.Context, rt registry.Route
// never minted; a fenced or conflicting row is refused on p, the paths the
// mint would use, with verb naming which caller refused ("not minted",
// "not backfilled"); every other row is ensureInstanceKey on p's layout,
-// with the bucket reader for rt.
+// with the bucket reader for rt and, for an HA host, its mint decision
+// (haMintGuard).
func (b *ExecBackend) ensureInstanceKeyAt(ctx context.Context, rt registry.Route, p instancePaths, create bool, verb string) (InstanceKeyOutcome, error) {
if rt.Replica {
return InstanceKeyReplica, nil
@@ -285,7 +284,11 @@ func (b *ExecBackend) ensureInstanceKeyAt(ctx context.Context, rt registry.Route
case LayoutFenced, LayoutConflict:
return InstanceKeyFailed, fmt.Errorf("not %s: %s", verb, p.reason)
}
- return ensureInstanceKey(ctx, p.dataDir, rt.Host+".env", p.layout == LayoutNested, create, b.configuredKeyFor(rt))
+ guard, err := b.haMintGuard(ctx, rt)
+ if err != nil {
+ return InstanceKeyFailed, err
+ }
+ return ensureInstanceKey(ctx, p.dataDir, rt.Host+".env", p.layout == LayoutNested, create, b.configuredKeyFor(rt), guard)
}
// openOwnEnv opens an own env file, <host>.env under dir: through
@@ -429,7 +432,11 @@ type bucketVerdict struct {
// without a verdict (the first read saw a key that has since gone) defers
// rather than mint on nothing, and the next attempt asks. Create-only,
// fail-closed and defer-on-unknown hold on every path.
-func ensureInstanceKey(ctx context.Context, dir, name string, beneath, create bool, configured configuredKeyReader) (InstanceKeyOutcome, error) {
+//
+// guard, when not nil, is asked once the locked read finds no key and the
+// bucket allows a mint, before anything is minted (an HA host's
+// haMintGuard): its refusal is returned and nothing is written.
+func ensureInstanceKey(ctx context.Context, dir, name string, beneath, create bool, configured configuredKeyReader, guard mintGuard) (InstanceKeyOutcome, error) {
path := filepath.Join(dir, name)
// Phase one, outside the lock. Nothing delivered here sets a key. The
// configuration may still: a first wake can run before the config
@@ -508,6 +515,14 @@ func ensureInstanceKey(ctx context.Context, dir, name string, beneath, create bo
return InstanceKeyFailed, pre.deferral
}
}
+ // No key on this read, the one the mint decides from: an HA host's
+ // mint decision is asked here, never on an earlier read (final review
+ // F2).
+ if guard != nil {
+ if err := guard(); err != nil {
+ return InstanceKeyFailed, err
+ }
+ }
minted, err := mintInstanceKey()
if err != nil {
return InstanceKeyFailed, fmt.Errorf("mint instance key for %s: %w", path, err)
diff --git a/internal/activator/prepare.go b/internal/activator/prepare.go
index 0ebde4575..4ff929947 100644
--- a/internal/activator/prepare.go
+++ b/internal/activator/prepare.go
@@ -77,29 +77,29 @@ 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).
+ // An HA host's secrets: the mint decision inside both producers,
+ // and the launch's env captured once, published and acknowledged,
+ // and handed to the launch as captured (hasecrets.go). prepareAt
+ // has no ctx of its own: haSecretsBudget bounds the manifest read
+ // and the publish, and configReadTimeout the key's bucket read.
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)
+ if haLaunchHooks.afterGate != nil {
+ haLaunchHooks.afterGate()
}
// 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.
- if err := EnsureAdminTokenBeneath(p.dataDir, rt.Host+".env"); err != nil {
+ if err := b.ensureAdminTokenFor(hctx, rt, p); err != nil {
return p, nil, nil, nil, instancekey.LayerNone, fmt.Errorf("admin token for %s: %w", rt.Host, err)
}
steps.mark(time.Now(), "admin token")
- if _, err := b.ensureInstanceKeyFor(context.Background(), rt, p); err != nil { // prepareAt has no ctx to bound the mint's bucket read; configReadTimeout does
+ if _, err := b.ensureInstanceKeyFor(hctx, rt, p); err != nil {
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)
+ env, keyLayer, err = b.launchEnvLayer(hctx, rt)
if err != nil {
return p, nil, nil, nil, instancekey.LayerNone, err
}