carlos / platform Public

feat: real storage and router readiness for managed boxes

Managed fleets 2b-2 Task 5. The console's storage and router_probe checks
now come from a probe that reaches the exact box. The console signs a
fresh request (32-byte nonce) with the mesh key in a new MAC domain over
channel, timestamp and body, and POSTs it to the hub's
/__carlos/fleet-probe on the reserved tunnel host. The hub verifies it
before any channel lookup (one identical 401 for every bad MAC), sends it
down exactly <fleet>/<label> with transportFor (never fleetChannelFor's
sibling fallback, no retry), bounds the request (1 KiB) and reply (4 KiB),
relays only a strict exact echo and attests the channel it used in
X-Carlos-Probe-Channel.

On a managed box the edge answers /__carlos/managed-probe ahead of demo,
routes and admission, only over its own tunnel with X-Carlos-Managed-Probe.
The agent's prober answers only its own fleet, label and op, one probe at
a time; with storage asked it PUTs, reads back and DELETEs
_carlos/probes/<label>/<nonce> with the delivered credentials (exactly 3
bucket calls) and reports the access key ID and the installed secrets key
fingerprint. Both probe headers are scrubbed from every other request.

router_probe passes only on a 200 attested for the box's own channel with
an exact echo; storage passes only on top of that, with ok, a key ID in
managed_fleet_delivered_keys and the registered fleet fingerprint. A
heartbeat, which any sibling can write, never passes either (C4).

Census: managedProber.challenge (nonrecord) and the serveDemoTraffic
re-pin in the 2b-2 record-write layer; root-read claims in
task-5-claims.tsv for the joint proposal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 908524bff2f7e28b79f265842b98ace3e248e09b parent 7eda50c
13 files changed, +2,343 −1
  • internal/console/managedprobe.go +160 −0
  • internal/console/managedprobe_test.go +421 −0
  • internal/edge/demo_traffic.go +1 −1
  • internal/edge/edge.go +22 −0
  • internal/edge/fleetprobe.go +251 −0
  • internal/edge/fleetprobe_test.go +546 −0
  • internal/host/agent.go +4 −0
  • internal/host/managedprobe.go +183 −0
  • internal/host/managedprobe_test.go +378 −0
  • internal/managedboot/probe.go +216 −0
  • internal/managedboot/probe_test.go +139 −0
  • internal/provision/managed_fleets_2b2_census_test.go +16 −0
  • internal/tunnelclient/tunnelclient.go +6 −0
diff --git a/internal/console/managedprobe.go b/internal/console/managedprobe.go
new file mode 100644
index 000000000..51c1dc37e
--- /dev/null
+++ b/internal/console/managedprobe.go
@@ -0,0 +1,160 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "slices"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/managedboot"
+)
+
+// The storage and router_probe readiness checks of a managed box (managed
+// fleets 2b-2 Task 5), bridged into managedExtraChecks.
+//
+// One probe per call: the console signs a fresh request with the mesh key
+// (the edge's signing rule over its mirrored keys) and POSTs it to the fleet
+// hub's probe door, which sends it down the box's own channel and nowhere
+// else (internal/edge's fleetprobe.go). router_probe passes only on a 200
+// whose X-Carlos-Probe-Channel names that exact channel and whose reply
+// echoes the request's fleet, label, op and nonce. The heartbeat never
+// passes either check (ledger ruling C4): every box of a fleet can write
+// every other box's status object, but none can answer on another box's
+// channel. storage passes only on such a reply, when the box proved its
+// bucket with an access key the console delivered to this fleet, and has
+// installed the fleet's registered secrets key.
+//
+// The probe costs the hub one request and the box three fleet-bucket
+// requests. The worker reaches it at most once a minute per enrolled box
+// (the LastHeartbeatAt attempt budget) and never for a ready or failed box;
+// Checks itself refuses any box that is not enrolled or publishing. Every
+// failure to learn anything is a pending check with no error, so 2a's
+// "pending unless pass" applies.
+
+// managedProbeTimeout bounds one probe, hub and box included.
+const managedProbeTimeout = 10 * time.Second
+
+// COPY: readiness reasons await controller copy review.
+const (
+ managedProbeRouterWaiting = "waiting for the box to answer a probe through its own tunnel" // COPY
+ managedProbeStorageWaiting = "waiting for the box to answer a storage probe" // COPY
+ managedProbeStorageFailed = "the box could not write, read back and delete a test object in the fleet bucket (%s)" // COPY
+ managedProbeKeyNotDelivered = "the box is using an access key that was not delivered to this fleet" // COPY
+ managedProbeKeyUnconfirmed = "waiting to confirm the box's access key" // COPY
+ managedProbeNoSecretsKey = "waiting for the box to install the fleet's secrets key" // COPY
+ managedProbeNoFleetKey = "waiting for the fleet's secrets key to be registered" // COPY
+ managedProbeWrongSecretsKey = "the box's secrets key is not the fleet's registered key" // COPY
+)
+
+type managedProbeChecks struct {
+ s *Server
+ url string
+ client *http.Client
+}
+
+// newManagedProbeChecks is the bridge for s, probing through the hub at
+// s.cfg.TunnelHost. It follows no redirect.
+func newManagedProbeChecks(s *Server) *managedProbeChecks {
+ return &managedProbeChecks{
+ s: s,
+ url: "https://" + s.cfg.TunnelHost + edge.FleetProbePath,
+ client: &http.Client{
+ Timeout: managedProbeTimeout,
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ },
+ }
+}
+
+// Checks implements managedExtraChecks.
+func (p *managedProbeChecks) Checks(ctx context.Context, b managedBox) (storage, router managedCheck, err error) {
+ storage = managedCheck{State: "pending", Reason: managedProbeStorageWaiting}
+ router = managedCheck{State: "pending", Reason: managedProbeRouterWaiting}
+ if p.s.cfg.HostClaim || (b.State != "enrolled" && b.State != "publishing") {
+ return storage, router, nil
+ }
+ reply, ok := p.probe(ctx, b)
+ if !ok {
+ return storage, router, nil
+ }
+ router = managedCheck{State: "pass"}
+ return p.storage(ctx, b, reply), router, nil
+}
+
+// probe sends one signed request and returns the reply only when the hub
+// attests b's own channel and the reply echoes the request exactly.
+func (p *managedProbeChecks) probe(ctx context.Context, b managedBox) (managedboot.ProbeReply, bool) {
+ current, next := p.s.edgeProofKeys(ctx)
+ nonce, err := managedboot.NewProbeNonce()
+ if err != nil {
+ return managedboot.ProbeReply{}, false
+ }
+ req := managedboot.ProbeRequest{Fleet: b.Fleet, Label: b.Label, Op: b.OpID, Nonce: nonce, Storage: true}
+ body, err := managedboot.EncodeProbeRequest(req)
+ if err != nil {
+ return managedboot.ProbeReply{}, false
+ }
+ channel := req.Channel()
+ auth := edge.SignFleetProbe(current, next, channel, body, time.Now())
+ if auth == "" {
+ return managedboot.ProbeReply{}, false
+ }
+ ctx, cancel := context.WithTimeout(ctx, managedProbeTimeout)
+ defer cancel()
+ hr, err := http.NewRequestWithContext(ctx, http.MethodPost, p.url, bytes.NewReader(body))
+ if err != nil {
+ return managedboot.ProbeReply{}, false
+ }
+ hr.Header.Set("Content-Type", "application/json")
+ hr.Header.Set(edge.FleetProbeAuthHeader, auth)
+ resp, err := p.client.Do(hr)
+ if err != nil {
+ return managedboot.ProbeReply{}, false
+ }
+ defer resp.Body.Close()
+ attested := resp.Header.Values(edge.FleetProbeChannelHeader)
+ if resp.StatusCode != http.StatusOK || len(attested) != 1 || attested[0] != channel {
+ return managedboot.ProbeReply{}, false
+ }
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, managedboot.MaxProbeReply+1))
+ if err != nil || len(raw) > managedboot.MaxProbeReply {
+ return managedboot.ProbeReply{}, false
+ }
+ reply, err := managedboot.ParseProbeReply(raw)
+ if err != nil || !reply.Echoes(req) {
+ return managedboot.ProbeReply{}, false
+ }
+ return reply, true
+}
+
+// storage judges an authentic reply's storage half.
+func (p *managedProbeChecks) storage(ctx context.Context, b managedBox, reply managedboot.ProbeReply) managedCheck {
+ if !reply.Storage.OK {
+ return managedCheck{State: "fail", Reason: fmt.Sprintf(managedProbeStorageFailed, reply.Storage.Code)}
+ }
+ delivered, err := p.s.store.managedDeliveredKeys(ctx, b.Fleet, b.Account)
+ if err != nil {
+ return managedCheck{State: "pending", Reason: managedProbeKeyUnconfirmed}
+ }
+ if !slices.Contains(delivered, reply.Storage.KeyID) {
+ return managedCheck{State: "fail", Reason: managedProbeKeyNotDelivered}
+ }
+ if reply.SecretsKeyFP == "" {
+ return managedCheck{State: "pending", Reason: managedProbeNoSecretsKey}
+ }
+ reg := p.s.store.managedRegistry
+ if reg == nil {
+ return managedCheck{State: "pending", Reason: managedProbeNoFleetKey}
+ }
+ fleet, err := reg.GetFleetContext(ctx, b.Fleet)
+ if err != nil || fleet == nil || !fleet.Managed || fleet.Account != b.Account || fleet.SecretsKeyFP == "" {
+ return managedCheck{State: "pending", Reason: managedProbeNoFleetKey}
+ }
+ if fleet.SecretsKeyFP != reply.SecretsKeyFP {
+ return managedCheck{State: "fail", Reason: managedProbeWrongSecretsKey}
+ }
+ return managedCheck{State: "pass"}
+}
diff --git a/internal/console/managedprobe_test.go b/internal/console/managedprobe_test.go
new file mode 100644
index 000000000..bbe1d7ed7
--- /dev/null
+++ b/internal/console/managedprobe_test.go
@@ -0,0 +1,421 @@
+package console
+
+import (
+ "context"
+ "crypto/ecdh"
+ "crypto/rand"
+ "encoding/base64"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/edgeproof"
+ "github.com/carlosframework/platform/internal/managedboot"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+const probeKeyID = "AKIAEXAMPLEEXAMPLE01"
+
+// fakeProbeHub is the fleet hub's probe door as the console meets it: it
+// checks the console's signature exactly as the hub does (the request's own
+// channel, either mirrored key, ±30 s) and answers with what answer says.
+type fakeProbeHub struct {
+ t *testing.T
+ srv *httptest.Server
+ key []byte
+ calls atomic.Int32
+ badAuth atomic.Int32
+ mu sync.Mutex
+ answer func(req managedboot.ProbeRequest, w http.ResponseWriter)
+ last managedboot.ProbeRequest
+}
+
+// echo is a box's honest reply to req, edited.
+func probeEcho(req managedboot.ProbeRequest, fp string, edit func(*managedboot.ProbeReply)) []byte {
+ r := managedboot.ProbeReply{Fleet: req.Fleet, Label: req.Label, Op: req.Op, Nonce: req.Nonce,
+ Storage: managedboot.ProbeStorage{OK: true, KeyID: probeKeyID}, SecretsKeyFP: fp}
+ if edit != nil {
+ edit(&r)
+ }
+ b, _ := managedboot.EncodeProbeReply(r)
+ return b
+}
+
+func (h *fakeProbeHub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ h.calls.Add(1)
+ body, _ := io.ReadAll(io.LimitReader(r.Body, managedboot.MaxProbeRequest+1))
+ req, err := managedboot.ParseProbeRequest(body)
+ auth := r.Header.Get(edge.FleetProbeAuthHeader)
+ ts, _, _ := strings.Cut(auth, ":")
+ sec, _ := strconv.ParseInt(ts, 10, 64)
+ if r.Method != http.MethodPost || r.URL.Path != edge.FleetProbePath || err != nil || !req.Storage ||
+ auth != edge.SignFleetProbe(h.key, nil, req.Channel(), body, time.Unix(sec, 0)) || time.Since(time.Unix(sec, 0)) > 30*time.Second {
+ h.badAuth.Add(1)
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ h.mu.Lock()
+ h.last = req
+ answer := h.answer
+ h.mu.Unlock()
+ answer(req, w)
+}
+
+func (h *fakeProbeHub) set(answer func(req managedboot.ProbeRequest, w http.ResponseWriter)) {
+ h.mu.Lock()
+ h.answer = answer
+ h.mu.Unlock()
+}
+
+// attest answers as the real hub does for a reply from req's own channel.
+func attest(w http.ResponseWriter, channel string, body []byte) {
+ w.Header().Set(edge.FleetProbeChannelHeader, channel)
+ w.Write(body)
+}
+
+// probeRig is readyFixture with the real probe bridge pointed at a fake
+// hub, a mesh key in the deployment bucket, the box's delivered key on
+// record and the fleet's secrets key registered.
+type probeRig struct {
+ s *Server
+ b managedBox
+ now time.Time
+ hub *fakeProbeHub
+ p *managedProbeChecks
+ fp string
+ pub string
+ check func() (managedCheck, managedCheck)
+}
+
+func newProbeRig(t *testing.T) *probeRig {
+ t.Helper()
+ s, b, now := readyFixture(t)
+ ctx := context.Background()
+ if err := edge.MintMeshKey(ctx, s.cfg.Releases); err != nil {
+ t.Fatal(err)
+ }
+ cur, _, err := edgeproof.LoadKeys(ctx, s.cfg.Releases)
+ if err != nil || len(cur) == 0 {
+ t.Fatal("mesh key", err)
+ }
+ if _, err := s.store.db.Exec(`INSERT INTO managed_fleet_delivered_keys(fleet,account,key_id) VALUES(?,?,?)`, b.Fleet, b.Account, probeKeyID); err != nil {
+ t.Fatal(err)
+ }
+ k, err := ecdh.P256().GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub := base64.StdEncoding.EncodeToString(k.PublicKey().Bytes())
+ fp := appconfig.KeyFingerprint(k.PublicKey())
+ reg, _ := openRegistry(s.cfg.Registry)
+ if err := reg.SetFleetSecretsKey(b.Fleet, pub, fp, "managed-box", now.Unix()); err != nil {
+ t.Fatal(err)
+ }
+ h := &fakeProbeHub{t: t, key: cur}
+ h.answer = func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Channel(), probeEcho(req, fp, nil))
+ }
+ h.srv = httptest.NewServer(h)
+ t.Cleanup(h.srv.Close)
+ p := newManagedProbeChecks(s)
+ p.url = h.srv.URL + edge.FleetProbePath
+ s.managedExtra = p
+ g := &probeRig{s: s, b: b, now: now, hub: h, p: p, fp: fp, pub: pub}
+ g.check = func() (managedCheck, managedCheck) {
+ t.Helper()
+ storage, router, err := p.Checks(ctx, g.b)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return storage, router
+ }
+ return g
+}
+
+// TestManagedProbeChecks pins the bridge's mapping: router passes only on
+// a 200 attested for the box's own channel with an exact echo; storage
+// passes only on top of that, with ok, a delivered key ID and the fleet's
+// registered secrets key; transport trouble is pending with no error.
+func TestManagedProbeChecks(t *testing.T) {
+ g := newProbeRig(t)
+ pass := managedCheck{State: "pass"}
+ storage, router := g.check()
+ if storage != pass || router != pass || g.hub.calls.Load() != 1 || g.hub.badAuth.Load() != 0 {
+ t.Fatalf("honest box: %+v %+v calls %d bad %d", storage, router, g.hub.calls.Load(), g.hub.badAuth.Load())
+ }
+ if g.hub.last.Fleet != g.b.Fleet || g.hub.last.Label != g.b.Label || g.hub.last.Op != g.b.OpID || len(g.hub.last.Nonce) != 64 {
+ t.Fatalf("request %+v", g.hub.last)
+ }
+ first := g.hub.last.Nonce
+ g.check()
+ if g.hub.last.Nonce == first {
+ t.Fatal("a nonce was reused")
+ }
+
+ pending := func(name string, storage, router managedCheck) {
+ t.Helper()
+ if router.State != "pending" || router.Reason == "" || storage.State != "pending" || storage.Reason == "" {
+ t.Errorf("%s: storage %+v router %+v, want both pending with reasons", name, storage, router)
+ }
+ }
+ pendingNow := func(name string, check func() (managedCheck, managedCheck)) {
+ t.Helper()
+ storage, router := check()
+ pending(name, storage, router)
+ }
+ var replayed []byte
+ for name, answer := range map[string]func(managedboot.ProbeRequest, http.ResponseWriter){
+ "no attestation": func(req managedboot.ProbeRequest, w http.ResponseWriter) { w.Write(probeEcho(req, g.fp, nil)) },
+ "a sibling's channel": func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Fleet+"/other-box", probeEcho(req, g.fp, nil))
+ },
+ "two attestations": func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ w.Header().Add(edge.FleetProbeChannelHeader, req.Channel())
+ w.Header().Add(edge.FleetProbeChannelHeader, req.Channel())
+ w.Write(probeEcho(req, g.fp, nil))
+ },
+ "another label echoed": func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Channel(), probeEcho(req, g.fp, func(r *managedboot.ProbeReply) { r.Label = "other-box" }))
+ },
+ "another op echoed": func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Channel(), probeEcho(req, g.fp, func(r *managedboot.ProbeReply) { r.Op = strings.Repeat("f", 32) }))
+ },
+ "replayed reply (old nonce)": func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ if replayed == nil {
+ old := req
+ old.Nonce = first
+ replayed = probeEcho(old, g.fp, nil)
+ }
+ attest(w, req.Channel(), replayed)
+ },
+ "hub 503": func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ },
+ "hub 502 attested": func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ w.Header().Set(edge.FleetProbeChannelHeader, req.Channel())
+ w.WriteHeader(http.StatusBadGateway)
+ w.Write(probeEcho(req, g.fp, nil))
+ },
+ "redirect": func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ w.Header().Set(edge.FleetProbeChannelHeader, req.Channel())
+ w.Header().Set("Location", g.hub.srv.URL+edge.FleetProbePath)
+ w.WriteHeader(http.StatusTemporaryRedirect)
+ },
+ "oversize reply": func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Channel(), append(probeEcho(req, g.fp, nil), make([]byte, managedboot.MaxProbeReply)...))
+ },
+ "not a reply": func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Channel(), []byte(`{"fleet":"`+req.Fleet+`"}`))
+ },
+ } {
+ g.hub.set(answer)
+ before := g.hub.calls.Load()
+ storage, router := g.check()
+ pending(name, storage, router)
+ if g.hub.calls.Load() != before+1 {
+ t.Errorf("%s: %d hub calls, want 1 (no redirect followed, no retry)", name, g.hub.calls.Load()-before)
+ }
+ }
+
+ // Storage is judged on an authentic reply, independently of router.
+ for _, c := range []struct {
+ name string
+ edit func(*managedboot.ProbeReply)
+ state string
+ reason string
+ }{
+ {"challenge failed", func(r *managedboot.ProbeReply) {
+ r.Storage = managedboot.ProbeStorage{KeyID: probeKeyID, Code: managedboot.ProbePutFailed}
+ }, "fail", "the box could not write, read back and delete a test object in the fleet bucket (put_failed)"},
+ {"no credentials", func(r *managedboot.ProbeReply) {
+ r.Storage = managedboot.ProbeStorage{Code: managedboot.ProbeNoCredentials}
+ }, "fail", "the box could not write, read back and delete a test object in the fleet bucket (no_credentials)"},
+ {"undelivered key", func(r *managedboot.ProbeReply) { r.Storage.KeyID = "AKIAOTHEROTHEROTHER1" }, "fail", managedProbeKeyNotDelivered},
+ {"no secrets key yet", func(r *managedboot.ProbeReply) { r.SecretsKeyFP = "" }, "pending", managedProbeNoSecretsKey},
+ {"another secrets key", func(r *managedboot.ProbeReply) { r.SecretsKeyFP = "sha256:" + strings.Repeat("ab", 32) }, "fail", managedProbeWrongSecretsKey},
+ } {
+ g.hub.set(func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Channel(), probeEcho(req, g.fp, c.edit))
+ })
+ storage, router := g.check()
+ if router != pass || storage.State != c.state || storage.Reason != c.reason {
+ t.Errorf("%s: storage %+v router %+v", c.name, storage, router)
+ }
+ }
+ g.hub.set(func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Channel(), probeEcho(req, g.fp, nil))
+ })
+
+ // A key delivered to another fleet or account does not count.
+ if _, err := g.s.store.db.Exec(`UPDATE managed_fleet_delivered_keys SET account='zz99' WHERE key_id=?`, probeKeyID); err != nil {
+ t.Fatal(err)
+ }
+ if storage, router := g.check(); storage.State != "fail" || router != pass {
+ t.Errorf("another account's key: %+v %+v", storage, router)
+ }
+ if _, err := g.s.store.db.Exec(`UPDATE managed_fleet_delivered_keys SET account=? WHERE key_id=?`, g.b.Account, probeKeyID); err != nil {
+ t.Fatal(err)
+ }
+ // No registered fleet key yet: storage waits.
+ reg, _ := openRegistry(g.s.cfg.Registry)
+ if err := reg.SetFleetSecretsKey(g.b.Fleet, "", "", "test", g.now.Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if storage, router := g.check(); storage.State != "pending" || storage.Reason != managedProbeNoFleetKey || router != pass {
+ t.Errorf("no registered key: %+v %+v", storage, router)
+ }
+ if err := reg.SetFleetSecretsKey(g.b.Fleet, g.pub, g.fp, "test", g.now.Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if storage, _ := g.check(); storage != pass {
+ t.Fatalf("restored: %+v", storage)
+ }
+
+ // The Task 4 key status fails storage whatever the probe says.
+ readyBeat(t, g.s, g.b, status.Box{Label: g.b.Label, GeneratedAt: g.now, ManagedKey: managedboot.KeyStatusObjectInvalid, Metrics: &status.BoxMetrics{Release: "v0.34.0", RootfsReady: true, Tunnel: "connected"}})
+ checks, err := g.s.managedReadiness(context.Background(), g.b, g.now)
+ if err != nil || checks["storage"].State != "fail" || checks["router_probe"] != pass {
+ t.Fatalf("key status with a passing probe: %+v %v", checks, err)
+ }
+
+ // The hub unreachable: pending, no error.
+ g.hub.srv.Close()
+ pendingNow("hub unreachable", g.check)
+
+ // No probe on a host-claim console, for a box not enrolled or
+ // publishing, or with no mesh key to sign with.
+ g2 := newProbeRig(t)
+ g2.s.cfg.HostClaim = true
+ pendingNow("host claim", g2.check)
+ g2.s.cfg.HostClaim = false
+ for _, state := range []string{"ready", "failed", "launching", "terminated"} {
+ g2.b.State = state
+ pendingNow(state, g2.check)
+ }
+ g2.b.State = "publishing"
+ if storage, router := g2.check(); storage != pass || router != pass {
+ t.Fatalf("publishing: %+v %+v", storage, router)
+ }
+ if g2.hub.calls.Load() != 1 {
+ t.Fatalf("%d probes, want only the publishing box's", g2.hub.calls.Load())
+ }
+ g3 := newProbeRig(t)
+ if err := g3.s.cfg.Releases.Delete(context.Background(), edgeproof.MeshKeyObject); err != nil {
+ t.Fatal(err)
+ }
+ g3.s.edgeProof = edgeProofState{}
+ pendingNow("no mesh key", g3.check)
+ if g3.hub.calls.Load() != 0 {
+ t.Fatal("probed with no mesh key")
+ }
+}
+
+// TestManagedProbeSiblingHeartbeat (ledger ruling C4): a fresh heartbeat in
+// the box's status object, as any box of the fleet can write it, never
+// makes the box ready without the exact-channel probe: with the target's
+// channel dark, or a reply that came from a sibling, the box stays enrolled
+// and no ready object is written.
+func TestManagedProbeSiblingHeartbeat(t *testing.T) {
+ for name, answer := range map[string]func(*probeRig) func(managedboot.ProbeRequest, http.ResponseWriter){
+ "target dark": func(*probeRig) func(managedboot.ProbeRequest, http.ResponseWriter) {
+ return func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ }
+ },
+ "sibling answers": func(g *probeRig) func(managedboot.ProbeRequest, http.ResponseWriter) {
+ return func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Fleet+"/sibling", probeEcho(req, g.fp, func(r *managedboot.ProbeReply) { r.Label = "sibling" }))
+ }
+ },
+ "sibling echoes the target": func(g *probeRig) func(managedboot.ProbeRequest, http.ResponseWriter) {
+ return func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Fleet+"/sibling", probeEcho(req, g.fp, nil))
+ }
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ g := newProbeRig(t)
+ g.hub.set(answer(g))
+ b := g.b
+ for i := 0; i < 6; i++ {
+ at := g.now.Add(time.Duration(i) * time.Minute)
+ readyBeat(t, g.s, b, status.Box{Label: b.Label, GeneratedAt: at, ManagedKey: managedboot.KeyStatusOK, Metrics: &status.BoxMetrics{Release: "v0.34.0", RootfsReady: true, Tunnel: "connected"}})
+ b = workerStep(t, g.s, at)
+ if b.State != "enrolled" || b.Checks["router_probe"].State == "pass" {
+ t.Fatalf("minute %d: %s %+v", i, b.State, b.Checks)
+ }
+ }
+ if _, _, err := g.s.cfg.Releases.Get(context.Background(), managedReadyKey(b)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("ready object written", err)
+ }
+ if g.hub.calls.Load() != 6 {
+ t.Fatalf("%d probes in 6 minutes", g.hub.calls.Load())
+ }
+ })
+ }
+}
+
+// TestManagedProbeBudget: at most one hub probe per enrolled box per 60 s
+// however often the worker passes; none once the box is ready or failed,
+// and none from an idle worker.
+func TestManagedProbeBudget(t *testing.T) {
+ g := newProbeRig(t)
+ g.hub.set(func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Channel(), probeEcho(req, "", nil)) // router passes, storage waits
+ })
+ b := g.b
+ for i := 0; i < 10; i++ {
+ b = workerStep(t, g.s, g.now.Add(time.Duration(i)*5*time.Second))
+ }
+ if n := g.hub.calls.Load(); n != 1 || b.State != "enrolled" {
+ t.Fatalf("10 passes in 50 s: %d probes, state %s", n, b.State)
+ }
+ readyBeat(t, g.s, b, status.Box{Label: b.Label, GeneratedAt: g.now.Add(time.Minute), Metrics: &status.BoxMetrics{Release: "v0.34.0", RootfsReady: true, Tunnel: "connected"}})
+ g.hub.set(func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Channel(), probeEcho(req, g.fp, nil))
+ })
+ b = workerStep(t, g.s, g.now.Add(time.Minute))
+ if n := g.hub.calls.Load(); n != 2 || b.State != "ready" {
+ t.Fatalf("after a minute: %d probes, state %s %+v", n, b.State, b.Checks)
+ }
+ for i := 1; i <= 30; i++ {
+ b = workerStep(t, g.s, g.now.Add(time.Minute+time.Duration(i)*time.Minute))
+ }
+ if n := g.hub.calls.Load(); n != 2 || b.State != "ready" {
+ t.Fatalf("ready box: %d probes, state %s", n, b.State)
+ }
+
+ f := newProbeRig(t)
+ workerAdvance(t, f.s, f.b, func(b *managedBox) { b.State = "failed"; b.LastError = "managed_test_failed" })
+ for i := 0; i < 10; i++ {
+ workerStep(t, f.s, f.now.Add(time.Duration(i)*time.Minute))
+ }
+ if st := workerBox(t, f.s).State; f.hub.calls.Load() != 0 || st == "ready" || st == "enrolled" {
+ t.Fatalf("failed box: %d probes, state %s", f.hub.calls.Load(), st)
+ }
+
+ idle := managedAPIFixture(t)
+ h := &fakeProbeHub{t: t}
+ h.srv = httptest.NewServer(h)
+ t.Cleanup(h.srv.Close)
+ p := newManagedProbeChecks(idle)
+ p.url = h.srv.URL + edge.FleetProbePath
+ idle.managedExtra = p
+ now := time.Now()
+ for i := 0; i < 20; i++ {
+ e2ePass(t, idle, now.Add(time.Duration(i)*time.Minute))
+ }
+ if h.calls.Load() != 0 {
+ t.Fatalf("idle worker: %d probes", h.calls.Load())
+ }
+}
diff --git a/internal/edge/demo_traffic.go b/internal/edge/demo_traffic.go
index 78e065246..50a9cff65 100644
--- a/internal/edge/demo_traffic.go
+++ b/internal/edge/demo_traffic.go
@@ -149,7 +149,7 @@ func (e *Edge) serveDemoTraffic(dst http.ResponseWriter, r *http.Request, up ups
geo := geoip.Capture(r.Header)
hopPresent := r.Header.Get(hopHeader) != ""
r, hopped := e.acceptHop(r, host)
- for _, key := range []string{assetAckHeader, assetExpiresHeader, assetFillHeader, tunnelclient.UpgradeHeader, tunnelclient.ReplicaProbeHeader} {
+ for _, key := range []string{assetAckHeader, assetExpiresHeader, assetFillHeader, tunnelclient.UpgradeHeader, tunnelclient.ReplicaProbeHeader, tunnelclient.ManagedProbeHeader, fleetProbeChannelHeader} {
r.Header.Del(key)
}
door, isDoor := doorCallerFrom(r.Context())
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 7ef38b291..fe249b9f3 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -142,6 +142,9 @@ type Edge struct {
// set, unflagged routes are still proxied straight (the flag is per host).
admission HAAdmission
act Activator
+ // managedProbe answers the hub's readiness probe on a managed box
+ // (fleetprobe.go); nil everywhere else.
+ managedProbe ManagedProbeResponder
// held is the edge-held event streams this edge holds (heldstream.go),
// built in New with DefaultHeldConfig; SetHeldConfig replaces it before
// serving.
@@ -1938,6 +1941,13 @@ func firstSegmentClean(p string) string {
}
func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ // A managed box's readiness probe (fleetprobe.go), ahead of demo
+ // handling, route lookup and tenant admission: a joining box with no
+ // routes answers it. Only a box with a responder takes the branch.
+ if e.managedProbe != nil && r.URL.Path == managedProbePath {
+ e.serveManagedProbe(w, r)
+ return
+ }
if e.handleDemoRequest(w, r, true) {
return
}
@@ -2007,6 +2017,12 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
e.serveReplicaConsole(w, r)
return
}
+ // The console's managed box probe (fleetprobe.go): a POST to the
+ // exact path; anything else keeps the hub's 404.
+ if r.Method == http.MethodPost && r.URL.RawPath == "" && r.URL.Path == fleetProbePath {
+ e.serveFleetProbe(w, r)
+ return
+ }
e.tunnels.ServeHTTP(w, r)
return
}
@@ -2054,6 +2070,10 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.Header.Del(tunnelclient.UpgradeHeader)
replicaProbe := replicaProbeAuthenticated(r) && !isDoor && !hopPresent
r.Header.Del(tunnelclient.ReplicaProbeHeader)
+ // The managed probe's marker and the hub's channel attestation are the
+ // hub's to send (fleetprobe.go), never a client's, on any arm.
+ r.Header.Del(tunnelclient.ManagedProbeHeader)
+ r.Header.Del(fleetProbeChannelHeader)
if e.serveDemoAPIAlias(w, r, host, hopped && demoHopWellFormed, demoHopPresent) {
return
}
@@ -3855,6 +3875,8 @@ func scrubTunnelMarkers(pr *httputil.ProxyRequest) {
pr.Out.Header.Del(tunnelclient.UpgradeHeader)
pr.Out.Header.Del(tunnelclient.UpgradedHeader)
pr.Out.Header.Del(tunnelclient.ReplicaProbeHeader)
+ pr.Out.Header.Del(tunnelclient.ManagedProbeHeader)
+ pr.Out.Header.Del(fleetProbeChannelHeader)
}
// errFleetDark is the sentinel fleetProxy's Transport returns when fleet has
diff --git a/internal/edge/fleetprobe.go b/internal/edge/fleetprobe.go
new file mode 100644
index 000000000..a10b2e5c0
--- /dev/null
+++ b/internal/edge/fleetprobe.go
@@ -0,0 +1,251 @@
+package edge
+
+import (
+ "bytes"
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/managedboot"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+// The managed box readiness probe (managed fleets 2b-2 Task 5).
+//
+// The console asks the fleet hub, on the reserved tunnel host, to probe one
+// managed box. The request is signed with the deployment's mesh key, which
+// only platform boxes hold, in its own MAC domain over the channel it names,
+// a timestamp and the body. The hub verifies it before it looks at any
+// channel, then sends the body down exactly that box's channel,
+// "<fleet>/<label>", with transportFor: never fleetChannelFor, whose
+// any-box-of-the-fleet fallback is the sibling hazard this probe exists to
+// rule out. Nothing is retried, on that channel or another. A 200 from the
+// hub carries the box's reply, checked to echo the request exactly, and
+// X-Carlos-Probe-Channel naming the channel the hub used: the hub's
+// attestation, which no box can set.
+//
+// On the box, the request arrives over its own tunnel (FromTunnel) with
+// ManagedProbeHeader set: a marker the hub sends only here and scrubs from
+// every other request. The box's responder answers only a request naming
+// its own fleet, label and op. The branch runs before demo handling, route
+// lookup and tenant admission, so a joining box with no routes answers.
+const (
+ fleetProbePath = "/__carlos/fleet-probe"
+ managedProbePath = "/__carlos/managed-probe"
+ fleetProbeDomain = "carlos-fleet-probe\x00"
+ fleetProbeAuthHeader = "X-Carlos-Fleet-Probe-Auth"
+ fleetProbeChannelHeader = "X-Carlos-Probe-Channel"
+ // fleetProbeReadTimeout bounds reading a probe request's body.
+ fleetProbeReadTimeout = 2 * time.Second
+)
+
+// The console's names for the hub door: it builds and signs the request
+// and reads the attestation, and must agree with the hub byte for byte.
+const (
+ FleetProbePath = fleetProbePath
+ FleetProbeAuthHeader = fleetProbeAuthHeader
+ FleetProbeChannelHeader = fleetProbeChannelHeader
+)
+
+// fleetProbeTimeout bounds the hub's whole exchange with the box; a
+// variable so witnesses run without real waits.
+var fleetProbeTimeout = 10 * time.Second
+
+// ManagedProbeResponder answers a probe on a managed box (internal/host's
+// managedProber). ErrManagedProbeNotMine refuses a request naming another
+// box; ErrManagedProbeBusy says a probe is already running.
+type ManagedProbeResponder interface {
+ Respond(ctx context.Context, req managedboot.ProbeRequest) (managedboot.ProbeReply, error)
+}
+
+var (
+ ErrManagedProbeNotMine = errors.New("managed probe: not for this box")
+ ErrManagedProbeBusy = errors.New("managed probe: a probe is already running")
+)
+
+// WithManagedProbe hands a managed box's responder to its edge. BYO boxes
+// get none and answer the probe path as any other unknown path.
+func WithManagedProbe(r ManagedProbeResponder) RunOption {
+ return func(e *Edge) { e.managedProbe = r }
+}
+
+// signFleetProbe is the X-Carlos-Fleet-Probe-Auth value: the timestamp, then
+// the hex HMAC over the domain, the channel, the timestamp and the body.
+func signFleetProbe(key []byte, channel string, body []byte, now time.Time) string {
+ ts := strconv.FormatInt(now.Unix(), 10)
+ return ts + ":" + hex.EncodeToString(fleetProbeMAC(key, channel, ts, body))
+}
+
+// SignFleetProbe is the console's signer: signingKey's choice of the two
+// mirrored keys (the successor the moment it exists), or "" with no key.
+func SignFleetProbe(current, next []byte, channel string, body []byte, now time.Time) string {
+ key := signingKey(current, next)
+ if len(key) == 0 {
+ return ""
+ }
+ return signFleetProbe(key, channel, body, now)
+}
+
+// verifyFleetProbeEitherKey checks header for channel and body under either
+// mirrored key: the timestamp within ±hopSkew of now, the MAC compared in
+// constant time.
+func verifyFleetProbeEitherKey(current, next []byte, channel, header string, body []byte, now time.Time) bool {
+ ts, sig, ok := strings.Cut(header, ":")
+ if !ok || ts == "" || sig == "" {
+ return false
+ }
+ sec, err := strconv.ParseInt(ts, 10, 64)
+ if err != nil {
+ return false
+ }
+ skew := now.Sub(time.Unix(sec, 0))
+ if skew < 0 {
+ skew = -skew
+ }
+ if skew > hopSkew {
+ return false
+ }
+ got, err := hex.DecodeString(sig)
+ if err != nil {
+ return false
+ }
+ if len(next) > 0 && hmac.Equal(got, fleetProbeMAC(next, channel, ts, body)) {
+ return true
+ }
+ return len(current) > 0 && hmac.Equal(got, fleetProbeMAC(current, channel, ts, body))
+}
+
+func fleetProbeMAC(key []byte, channel, ts string, body []byte) []byte {
+ mac := hmac.New(sha256.New, key)
+ mac.Write([]byte(fleetProbeDomain))
+ mac.Write([]byte(channel))
+ mac.Write([]byte("\n"))
+ mac.Write([]byte(ts))
+ mac.Write([]byte("\n"))
+ mac.Write(body)
+ return mac.Sum(nil)
+}
+
+// readProbeBody reads at most limit bytes of r's body within
+// fleetProbeReadTimeout. ok is false for a larger body or a failed read,
+// after which the connection is closed.
+func readProbeBody(w http.ResponseWriter, r *http.Request, limit int64) ([]byte, bool) {
+ rc := http.NewResponseController(w)
+ bounded := rc.SetReadDeadline(time.Now().Add(fleetProbeReadTimeout)) == nil
+ body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, limit))
+ if err != nil {
+ w.Header().Set("Connection", "close")
+ return nil, false
+ }
+ if bounded {
+ rc.SetReadDeadline(time.Time{})
+ }
+ return body, true
+}
+
+// serveFleetProbe is the hub's door: a POST to fleetProbePath on the
+// reserved tunnel host. Every authentication failure is the same bare 401,
+// answered before any channel is looked up.
+func (e *Edge) serveFleetProbe(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ body, ok := readProbeBody(w, r, managedboot.MaxProbeRequest)
+ if !ok {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ auth := r.Header.Values(fleetProbeAuthHeader)
+ req, err := managedboot.ParseProbeRequest(body)
+ current, next := e.homes.Load().meshKeys()
+ if err != nil || len(auth) != 1 || !verifyFleetProbeEitherKey(current, next, req.Channel(), auth[0], body, time.Now()) {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ channel := req.Channel()
+ hub := e.tunnels
+ if hub == nil || hub.channel(channel) == nil {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), fleetProbeTimeout)
+ defer cancel()
+ out, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://"+hub.Host()+managedProbePath, bytes.NewReader(body))
+ if err != nil {
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ }
+ out.Header.Set("Content-Type", "application/json")
+ out.Header.Set(tunnelclient.ManagedProbeHeader, "1")
+ // The exact channel, one attempt: transportFor never falls back to
+ // another channel, and the tunnel's client connection never retries.
+ resp, err := hub.transportFor(channel).RoundTrip(out)
+ if err != nil {
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ io.Copy(io.Discard, io.LimitReader(resp.Body, managedboot.MaxProbeReply))
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ }
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, managedboot.MaxProbeReply+1))
+ if err != nil || len(raw) > managedboot.MaxProbeReply {
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ }
+ reply, err := managedboot.ParseProbeReply(raw)
+ if err != nil || !reply.Echoes(req) {
+ w.WriteHeader(http.StatusBadGateway)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set(fleetProbeChannelHeader, channel)
+ w.WriteHeader(http.StatusOK)
+ w.Write(raw)
+}
+
+// serveManagedProbe is the box's branch, taken only on a managed box (a
+// responder is set) for managedProbePath. Anything but a tunnelled POST
+// carrying the marker, a well-formed request and the responder's answer
+// is a bare 404; a responder already busy is a 503.
+func (e *Edge) serveManagedProbe(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ if r.Method != http.MethodPost || !tunnelclient.FromTunnel(r.Context()) || r.Header.Get(tunnelclient.ManagedProbeHeader) != "1" {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ body, ok := readProbeBody(w, r, managedboot.MaxProbeRequest)
+ if !ok {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ req, err := managedboot.ParseProbeRequest(body)
+ if err != nil {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ reply, err := e.managedProbe.Respond(r.Context(), req)
+ if errors.Is(err, ErrManagedProbeBusy) {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ if err != nil || !reply.Echoes(req) {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ raw, err := managedboot.EncodeProbeReply(reply)
+ if err != nil {
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ w.Write(raw)
+}
diff --git a/internal/edge/fleetprobe_test.go b/internal/edge/fleetprobe_test.go
new file mode 100644
index 000000000..b4a00f34a
--- /dev/null
+++ b/internal/edge/fleetprobe_test.go
@@ -0,0 +1,546 @@
+package edge
+
+import (
+ "bytes"
+ "context"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/managedboot"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+const probeOp = "0123456789abcdef0123456789abcdef"
+
+// probeBox is a fake box responder: it answers only its own fleet, label
+// and op, the way internal/host's managedProber does, and counts what it
+// was asked. edit, when set, changes its reply (a misbehaving box).
+type probeBox struct {
+ fleet, label string
+ calls atomic.Int32
+ edit func(*managedboot.ProbeReply)
+}
+
+func (p *probeBox) Respond(_ context.Context, req managedboot.ProbeRequest) (managedboot.ProbeReply, error) {
+ p.calls.Add(1)
+ if req.Fleet != p.fleet || req.Label != p.label || req.Op != probeOp {
+ return managedboot.ProbeReply{}, ErrManagedProbeNotMine
+ }
+ r := managedboot.ProbeReply{Fleet: req.Fleet, Label: req.Label, Op: req.Op, Nonce: req.Nonce,
+ Storage: managedboot.ProbeStorage{OK: true, KeyID: "AKIAEXAMPLEEXAMPLE01"}}
+ if p.edit != nil {
+ p.edit(&r)
+ }
+ return r, nil
+}
+
+// probeRig is a hub edge with a mesh key and fleet "shop" (box-a, box-b),
+// and box edges that dial it as their own channels.
+type probeRig struct {
+ t *testing.T
+ hub *Edge
+ tunnels *TunnelHub
+ url string
+ host string
+ key []byte
+ seen map[string]*atomic.Int32 // every request each box was handed
+ boxes map[string]*probeBox
+ stops []func()
+}
+
+func newProbeRig(t *testing.T, routes ...registry.Route) *probeRig {
+ t.Helper()
+ reg := openReg(t)
+ if err := reg.UpsertFleet(registry.Fleet{Name: "shop", Account: "abc", Bucket: "shop-data"}); err != nil {
+ t.Fatal(err)
+ }
+ for _, label := range []string{"box-a", "box-b"} {
+ if err := reg.AddFleetBox(registry.FleetBox{Fleet: "shop", Label: label, TokenHash: sha256Hex("tok-" + label), Status: "active"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, rt := range routes {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ u, _ := url.Parse(srv.URL)
+ hub := NewTunnelHub(u.Hostname(), nil)
+ e.EnableTunnels(hub)
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ s := meshTestStore(t)
+ if err := mintMeshKey(context.Background(), s); err != nil {
+ t.Fatal(err)
+ }
+ m := newHomeMap(s, "hub")
+ refreshHomeMap(t, m)
+ e.homes.Store(m)
+ key, _ := m.meshKeys()
+ g := &probeRig{t: t, hub: e, tunnels: hub, url: srv.URL, host: u.Hostname(), key: key,
+ seen: map[string]*atomic.Int32{}, boxes: map[string]*probeBox{}}
+ t.Cleanup(func() {
+ for _, stop := range g.stops {
+ stop()
+ }
+ })
+ return g
+}
+
+// connect dials label as a managed box: a real Edge carrying the fake
+// responder through WithManagedProbe, served over the production tunnel
+// client loop.
+func (g *probeRig) connect(label string) *probeBox {
+ g.t.Helper()
+ box, err := New(openReg(g.t), nil)
+ if err != nil {
+ g.t.Fatal(err)
+ }
+ p := &probeBox{fleet: "shop", label: label}
+ WithManagedProbe(p)(box)
+ g.boxes[label] = p
+ return g.connectHandler(label, box)
+}
+
+// connectHandler dials label with h as the box's handler.
+func (g *probeRig) connectHandler(label string, h http.Handler) *probeBox {
+ g.t.Helper()
+ n := new(atomic.Int32)
+ g.seen[label] = n
+ g.stops = append(g.stops, startFakeRemoteHost(g.t, g.url, "shop/"+label, "tok-"+label, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ n.Add(1)
+ h.ServeHTTP(w, r)
+ })))
+ waitForTunnelState(g.t, g.tunnels, "shop/"+label, "connected", e2eReconnectBound)
+ return g.boxes[label]
+}
+
+func (g *probeRig) seenBy(label string) int32 {
+ if n := g.seen[label]; n != nil {
+ return n.Load()
+ }
+ return 0
+}
+
+func probeRequest(t *testing.T, label string) (managedboot.ProbeRequest, []byte) {
+ t.Helper()
+ n, err := managedboot.NewProbeNonce()
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := managedboot.ProbeRequest{Fleet: "shop", Label: label, Op: probeOp, Nonce: n, Storage: true}
+ body, err := managedboot.EncodeProbeRequest(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return req, body
+}
+
+// post sends body to the hub's probe door with auth (none when "").
+func (g *probeRig) post(method, host, auth string, body []byte) *http.Response {
+ g.t.Helper()
+ req, err := http.NewRequest(method, g.url+fleetProbePath, bytes.NewReader(body))
+ if err != nil {
+ g.t.Fatal(err)
+ }
+ req.Host = host
+ if auth != "" {
+ req.Header.Set(fleetProbeAuthHeader, auth)
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ g.t.Fatal(err)
+ }
+ g.t.Cleanup(func() { resp.Body.Close() })
+ return resp
+}
+
+func (g *probeRig) probe(label string) (managedboot.ProbeRequest, *http.Response) {
+ req, body := probeRequest(g.t, label)
+ return req, g.post(http.MethodPost, g.host, signFleetProbe(g.key, req.Channel(), body, time.Now()), body)
+}
+
+func readAll(t *testing.T, resp *http.Response) []byte {
+ t.Helper()
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+// TestFleetProbeExactChannel (review focus 5): the hub sends a probe down
+// the channel the request names and no other. With the target dark and a
+// sibling connected the hub answers 503 and the sibling sees nothing; a
+// connected target gets the only request; a box answers only a probe naming
+// its own fleet, label and op; a reply that echoes another box or nonce is
+// never relayed as a pass.
+func TestFleetProbeExactChannel(t *testing.T) {
+ g := newProbeRig(t)
+ g.connect("box-b")
+
+ _, resp := g.probe("box-a")
+ if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get(fleetProbeChannelHeader) != "" {
+ t.Fatalf("dark target: %d %v", resp.StatusCode, resp.Header)
+ }
+ if g.seenBy("box-b") != 0 || g.boxes["box-b"].calls.Load() != 0 {
+ t.Fatal("the probe for a dark box-a reached its sibling box-b")
+ }
+
+ a := g.connect("box-a")
+ req, resp := g.probe("box-a")
+ raw := readAll(t, resp)
+ if resp.StatusCode != http.StatusOK || resp.Header.Get(fleetProbeChannelHeader) != "shop/box-a" {
+ t.Fatalf("connected target: %d %v %s", resp.StatusCode, resp.Header, raw)
+ }
+ reply, err := managedboot.ParseProbeReply(raw)
+ if err != nil || !reply.Echoes(req) {
+ t.Fatalf("reply %s: %v", raw, err)
+ }
+ if a.calls.Load() != 1 || g.seenBy("box-a") != 1 || g.seenBy("box-b") != 0 {
+ t.Fatalf("calls: a=%d seen a=%d b=%d", a.calls.Load(), g.seenBy("box-a"), g.seenBy("box-b"))
+ }
+
+ // A request that reaches a box naming another box, fleet or op (a
+ // misrouted request) is a 404 from the box, whatever it names.
+ box, _ := New(openReg(t), nil)
+ WithManagedProbe(a)(box)
+ for name, edit := range map[string]func(*managedboot.ProbeRequest){
+ "other label": func(r *managedboot.ProbeRequest) { r.Label = "box-b" },
+ "other fleet": func(r *managedboot.ProbeRequest) { r.Fleet = "other" },
+ "other op": func(r *managedboot.ProbeRequest) { r.Op = strings.Repeat("f", 32) },
+ } {
+ r, _ := probeRequest(t, "box-a")
+ edit(&r)
+ body, _ := managedboot.EncodeProbeRequest(r)
+ w := serveMarked(box, body, true)
+ if w.Code != http.StatusNotFound {
+ t.Errorf("%s: box answered %d", name, w.Code)
+ }
+ }
+
+ // A box that echoes another label or another nonce: the hub relays no
+ // pass and no channel attestation.
+ for name, edit := range map[string]func(*managedboot.ProbeReply){
+ "another label": func(r *managedboot.ProbeReply) { r.Label = "box-b" },
+ "another nonce": func(r *managedboot.ProbeReply) { r.Nonce = strings.Repeat("0", 64) },
+ } {
+ a.edit = edit
+ _, resp := g.probe("box-a")
+ if resp.StatusCode == http.StatusOK || resp.Header.Get(fleetProbeChannelHeader) != "" {
+ t.Errorf("%s: hub relayed %d %v", name, resp.StatusCode, resp.Header)
+ }
+ }
+ if g.seenBy("box-b") != 0 {
+ t.Fatal("a probe reached the sibling")
+ }
+}
+
+// serveMarked hands body to h as a tunnelled managed-probe request, as the
+// box's tunnel client would (marked, header set when withHeader).
+func serveMarked(h http.Handler, body []byte, withHeader bool) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(http.MethodPost, "https://tunnel.example"+managedProbePath, bytes.NewReader(body))
+ if withHeader {
+ r.Header.Set(tunnelclient.ManagedProbeHeader, "1")
+ }
+ w := httptest.NewRecorder()
+ tunnelclient.Mark(h).ServeHTTP(w, r)
+ return w
+}
+
+// TestFleetProbeAuth: every bad MAC is the identical 401 before any channel
+// lookup; a signature under the rotation successor is accepted; the door is
+// a POST on the hub's host only; the probe markers are scrubbed from every
+// other request; and a fleet box cannot read the mesh key through the store
+// door.
+func TestFleetProbeAuth(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, "managed=%q channel=%q", r.Header.Get(tunnelclient.ManagedProbeHeader), r.Header.Get(fleetProbeChannelHeader))
+ }))
+ t.Cleanup(backend.Close)
+ g := newProbeRig(t,
+ registry.Route{Host: "local.example", Kind: "service", Addr: backend.Listener.Addr().String(), Status: "ready"},
+ registry.Route{Host: "app.example", Kind: "instance", Status: "ready", Region: registry.PlacementTarget("shop"), FleetBox: "box-b"},
+ )
+ a := g.connect("box-a")
+ req, body := probeRequest(t, "box-a")
+ now := time.Now()
+ otherKey := bytes.Repeat([]byte{7}, 32)
+ altered := bytes.Replace(body, []byte(req.Nonce), []byte(strings.Repeat("e", 64)), 1)
+ good := signFleetProbe(g.key, req.Channel(), body, now)
+ ts, sig, _ := strings.Cut(good, ":")
+ cases := []struct {
+ name, auth string
+ body []byte
+ }{
+ {"missing", "", body},
+ {"garbled", "not-a-mac", body},
+ {"no timestamp", ":" + sig, body},
+ {"bad hex", ts + ":zz" + sig[2:], body},
+ {"expired", signFleetProbe(g.key, req.Channel(), body, now.Add(-31*time.Second)), body},
+ {"future", signFleetProbe(g.key, req.Channel(), body, now.Add(31*time.Second)), body},
+ {"wrong key", signFleetProbe(otherKey, req.Channel(), body, now), body},
+ {"wrong channel", signFleetProbe(g.key, "shop/box-b", body, now), body},
+ {"altered body", good, altered},
+ {"hop mac", signHop(g.key, req.Channel(), now), body},
+ {"burst mac", signBurstNotice(g.key, req.Channel(), now, body), body},
+ {"not json", signFleetProbe(g.key, req.Channel(), []byte("{"), now), []byte("{")},
+ }
+ type shape struct {
+ code int
+ hdr string
+ body string
+ }
+ var want *shape
+ for _, c := range cases {
+ resp := g.post(http.MethodPost, g.host, c.auth, c.body)
+ got := shape{resp.StatusCode, fmt.Sprint(resp.Header.Get("Content-Type"), resp.Header.Get(fleetProbeChannelHeader), resp.Header.Get("Cache-Control")), string(readAll(t, resp))}
+ if got.code != http.StatusUnauthorized {
+ t.Errorf("%s: %d, want 401", c.name, got.code)
+ }
+ if want == nil {
+ want = &got
+ } else if got != *want {
+ t.Errorf("%s: %+v differs from %+v", c.name, got, *want)
+ }
+ }
+ if a.calls.Load() != 0 || g.seenBy("box-a") != 0 {
+ t.Fatal("an unauthenticated probe reached the box")
+ }
+ // Two auth headers are refused too.
+ r2, _ := http.NewRequest(http.MethodPost, g.url+fleetProbePath, bytes.NewReader(body))
+ r2.Host = g.host
+ r2.Header.Add(fleetProbeAuthHeader, good)
+ r2.Header.Add(fleetProbeAuthHeader, good)
+ if resp, err := http.DefaultClient.Do(r2); err != nil || resp.StatusCode != http.StatusUnauthorized {
+ t.Fatalf("two auth headers: %v %v", resp, err)
+ }
+
+ // The rotation successor: once mirrored, a signature under either key
+ // verifies.
+ next := bytes.Repeat([]byte{9}, 32)
+ m := g.hub.homes.Load()
+ m.keyMu.Lock()
+ m.keyNext = []byte(hex.EncodeToString(next))
+ m.keyMu.Unlock()
+ cur, nxt := m.meshKeys()
+ for name, key := range map[string][]byte{"next": nxt, "current": cur} {
+ req, body := probeRequest(t, "box-a")
+ resp := g.post(http.MethodPost, g.host, signFleetProbe(key, req.Channel(), body, time.Now()), body)
+ if resp.StatusCode != http.StatusOK {
+ t.Errorf("%s key: %d", name, resp.StatusCode)
+ }
+ }
+ if got := SignFleetProbe(cur, nxt, "shop/box-a", body, now); got != signFleetProbe(nxt, "shop/box-a", body, now) {
+ t.Error("SignFleetProbe does not prefer the rotation successor")
+ }
+ if SignFleetProbe(nil, nil, "shop/box-a", body, now) != "" {
+ t.Error("signed with no key")
+ }
+
+ // GET, and any other host, never reach the door.
+ before := a.calls.Load()
+ auth := signFleetProbe(cur, req.Channel(), body, time.Now())
+ if resp := g.post(http.MethodGet, g.host, auth, nil); resp.StatusCode != http.StatusNotFound {
+ t.Errorf("GET: %d", resp.StatusCode)
+ }
+ if resp := g.post(http.MethodPost, "other.example", auth, body); resp.StatusCode == http.StatusOK {
+ t.Errorf("another host: %d", resp.StatusCode)
+ }
+ if a.calls.Load() != before {
+ t.Fatal("GET or another host reached the box")
+ }
+
+ // The probe markers never ride ordinary traffic: not to a local
+ // upstream, not down a fleet channel, and a visitor cannot make a box
+ // answer a probe.
+ b := g.connect("box-b")
+ visit := func(host, path string) string {
+ r, _ := http.NewRequest(http.MethodPost, g.url+path, strings.NewReader(string(body)))
+ r.Host = host
+ r.Header.Set(tunnelclient.ManagedProbeHeader, "1")
+ r.Header.Set(fleetProbeChannelHeader, "shop/box-b")
+ resp, err := http.DefaultClient.Do(r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ return fmt.Sprint(resp.StatusCode, " ", string(readAll(t, resp)))
+ }
+ if got := visit("local.example", "/"); got != `200 managed="" channel=""` {
+ t.Errorf("local upstream saw %s", got)
+ }
+ if got := visit("app.example", managedProbePath); !strings.HasPrefix(got, "404") || b.calls.Load() != 0 {
+ t.Errorf("a visitor's probe on a fleet route: %s, responder calls %d", got, b.calls.Load())
+ }
+
+ // A fleet box's token reads no mesh key through the store door.
+ d, store := newTestDoor(t)
+ seedObject(t, store, meshKeyKey, "fake-mesh-shared-secret")
+ if w := doorDo(d, "GET", "/store/o/"+meshKeyKey, "", nil); w.Code != http.StatusNotFound || strings.Contains(w.Body.String(), "fake-mesh") {
+ t.Fatalf("mesh key through the door: %d", w.Code)
+ }
+}
+
+// TestFleetProbeBounds: the hub bounds what it reads and waits for, relays
+// nothing but a clean 200 with an exact echo, attests the channel it used,
+// and never tries another channel after a failure.
+func TestFleetProbeBounds(t *testing.T) {
+ restore := fleetProbeTimeout
+ fleetProbeTimeout = 300 * time.Millisecond
+ t.Cleanup(func() { fleetProbeTimeout = restore })
+ g := newProbeRig(t)
+ b := g.connect("box-b")
+
+ // An oversize request is refused before the MAC or any channel.
+ req, _ := probeRequest(t, "box-a")
+ big := []byte(strings.Replace(mustEncode(t, req), `"storage":true`, `"storage":true`+strings.Repeat(" ", managedboot.MaxProbeRequest), 1))
+ if resp := g.post(http.MethodPost, g.host, signFleetProbe(g.key, req.Channel(), big, time.Now()), big); resp.StatusCode != http.StatusBadRequest {
+ t.Fatalf("oversize request: %d", resp.StatusCode)
+ }
+
+ var mode atomic.Value
+ var release sync.Once
+ stall := make(chan struct{})
+ t.Cleanup(func() { release.Do(func() { close(stall) }) })
+ g.connectHandler("box-a", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ raw, _ := io.ReadAll(r.Body)
+ req, _ := managedboot.ParseProbeRequest(raw)
+ echo, _ := managedboot.EncodeProbeReply(managedboot.ProbeReply{Fleet: req.Fleet, Label: req.Label, Op: req.Op, Nonce: req.Nonce})
+ switch mode.Load().(string) {
+ case "ok":
+ w.Write(echo)
+ case "huge":
+ w.Write(append(echo, bytes.Repeat([]byte(" "), managedboot.MaxProbeReply)...))
+ case "redirect":
+ http.Redirect(w, r, "https://elsewhere.example/", http.StatusFound)
+ case "error":
+ w.WriteHeader(http.StatusInternalServerError)
+ w.Write(echo)
+ case "slow":
+ select {
+ case <-stall:
+ case <-r.Context().Done():
+ }
+ case "reset":
+ panic(http.ErrAbortHandler)
+ case "garbage":
+ w.Write([]byte(`{"fleet":"shop"}`))
+ }
+ }))
+ for _, m := range []string{"huge", "redirect", "error", "slow", "reset", "garbage"} {
+ mode.Store(m)
+ before := g.seenBy("box-a")
+ start := time.Now()
+ _, resp := g.probe("box-a")
+ readAll(t, resp)
+ if resp.StatusCode == http.StatusOK || resp.Header.Get(fleetProbeChannelHeader) != "" {
+ t.Errorf("%s: relayed %d %v", m, resp.StatusCode, resp.Header)
+ }
+ if m == "slow" && time.Since(start) > 5*time.Second {
+ t.Errorf("slow box held the hub %s", time.Since(start))
+ }
+ if g.seenBy("box-a") != before+1 {
+ t.Errorf("%s: box-a saw %d requests, want exactly one (no retry)", m, g.seenBy("box-a")-before)
+ }
+ }
+ release.Do(func() { close(stall) })
+ if g.seenBy("box-b") != 0 || b.calls.Load() != 0 {
+ t.Fatal("a failed probe was retried on the sibling")
+ }
+ mode.Store("ok")
+ _, resp := g.probe("box-a")
+ if resp.StatusCode != http.StatusOK || resp.Header.Get(fleetProbeChannelHeader) != "shop/box-a" || resp.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("clean answer: %d %v", resp.StatusCode, resp.Header)
+ }
+}
+
+func mustEncode(t *testing.T, r managedboot.ProbeRequest) string {
+ t.Helper()
+ b, err := managedboot.EncodeProbeRequest(r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
+
+// TestManagedProbeEdgeBranch: the box branch answers only a tunnelled POST
+// carrying the marker, before any route or admission; a box without a
+// responder (BYO) leaves the path to ordinary routing; a busy responder is
+// a 503 and an oversize body is refused unread by the responder.
+func TestManagedProbeEdgeBranch(t *testing.T) {
+ p := &probeBox{fleet: "shop", label: "box-a"}
+ box, err := New(openReg(t), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ WithManagedProbe(p)(box)
+ box.admission = closedAdmission{}
+ _, body := probeRequest(t, "box-a")
+ if w := serveMarked(box, body, true); w.Code != http.StatusOK || w.Header().Get("Cache-Control") != "no-store" {
+ t.Fatalf("joining box with no routes: %d %s", w.Code, w.Body)
+ }
+ if w := serveMarked(box, body, false); w.Code != http.StatusNotFound {
+ t.Fatalf("no marker header: %d", w.Code)
+ }
+ unmarked := httptest.NewRequest(http.MethodPost, "https://tunnel.example"+managedProbePath, bytes.NewReader(body))
+ unmarked.Header.Set(tunnelclient.ManagedProbeHeader, "1")
+ w := httptest.NewRecorder()
+ box.ServeHTTP(w, unmarked)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("not from the tunnel: %d", w.Code)
+ }
+ get := httptest.NewRequest(http.MethodGet, "https://tunnel.example"+managedProbePath, nil)
+ get.Header.Set(tunnelclient.ManagedProbeHeader, "1")
+ w = httptest.NewRecorder()
+ tunnelclient.Mark(box).ServeHTTP(w, get)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("GET: %d", w.Code)
+ }
+ calls := p.calls.Load()
+ if w := serveMarked(box, append(body, bytes.Repeat([]byte(" "), managedboot.MaxProbeRequest)...), true); w.Code != http.StatusNotFound || p.calls.Load() != calls {
+ t.Fatalf("oversize: %d, responder calls %d", w.Code, p.calls.Load()-calls)
+ }
+ busy := &busyBox{}
+ WithManagedProbe(busy)(box)
+ if w := serveMarked(box, body, true); w.Code != http.StatusServiceUnavailable {
+ t.Fatalf("busy: %d", w.Code)
+ }
+ byo, _ := New(openReg(t), nil)
+ if w := serveMarked(byo, body, true); w.Code == http.StatusOK {
+ t.Fatalf("a BYO box answered a probe: %d", w.Code)
+ }
+ if WithManagedProbe(nil) == nil {
+ t.Fatal("WithManagedProbe(nil) is nil")
+ }
+}
+
+type busyBox struct{}
+
+func (busyBox) Respond(context.Context, managedboot.ProbeRequest) (managedboot.ProbeReply, error) {
+ return managedboot.ProbeReply{}, ErrManagedProbeBusy
+}
+
+// closedAdmission refuses all tenant work, as a joining managed box does.
+type closedAdmission struct{}
+
+func (closedAdmission) TenantAdmitted() bool { return false }
+func (closedAdmission) TenantAdmissionStarting() bool { return true }
+func (closedAdmission) TenantAdmissionExempt(registry.Route) bool { return false }
diff --git a/internal/host/agent.go b/internal/host/agent.go
index e953b6dbe..f1aeac0f8 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1215,6 +1215,10 @@ func runAgent(args []string, buildClaims ClaimFactory) {
if admissionOption != nil {
edgeOpts = append(edgeOpts, admissionOption)
}
+ // A managed box answers the console's readiness probe (managedprobe.go).
+ if probeOption := managedProbeOption(join); probeOption != nil {
+ edgeOpts = append(edgeOpts, probeOption)
+ }
healthCtx, healthCancel := context.WithCancel(context.Background())
var healthWG sync.WaitGroup
defer func() { healthCancel(); healthWG.Wait() }()
diff --git a/internal/host/managedprobe.go b/internal/host/managedprobe.go
new file mode 100644
index 000000000..0780fbfa8
--- /dev/null
+++ b/internal/host/managedprobe.go
@@ -0,0 +1,183 @@
+package host
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+ "io"
+ "os"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/managedboot"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// A managed box's answer to the console's readiness probe (managed fleets
+// 2b-2 Task 5). The hub sends the probe down this box's own channel only
+// (internal/edge's fleetprobe.go); the prober answers only a probe naming
+// this box's fleet, label and op, as root recorded them in its identity.
+//
+// With storage asked, it proves the fleet bucket with the credentials the
+// console delivered at enrolment: one create-only PUT of
+// _carlos/probes/<label>/<nonce>, one GET compared byte for byte, one
+// DELETE, and nothing else. It reports the access key ID of the credentials
+// file (never the secret) and, whatever happened, the fingerprint of the
+// secrets key the box has installed, for the console to check against what
+// it delivered and registered. It runs as the carlos user, as the agent
+// does, through the normal SDK chain over /etc/carlos/credentials (root:carlos
+// 0640), the same file the hibernate lease uses. One probe at a time.
+
+// managedProbeTimeout bounds the storage challenge, inside the hub's 10 s.
+const managedProbeTimeout = 8 * time.Second
+
+// managedProbeCredentialsLimit bounds the read of the credentials file.
+const managedProbeCredentialsLimit = 4 << 10
+
+type managedProber struct {
+ id managedboot.Identity
+ getenv func(string) string
+ open func(context.Context) (release.Store, error)
+ readCreds func() ([]byte, error)
+ busy sync.Mutex
+ timeout time.Duration
+}
+
+// managedProberFor is the prober for a managed box's join, or nil on a BYO
+// box or one whose identity did not load: there is nobody to answer as.
+func managedProberFor(j *managedJoin) *managedProber {
+ if j == nil || j.id.Validate() != nil {
+ return nil
+ }
+ p := &managedProber{id: j.id, getenv: os.Getenv, timeout: managedProbeTimeout}
+ p.open = func(ctx context.Context) (release.Store, error) {
+ bucket, region := p.getenv("CARLOS_HIBERNATE_BUCKET"), p.getenv("CARLOS_HIBERNATE_REGION")
+ if bucket == "" || region == "" {
+ return nil, errors.New("managed probe: host.env names no fleet bucket")
+ }
+ return lease.NewFilesStore(ctx, bucket, region)
+ }
+ p.readCreds = func() ([]byte, error) {
+ f, err := os.Open(managedboot.CredentialsPath)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ return io.ReadAll(io.LimitReader(f, managedProbeCredentialsLimit))
+ }
+ return p
+}
+
+// managedProbeOption is the agent's edge option for the prober; nil when
+// there is none.
+func managedProbeOption(j *managedJoin) edge.RunOption {
+ p := managedProberFor(j)
+ if p == nil {
+ return nil
+ }
+ return edge.WithManagedProbe(p)
+}
+
+// Respond implements edge.ManagedProbeResponder.
+func (p *managedProber) Respond(ctx context.Context, req managedboot.ProbeRequest) (managedboot.ProbeReply, error) {
+ if req.Fleet != p.id.Fleet || req.Label != p.id.Label || req.Op != p.id.Op {
+ return managedboot.ProbeReply{}, edge.ErrManagedProbeNotMine
+ }
+ if !p.busy.TryLock() {
+ return managedboot.ProbeReply{}, edge.ErrManagedProbeBusy
+ }
+ defer p.busy.Unlock()
+ reply := managedboot.ProbeReply{Fleet: req.Fleet, Label: req.Label, Op: req.Op, Nonce: req.Nonce, SecretsKeyFP: p.installedKeyFP()}
+ if req.Storage {
+ reply.Storage = p.challenge(ctx, req)
+ }
+ return reply, nil
+}
+
+// installedKeyFP is the fingerprint of CARLOS_SECRETS_KEY, "" when the box
+// has none or it does not parse.
+func (p *managedProber) installedKeyFP() string {
+ raw := strings.TrimSpace(p.getenv("CARLOS_SECRETS_KEY"))
+ if raw == "" {
+ return ""
+ }
+ priv, err := appconfig.ParsePrivateKey(raw, "CARLOS_SECRETS_KEY")
+ if err != nil {
+ return ""
+ }
+ return appconfig.KeyFingerprint(priv.PublicKey())
+}
+
+// keyID is the delivered credentials' access key ID. The SDK chain would
+// prefer environment keys or a named profile over the file, so either one
+// set means the bucket calls would not prove the delivered key: refused.
+func (p *managedProber) keyID() (string, error) {
+ if p.getenv("AWS_SHARED_CREDENTIALS_FILE") != managedboot.CredentialsPath {
+ return "", errors.New("managed probe: not the delivered credentials file")
+ }
+ for _, k := range []string{"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_PROFILE", "AWS_DEFAULT_PROFILE"} {
+ if p.getenv(k) != "" {
+ return "", errors.New("managed probe: credentials would not come from the delivered file")
+ }
+ }
+ raw, err := p.readCreds()
+ if err != nil {
+ return "", err
+ }
+ return managedboot.CredentialsKeyID(raw)
+}
+
+// challenge writes, reads back and deletes one object under the box's own
+// probe prefix: three bucket calls, two when the write fails.
+func (p *managedProber) challenge(ctx context.Context, req managedboot.ProbeRequest) managedboot.ProbeStorage {
+ id, err := p.keyID()
+ if err != nil {
+ return managedboot.ProbeStorage{Code: managedboot.ProbeNoCredentials}
+ }
+ fail := func(code string) managedboot.ProbeStorage { return managedboot.ProbeStorage{KeyID: id, Code: code} }
+ ctx, cancel := context.WithTimeout(ctx, p.timeout)
+ defer cancel()
+ s, err := p.open(ctx)
+ if err != nil {
+ return fail(managedboot.ProbeNoBucket)
+ }
+ o, ok := s.(release.Opener)
+ if !ok {
+ return fail(managedboot.ProbeNoBucket)
+ }
+ buf := make([]byte, 32)
+ if _, err := rand.Read(buf); err != nil {
+ return fail(managedboot.ProbePutFailed)
+ }
+ want := []byte(req.Nonce + ":" + hex.EncodeToString(buf))
+ key := managedboot.ProbeObjectKey(p.id.Label, req.Nonce)
+ if _, err := s.Put(ctx, key, want, ""); err != nil {
+ return fail(managedboot.ProbePutFailed)
+ }
+ code := ""
+ if body, _, err := o.Open(ctx, key); err != nil {
+ code = managedboot.ProbeGetFailed
+ } else {
+ got, err := io.ReadAll(io.LimitReader(body, int64(len(want))+1))
+ body.Close()
+ switch {
+ case err != nil:
+ code = managedboot.ProbeGetFailed
+ case !bytes.Equal(got, want):
+ code = managedboot.ProbeMismatch
+ }
+ }
+ if err := s.Delete(ctx, key); err != nil && code == "" {
+ code = managedboot.ProbeDeleteFailed
+ }
+ if code != "" {
+ return fail(code)
+ }
+ return managedboot.ProbeStorage{OK: true, KeyID: id}
+}
diff --git a/internal/host/managedprobe_test.go b/internal/host/managedprobe_test.go
new file mode 100644
index 000000000..b3bd0f368
--- /dev/null
+++ b/internal/host/managedprobe_test.go
@@ -0,0 +1,378 @@
+//go:build linux
+
+package host
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdh"
+ "crypto/rand"
+ "encoding/base64"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/managedboot"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/tunnelclient"
+)
+
+// probeBucket is the fleet bucket as the prober sees it: a DirStore with
+// every call counted and any verb failable.
+type probeBucket struct {
+ *release.DirStore
+ mu sync.Mutex
+ puts, gets, deletes int
+ keys []string
+ failPut, failGet, failD bool
+ swap []byte // replaces the stored body before the read-back
+ hold chan struct{}
+}
+
+func (b *probeBucket) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ b.mu.Lock()
+ b.puts++
+ b.keys = append(b.keys, "PUT "+key+" "+ifMatch)
+ fail, hold := b.failPut, b.hold
+ b.mu.Unlock()
+ if hold != nil {
+ <-hold
+ }
+ if fail {
+ return "", errors.New("AccessDenied")
+ }
+ etag, err := b.DirStore.Put(ctx, key, body, ifMatch)
+ if err == nil && b.swap != nil {
+ b.DirStore.Put(ctx, key, b.swap, etag)
+ }
+ return etag, err
+}
+
+func (b *probeBucket) Open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ b.mu.Lock()
+ b.gets++
+ b.keys = append(b.keys, "GET "+key)
+ fail := b.failGet
+ b.mu.Unlock()
+ if fail {
+ return nil, "", errors.New("SlowDown")
+ }
+ return b.DirStore.Open(ctx, key)
+}
+
+func (b *probeBucket) Get(ctx context.Context, key string) ([]byte, string, error) {
+ b.mu.Lock()
+ b.gets++
+ b.mu.Unlock()
+ return nil, "", errors.New("the prober must read back through Open")
+}
+
+func (b *probeBucket) Delete(ctx context.Context, key string) error {
+ b.mu.Lock()
+ b.deletes++
+ b.keys = append(b.keys, "DELETE "+key)
+ fail := b.failD
+ b.mu.Unlock()
+ if fail {
+ return errors.New("AccessDenied")
+ }
+ return b.DirStore.Delete(ctx, key)
+}
+
+func (b *probeBucket) calls() int {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.puts + b.gets + b.deletes
+}
+
+const probeSecret = "abcdEFGH1234/+=ijklmnopqrstuvwx"
+
+// probeEnv is a managed box's host.env as the agent sees it, with the
+// installed secrets key when priv is set.
+func managedProbeEnv(priv string) func(string) string {
+ env := map[string]string{
+ "AWS_SHARED_CREDENTIALS_FILE": managedboot.CredentialsPath,
+ "CARLOS_HIBERNATE_BUCKET": "shop-data",
+ "CARLOS_HIBERNATE_REGION": "eu-west-1",
+ "CARLOS_SECRETS_KEY": priv,
+ }
+ return func(k string) string { return env[k] }
+}
+
+func probeKeyPair(t *testing.T) (priv, fp string) {
+ t.Helper()
+ k, err := ecdh.P256().GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return base64.StdEncoding.EncodeToString(k.Bytes()), appconfig.KeyFingerprint(k.PublicKey())
+}
+
+// probeFixture is a joining managed box's edge carrying its production
+// prober (managedProberFor) over a counting bucket and a credentials file.
+func probeFixture(t *testing.T) (*edge.Edge, *managedProber, *probeBucket, *joinFixture) {
+ t.Helper()
+ f := newJoinFixture(t)
+ j := f.join(t)
+ if !j.Joining() {
+ t.Fatal("fixture box is not joining")
+ }
+ p := managedProberFor(j)
+ if p == nil {
+ t.Fatal("no prober for a managed box")
+ }
+ bucket := &probeBucket{DirStore: release.NewDirStore(t.TempDir())}
+ creds, err := managedboot.RenderCredentials(managedboot.EnrolCredentials{ID: "AKIAEXAMPLEEXAMPLE01", Secret: []byte(probeSecret)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ p.open = func(context.Context) (release.Store, error) { return bucket, nil }
+ p.readCreds = func() ([]byte, error) { return creds, nil }
+ p.getenv = managedProbeEnv("")
+ e, err := edge.New(openTestRegistry(t), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ j.bind(nil, nil)(e)
+ edge.WithManagedProbe(p)(e)
+ return e, p, bucket, f
+}
+
+func openTestRegistry(t *testing.T) *registry.Registry {
+ t.Helper()
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ return reg
+}
+
+func probeAsk(t *testing.T, h http.Handler, req managedboot.ProbeRequest, marked, header bool) (*httptest.ResponseRecorder, managedboot.ProbeReply) {
+ t.Helper()
+ body, err := managedboot.EncodeProbeRequest(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := httptest.NewRequest(http.MethodPost, "https://tunnel.example/__carlos/managed-probe", bytes.NewReader(body))
+ if header {
+ r.Header.Set(tunnelclient.ManagedProbeHeader, "1")
+ }
+ w := httptest.NewRecorder()
+ if marked {
+ tunnelclient.Mark(h).ServeHTTP(w, r)
+ } else {
+ h.ServeHTTP(w, r)
+ }
+ var reply managedboot.ProbeReply
+ if w.Code == http.StatusOK {
+ if reply, err = managedboot.ParseProbeReply(w.Body.Bytes()); err != nil {
+ t.Fatalf("reply %s: %v", w.Body, err)
+ }
+ }
+ return w, reply
+}
+
+func probeFor(t *testing.T, id managedboot.Identity) managedboot.ProbeRequest {
+ t.Helper()
+ n, err := managedboot.NewProbeNonce()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return managedboot.ProbeRequest{Fleet: id.Fleet, Label: id.Label, Op: id.Op, Nonce: n, Storage: true}
+}
+
+// TestManagedProbeResponder: a joining box with no routes answers a
+// tunnelled probe naming itself, proving its bucket with exactly one PUT,
+// one GET and one DELETE of _carlos/probes/<label>/<nonce> under the
+// delivered credentials; it reports the key ID (never the secret) and the
+// installed key's fingerprint; it refuses anything else with no bucket
+// work; and runs one probe at a time.
+func TestManagedProbeResponder(t *testing.T) {
+ e, p, bucket, f := probeFixture(t)
+ id := f.m.ID
+ req := probeFor(t, id)
+
+ w, reply := probeAsk(t, e, req, true, true)
+ if w.Code != http.StatusOK || !reply.Echoes(req) {
+ t.Fatalf("joining box: %d %s", w.Code, w.Body)
+ }
+ if !reply.Storage.OK || reply.Storage.KeyID != "AKIAEXAMPLEEXAMPLE01" || reply.Storage.Code != "" || reply.SecretsKeyFP != "" {
+ t.Fatalf("reply %+v", reply)
+ }
+ key := managedboot.ProbeObjectKey(id.Label, req.Nonce)
+ want := []string{"PUT " + key + " ", "GET " + key, "DELETE " + key}
+ if strings.Join(bucket.keys, "|") != strings.Join(want, "|") {
+ t.Fatalf("bucket calls %q, want %q", bucket.keys, want)
+ }
+ if _, _, err := bucket.DirStore.Get(context.Background(), key); err == nil {
+ t.Fatal("challenge object left behind")
+ }
+ if strings.Contains(w.Body.String(), probeSecret) || strings.Contains(w.Body.String(), "aws_secret") {
+ t.Fatal("the secret left the box")
+ }
+
+ // Refusals: not over the tunnel, no marker, another box. No bucket
+ // work for any.
+ before := bucket.calls()
+ if w, _ := probeAsk(t, e, probeFor(t, id), false, true); w.Code != http.StatusNotFound {
+ t.Errorf("not from the tunnel: %d", w.Code)
+ }
+ if w, _ := probeAsk(t, e, probeFor(t, id), true, false); w.Code != http.StatusNotFound {
+ t.Errorf("no marker: %d", w.Code)
+ }
+ for name, edit := range map[string]func(*managedboot.ProbeRequest){
+ "another label": func(r *managedboot.ProbeRequest) { r.Label = "other-box" },
+ "another fleet": func(r *managedboot.ProbeRequest) { r.Fleet = "other" },
+ "another op": func(r *managedboot.ProbeRequest) { r.Op = strings.Repeat("e", 32) },
+ } {
+ r := probeFor(t, id)
+ edit(&r)
+ if w, _ := probeAsk(t, e, r, true, true); w.Code != http.StatusNotFound {
+ t.Errorf("%s: %d", name, w.Code)
+ }
+ }
+ if bucket.calls() != before {
+ t.Fatalf("refused probes did bucket work: %d calls", bucket.calls()-before)
+ }
+
+ // Without storage the bucket is untouched.
+ r := probeFor(t, id)
+ r.Storage = false
+ if w, reply := probeAsk(t, e, r, true, true); w.Code != http.StatusOK || reply.Storage != (managedboot.ProbeStorage{}) || bucket.calls() != before {
+ t.Fatalf("storage=false: %d %+v", w.Code, reply)
+ }
+
+ // The installed key's fingerprint; a key that does not parse is none.
+ priv, fp := probeKeyPair(t)
+ p.getenv = managedProbeEnv(priv)
+ if _, reply := probeAsk(t, e, probeFor(t, id), true, true); reply.SecretsKeyFP != fp {
+ t.Fatalf("fp %q, want %q", reply.SecretsKeyFP, fp)
+ }
+ p.getenv = managedProbeEnv("garbage")
+ if _, reply := probeAsk(t, e, probeFor(t, id), true, true); reply.SecretsKeyFP != "" {
+ t.Fatalf("fp from a bad key: %q", reply.SecretsKeyFP)
+ }
+ p.getenv = managedProbeEnv(priv)
+
+ // Failures are codes, never text, and a failed read-back still deletes.
+ for _, c := range []struct {
+ name string
+ arm func()
+ code string
+ calls int
+ }{
+ {"put fails", func() { bucket.failPut = true }, managedboot.ProbePutFailed, 1},
+ {"get fails", func() { bucket.failGet = true }, managedboot.ProbeGetFailed, 3},
+ {"read-back differs", func() { bucket.swap = []byte("someone else's bytes") }, managedboot.ProbeMismatch, 3},
+ {"delete fails", func() { bucket.failD = true }, managedboot.ProbeDeleteFailed, 3},
+ {"no bucket", func() {
+ p.open = func(context.Context) (release.Store, error) { return nil, errors.New("no region") }
+ }, managedboot.ProbeNoBucket, 0},
+ {"no credentials file", func() { p.readCreds = func() ([]byte, error) { return nil, errors.New("ENOENT") } }, managedboot.ProbeNoCredentials, 0},
+ {"credentials from elsewhere", func() {
+ env := managedProbeEnv(priv)
+ p.getenv = func(k string) string {
+ if k == "AWS_ACCESS_KEY_ID" {
+ return "AKIAOTHEROTHEROTHER1"
+ }
+ return env(k)
+ }
+ }, managedboot.ProbeNoCredentials, 0},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ saveOpen, saveCreds, saveEnv := p.open, p.readCreds, p.getenv
+ defer func() {
+ p.open, p.readCreds, p.getenv = saveOpen, saveCreds, saveEnv
+ bucket.failPut, bucket.failGet, bucket.failD, bucket.swap = false, false, false, nil
+ }()
+ c.arm()
+ before := bucket.calls()
+ w, reply := probeAsk(t, e, probeFor(t, id), true, true)
+ if w.Code != http.StatusOK || reply.Storage.OK || reply.Storage.Code != c.code {
+ t.Fatalf("%d %+v, want code %s", w.Code, reply, c.code)
+ }
+ if got := bucket.calls() - before; got != c.calls {
+ t.Fatalf("%d bucket calls, want %d", got, c.calls)
+ }
+ })
+ }
+
+ // One probe at a time: a second probe while the first holds the bucket
+ // is a 503 and does no bucket work.
+ hold := make(chan struct{})
+ bucket.mu.Lock()
+ bucket.hold = hold
+ bucket.mu.Unlock()
+ before = bucket.puts
+ done := make(chan *httptest.ResponseRecorder)
+ go func() {
+ w, _ := probeAsk(t, e, probeFor(t, id), true, true)
+ done <- w
+ }()
+ for {
+ bucket.mu.Lock()
+ n := bucket.puts
+ bucket.mu.Unlock()
+ if n > before {
+ break
+ }
+ time.Sleep(time.Millisecond)
+ }
+ before = bucket.calls()
+ if w, _ := probeAsk(t, e, probeFor(t, id), true, true); w.Code != http.StatusServiceUnavailable || bucket.calls() != before {
+ t.Fatalf("concurrent probe: %d, %d bucket calls", w.Code, bucket.calls()-before)
+ }
+ bucket.mu.Lock()
+ bucket.hold = nil
+ bucket.mu.Unlock()
+ close(hold)
+ if w := <-done; w.Code != http.StatusOK {
+ t.Fatalf("held probe: %d", w.Code)
+ }
+}
+
+// TestManagedProbeBudgetBucketCalls: each storage probe is exactly three
+// fleet-bucket requests, whatever the number of probes.
+func TestManagedProbeBudgetBucketCalls(t *testing.T) {
+ e, _, bucket, f := probeFixture(t)
+ for i := 1; i <= 5; i++ {
+ if w, _ := probeAsk(t, e, probeFor(t, f.m.ID), true, true); w.Code != http.StatusOK {
+ t.Fatal(w.Code)
+ }
+ if bucket.puts != i || bucket.gets != i || bucket.deletes != i {
+ t.Fatalf("after %d probes: %d puts %d gets %d deletes", i, bucket.puts, bucket.gets, bucket.deletes)
+ }
+ }
+}
+
+// TestManagedProbeWiring: the agent hands the edge a prober only on a
+// managed box with a valid identity, through the production option; a BYO
+// box (no join) gets none.
+func TestManagedProbeWiring(t *testing.T) {
+ if managedProbeOption(nil) != nil || managedProberFor(nil) != nil {
+ t.Fatal("a BYO box got a prober")
+ }
+ f := newJoinFixture(t)
+ j := f.join(t)
+ if managedProbeOption(j) == nil {
+ t.Fatal("a managed box got no prober")
+ }
+ p := managedProberFor(j)
+ if p.id != f.m.ID || p.open == nil || p.readCreds == nil || p.getenv == nil {
+ t.Fatalf("prober %+v", p)
+ }
+ broken := &managedJoin{refused: true}
+ if managedProbeOption(broken) != nil {
+ t.Fatal("a box with no valid identity got a prober")
+ }
+}
diff --git a/internal/managedboot/probe.go b/internal/managedboot/probe.go
new file mode 100644
index 000000000..1ea0af655
--- /dev/null
+++ b/internal/managedboot/probe.go
@@ -0,0 +1,216 @@
+package managedboot
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io"
+ "regexp"
+ "strings"
+)
+
+// The readiness probe's wire (managed fleets 2b-2 Task 5). The console asks
+// the fleet hub to probe one box; the hub sends the request down that box's
+// own channel, "<fleet>/<label>", and nowhere else; the box answers only a
+// request naming its own fleet, label and op, and proves its fleet bucket
+// and secrets key on the way. The console passes router_probe only on an
+// exact echo the hub attests came back over that channel.
+
+const (
+ // MaxProbeRequest bounds a probe request's body at the hub and the box.
+ MaxProbeRequest = 1 << 10
+ // MaxProbeReply bounds a box's answer at the hub and the console.
+ MaxProbeReply = 4 << 10
+ // ProbePrefix is where a box's storage challenge objects live in its
+ // fleet bucket (the fleet-data policy's _carlos/probes/*).
+ ProbePrefix = "_carlos/probes/"
+)
+
+// Storage challenge failure codes: what a box reports when it could not
+// write, read back and delete its challenge object. Never free text.
+const (
+ ProbeNoCredentials = "no_credentials"
+ ProbeNoBucket = "no_bucket"
+ ProbePutFailed = "put_failed"
+ ProbeGetFailed = "get_failed"
+ ProbeMismatch = "mismatch"
+ ProbeDeleteFailed = "delete_failed"
+)
+
+var (
+ nonceRE = regexp.MustCompile(`^[0-9a-f]{64}$`)
+ probeCodeRE = regexp.MustCompile(`^[a-z_]{1,32}$`)
+ keyFPRE = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
+ errProbe = errors.New("managedboot: invalid probe message")
+)
+
+// ProbeRequest names the one box a probe is for, the console's nonce, and
+// whether the box should prove its fleet bucket.
+type ProbeRequest struct {
+ Fleet string `json:"fleet"`
+ Label string `json:"label"`
+ Op string `json:"op"`
+ Nonce string `json:"nonce"`
+ Storage bool `json:"storage"`
+}
+
+// ProbeStorage is a box's storage challenge result. KeyID is the access key
+// ID in the box's credentials file, never the secret.
+type ProbeStorage struct {
+ OK bool `json:"ok"`
+ KeyID string `json:"key_id"`
+ Code string `json:"code"`
+}
+
+// ProbeReply echoes the request's identity and nonce, with the storage
+// result and the fingerprint of the secrets key the box has installed (""
+// when it has none).
+type ProbeReply struct {
+ Fleet string `json:"fleet"`
+ Label string `json:"label"`
+ Op string `json:"op"`
+ Nonce string `json:"nonce"`
+ Storage ProbeStorage `json:"storage"`
+ SecretsKeyFP string `json:"secrets_key_fp"`
+}
+
+// Channel is the hub channel the request is for.
+func (r ProbeRequest) Channel() string { return r.Fleet + "/" + r.Label }
+
+// Validate checks every field against the launch allowlists.
+func (r ProbeRequest) Validate() error {
+ if !nameRE.MatchString(r.Fleet) || !nameRE.MatchString(r.Label) || !opRE.MatchString(r.Op) || !nonceRE.MatchString(r.Nonce) {
+ return errProbe
+ }
+ return nil
+}
+
+// Validate checks the reply's identity, nonce and fields. A passing storage
+// result carries a key ID and no code; a failing one carries a code.
+func (r ProbeReply) Validate() error {
+ if !nameRE.MatchString(r.Fleet) || !nameRE.MatchString(r.Label) || !opRE.MatchString(r.Op) || !nonceRE.MatchString(r.Nonce) {
+ return errProbe
+ }
+ if r.SecretsKeyFP != "" && !keyFPRE.MatchString(r.SecretsKeyFP) {
+ return errProbe
+ }
+ st := r.Storage
+ if st.KeyID != "" && !accessKeyRE.MatchString(st.KeyID) {
+ return errProbe
+ }
+ if st.Code != "" && !probeCodeRE.MatchString(st.Code) {
+ return errProbe
+ }
+ if st.OK && (st.KeyID == "" || st.Code != "") {
+ return errProbe
+ }
+ return nil
+}
+
+// Echoes reports whether r answers exactly req: the same fleet, label, op
+// and nonce.
+func (r ProbeReply) Echoes(req ProbeRequest) bool {
+ return r.Fleet == req.Fleet && r.Label == req.Label && r.Op == req.Op && r.Nonce == req.Nonce
+}
+
+// NewProbeNonce is 32 random bytes, hex.
+func NewProbeNonce() (string, error) {
+ b := make([]byte, 32)
+ if _, err := rand.Read(b); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(b), nil
+}
+
+// ProbeObjectKey is the storage challenge object for label and nonce.
+func ProbeObjectKey(label, nonce string) string { return ProbePrefix + label + "/" + nonce }
+
+// EncodeProbeRequest is the one encoding of a valid request.
+func EncodeProbeRequest(r ProbeRequest) ([]byte, error) {
+ if err := r.Validate(); err != nil {
+ return nil, err
+ }
+ return json.Marshal(r)
+}
+
+// ParseProbeRequest decodes at most MaxProbeRequest bytes strictly: unknown
+// or missing fields, trailing values and invalid fields are refused.
+func ParseProbeRequest(b []byte) (ProbeRequest, error) {
+ var r ProbeRequest
+ if len(b) > MaxProbeRequest || strictProbe(b, &r, []string{"fleet", "label", "op", "nonce", "storage"}) != nil {
+ return ProbeRequest{}, errProbe
+ }
+ if err := r.Validate(); err != nil {
+ return ProbeRequest{}, err
+ }
+ return r, nil
+}
+
+// EncodeProbeReply is the one encoding of a valid reply.
+func EncodeProbeReply(r ProbeReply) ([]byte, error) {
+ if err := r.Validate(); err != nil {
+ return nil, err
+ }
+ b, err := json.Marshal(r)
+ if err != nil || len(b) > MaxProbeReply {
+ return nil, errProbe
+ }
+ return b, nil
+}
+
+// ParseProbeReply decodes at most MaxProbeReply bytes strictly.
+func ParseProbeReply(b []byte) (ProbeReply, error) {
+ var r ProbeReply
+ if len(b) > MaxProbeReply || strictProbe(b, &r, []string{"fleet", "label", "op", "nonce", "storage", "secrets_key_fp"}) != nil {
+ return ProbeReply{}, errProbe
+ }
+ if err := r.Validate(); err != nil {
+ return ProbeReply{}, err
+ }
+ return r, nil
+}
+
+// strictProbe decodes one JSON object into v with no unknown fields and
+// every top-level field in required present exactly once.
+func strictProbe(b []byte, v any, required []string) error {
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(b, &fields); err != nil || len(fields) != len(required) {
+ return errProbe
+ }
+ for _, name := range required {
+ if _, ok := fields[name]; !ok {
+ return errProbe
+ }
+ }
+ dec := json.NewDecoder(bytes.NewReader(b))
+ dec.DisallowUnknownFields()
+ if dec.Decode(v) != nil {
+ return errProbe
+ }
+ var extra any
+ if dec.Decode(&extra) != io.EOF {
+ return errProbe
+ }
+ return nil
+}
+
+// CredentialsKeyID is the access key ID in CredentialsPath's bytes, which
+// must be exactly RenderCredentials' form.
+func CredentialsKeyID(b []byte) (string, error) {
+ const head = "[default]\naws_access_key_id = "
+ rest, ok := strings.CutPrefix(string(b), head)
+ if !ok {
+ return "", errProbe
+ }
+ id, secret, ok := strings.Cut(rest, "\naws_secret_access_key = ")
+ if !ok || !accessKeyRE.MatchString(id) {
+ return "", errProbe
+ }
+ secret, ok = strings.CutSuffix(secret, "\n")
+ if !ok || !secretKeyRE.MatchString(secret) {
+ return "", errProbe
+ }
+ return id, nil
+}
diff --git a/internal/managedboot/probe_test.go b/internal/managedboot/probe_test.go
new file mode 100644
index 000000000..e6b93944e
--- /dev/null
+++ b/internal/managedboot/probe_test.go
@@ -0,0 +1,139 @@
+package managedboot
+
+import (
+ "strings"
+ "testing"
+)
+
+func probeTestRequest(t *testing.T) ProbeRequest {
+ t.Helper()
+ n, err := NewProbeNonce()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return ProbeRequest{Fleet: "shop", Label: "box-a", Op: strings.Repeat("ab", 16), Nonce: n, Storage: true}
+}
+
+// TestManagedProbeWire pins the probe's strict wire: the one encoding, the
+// size caps, unknown, missing and trailing fields refused, and the reply's
+// field rules (a key ID, never a secret; codes from the allowlist only).
+func TestManagedProbeWire(t *testing.T) {
+ req := probeTestRequest(t)
+ if len(req.Nonce) != 64 {
+ t.Fatalf("nonce %q is not 32 bytes of hex", req.Nonce)
+ }
+ if other := probeTestRequest(t); other.Nonce == req.Nonce {
+ t.Fatal("two nonces are equal")
+ }
+ raw, err := EncodeProbeRequest(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := ParseProbeRequest(raw)
+ if err != nil || got != req || got.Channel() != "shop/box-a" {
+ t.Fatalf("round trip: %+v %v", got, err)
+ }
+ for name, body := range map[string]string{
+ "unknown field": strings.Replace(string(raw), `"storage":true`, `"storage":true,"x":1`, 1),
+ "missing field": strings.Replace(string(raw), `,"storage":true`, ``, 1),
+ "trailing": string(raw) + "{}",
+ "bad label": strings.Replace(string(raw), `box-a`, `Box/A`, 1),
+ "bad op": strings.Replace(string(raw), req.Op, "zz", 1),
+ "short nonce": strings.Replace(string(raw), req.Nonce, req.Nonce[:62], 1),
+ "oversize": strings.Replace(string(raw), `"storage":true`, `"storage":true `+strings.Repeat(" ", MaxProbeRequest), 1),
+ "not json": "nope",
+ } {
+ if _, err := ParseProbeRequest([]byte(body)); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+ if _, err := EncodeProbeRequest(ProbeRequest{Fleet: "shop", Label: "a/b", Op: req.Op, Nonce: req.Nonce}); err == nil {
+ t.Error("encoded an invalid label")
+ }
+
+ reply := ProbeReply{Fleet: req.Fleet, Label: req.Label, Op: req.Op, Nonce: req.Nonce,
+ Storage: ProbeStorage{OK: true, KeyID: "AKIAEXAMPLEEXAMPLE01"}, SecretsKeyFP: "sha256:" + strings.Repeat("0f", 32)}
+ rb, err := EncodeProbeReply(reply)
+ if err != nil {
+ t.Fatal(err)
+ }
+ back, err := ParseProbeReply(rb)
+ if err != nil || back != reply || !back.Echoes(req) {
+ t.Fatalf("reply round trip: %+v %v", back, err)
+ }
+ for name, edit := range map[string]func(*ProbeReply){
+ "ok with a code": func(r *ProbeReply) { r.Storage.Code = ProbePutFailed },
+ "ok without key": func(r *ProbeReply) { r.Storage.KeyID = "" },
+ "free text code": func(r *ProbeReply) { r.Storage.OK, r.Storage.Code = false, "the bucket said: no" },
+ "a secret as id": func(r *ProbeReply) { r.Storage.KeyID = "abc/def+ghi=jklmnopqrs" },
+ "bad fingerprint": func(r *ProbeReply) { r.SecretsKeyFP = "md5:abc" },
+ "another fleet": func(r *ProbeReply) { r.Fleet = "Other!" },
+ "nonce not hex": func(r *ProbeReply) { r.Nonce = strings.Repeat("g", 64) },
+ "oversize key id": func(r *ProbeReply) { r.Storage.KeyID = strings.Repeat("A", 129) },
+ "oversize code": func(r *ProbeReply) { r.Storage.OK, r.Storage.Code = false, strings.Repeat("a", 33) },
+ "label not echoed?": func(r *ProbeReply) { r.Label = "" },
+ } {
+ r := reply
+ edit(&r)
+ if _, err := EncodeProbeReply(r); err == nil {
+ t.Errorf("%s: encoded", name)
+ }
+ }
+ failed := reply
+ failed.Storage = ProbeStorage{KeyID: "AKIAEXAMPLEEXAMPLE01", Code: ProbeGetFailed}
+ if _, err := EncodeProbeReply(failed); err != nil {
+ t.Errorf("a failed challenge with a code: %v", err)
+ }
+ for _, other := range []func(*ProbeReply){
+ func(r *ProbeReply) { r.Label = "box-b" },
+ func(r *ProbeReply) { r.Fleet = "other" },
+ func(r *ProbeReply) { r.Op = strings.Repeat("cd", 16) },
+ func(r *ProbeReply) { r.Nonce = strings.Repeat("0", 64) },
+ } {
+ r := reply
+ other(&r)
+ if r.Echoes(req) {
+ t.Errorf("%+v echoes %+v", r, req)
+ }
+ }
+ for name, body := range map[string]string{
+ "unknown nested": strings.Replace(string(rb), `"code":""`, `"code":"","secret":"x"`, 1),
+ "missing fp": strings.Replace(string(rb), `,"secrets_key_fp":"sha256:`+strings.Repeat("0f", 32)+`"`, ``, 1),
+ "oversize": string(rb) + strings.Repeat(" ", MaxProbeReply),
+ } {
+ if _, err := ParseProbeReply([]byte(body)); err == nil {
+ t.Errorf("reply %s: accepted", name)
+ }
+ }
+ if k := ProbeObjectKey("box-a", req.Nonce); k != "_carlos/probes/box-a/"+req.Nonce {
+ t.Fatal(k)
+ }
+}
+
+// TestManagedProbeCredentialsKeyID: the key ID comes only from the exact
+// RenderCredentials form, and the secret is never returned.
+func TestManagedProbeCredentialsKeyID(t *testing.T) {
+ c := EnrolCredentials{ID: "AKIAEXAMPLEEXAMPLE01", Secret: []byte("abcdEFGH1234/+=ijklmnopqrstuvwx")}
+ raw, err := RenderCredentials(c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ id, err := CredentialsKeyID(raw)
+ if err != nil || id != c.ID {
+ t.Fatalf("%q %v", id, err)
+ }
+ for name, body := range map[string]string{
+ "empty": "",
+ "no secret": "[default]\naws_access_key_id = AKIAEXAMPLEEXAMPLE01\n",
+ "profile": strings.Replace(string(raw), "[default]", "[other]", 1),
+ "extra line": string(raw) + "region = x\n",
+ "no newline": strings.TrimSuffix(string(raw), "\n"),
+ "bad id": strings.Replace(string(raw), c.ID, "AKIA EXAMPLE", 1),
+ "bad secret": strings.Replace(string(raw), string(c.Secret), "short", 1),
+ "second entry": string(raw) + string(raw),
+ } {
+ if _, err := CredentialsKeyID([]byte(body)); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+}
diff --git a/internal/provision/managed_fleets_2b2_census_test.go b/internal/provision/managed_fleets_2b2_census_test.go
index cc8d467cf..d29c761df 100644
--- a/internal/provision/managed_fleets_2b2_census_test.go
+++ b/internal/provision/managed_fleets_2b2_census_test.go
@@ -52,16 +52,32 @@ package provision
// (initialOnly), whose only writes are recordFleetKeyFP (the reviewed
// owner-record append) and the registry's SetFleetSecretsKey; no
// instance or sidecar record. The instances literal stays key-site.
+//
+// Task 5 adds one non-record write and re-pins serveDemoTraffic:
+// - host.managedProber.challenge (the agent, as carlos, answering the
+// console's readiness probe on a managed box) PUTs
+// _carlos/probes/<label>/<nonce> create-only (ifMatch "") into the
+// fleet's OWN bucket (lease.NewFilesStore over the delivered
+// credentials file), reads it back and deletes it. Random bytes, no
+// instance or sidecar record and no deployment-store key: nonrecord.
+// Witnessed by TestManagedProbeResponder and
+// TestManagedProbeBudgetBucketCalls.
+// - Edge.serveDemoTraffic also scrubs the managed probe marker and the
+// hub's channel attestation from demo requests (two names added to its
+// header scrub list); its gzip-pool Put is unchanged. Witnessed by
+// TestFleetProbeAuth.
func managedFleets2b2WriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), managedFleets2b1WriteCensusInventory()...)
entries = append(entries, censusEntry{"internal/managedboot/hostenv.go", "ManagedHostEnv", "key-site", "lit:instances", "475c33aef5f55a5ffcaa97f8caa8eb30b0027a0d19486e88f1980909e468b5f5"})
entries = append(entries, censusEntry{"internal/host/managedkey.go", "ensureFleetKey", "nonrecord", "sel:Put", "2c319a1f3d4c4920f120b91e1b9f5063257225d161399934160d08a23c6b9984"})
+ entries = append(entries, censusEntry{"internal/host/managedprobe.go", "managedProber.challenge", "nonrecord", "sel:Put", "8ddc47d1e39d847d7adfdba3abdae49aec045868ca2be1d4a5602dc911216625"})
repins := []censusEntry{
{"internal/console/server.go", "NewServer", "key-site", "lit:instances", "30ef695663c7c0807d1dd8c20e66c32adb9a607d40ec6e30624c6ca403cee281"},
{"internal/console/managedworker.go", "Server.managedPublishFresh", "nonrecord", "sel:Put", "a9345cd73b16e931e72637adf34274479ce2c7ad001eb8d53d088844a8af9c53"},
{"internal/provision/reconcile.go", "Reconcile", "key-site", "key:RecordKey", "5da0a14b597609fa3d212c7e79a3d2895426e238cace01b5770653d9ab9e97fe"},
{"internal/provision/sidecar_reconcile.go", "ReconcileSidecars", "key-site", "key:ParseSidecarKey,key:SidecarRecordKey,lit:sidecars", "5e3401e3cb68a5bd7688a0e53aa0791fa5ac54b4d14bcd7bcc6cd3daf521db5e"},
{"internal/host/bootstrap.go", "bootstrapWithGroup", "key-site", "lit:instances", "710ca018c8f6f9e77067dc41389606c6d53312058f7710aab68ecfc991207ec7"},
+ {"internal/edge/demo_traffic.go", "Edge.serveDemoTraffic", "nonrecord", "sel:Put", "b63349fa62442d4d0d935b0582c276c8fcf16ebddfd1cec5cc314f1da51297ba"},
}
for _, r := range repins {
found := false
diff --git a/internal/tunnelclient/tunnelclient.go b/internal/tunnelclient/tunnelclient.go
index 464840926..cb8c35a0e 100644
--- a/internal/tunnelclient/tunnelclient.go
+++ b/internal/tunnelclient/tunnelclient.go
@@ -271,6 +271,12 @@ func Dial(ctx context.Context, rawURL, name, token string) (net.Conn, error) {
// ReplicaProbeHeader marks private hub health requests, never visitor traffic.
const ReplicaProbeHeader = "X-Carlos-Replica-Probe"
+// ManagedProbeHeader marks the hub's readiness probe to a managed box
+// (internal/edge's fleetprobe.go). The hub sends it only on the probe it
+// forwards down the box's own channel and deletes it from every other
+// request; a box believes it only on a request that came over its tunnel.
+const ManagedProbeHeader = "X-Carlos-Managed-Probe"
+
type tunnelKey struct{}
// FromTunnel reports whether a request was served over a tunnel this client