Skip to content

Agent Mesh

controlplane, node: fixes from the security review of operator-owned keys

Antonio Ojeac34e3ca69842
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index 30b868dd..8006dcc5 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -327,6 +327,16 @@ func (s *Server) Init() error {
go s.watchOperatorSigningKeys()
}
_, _, err := s.store.GetCurrentKey(ctx)
+ if err == nil && s.operatorKeys == nil {
+ // Keys in the store and no --signing-key-path: either this control
+ // plane generated them, or an operator used to supply them and the
+ // flag is gone. Rotation is about to be automatic either way; say so
+ // when no rotation was ever scheduled, which is how the second case
+ // looks.
+ if next, nerr := s.store.NextKeyRotation(ctx); nerr == nil && next.IsZero() && s.config.KeyRotationInterval > 0 {
+ logger.Warnw("Signing keys found in the store with no rotation schedule; automatic rotation takes over. If these keys were operator-managed, restore --signing-key-path", "first_rotation_in", s.config.KeyRotationInterval.String())
+ }
+ }
if err == storage.ErrNotFound {
logger.Info("Generating initial control plane signing keys...")
pub, priv, err := ed25519.GenerateKey(rand.Reader)
diff --git a/internal/controlplane/signingkeys.go b/internal/controlplane/signingkeys.go
index 0750f1a3..a688d2f5 100644
--- a/internal/controlplane/signingkeys.go
+++ b/internal/controlplane/signingkeys.go
@@ -26,6 +26,8 @@ import (
"errors"
"fmt"
"os"
+ "slices"
+ "sort"
"time"
"github.com/google/agentmesh/api"
@@ -104,8 +106,13 @@ func parseOperatorSigningKeys(path string, data []byte) (*operatorSigningKeys, e
return nil, fmt.Errorf("signing keys %s: unsupported key type %T (want Ed25519 or P-256)", path, parsed)
}
}
- if len(keys.ed25519) == 0 && len(keys.es256) == 0 {
- return nil, fmt.Errorf("signing keys %s: no private key found", path)
+ // Owning the keys means owning both: a file with one kind would leave
+ // the other generated per store and no longer rotated by anyone.
+ if len(keys.ed25519) == 0 {
+ return nil, fmt.Errorf("signing keys %s: no Ed25519 key (the Biscuit signing key); the file must carry at least one key of each kind", path)
+ }
+ if len(keys.es256) == 0 {
+ return nil, fmt.Errorf("signing keys %s: no P-256 key (the ES256 key for /sts/token and /jwks); the file must carry at least one key of each kind", path)
}
return keys, nil
}
@@ -118,58 +125,38 @@ func keyFingerprint(pub []byte) string {
}
// reconcileEd25519Keyring makes the store's Biscuit keyring reflect keys:
-// keys[0] current, the rest valid for verification until gracePeriod from
-// now. It goes through the same SaveInitialKey / RotateKeys path as
-// automatic rotation, so a store that already matches is left alone, a store
-// that holds a key the operator does not know (one the control plane
-// generated before the operator took over) keeps it valid for the grace
-// period, and every verifier learns the new set from /keys the usual way.
+// keys[0] current, the rest valid for verification while the operator lists
+// them, every other valid key (one the control plane generated before the
+// operator took over, one the operator dropped) kept for gracePeriod so that
+// credentials it signed keep verifying meanwhile. One store transaction; a
+// set already in place is a no-op, a key moved back to the front becomes
+// current again, and an expired row of a listed key is replaced.
func reconcileEd25519Keyring(ctx context.Context, store storage.Store, keys []ed25519.PrivateKey, gracePeriod time.Duration) error {
if len(keys) == 0 {
return nil
}
- valid, err := store.GetAllValidKeys(ctx)
+ before, err := store.GetAllValidKeys(ctx)
if err != nil && !errors.Is(err, storage.ErrNotFound) {
return fmt.Errorf("read keyring: %w", err)
}
- known := func(pub ed25519.PublicKey) bool {
- for _, k := range valid {
- if k.Public.Equal(pub) {
- return true
- }
- }
- return false
+ pair := func(priv ed25519.PrivateKey) storage.KeyPair {
+ return storage.KeyPair{Private: priv, Public: priv.Public().(ed25519.PublicKey)}
}
- // Oldest first, so that the first key in the file ends up current.
- for i := len(keys) - 1; i >= 0; i-- {
- priv := keys[i]
- pub := priv.Public().(ed25519.PublicKey)
- if known(pub) {
- continue
- }
- if len(valid) == 0 {
- if err := store.SaveInitialKey(ctx, priv, pub); err != nil {
- return fmt.Errorf("save signing key %s: %w", keyFingerprint(pub), err)
- }
- } else if err := store.RotateKeys(ctx, priv, pub, gracePeriod); err != nil {
- return fmt.Errorf("install signing key %s: %w", keyFingerprint(pub), err)
- }
- valid = append(valid, storage.KeyPair{Private: priv, Public: pub})
- logger.Infow("Installed operator signing key", "algorithm", "ed25519", "fingerprint", keyFingerprint(pub))
+ verifying := make([]storage.KeyPair, 0, len(keys)-1)
+ for _, k := range keys[1:] {
+ verifying = append(verifying, pair(k))
}
- _, currentPub, err := store.GetCurrentKey(ctx)
- if err != nil {
- return fmt.Errorf("read current signing key: %w", err)
+ current := pair(keys[0])
+ if err := store.SetKeyring(ctx, current, verifying, gracePeriod); err != nil {
+ return fmt.Errorf("set signing keys: %w", err)
}
- if wantPub := keys[0].Public().(ed25519.PublicKey); !currentPub.Equal(wantPub) {
- // The first key in the file is known but not current, which happens
- // when the operator moves a previous key back to the front; the
- // store's current key becomes a verification-only key.
- if err := store.RotateKeys(ctx, keys[0], wantPub, gracePeriod); err != nil {
- return fmt.Errorf("make signing key %s current: %w", keyFingerprint(wantPub), err)
+ logKeyringChange("ed25519", keyPairFingerprints(before), func() []string {
+ after, err := store.GetAllValidKeys(ctx)
+ if err != nil {
+ return nil
}
- logger.Infow("Operator signing key made current", "algorithm", "ed25519", "fingerprint", keyFingerprint(wantPub))
- }
+ return keyPairFingerprints(after)
+ }(), keyFingerprint(current.Public))
return nil
}
@@ -180,60 +167,73 @@ func reconcileES256Keyring(ctx context.Context, store storage.Store, keys []*ecd
if len(keys) == 0 {
return nil
}
- valid, err := store.GetAllValidOIDCKeys(ctx)
+ before, err := store.GetAllValidOIDCKeys(ctx)
if err != nil && !errors.Is(err, storage.ErrNotFound) {
return fmt.Errorf("read ES256 keyring: %w", err)
}
- known := make(map[string]bool, len(valid))
- for _, k := range valid {
- known[k.Kid] = true
- }
- encode := func(priv *ecdsa.PrivateKey) (kid string, privBytes, pubBytes []byte, err error) {
- pubBytes, err = priv.PublicKey.Bytes()
+ encode := func(priv *ecdsa.PrivateKey) (storage.OIDCKeyPair, error) {
+ pubBytes, err := priv.PublicKey.Bytes()
if err != nil || len(pubBytes) != 65 {
- return "", nil, nil, fmt.Errorf("encode P-256 public key: %w", err)
+ return storage.OIDCKeyPair{}, fmt.Errorf("encode P-256 public key: %w", err)
}
- privBytes, err = x509.MarshalECPrivateKey(priv)
+ privBytes, err := x509.MarshalECPrivateKey(priv)
if err != nil {
- return "", nil, nil, fmt.Errorf("encode P-256 private key: %w", err)
+ return storage.OIDCKeyPair{}, fmt.Errorf("encode P-256 private key: %w", err)
}
- return es256Kid(pubBytes), privBytes, pubBytes, nil
+ return storage.OIDCKeyPair{Kid: es256Kid(pubBytes), PrivateKey: privBytes, PublicKey: pubBytes}, nil
+ }
+ current, err := encode(keys[0])
+ if err != nil {
+ return err
}
- for i := len(keys) - 1; i >= 0; i-- {
- kid, privBytes, pubBytes, err := encode(keys[i])
+ verifying := make([]storage.OIDCKeyPair, 0, len(keys)-1)
+ for _, k := range keys[1:] {
+ kp, err := encode(k)
if err != nil {
return err
}
- if known[kid] {
- continue
- }
- if len(known) == 0 {
- if err := store.SaveInitialOIDCKey(ctx, kid, privBytes, pubBytes); err != nil {
- return fmt.Errorf("save ES256 key %s: %w", kid, err)
- }
- } else if err := store.RotateOIDCKeys(ctx, kid, privBytes, pubBytes, gracePeriod); err != nil {
- return fmt.Errorf("install ES256 key %s: %w", kid, err)
- }
- known[kid] = true
- logger.Infow("Installed operator signing key", "algorithm", "es256", "kid", kid)
+ verifying = append(verifying, kp)
}
- wantKid, privBytes, pubBytes, err := encode(keys[0])
- if err != nil {
- return err
- }
- current, err := store.GetCurrentOIDCKey(ctx)
- if err != nil {
- return fmt.Errorf("read current ES256 key: %w", err)
+ if err := store.SetOIDCKeyring(ctx, current, verifying, gracePeriod); err != nil {
+ return fmt.Errorf("set ES256 keys: %w", err)
}
- if current == nil || current.Kid != wantKid {
- if err := store.RotateOIDCKeys(ctx, wantKid, privBytes, pubBytes, gracePeriod); err != nil {
- return fmt.Errorf("make ES256 key %s current: %w", wantKid, err)
+ logKeyringChange("es256", oidcKids(before), func() []string {
+ after, err := store.GetAllValidOIDCKeys(ctx)
+ if err != nil {
+ return nil
}
- logger.Infow("Operator signing key made current", "algorithm", "es256", "kid", wantKid)
- }
+ return oidcKids(after)
+ }(), current.Kid)
return nil
}
+func keyPairFingerprints(keys []storage.KeyPair) []string {
+ out := make([]string, 0, len(keys))
+ for _, k := range keys {
+ out = append(out, keyFingerprint(k.Public))
+ }
+ sort.Strings(out)
+ return out
+}
+
+func oidcKids(keys []storage.OIDCKeyPair) []string {
+ out := make([]string, 0, len(keys))
+ for _, k := range keys {
+ out = append(out, k.Kid)
+ }
+ sort.Strings(out)
+ return out
+}
+
+// logKeyringChange says what the operator's file did to the keyring, in
+// public identifiers only, and nothing when it did nothing.
+func logKeyringChange(algorithm string, before, after []string, signing string) {
+ if slices.Equal(before, after) {
+ return
+ }
+ logger.Infow("Operator signing keys installed", "algorithm", algorithm, "signing", signing, "valid_before", before, "valid_after", after)
+}
+
// installOperatorSigningKeys reconciles both keyrings from keys and reports
// whether the Biscuit signing key changed, so the caller can announce it.
func (s *Server) installOperatorSigningKeys(ctx context.Context, keys *operatorSigningKeys) (bool, error) {
diff --git a/internal/controlplane/signingkeys_test.go b/internal/controlplane/signingkeys_test.go
index 607f30cc..63b141d6 100644
--- a/internal/controlplane/signingkeys_test.go
+++ b/internal/controlplane/signingkeys_test.go
@@ -101,7 +101,7 @@ func TestLoadOperatorSigningKeys(t *testing.T) {
if err != nil {
t.Fatalf("MarshalECPrivateKey: %v", err)
}
- path := writeKeyFile(t, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}))
+ path := writeKeyFile(t, pemPKCS8(t, edA), pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}))
keys, err := loadOperatorSigningKeys(path)
if err != nil {
t.Fatalf("loadOperatorSigningKeys: %v", err)
@@ -142,8 +142,19 @@ func TestLoadOperatorSigningKeys(t *testing.T) {
t.Run("empty file is refused", func(t *testing.T) {
_, err := loadOperatorSigningKeys(writeKeyFile(t, []byte("not pem at all\n")))
- if err == nil || !strings.Contains(err.Error(), "no private key found") {
- t.Fatalf("err = %v, want no private key found", err)
+ if err == nil || !strings.Contains(err.Error(), "no Ed25519 key") {
+ t.Fatalf("err = %v, want a refusal naming the missing Ed25519 key", err)
+ }
+ })
+
+ t.Run("one kind only is refused", func(t *testing.T) {
+ _, err := loadOperatorSigningKeys(writeKeyFile(t, pemPKCS8(t, edA)))
+ if err == nil || !strings.Contains(err.Error(), "no P-256 key") {
+ t.Fatalf("err = %v, want a refusal naming the missing P-256 key", err)
+ }
+ _, err = loadOperatorSigningKeys(writeKeyFile(t, pemPKCS8(t, ecA)))
+ if err == nil || !strings.Contains(err.Error(), "no Ed25519 key") {
+ t.Fatalf("err = %v, want a refusal naming the missing Ed25519 key", err)
}
})
@@ -233,6 +244,72 @@ func TestReconcileEd25519Keyring(t *testing.T) {
}
})
+ t.Run("rollback: previous key moved back to the front", func(t *testing.T) {
+ store := newStore(t)
+ if err := reconcileEd25519Keyring(ctx, store, []ed25519.PrivateKey{current, previous}, time.Hour); err != nil {
+ t.Fatalf("reconcile [current previous]: %v", err)
+ }
+ if err := reconcileEd25519Keyring(ctx, store, []ed25519.PrivateKey{previous, current}, time.Hour); err != nil {
+ t.Fatalf("reconcile [previous current]: %v", err)
+ }
+ _, gotPub, err := store.GetCurrentKey(ctx)
+ if err != nil {
+ t.Fatalf("GetCurrentKey: %v", err)
+ }
+ if !gotPub.Equal(pubOf(previous)) {
+ t.Fatalf("current key = %s, want %s (moved back to the front)", keyFingerprint(gotPub), keyFingerprint(pubOf(previous)))
+ }
+ if valid := validPubs(t, store); len(valid) != 2 {
+ t.Fatalf("valid keys = %d after the rollback, want 2", len(valid))
+ }
+ })
+
+ t.Run("persistent store: restart after the grace period", func(t *testing.T) {
+ // The store outlives the control plane (SQLite file, PostgreSQL). The
+ // operator published [current previous], the previous key was dropped
+ // from the file, its grace period ran out, and the control plane
+ // restarts on a file that lists it again as verifying: the expired
+ // row must not stop the start.
+ dbPath := filepath.Join(t.TempDir(), "cp.db")
+ store, err := storage.NewSQLStore("sqlite", dbPath)
+ if err != nil {
+ t.Fatalf("NewSQLStore: %v", err)
+ }
+ const grace = 20 * time.Millisecond
+ if err := reconcileEd25519Keyring(ctx, store, []ed25519.PrivateKey{current, previous}, grace); err != nil {
+ t.Fatalf("reconcile v1: %v", err)
+ }
+ if err := reconcileEd25519Keyring(ctx, store, []ed25519.PrivateKey{current}, grace); err != nil {
+ t.Fatalf("reconcile drop: %v", err)
+ }
+ time.Sleep(2 * grace)
+ if valid := validPubs(t, store); valid[string(pubOf(previous))] {
+ t.Fatal("dropped key still valid after its grace period")
+ }
+ if err := store.Close(); err != nil {
+ t.Fatalf("Close: %v", err)
+ }
+ store, err = storage.NewSQLStore("sqlite", dbPath)
+ if err != nil {
+ t.Fatalf("NewSQLStore (restart): %v", err)
+ }
+ defer func() { _ = store.Close() }()
+ if err := reconcileEd25519Keyring(ctx, store, []ed25519.PrivateKey{current, previous}, grace); err != nil {
+ t.Fatalf("reconcile after restart with an expired row of a listed key: %v", err)
+ }
+ valid := validPubs(t, store)
+ if len(valid) != 2 || !valid[string(pubOf(previous))] {
+ t.Fatalf("valid keys = %d after restart, want both listed keys", len(valid))
+ }
+ _, gotPub, err := store.GetCurrentKey(ctx)
+ if err != nil {
+ t.Fatalf("GetCurrentKey: %v", err)
+ }
+ if !gotPub.Equal(pubOf(current)) {
+ t.Fatalf("current key = %s, want %s", keyFingerprint(gotPub), keyFingerprint(pubOf(current)))
+ }
+ })
+
t.Run("operator rotation: new key first, previous kept", func(t *testing.T) {
store := newStore(t)
if err := reconcileEd25519Keyring(ctx, store, []ed25519.PrivateKey{previous}, time.Hour); err != nil {
@@ -296,7 +373,35 @@ func TestReconcileES256Keyring(t *testing.T) {
t.Fatalf("GetAllValidOIDCKeys: %v", err)
}
if len(all) != 2 {
- t.Fatalf("valid ES256 keys = %d after rotation, want 2 (previous kept for the grace period)", len(all))
+ t.Fatalf("valid ES256 keys = %d after rotation, want 2 (previous kept while listed)", len(all))
+ }
+ // Rollback: v1 moved back to the front.
+ if err := reconcileES256Keyring(ctx, store, []*ecdsa.PrivateKey{v1, v2}, time.Hour); err != nil {
+ t.Fatalf("reconcile rollback: %v", err)
+ }
+ cur, err = store.GetCurrentOIDCKey(ctx)
+ if err != nil || cur == nil {
+ t.Fatalf("GetCurrentOIDCKey: %v (%v)", err, cur)
+ }
+ if cur.Kid != kidOf(t, v1) {
+ t.Fatalf("current kid after rollback = %s, want %s", cur.Kid, kidOf(t, v1))
+ }
+ // Drop v2 with a short grace, let it expire, list it again: the expired
+ // row is replaced, not a constraint error.
+ const grace = 20 * time.Millisecond
+ if err := reconcileES256Keyring(ctx, store, []*ecdsa.PrivateKey{v1}, grace); err != nil {
+ t.Fatalf("reconcile drop: %v", err)
+ }
+ time.Sleep(2 * grace)
+ if err := reconcileES256Keyring(ctx, store, []*ecdsa.PrivateKey{v1, v2}, grace); err != nil {
+ t.Fatalf("reconcile with an expired row of a listed key: %v", err)
+ }
+ all, err = store.GetAllValidOIDCKeys(ctx)
+ if err != nil {
+ t.Fatalf("GetAllValidOIDCKeys: %v", err)
+ }
+ if len(all) != 2 {
+ t.Fatalf("valid ES256 keys = %d after relisting an expired key, want 2", len(all))
}
}
diff --git a/internal/node/controlplane_sync.go b/internal/node/controlplane_sync.go
index 68015d4d..69be4182 100644
--- a/internal/node/controlplane_sync.go
+++ b/internal/node/controlplane_sync.go
@@ -383,9 +383,17 @@ func (n *AgentMeshNode) controlPlaneForgotUs(err error) bool {
return errors.As(err, &se) && se.Code == http.StatusUnauthorized
}
+// reenrollCooldown bounds how often a node spends its bootstrap token on a
+// re-enrollment: a 401 is a claim by whoever answered the control plane
+// URL, and one attempt per cooldown is all it can cause. A package variable
+// so a test can shorten it.
+var reenrollCooldown = time.Minute
+
// recoverEnrollment enrolls again with the bootstrap token at
-// Options.BootstrapTokenPath and reports whether it did. Without a path the
-// node leaves recovery to the renewal loop and says so once per failure.
+// Options.BootstrapTokenPath and reports whether it did. The answer must
+// verify under a control plane key this node already trusts, so a party
+// that merely answers the URL cannot replace the trust root. Without a path
+// the node leaves recovery to the renewal loop and says so once per failure.
func (n *AgentMeshNode) recoverEnrollment(ctx context.Context) bool {
path := n.config.BootstrapTokenPath
if path == "" {
@@ -393,6 +401,16 @@ func (n *AgentMeshNode) recoverEnrollment(ctx context.Context) bool {
reenrollmentsTotal.WithLabelValues("no_token").Inc()
return false
}
+ n.reenrollMu.Lock()
+ since := time.Since(n.lastReenroll)
+ if !n.lastReenroll.IsZero() && since < reenrollCooldown {
+ n.reenrollMu.Unlock()
+ logger.Warnw("Control plane no longer recognizes this node's credential; a re-enrollment was attempted recently, not trying again yet", "since", since.Round(time.Second).String(), "cooldown", reenrollCooldown.String())
+ reenrollmentsTotal.WithLabelValues("cooldown").Inc()
+ return false
+ }
+ n.lastReenroll = time.Now()
+ n.reenrollMu.Unlock()
raw, err := os.ReadFile(path)
if err != nil {
logger.Warnw("Control plane no longer recognizes this node's credential; bootstrap token unreadable", "path", path, "error", err)
@@ -411,7 +429,7 @@ func (n *AgentMeshNode) recoverEnrollment(ctx context.Context) bool {
enroll := n.enrollBootstrapFn
if enroll == nil {
enroll = func(ctx context.Context, controlPlaneURL, token string) error {
- _, err := n.enrollBootstrapCredential(ctx, controlPlaneURL, token)
+ _, err := n.enrollBootstrapCredential(ctx, controlPlaneURL, token, true)
return err
}
}
diff --git a/internal/node/controlplane_sync_test.go b/internal/node/controlplane_sync_test.go
index aadb6ad3..e1d4e7f3 100644
--- a/internal/node/controlplane_sync_test.go
+++ b/internal/node/controlplane_sync_test.go
@@ -23,6 +23,7 @@ import (
"path/filepath"
"sync/atomic"
"testing"
+ "time"
"github.com/google/agentmesh/api"
)
@@ -112,3 +113,113 @@ func TestSyncRecoversWhenControlPlaneForgotNode(t *testing.T) {
}
})
}
+
+// TestRecoverEnrollmentTrustsOnlyKnownKeys drives the real re-enrollment
+// exchange against a mock control plane. The node already has a trust
+// root; whoever answers the URL with a 401 and then an enrollment response
+// of its own making must not be able to replace it, and one attempt per
+// cooldown is all a 401 can cause.
+func TestRecoverEnrollmentTrustsOnlyKnownKeys(t *testing.T) {
+ prev := reenrollCooldown
+ reenrollCooldown = 50 * time.Millisecond
+ t.Cleanup(func() { reenrollCooldown = prev })
+
+ newHarness := func(t *testing.T, answer func(h *refreshHarness) *api.BootstrapEnrollResponse) (*refreshHarness, *atomic.Int32) {
+ t.Helper()
+ var enrolls atomic.Int32
+ harness := newRefreshHarness(t, func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "unexpected refresh", http.StatusInternalServerError)
+ })
+ mux := http.NewServeMux()
+ mux.HandleFunc("/keys", keysHandler(t, []ed25519.PublicKey{harness.cpPub}, []ed25519.PrivateKey{harness.cpPriv}))
+ mux.HandleFunc("/info", protoHandler(t, &api.ControlPlaneInfoResponse{}))
+ mux.HandleFunc("/policies", func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "Unauthorized: node credential required", http.StatusUnauthorized)
+ })
+ mux.HandleFunc("/enroll", func(w http.ResponseWriter, r *http.Request) {
+ enrolls.Add(1)
+ protoHandler(t, answer(harness))(w, r)
+ })
+ server := httptest.NewServer(mux)
+ t.Cleanup(server.Close)
+ if err := harness.node.Store.SaveControlPlaneURL(server.URL); err != nil {
+ t.Fatal(err)
+ }
+ tokenPath := filepath.Join(t.TempDir(), "join-token")
+ if err := os.WriteFile(tokenPath, []byte("mesh_tok_test"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ harness.node.config.BootstrapTokenPath = tokenPath
+ return harness, &enrolls
+ }
+
+ t.Run("an answer under an unknown key is refused and nothing is persisted", func(t *testing.T) {
+ _, roguePriv := mustGenerateKey(t)
+ roguePub := roguePriv.Public().(ed25519.PublicKey)
+ harness, enrolls := newHarness(t, func(h *refreshHarness) *api.BootstrapEnrollResponse {
+ return &api.BootstrapEnrollResponse{
+ Status: api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED,
+ BiscuitToken: mintRoleBiscuit(t, roguePriv, h.peerID, api.RoleNode),
+ ControlPlanePublicKey: roguePub,
+ RouterAddresses: []string{"/dns4/rogue.example/tcp/443/wss/p2p/12D3KooWDk5pWkyxVERi6kt3TyRZCaXWqg441QEQxaGkn5rWHB21"},
+ }
+ })
+ if err := harness.node.SyncControlPlane(context.Background()); err == nil {
+ t.Fatal("sync succeeded although the only enrollment answer came from an unknown key")
+ }
+ if enrolls.Load() != 1 {
+ t.Fatalf("enroll attempts = %d, want 1", enrolls.Load())
+ }
+ harness.storedIdentityUnchanged(t)
+ cpPub, _, err := harness.node.Store.LoadMeshConfig()
+ if err != nil {
+ t.Fatalf("LoadMeshConfig: %v", err)
+ }
+ if !ed25519.PublicKey(cpPub).Equal(harness.cpPub) {
+ t.Fatal("the pinned control plane key was replaced by the one in a refused answer")
+ }
+ if harness.node.isTrustedKey(roguePub) {
+ t.Fatal("the key from a refused answer entered the trust set")
+ }
+ })
+
+ t.Run("an answer under a trusted key is accepted", func(t *testing.T) {
+ harness, enrolls := newHarness(t, func(h *refreshHarness) *api.BootstrapEnrollResponse {
+ return &api.BootstrapEnrollResponse{
+ Status: api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED,
+ BiscuitToken: mintRoleBiscuit(t, h.cpPriv, h.peerID, api.RoleNode),
+ ControlPlanePublicKey: h.cpPub,
+ }
+ })
+ // /policies answers 401 for ever here, so the retried pull still
+ // fails; what matters is that the credential was accepted.
+ _ = harness.node.SyncControlPlane(context.Background())
+ if enrolls.Load() != 1 {
+ t.Fatalf("enroll attempts = %d, want 1", enrolls.Load())
+ }
+ if string(harness.node.GetIdentity()) == string(harness.identity) {
+ t.Fatal("the node kept its old credential after an answer under a trusted key")
+ }
+ })
+
+ t.Run("one attempt per cooldown", func(t *testing.T) {
+ harness, enrolls := newHarness(t, func(h *refreshHarness) *api.BootstrapEnrollResponse {
+ return &api.BootstrapEnrollResponse{
+ Status: api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED,
+ BiscuitToken: mintRoleBiscuit(t, h.cpPriv, h.peerID, api.RoleNode),
+ ControlPlanePublicKey: h.cpPub,
+ }
+ })
+ for range 3 {
+ _ = harness.node.SyncControlPlane(context.Background())
+ }
+ if enrolls.Load() != 1 {
+ t.Fatalf("enroll attempts within the cooldown = %d, want 1", enrolls.Load())
+ }
+ time.Sleep(2 * reenrollCooldown)
+ _ = harness.node.SyncControlPlane(context.Background())
+ if enrolls.Load() != 2 {
+ t.Fatalf("enroll attempts after the cooldown = %d, want 2", enrolls.Load())
+ }
+ })
+}
diff --git a/internal/node/enroll.go b/internal/node/enroll.go
index 32d51a64..d1191d42 100644
--- a/internal/node/enroll.go
+++ b/internal/node/enroll.go
@@ -18,6 +18,9 @@ import (
"bytes"
"context"
"crypto/ed25519"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
"fmt"
"io"
"net/http"
@@ -261,7 +264,7 @@ func (n *AgentMeshNode) joinRouters(ctx context.Context, controlPlaneURL string,
// EnrollBootstrap enrolls the node with the control plane using a pre-shared bootstrap token.
// If the enrollment status is PENDING, it polls the status endpoint until approved or rejected.
func (n *AgentMeshNode) EnrollBootstrap(ctx context.Context, controlPlaneURL string, bootstrapToken string) error {
- enrollResp, err := n.enrollBootstrapCredential(ctx, controlPlaneURL, bootstrapToken)
+ enrollResp, err := n.enrollBootstrapCredential(ctx, controlPlaneURL, bootstrapToken, false)
if err != nil {
return err
}
@@ -280,11 +283,22 @@ func (n *AgentMeshNode) EnrollBootstrap(ctx context.Context, controlPlaneURL str
// enrollBootstrapCredential is the HTTP half of EnrollBootstrap: it obtains
// a credential with the bootstrap token and persists it with the mesh
-// configuration, without attaching to routers. A node that is already on
-// the mesh and only needs the control plane to know it again (the control
-// plane lost its store) uses this half alone.
-func (n *AgentMeshNode) enrollBootstrapCredential(ctx context.Context, controlPlaneURL string, bootstrapToken string) (*api.BootstrapEnrollResponse, error) {
- pubKey := n.Host.Peerstore().PubKey(n.Host.ID())
+// configuration, without attaching to routers. With trustedOnly, for a node
+// that already has a trust root and only needs the control plane to know it
+// again (the control plane lost its store), the answer must verify under a
+// key the node already trusts; without it, first enrollment, the key in
+// the answer is trusted on first use.
+func (n *AgentMeshNode) enrollBootstrapCredential(ctx context.Context, controlPlaneURL string, bootstrapToken string, trustedOnly bool) (*api.BootstrapEnrollResponse, error) {
+ // The identity is the node key; the host, when there is one, carries
+ // the same key.
+ if n.config.PrivKey == nil {
+ return nil, errors.New("node has no private key")
+ }
+ pubKey := n.config.PrivKey.GetPublic()
+ peerID, err := peer.IDFromPublicKey(pubKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to derive peer ID: %w", err)
+ }
pubBytes, err := crypto.MarshalPublicKey(pubKey)
if err != nil {
return nil, fmt.Errorf("failed to marshal public key: %w", err)
@@ -298,13 +312,13 @@ func (n *AgentMeshNode) enrollBootstrapCredential(ctx context.Context, controlPl
client := controlPlaneHTTPClient(30 * time.Second)
resp, err := cpclient.DoWithChallengeRetry(ctx, client, time.Now, cpclient.DefaultEnrollBackoff, func(enrollTS int64) (*http.Request, error) {
- enrollSig, err := n.config.PrivKey.Sign(api.EnrollChallenge(n.Host.ID().String(), enrollTS))
+ enrollSig, err := n.config.PrivKey.Sign(api.EnrollChallenge(peerID.String(), enrollTS))
if err != nil {
return nil, fmt.Errorf("failed to sign enrollment challenge: %w", err)
}
req := &api.BootstrapEnrollRequest{
BootstrapToken: bootstrapToken,
- PeerId: n.Host.ID().String(),
+ PeerId: peerID.String(),
PublicKey: pubBytes,
RequestedRole: n.config.RequiredRole,
Labels: n.labels(),
@@ -355,7 +369,7 @@ func (n *AgentMeshNode) enrollBootstrapCredential(ctx context.Context, controlPl
}
u = u.JoinPath("enroll", "status")
q := u.Query()
- q.Set("peer_id", n.Host.ID().String())
+ q.Set("peer_id", peerID.String())
u.RawQuery = q.Encode()
statusURL := u.String()
ticker := time.NewTicker(2 * time.Second)
@@ -374,7 +388,7 @@ func (n *AgentMeshNode) enrollBootstrapCredential(ctx context.Context, controlPl
if err != nil {
return nil, fmt.Errorf("failed to create status request: %w", err)
}
- if err := cpclient.SetChallengeHeaders(hReq, n.config.PrivKey, api.EnrollStatusChallenge(n.Host.ID().String(), ts), ts); err != nil {
+ if err := cpclient.SetChallengeHeaders(hReq, n.config.PrivKey, api.EnrollStatusChallenge(peerID.String(), ts), ts); err != nil {
return nil, fmt.Errorf("failed to sign enrollment status challenge: %w", err)
}
return hReq, nil
@@ -426,7 +440,20 @@ func (n *AgentMeshNode) enrollBootstrapCredential(ctx context.Context, controlPl
return nil, fmt.Errorf("received invalid control plane public key size: %d bytes", len(enrollResp.ControlPlanePublicKey))
}
- if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, ed25519.PublicKey(enrollResp.ControlPlanePublicKey), n.config.RequiredRole, n.BiscuitTimeout); err != nil {
+ if trustedOnly {
+ // This node already has a trust root. Whoever answered may name any
+ // key in the response; only a credential that verifies under a key
+ // this node trusts, for this node, with the required role, replaces
+ // the one it holds, and a response naming another key is refused:
+ // a party able to answer the control plane URL would otherwise
+ // swap the trust root and the router list with a single 401.
+ if !n.isTrustedKey(enrollResp.ControlPlanePublicKey) {
+ return nil, fmt.Errorf("re-enrollment answer names a control plane key this node does not trust (%s); refusing to replace the trust root", keyFingerprintHex(enrollResp.ControlPlanePublicKey))
+ }
+ if err := n.verifyOwnBiscuit(enrollResp.BiscuitToken); err != nil {
+ return nil, fmt.Errorf("re-enrollment credential does not verify under a trusted control plane key: %w", err)
+ }
+ } else if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, ed25519.PublicKey(enrollResp.ControlPlanePublicKey), n.config.RequiredRole, n.BiscuitTimeout); err != nil {
return nil, fmt.Errorf("enrolled biscuit token lacks required role %q: %w", n.config.RequiredRole, err)
}
@@ -446,3 +473,21 @@ func (n *AgentMeshNode) enrollBootstrapCredential(ctx context.Context, controlPl
n.adoptEnrolledKeys(ctx, controlPlaneURL, enrollResp.ControlPlanePublicKey)
return enrollResp, nil
}
+
+// isTrustedKey reports whether pub is one of the control plane keys this
+// node trusts now.
+func (n *AgentMeshNode) isTrustedKey(pub []byte) bool {
+ for _, k := range n.getTrustedPublicKeys() {
+ if k.Equal(ed25519.PublicKey(pub)) {
+ return true
+ }
+ }
+ return false
+}
+
+// keyFingerprintHex identifies a public key in a message the way the
+// control plane and routers do in theirs.
+func keyFingerprintHex(pub []byte) string {
+ sum := sha256.Sum256(pub)
+ return hex.EncodeToString(sum[:8])
+}
diff --git a/internal/node/node.go b/internal/node/node.go
index a2294b34..6f9cd5c8 100644
--- a/internal/node/node.go
+++ b/internal/node/node.go
@@ -146,7 +146,10 @@ func (n *AgentMeshNode) isAdmitted(p peer.ID) bool {
type AgentMeshNode struct {
config Options
// enrollBootstrapFn is EnrollBootstrap unless a test injects the step.
- enrollBootstrapFn func(ctx context.Context, controlPlaneURL, bootstrapToken string) error
+ enrollBootstrapFn func(ctx context.Context, controlPlaneURL, bootstrapToken string) error
+ // lastReenroll is when recoverEnrollment last spent the bootstrap token.
+ lastReenroll time.Time
+ reenrollMu sync.Mutex
Host host.Host
Directory Directory
PubSub *pubsub.PubSub
diff --git a/internal/node/refresh_test.go b/internal/node/refresh_test.go
index 3efd7aed..c66510f5 100644
--- a/internal/node/refresh_test.go
+++ b/internal/node/refresh_test.go
@@ -106,7 +106,7 @@ func newRefreshHarness(t *testing.T, refresh http.HandlerFunc) *refreshHarness {
Store: store,
trustedKeys: []TrustedKey{{Key: cpPub, ReceivedAt: time.Now()}},
BiscuitTimeout: 500 * time.Millisecond,
- config: Options{RequiredRole: api.RoleNode},
+ config: Options{RequiredRole: api.RoleNode, PrivKey: privKey},
}
node.SetIdentityCache(current)
return &refreshHarness{node: node, cpPub: cpPub, cpPriv: cpPriv, peerID: peerID, identity: current}
diff --git a/internal/storage/sql_store.go b/internal/storage/sql_store.go
index 266e7dd1..7b1abd42 100644
--- a/internal/storage/sql_store.go
+++ b/internal/storage/sql_store.go
@@ -914,6 +914,59 @@ func (s *SQLStore) RotateKeys(ctx context.Context, newPriv ed25519.PrivateKey, n
return tx.Commit()
}
+// operatorKeyNoExpiry marks a key the operator lists for verification: valid
+// until the operator drops it, at which point SetKeyring gives it a grace
+// period. Far enough that no clock reaches it, finite so that the column
+// stays "not current".
+var operatorKeyNoExpiry = time.Date(9999, 12, 31, 0, 0, 0, 0, time.UTC)
+
+// SetKeyring implements Store.
+func (s *SQLStore) SetKeyring(ctx context.Context, current KeyPair, verifying []KeyPair, gracePeriod time.Duration) error {
+ if len(current.Public) == 0 {
+ return errors.New("SetKeyring: no current key")
+ }
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback() }()
+ now := time.Now()
+
+ if _, err := tx.ExecContext(ctx, s.rebind(`DELETE FROM keyring WHERE expiration IS NOT NULL AND expiration <= ?`), now.UnixMilli()); err != nil {
+ return err
+ }
+ upsert := s.rebind(`INSERT INTO keyring (private_key, public_key, expiration, created_at) VALUES (?, ?, ?, ?)
+ ON CONFLICT (public_key) DO UPDATE SET private_key = excluded.private_key, expiration = excluded.expiration`)
+ for _, k := range verifying {
+ if _, err := tx.ExecContext(ctx, upsert, []byte(k.Private), []byte(k.Public), operatorKeyNoExpiry.UnixMilli(), now.UnixMilli()); err != nil {
+ return err
+ }
+ }
+ if _, err := tx.ExecContext(ctx, upsert, []byte(current.Private), []byte(current.Public), nil, now.UnixMilli()); err != nil {
+ return err
+ }
+
+ // Every other key that is still valid: the one that was current before,
+ // or one the operator dropped from the file; both get the grace period
+ // unless they are already expiring sooner.
+ listed := make([]any, 0, len(verifying)+1)
+ placeholders := make([]string, 0, len(verifying)+1)
+ for _, k := range verifying {
+ listed = append(listed, []byte(k.Public))
+ placeholders = append(placeholders, "?")
+ }
+ listed = append(listed, []byte(current.Public))
+ placeholders = append(placeholders, "?")
+ grace := now.Add(gracePeriod).UnixMilli()
+ args := append([]any{grace}, listed...)
+ args = append(args, grace)
+ retire := s.rebind(`UPDATE keyring SET expiration = ? WHERE public_key NOT IN (` + strings.Join(placeholders, ", ") + `) AND (expiration IS NULL OR expiration > ?)`)
+ if _, err := tx.ExecContext(ctx, retire, args...); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
// SaveInitialKey implements Store.
func (s *SQLStore) SaveInitialKey(ctx context.Context, priv ed25519.PrivateKey, pub ed25519.PublicKey) error {
query := s.rebind(`INSERT INTO keyring (private_key, public_key, created_at) VALUES (?, ?, ?)`)
@@ -2185,6 +2238,49 @@ func (s *SQLStore) SaveInitialOIDCKey(ctx context.Context, kid string, priv, pub
return err
}
+// SetOIDCKeyring implements Store.
+func (s *SQLStore) SetOIDCKeyring(ctx context.Context, current OIDCKeyPair, verifying []OIDCKeyPair, gracePeriod time.Duration) error {
+ if current.Kid == "" {
+ return errors.New("SetOIDCKeyring: no current key")
+ }
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback() }()
+ now := time.Now()
+
+ if _, err := tx.ExecContext(ctx, s.rebind(`DELETE FROM oidc_keyring WHERE expiration IS NOT NULL AND expiration <= ?`), now.UnixMilli()); err != nil {
+ return err
+ }
+ upsert := s.rebind(`INSERT INTO oidc_keyring (kid, private_key, public_key, expiration, created_at) VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT (kid) DO UPDATE SET private_key = excluded.private_key, public_key = excluded.public_key, expiration = excluded.expiration`)
+ for _, k := range verifying {
+ if _, err := tx.ExecContext(ctx, upsert, k.Kid, k.PrivateKey, k.PublicKey, operatorKeyNoExpiry.UnixMilli(), now.UnixMilli()); err != nil {
+ return err
+ }
+ }
+ if _, err := tx.ExecContext(ctx, upsert, current.Kid, current.PrivateKey, current.PublicKey, nil, now.UnixMilli()); err != nil {
+ return err
+ }
+ listed := make([]any, 0, len(verifying)+1)
+ placeholders := make([]string, 0, len(verifying)+1)
+ for _, k := range verifying {
+ listed = append(listed, k.Kid)
+ placeholders = append(placeholders, "?")
+ }
+ listed = append(listed, current.Kid)
+ placeholders = append(placeholders, "?")
+ grace := now.Add(gracePeriod).UnixMilli()
+ args := append([]any{grace}, listed...)
+ args = append(args, grace)
+ retire := s.rebind(`UPDATE oidc_keyring SET expiration = ? WHERE kid NOT IN (` + strings.Join(placeholders, ", ") + `) AND (expiration IS NULL OR expiration > ?)`)
+ if _, err := tx.ExecContext(ctx, retire, args...); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
// RotateOIDCKeys implements Store.
func (s *SQLStore) RotateOIDCKeys(ctx context.Context, kid string, newPriv, newPub []byte, gracePeriod time.Duration) error {
tx, err := s.db.BeginTx(ctx, nil)
diff --git a/internal/storage/storage.go b/internal/storage/storage.go
index 80ccb070..6b59b8e5 100644
--- a/internal/storage/storage.go
+++ b/internal/storage/storage.go
@@ -260,6 +260,16 @@ type Store interface {
// SaveInitialKey sets the initial key pair if no keys exist yet.
SaveInitialKey(ctx context.Context, priv ed25519.PrivateKey, pub ed25519.PublicKey) error
+ // SetKeyring makes the keyring reflect a set the operator owns, in one
+ // transaction: current becomes the signing key, each of verifying stays
+ // valid for verification for as long as the operator lists it, and any
+ // other key still valid in the store is given gracePeriod to expire so
+ // that credentials it signed keep verifying meanwhile. Keys already
+ // present are updated in place, so the same set applied twice is a
+ // no-op and a key moved back to the front becomes current again.
+ // Expired rows are purged first.
+ SetKeyring(ctx context.Context, current KeyPair, verifying []KeyPair, gracePeriod time.Duration) error
+
// SaveUser creates or updates a User.
SaveUser(ctx context.Context, user *User) error
@@ -436,6 +446,9 @@ type Store interface {
// RotateOIDCKeys rotates the current ES256 key to a new key pair and sets the expiration of the old key.
RotateOIDCKeys(ctx context.Context, kid string, newPriv, newPub []byte, gracePeriod time.Duration) error
+ // SetOIDCKeyring is SetKeyring for the ES256 keyring, keyed by kid.
+ SetOIDCKeyring(ctx context.Context, current OIDCKeyPair, verifying []OIDCKeyPair, gracePeriod time.Duration) error
+
// SaveRevokedBiscuit persists a Biscuit revocation ID until its expiration time.
SaveRevokedBiscuit(ctx context.Context, revocationID string, expiresAt time.Time) error
diff --git a/site/content/docs/guides/cloud-run.md b/site/content/docs/guides/cloud-run.md
index e3f72875..032ed756 100644
--- a/site/content/docs/guides/cloud-run.md
+++ b/site/content/docs/guides/cloud-run.md
@@ -106,20 +106,24 @@ JWTs) the first key in the file signs and every later one only verifies.
{"algorithm": "ed25519", "fingerprint": "…"}` and `Operator signing keys
reloaded … "signing_key_changed": true`, `/keys` publishes both keys, new
credentials are signed by the new one, and a `KEY_ROTATION` event tells
- routers and nodes to refresh. Credentials signed by the previous key keep
- verifying for `--control-plane-key-grace-period` (default 1h) from the
- moment the new key was installed. Routers log `Control plane signing keys
- changed` with the fingerprints they now trust.
-3. **Wait out the overlap**: at least the grace period, and at least as long
- as the longest-lived credential the previous key signed (the Biscuit TTL
- for Ed25519, the STS JWT lifetime for P-256).
+ routers and nodes to refresh. A key stays valid for verification for as
+ long as you list it. Routers log `Control plane signing keys changed`
+ with the fingerprints they now trust.
+3. **Wait out the overlap**: at least as long as the longest-lived
+ credential the previous key signed (the Biscuit TTL for Ed25519, the STS
+ JWT lifetime for P-256).
4. **Drop the previous key** the same way:
```bash
cat ed25519-v2.pem p256-v1.pem | gcloud secrets versions add mesh-signing-keys --data-file=-
gcloud secrets versions destroy 1 --secret=mesh-signing-keys # when nothing may ever need it again
```
- On a running instance the dropped key stays valid until its grace period
- ends; a new instance never installs it.
+ A running instance gives the dropped key `--control-plane-key-grace-period`
+ (default 1h) before it stops verifying; a new instance never installs it.
+ Moving a previous key back to the front makes it the signing key again.
+
+The file must carry at least one key of each kind: owning the keys means
+owning both, and a file with only one kind is refused rather than leaving
+the other generated and unrotated.
What a verifier accepts is always `/keys`, signed by every valid key, so a
node still holding the previous key accepts the response that announces the
diff --git a/site/content/docs/reference/control-plane.md b/site/content/docs/reference/control-plane.md
index 74274742..d541ed5b 100644
--- a/site/content/docs/reference/control-plane.md
+++ b/site/content/docs/reference/control-plane.md
@@ -33,7 +33,7 @@ agentmesh-control-plane admin unban --peer <id> lift a ban
| `--auto-approve-enrollment` | `false` | Issue credentials for valid bootstrap-token enrollments immediately instead of queueing them for approval. |
| `--biscuit-ttl` | `24h` | Lifetime of each credential. If the OIDC token expires sooner, the credential expires with it. |
| `--oidc-session-ttl` | `2160h` (90 days) | How long a human OIDC enrollment may keep refreshing before the identity must log in again. |
-| `--signing-key-path` | | PEM file with the control plane's private signing keys (PKCS#8 or SEC 1): Ed25519 for Biscuits, P-256 for the ES256 JWTs behind `/sts/token` and `/jwks`. The first key of each kind signs, later ones only verify. The keys are installed into the store through the normal rotation path, so verifiers learn them from `/keys` and `/jwks` as after any rotation, and a key the control plane generated earlier stays valid for `--key-grace-period`. Turns automatic rotation off: rotate by publishing a new first key and keeping the previous one until every credential it signed has expired. `agentmesh_control_plane_operator_signing_keys{algorithm}` counts the keys loaded. |
+| `--signing-key-path` | | PEM file with the control plane's private signing keys (PKCS#8 or SEC 1): Ed25519 for Biscuits, P-256 for the ES256 JWTs behind `/sts/token` and `/jwks`. At least one key of each kind is required. The first key of each kind signs, later ones verify for as long as they are listed; a key the control plane generated earlier, or one dropped from the file, stays valid for `--key-grace-period`. Verifiers learn the set from `/keys` and `/jwks` as after any rotation. Turns automatic rotation off; the file is re-read every 30s, so rotation is publishing a new first key and keeping the previous one until every credential it signed has expired. `agentmesh_control_plane_operator_signing_keys{algorithm}` counts the keys loaded. |
| `--workload-session-ttl` | `48h` | How long a workload OIDC enrollment (`--workload-issuer`) may refresh without presenting a fresh platform JWT in `TokenRefreshRequest.jwt`. |
| `--key-rotation-interval` | `24h` | How often a new signing key is generated. `0` disables rotation. |
| `--key-grace-period` | `1h` | How long a rotated-out key stays accepted. Credentials signed by a retired key cannot be verified or refreshed. Nodes and routers must pull `/keys` well within this window (`agentmesh-node --control-plane-sync-interval`, `agentmesh-router --keys-sync-interval`). |
diff --git a/tests/integration/operator_keys_test.go b/tests/integration/operator_keys_test.go
index 9a9c78ea..8055fab9 100644
--- a/tests/integration/operator_keys_test.go
+++ b/tests/integration/operator_keys_test.go
@@ -16,10 +16,13 @@ package integration_test
import (
"context"
+ "crypto/ecdsa"
"crypto/ed25519"
+ "crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
+ "errors"
"fmt"
"io"
"net/http"
@@ -29,6 +32,7 @@ import (
"time"
"github.com/google/agentmesh/api"
+ cpclient "github.com/google/agentmesh/internal/controlplane/client"
"github.com/google/agentmesh/internal/identity"
"github.com/google/agentmesh/internal/node"
"github.com/google/agentmesh/internal/standalone"
@@ -62,7 +66,8 @@ func TestOperatorSigningKeyRotationProcess(t *testing.T) {
keyFile := filepath.Join(t.TempDir(), "signing-keys.pem")
v1, v2 := newOperatorEd25519(t), newOperatorEd25519(t)
- writeOperatorKeyFile(t, keyFile, v1)
+ es256 := newOperatorP256(t)
+ writeOperatorKeyFile(t, keyFile, es256, v1)
// The operator's grace period is the overlap during which a credential
// under the previous key still verifies.
@@ -112,7 +117,7 @@ func TestOperatorSigningKeyRotationProcess(t *testing.T) {
}
t.Run("live rotation without a restart", func(t *testing.T) {
- writeOperatorKeyFile(t, keyFile, v2, v1)
+ writeOperatorKeyFile(t, keyFile, es256, v2, v1)
// The control plane re-reads the file on its own timer; the test is
// time-bounded, so ask for the pass directly.
hub.ReloadOperatorSigningKeys()
@@ -156,7 +161,7 @@ func TestOperatorSigningKeyRotationProcess(t *testing.T) {
})
t.Run("dropping the previous key refuses what it signed", func(t *testing.T) {
- writeOperatorKeyFile(t, keyFile, v2)
+ writeOperatorKeyFile(t, keyFile, es256, v2)
if err := hub.Close(); err != nil {
t.Fatalf("hub.Close: %v", err)
}
@@ -166,12 +171,17 @@ func TestOperatorSigningKeyRotationProcess(t *testing.T) {
if err := identity.VerifyBiscuitRole(credV1, pubOf(v2), api.RoleNode, 5*time.Second); err == nil {
t.Fatal("a credential under the dropped key still verifies under the only published key")
}
- if err := meshNode.SyncControlPlane(ctx); err != nil {
- t.Fatalf("node did not recover after the key was dropped: %v", err)
- }
+ // The node's credential, issued under v2 by the previous recovery,
+ // still verifies; that recovery was moments ago, so the control
+ // plane's 401 on this fresh store is reported, not answered with
+ // another spend of the bootstrap token until the cooldown passes.
if err := identity.VerifyBiscuitRole(meshNode.GetIdentity(), pubOf(v2), api.RoleNode, 5*time.Second); err != nil {
t.Fatalf("node's credential after the drop does not verify under v2: %v", err)
}
+ var se *cpclient.StatusError
+ if err := meshNode.SyncControlPlane(ctx); !errors.As(err, &se) || se.Code != http.StatusUnauthorized {
+ t.Fatalf("sync within the re-enrollment cooldown = %v, want the control plane's 401 reported", err)
+ }
})
}
@@ -184,13 +194,29 @@ func newOperatorEd25519(t *testing.T) ed25519.PrivateKey {
return priv
}
+func newOperatorP256(t *testing.T) *ecdsa.PrivateKey {
+ t.Helper()
+ priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ t.Fatalf("ecdsa.GenerateKey: %v", err)
+ }
+ return priv
+}
+
func pubOf(k ed25519.PrivateKey) ed25519.PublicKey { return k.Public().(ed25519.PublicKey) }
-// writeOperatorKeyFile writes keys as PKCS#8 PEM blocks in order, the first
-// being the signing key, the way an operator publishes a rotation.
-func writeOperatorKeyFile(t *testing.T, path string, keys ...ed25519.PrivateKey) {
+// writeOperatorKeyFile writes keys as PKCS#8 PEM blocks in order; for each
+// kind the first is the signing key, the way an operator publishes a
+// rotation. The ES256 key is listed first here only so the Ed25519 order
+// reads left to right.
+func writeOperatorKeyFile(t *testing.T, path string, es256 *ecdsa.PrivateKey, keys ...ed25519.PrivateKey) {
t.Helper()
var data []byte
+ der, err := x509.MarshalPKCS8PrivateKey(es256)
+ if err != nil {
+ t.Fatalf("MarshalPKCS8PrivateKey (P-256): %v", err)
+ }
+ data = append(data, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})...)
for _, k := range keys {
der, err := x509.MarshalPKCS8PrivateKey(k)
if err != nil {