Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
controlplane: reload the operator's signing key file; test the rotation end to end
Antonio Ojea6b19ec27b493
diff --git a/internal/controlplane/metrics.go b/internal/controlplane/metrics.goindex 222baa40..a3a6a68c 100644--- a/internal/controlplane/metrics.go+++ b/internal/controlplane/metrics.go@@ -68,6 +68,15 @@ var (},[]string{"algorithm"},)++ // operatorSigningKeysReloadErrors counts the times the key file changed+ // but could not be read, parsed or installed; the keys in use stay.+ operatorSigningKeysReloadErrors = promauto.NewCounter(+ prometheus.CounterOpts{+ Name: "agentmesh_control_plane_operator_signing_keys_reload_errors_total",+ Help: "Times the operator signing key file could not be reloaded; the keys already in use were kept",+ },+ ))// observeRoute counts and times requests to one registered mux pattern. Thediff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex dd4a17f8..30b868dd 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -143,8 +143,10 @@ type Server struct {// embedders) starts no second resolver for the same issuer.resolving map[string]bool// operatorKeys are the signing keys the operator supplied, nil when the- // control plane generates and rotates its own.+ // control plane generates and rotates its own; operatorKeysMu guards it+ // against the file watcher.operatorKeys *operatorSigningKeys+ operatorKeysMu sync.Mutexproviders map[string]*oidc.ProviderworkloadIssuers map[string]boolworkloadEmailSuffixes map[string][]string@@ -309,16 +311,20 @@ func (s *Server) Init() error {// Initialize Keyringctx := context.Background()if s.operatorKeys != nil {- if err := reconcileEd25519Keyring(ctx, s.store, s.operatorKeys.ed25519, s.config.KeyGracePeriod); err != nil {+ // The ES256 half was installed in NewServer, before the signer loaded+ // from the store; this installs the Ed25519 half and is a no-op for+ // the other.+ if _, err := s.installOperatorSigningKeys(ctx, s.operatorKeys); err != nil {return fmt.Errorf("operator signing keys: %w", err)}- operatorSigningKeysGauge.WithLabelValues("ed25519").Set(float64(len(s.operatorKeys.ed25519)))- operatorSigningKeysGauge.WithLabelValues("es256").Set(float64(len(s.operatorKeys.es256)))logger.Infow("Signing keys are operator-managed; automatic key rotation is off","path", s.config.SigningKeyPath,"ed25519_keys", len(s.operatorKeys.ed25519),"es256_keys", len(s.operatorKeys.es256),+ "reload_interval", operatorSigningKeysReloadInterval.String(),"rotation", "put the new key first in the file and keep the previous one for the grace period")+ s.wg.Add(1)+ go s.watchOperatorSigningKeys()}_, _, err := s.store.GetCurrentKey(ctx)if err == storage.ErrNotFound {diff --git a/internal/controlplane/signingkeys.go b/internal/controlplane/signingkeys.goindex 29346312..0750f1a3 100644--- a/internal/controlplane/signingkeys.go+++ b/internal/controlplane/signingkeys.go@@ -28,6 +28,7 @@ import ("os""time"+ "github.com/google/agentmesh/api""github.com/google/agentmesh/internal/storage")@@ -46,6 +47,18 @@ import (type operatorSigningKeys struct {ed25519 []ed25519.PrivateKeyes256 []*ecdsa.PrivateKey+ // digest of the file content these keys came from, so the watcher+ // reconciles only when the operator published something new.+ digest [sha256.Size]byte+}++// currentEd25519 is the public key the file names as the Biscuit signing+// key, nil when the file carries no Ed25519 key.+func (k *operatorSigningKeys) currentEd25519() ed25519.PublicKey {+ if k == nil || len(k.ed25519) == 0 {+ return nil+ }+ return k.ed25519[0].Public().(ed25519.PublicKey)}// loadOperatorSigningKeys reads and validates the PEM file at path.@@ -54,6 +67,17 @@ func loadOperatorSigningKeys(path string) (*operatorSigningKeys, error) {if err != nil {return nil, fmt.Errorf("read signing keys: %w", err)}+ keys, err := parseOperatorSigningKeys(path, data)+ if err != nil {+ return nil, err+ }+ keys.digest = sha256.Sum256(data)+ return keys, nil+}++// parseOperatorSigningKeys validates the PEM content of the file at path.+func parseOperatorSigningKeys(path string, data []byte) (*operatorSigningKeys, error) {+ var err errorkeys := &operatorSigningKeys{}for block, rest := pem.Decode(data); block != nil; block, rest = pem.Decode(rest) {var parsed any@@ -209,3 +233,89 @@ func reconcileES256Keyring(ctx context.Context, store storage.Store, keys []*ecd}return nil}++// 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) {+ _, before, err := s.store.GetCurrentKey(ctx)+ if err != nil && !errors.Is(err, storage.ErrNotFound) {+ return false, fmt.Errorf("read current signing key: %w", err)+ }+ if err := reconcileES256Keyring(ctx, s.store, keys.es256, s.config.KeyGracePeriod); err != nil {+ return false, err+ }+ if err := reconcileEd25519Keyring(ctx, s.store, keys.ed25519, s.config.KeyGracePeriod); err != nil {+ return false, err+ }+ operatorSigningKeysGauge.WithLabelValues("ed25519").Set(float64(len(keys.ed25519)))+ operatorSigningKeysGauge.WithLabelValues("es256").Set(float64(len(keys.es256)))+ now := keys.currentEd25519()+ return now != nil && !before.Equal(now), nil+}++// operatorSigningKeysReloadInterval is how often the control plane looks at+// the key file for a change. A package variable so a test can shorten it.+var operatorSigningKeysReloadInterval = 30 * time.Second++// watchOperatorSigningKeys re-reads the key file on a timer and installs+// what changed, so that a rotation is the operator publishing a new file+// and nothing else: no restart, no redeploy. Polling rather than inotify,+// because a Kubernetes Secret volume updates through an atomic symlink swap+// and a Cloud Run secret volume through the platform, neither of which a+// watch on the file itself sees reliably. A file that fails to parse keeps+// the keys in use and is counted and logged; a change of the signing key+// is announced to the mesh the way automatic rotation announces one.+func (s *Server) watchOperatorSigningKeys() {+ defer s.wg.Done()+ ticker := time.NewTicker(operatorSigningKeysReloadInterval)+ defer ticker.Stop()+ for {+ select {+ case <-s.ctx.Done():+ return+ case <-ticker.C:+ }+ s.reloadOperatorSigningKeys()+ }+}++// ReloadOperatorSigningKeys is one pass of the key file watcher, for callers+// that cannot wait for its timer (tests, an operator signal).+func (s *Server) ReloadOperatorSigningKeys() {+ if s.operatorKeys == nil {+ return+ }+ s.reloadOperatorSigningKeys()+}++// reloadOperatorSigningKeys is one pass of watchOperatorSigningKeys.+func (s *Server) reloadOperatorSigningKeys() {+ keys, err := loadOperatorSigningKeys(s.config.SigningKeyPath)+ if err != nil {+ operatorSigningKeysReloadErrors.Inc()+ logger.Warnw("Operator signing keys not reloaded; keeping the keys in use", "path", s.config.SigningKeyPath, "error", err)+ return+ }+ s.operatorKeysMu.Lock()+ unchanged := s.operatorKeys != nil && keys.digest == s.operatorKeys.digest+ s.operatorKeysMu.Unlock()+ if unchanged {+ return+ }+ changed, err := s.installOperatorSigningKeys(s.ctx, keys)+ if err != nil {+ operatorSigningKeysReloadErrors.Inc()+ logger.Errorw("Operator signing keys changed but could not be installed", "path", s.config.SigningKeyPath, "error", err)+ return+ }+ s.operatorKeysMu.Lock()+ s.operatorKeys = keys+ s.operatorKeysMu.Unlock()+ logger.Infow("Operator signing keys reloaded", "path", s.config.SigningKeyPath,+ "ed25519_keys", len(keys.ed25519), "es256_keys", len(keys.es256), "signing_key_changed", changed)+ if changed {+ if err := s.getMeshAdapter().PublishEvent(s.ctx, api.MeshEvent_KEY_ROTATION, "", keys.currentEd25519()); err != nil {+ logger.Warnf("Failed to publish KEY_ROTATION event to mesh: %v", err)+ }+ }+}diff --git a/internal/controlplane/signingkeys_test.go b/internal/controlplane/signingkeys_test.goindex 71b36438..607f30cc 100644--- a/internal/controlplane/signingkeys_test.go+++ b/internal/controlplane/signingkeys_test.go@@ -378,3 +378,96 @@ func firstKid(jwks JSONWebKeySet) string {}return jwks.Keys[0].Kid}++// TestOperatorSigningKeysReload is a rotation as the operator performs it:+// the file changes under a running control plane and nothing is restarted.+// The new first key becomes the signing key, the previous one stays for+// verification, and a file that does not parse leaves the keys in use.+func TestOperatorSigningKeysReload(t *testing.T) {+ issuer, _ := startCustomMockOIDC(t)+ v1, v2 := newEd25519(t), newEd25519(t)+ ec := newP256(t)+ path := writeKeyFile(t, pemPKCS8(t, v1), pemPKCS8(t, ec))++ srv, store, baseURL := setupTestServer(t, issuer, func(o *Options) {+ o.SigningKeyPath = path+ })+ defer func() { _ = srv.Close() }()+ ctx := context.Background()+ pub := func(k ed25519.PrivateKey) ed25519.PublicKey { return k.Public().(ed25519.PublicKey) }+ keysOnWire := func(t *testing.T) map[string]bool {+ t.Helper()+ resp, err := http.Get(baseURL + "/keys")+ if err != nil {+ t.Fatalf("GET /keys: %v", err)+ }+ body, err := io.ReadAll(resp.Body)+ _ = resp.Body.Close()+ if err != nil {+ t.Fatalf("read /keys: %v", err)+ }+ var keys api.KeysResponse+ if err := proto.Unmarshal(body, &keys); err != nil {+ t.Fatalf("Unmarshal KeysResponse: %v", err)+ }+ out := map[string]bool{}+ for _, k := range keys.PublicKeys {+ out[string(k)] = true+ }+ return out+ }++ // No change: a reload pass installs nothing.+ srv.reloadOperatorSigningKeys()+ if got := keysOnWire(t); len(got) != 1 || !got[string(pub(v1))] {+ t.Fatalf("/keys after a no-op reload = %d keys, want only v1", len(got))+ }++ // A file that does not parse is refused and the keys in use stay.+ if err := os.WriteFile(path, []byte("-----BEGIN GARBAGE-----\nAAAA\n-----END GARBAGE-----\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ srv.reloadOperatorSigningKeys()+ if got := keysOnWire(t); len(got) != 1 || !got[string(pub(v1))] {+ t.Fatalf("/keys after a bad file = %d keys, want only v1 kept", len(got))+ }++ // The rotation: v2 first, v1 kept.+ if err := os.WriteFile(path, append(append(pemPKCS8(t, v2), pemPKCS8(t, v1)...), pemPKCS8(t, ec)...), 0o600); err != nil {+ t.Fatal(err)+ }+ srv.reloadOperatorSigningKeys()+ got := keysOnWire(t)+ if len(got) != 2 || !got[string(pub(v1))] || !got[string(pub(v2))] {+ t.Fatalf("/keys after rotation = %d keys, want v1 and v2", len(got))+ }+ _, current, err := store.GetCurrentKey(ctx)+ if err != nil {+ t.Fatalf("GetCurrentKey: %v", err)+ }+ if !current.Equal(pub(v2)) {+ t.Fatalf("signing key after rotation = %s, want %s (v2, first in the file)", keyFingerprint(current), keyFingerprint(pub(v2)))+ }+ // The ES256 key did not change and was not reinstalled.+ all, err := store.GetAllValidOIDCKeys(ctx)+ if err != nil {+ t.Fatalf("GetAllValidOIDCKeys: %v", err)+ }+ if len(all) != 1 {+ t.Fatalf("ES256 keys after a rotation of the Ed25519 key = %d, want 1", len(all))+ }++ // Dropping v1 from the file: v2 stays current, v1 keeps verifying until+ // its grace period ends (the store's business, not the file's).+ if err := os.WriteFile(path, append(pemPKCS8(t, v2), pemPKCS8(t, ec)...), 0o600); err != nil {+ t.Fatal(err)+ }+ srv.reloadOperatorSigningKeys()+ _, current, err = store.GetCurrentKey(ctx)+ if err != nil {+ t.Fatalf("GetCurrentKey: %v", err)+ }+ if !current.Equal(pub(v2)) {+ t.Fatalf("signing key after dropping v1 = %s, want %s (v2)", keyFingerprint(current), keyFingerprint(pub(v2)))+ }+}diff --git a/internal/node/controlplane_sync.go b/internal/node/controlplane_sync.goindex 20334c3d..68015d4d 100644--- a/internal/node/controlplane_sync.go+++ b/internal/node/controlplane_sync.go@@ -45,7 +45,20 @@ import (// stop a key rotation from landing; the errors are reported together. Called// once before Start, so the node dials the routers the control plane knows// now and enforces the bans it holds now, and then by the sync loop.+//+// A 401 to this node's own calls means the control plane no longer knows+// it (a control plane that lost its store but kept its keys); with a+// bootstrap token at hand the node enrolls again and the pull is repeated+// once.func (n *AgentMeshNode) SyncControlPlane(ctx context.Context) error {+ err := n.syncControlPlaneOnce(ctx)+ if err != nil && n.controlPlaneForgotUs(err) && n.recoverEnrollment(ctx) {+ return n.syncControlPlaneOnce(ctx)+ }+ return err+}++func (n *AgentMeshNode) syncControlPlaneOnce(ctx context.Context) error {if n.Store == nil {return errors.New("node has no store")}@@ -333,9 +346,6 @@ func (n *AgentMeshNode) startControlPlaneSyncLoop(ctx context.Context, intervaltimer.Reset(interval + time.Duration(rand.Int63n(int64(interval/10)+1)))err := n.SyncControlPlane(ctx)- if err != nil && n.controlPlaneForgotUs(err) && n.recoverEnrollment(ctx) {- err = n.SyncControlPlane(ctx)- }switch {case err != nil && failures == 0:logger.Warnf("Control plane sync failed: %v", err)diff --git a/internal/node/controlplane_sync_test.go b/internal/node/controlplane_sync_test.goindex b246193e..aadb6ad3 100644--- a/internal/node/controlplane_sync_test.go+++ b/internal/node/controlplane_sync_test.go@@ -72,19 +72,17 @@ func TestSyncRecoversWhenControlPlaneForgotNode(t *testing.T) {return nil}- err := harness.node.SyncControlPlane(context.Background())+ err := harness.node.syncControlPlaneOnce(context.Background())if !harness.node.controlPlaneForgotUs(err) {t.Fatalf("sync error = %v, want a 401 the node recognizes as a forgotten enrollment", err)}- if !harness.node.recoverEnrollment(context.Background()) {- t.Fatal("recoverEnrollment returned false with a readable bootstrap token")+ // One SyncControlPlane recovers and completes the pull.+ if err := harness.node.SyncControlPlane(context.Background()); err != nil {+ t.Fatalf("sync with recovery: %v", err)}if enrolledWith != "mesh_tok_test" {t.Fatalf("enrolled with %q, want the trimmed token from the file", enrolledWith)}- if err := harness.node.SyncControlPlane(context.Background()); err != nil {- t.Fatalf("sync after re-enrollment: %v", err)- }})t.Run("without a token path it waits for the renewal loop", func(t *testing.T) {@@ -93,10 +91,7 @@ func TestSyncRecoversWhenControlPlaneForgotNode(t *testing.T) {harness.node.enrollBootstrapFn = func(context.Context, string, string) error { called = true; return nil }err := harness.node.SyncControlPlane(context.Background())if !harness.node.controlPlaneForgotUs(err) {- t.Fatalf("sync error = %v, want a recognized 401", err)- }- if harness.node.recoverEnrollment(context.Background()) {- t.Fatal("recoverEnrollment returned true without a bootstrap token path")+ t.Fatalf("sync error = %v, want the 401 passed through when there is no token to recover with", err)}if called {t.Fatal("enrollment attempted without a token")diff --git a/internal/router/router.go b/internal/router/router.goindex d0821de1..4ce31fb2 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -18,7 +18,9 @@ import ("bytes""context""crypto/ed25519"+ "crypto/sha256""encoding/base64"+ "encoding/hex""errors""fmt""net"@@ -912,10 +914,21 @@ func (r *Router) syncKeys() error {}r.keysMu.Lock()+ changed := !samePublicKeys(r.trustedPublicKeys, newKeys)r.trustedPublicKeys = newKeysr.credential.pin(newKeys)refresh := r.credential.predatesRotation(newKeys)r.keysMu.Unlock()+ if changed {+ // The set a member's credential is verified against; a refusal+ // with "no valid key found" is read against this line.+ fps := make([]string, 0, len(newKeys))+ for _, k := range newKeys {+ sum := sha256.Sum256(k)+ fps = append(fps, hex.EncodeToString(sum[:8]))+ }+ logger.Infow("Control plane signing keys changed", "keys", len(newKeys), "fingerprints", fps, "credential_refresh", refresh)+ }if refresh {if err := r.RefreshEnrollment(r.ctx); err != nil {@@ -2000,3 +2013,20 @@ func (r *Router) verifyOwnBiscuit(token []byte, peerID peer.ID) error {}return identity.VerifyBiscuitRole(token, key, r.config.RequiredRole, r.config.BiscuitTimeout)}++// samePublicKeys reports whether a and b hold the same keys in any order.+func samePublicKeys(a, b []ed25519.PublicKey) bool {+ if len(a) != len(b) {+ return false+ }+ seen := make(map[string]bool, len(a))+ for _, k := range a {+ seen[string(k)] = true+ }+ for _, k := range b {+ if !seen[string(k)] {+ return false+ }+ }+ return true+}diff --git a/internal/standalone/standalone.go b/internal/standalone/standalone.goindex e8ad74b5..6ab1c7fa 100644--- a/internal/standalone/standalone.go+++ b/internal/standalone/standalone.go@@ -471,6 +471,10 @@ func (s *Server) PublicURL() string {// AdminToken returns the resolved admin API token.func (s *Server) AdminToken() string { return s.adminToken }+// ReloadOperatorSigningKeys re-reads the operator's signing key file now+// instead of at the watcher's next tick. A no-op without --signing-key-path.+func (s *Server) ReloadOperatorSigningKeys() { s.cp.ReloadOperatorSigningKeys() }+// JoinToken returns the resolved cluster join token, or "" when the server// runs with DisableJoinToken.func (s *Server) JoinToken() string { return s.joinToken }diff --git a/site/content/docs/guides/cloud-run.md b/site/content/docs/guides/cloud-run.mdindex 0138d19a..e3f72875 100644--- a/site/content/docs/guides/cloud-run.md+++ b/site/content/docs/guides/cloud-run.md@@ -58,7 +58,8 @@ Without PostgreSQL every revision starts from an empty store, which meansnew signing keys: every credential the mesh issued stops verifying until eachnode re-enrolls. If you want the root of trust in your hands anyway, keep thekeys in Secret Manager (wrap the secret with your own Cloud KMS key if you-want) and mount them as a file; do the same with the policy:+want: `--kms-key-name` on `gcloud secrets create`) and mount them as a file;+do the same with the policy:```bashopenssl genpkey -algorithm ed25519 -out ed25519-v1.pem@@ -76,19 +77,57 @@ gcloud run services update agentmesh-one --project "$PROJECT" --region "$REGION"(Cloud Run mounts one secret per directory, hence the two paths.) Thecontrol plane installs the keys and seeds the policy on every start, so a new-revision changes neither; credentials issued before it keep verifying, and-`/keys` and `/jwks` publish the same keys. Automatic rotation is off while the-file is present; **you rotate**: generate the new key, put it first in the-file, keep the previous one until every credential it signed has expired-(the Biscuit TTL for Ed25519, the STS JWT lifetime for P-256), publish the new-secret version, roll a revision, then drop the old key the same way.--What this does not keep is the enrollment records. A node's own calls to the-control plane (policy sync, catalog, refresh) answer `401 node credential-required` after a revision; a node started with `--bootstrap-token-path`-notices that at its next sync and enrolls again with the token, without a-restart, and the data plane is unaffected in the meantime. PostgreSQL keeps-the records too.+revision changes neither: credentials issued before it keep verifying, and+`/keys` and `/jwks` publish the same keys. While the file is present the+control plane never generates or rotates a key on its own; it re-reads the+file every 30 seconds and installs what changed, and the log says+`Signing keys are operator-managed; automatic key rotation is off`.++Nodes started with `--bootstrap-token-path` complete the picture: after a+revision the control plane does not know them (enrollment records live in+the store), they notice at their next sync (`401 node credential required`)+and enroll again with the token, without a restart. PostgreSQL keeps the+records too, and is what you want for durable revocations.++#### Rotating the keys++Rotation is yours, and it is an edit to the file; nothing is restarted or+redeployed. For each kind of key (Ed25519 for Biscuits, P-256 for the ES256+JWTs) the first key in the file signs and every later one only verifies.++1. **Generate** the new key where you keep keys (never on the control plane):+ `openssl genpkey -algorithm ed25519 -out ed25519-v2.pem`.+2. **Publish the overlap**: new key first, the previous one kept after it.+ ```bash+ cat ed25519-v2.pem ed25519-v1.pem p256-v1.pem | gcloud secrets versions add mesh-signing-keys --data-file=-+ ```+ Cloud Run updates the mounted `latest` in the running instance; within+ about a minute the control plane logs `Installed operator signing key+ {"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).+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.++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+new one. The two kinds of key rotate independently.++The whole procedure, including a control plane that restarts with an empty+store between steps, is exercised by+`TestOperatorSigningKeyRotationProcess` in `tests/integration`.Why each Cloud Run flag matters:diff --git a/tests/integration/operator_keys_test.go b/tests/integration/operator_keys_test.gonew file mode 100644index 00000000..9a9c78ea--- /dev/null+++ b/tests/integration/operator_keys_test.go@@ -0,0 +1,282 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package integration_test++import (+ "context"+ "crypto/ed25519"+ "crypto/rand"+ "crypto/x509"+ "encoding/pem"+ "fmt"+ "io"+ "net/http"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/google/agentmesh/api"+ "github.com/google/agentmesh/internal/identity"+ "github.com/google/agentmesh/internal/node"+ "github.com/google/agentmesh/internal/standalone"+ "github.com/libp2p/go-libp2p/core/crypto"+ "google.golang.org/protobuf/proto"+)++// TestOperatorSigningKeyRotationProcess runs the rotation an operator+// performs on a control plane whose signing keys come from a file they own+// (--signing-key-path), end to end against a stock node:+//+// 1. live rotation: the operator publishes a new file with the new key+// first and the previous one kept; the running control plane picks it+// up, publishes both on /keys, signs with the new one, and the node+// refreshes to a credential under the new key without a restart;+// 2. a control plane that restarts with an empty store (agentmesh-one on+// Cloud Run without a database) comes back on the same keys, the node's+// credential still verifies, and the node, which the control plane no+// longer knows, enrolls again with its bootstrap token on its own;+// 3. the operator drops the previous key: a credential under it is refused,+// the node already holds one under the new key and keeps working.+func TestOperatorSigningKeyRotationProcess(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ defer cancel()++ const joinToken = "mesh_tok_operator_keys_test"+ const adminToken = "mesh_adm_operator_keys_test"+ port := getFreePort(t)+ bind := fmt.Sprintf("127.0.0.1:%d", port)+ controlPlaneURL := "http://" + bind++ keyFile := filepath.Join(t.TempDir(), "signing-keys.pem")+ v1, v2 := newOperatorEd25519(t), newOperatorEd25519(t)+ writeOperatorKeyFile(t, keyFile, v1)++ // The operator's grace period is the overlap during which a credential+ // under the previous key still verifies.+ startHub := func(t *testing.T, dataDir string) *standalone.Server {+ t.Helper()+ srv, err := standalone.New(standalone.Options{+ BindAddress: bind,+ DataDir: dataDir,+ JoinToken: joinToken,+ AdminToken: adminToken,+ ControlPlane: standalone.ControlPlaneTunables{+ SigningKeyPath: keyFile,+ KeyGracePeriod: time.Hour,+ },+ })+ if err != nil {+ t.Fatalf("standalone.New: %v", err)+ }+ if err := srv.Start(ctx); err != nil {+ t.Fatalf("standalone.Start: %v", err)+ }+ waitForActiveRouters(t, port, 1, 10*time.Second)+ return srv+ }+ hub := startHub(t, t.TempDir())++ // A stock node with the bootstrap token in a file, as a Kubernetes+ // Secret or a Cloud Run secret mounts it, and a short sync so the test+ // sees it act.+ tokenPath := filepath.Join(t.TempDir(), "join-token")+ if err := os.WriteFile(tokenPath, []byte(joinToken), 0o600); err != nil {+ t.Fatal(err)+ }+ meshNode := newOperatorKeysTestNode(t, ctx, tokenPath)+ if err := meshNode.EnrollBootstrap(ctx, controlPlaneURL, joinToken); err != nil {+ t.Fatalf("EnrollBootstrap: %v", err)+ }+ // The CLI records the control plane the node joined; the sync and the+ // recovery read it from there.+ if err := meshNode.Store.SaveControlPlaneURL(controlPlaneURL); err != nil {+ t.Fatalf("SaveControlPlaneURL: %v", err)+ }+ credV1 := append([]byte(nil), meshNode.GetIdentity()...)+ assertKeysOnWire(t, controlPlaneURL, pubOf(v1))+ if err := identity.VerifyBiscuitRole(credV1, pubOf(v1), api.RoleNode, 5*time.Second); err != nil {+ t.Fatalf("credential issued under v1 does not verify under v1: %v", err)+ }++ t.Run("live rotation without a restart", func(t *testing.T) {+ writeOperatorKeyFile(t, keyFile, 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()+ assertKeysOnWire(t, controlPlaneURL, pubOf(v1), pubOf(v2))++ // The node learns the new key and refreshes to a credential under it;+ // the credential it held under v1 keeps verifying meanwhile.+ if err := meshNode.SyncControlPlane(ctx); err != nil {+ t.Fatalf("sync after rotation: %v", err)+ }+ credV2 := meshNode.GetIdentity()+ if err := identity.VerifyBiscuitRole(credV2, pubOf(v2), api.RoleNode, 5*time.Second); err != nil {+ t.Fatalf("node's credential after the rotation does not verify under v2: %v", err)+ }+ if err := identity.VerifyBiscuitRole(credV1, pubOf(v1), api.RoleNode, 5*time.Second); err != nil {+ t.Fatalf("credential under the previous key stopped verifying during the overlap: %v", err)+ }+ })++ t.Run("restart with an empty store keeps the keys", func(t *testing.T) {+ if err := hub.Close(); err != nil {+ t.Fatalf("hub.Close: %v", err)+ }+ hub = startHub(t, t.TempDir())+ assertKeysOnWire(t, controlPlaneURL, pubOf(v1), pubOf(v2))++ // The control plane does not know the node any more; the node's+ // sync answers the 401 by enrolling again with the token it holds+ // and completes the pull, which shows as a new credential.+ before := append([]byte(nil), meshNode.GetIdentity()...)+ if err := meshNode.SyncControlPlane(ctx); err != nil {+ t.Fatalf("sync against the fresh store did not recover: %v", err)+ }+ after := meshNode.GetIdentity()+ if string(after) == string(before) {+ t.Fatal("node kept its credential; the control plane cannot know it without a new enrollment")+ }+ if err := identity.VerifyBiscuitRole(after, pubOf(v2), api.RoleNode, 5*time.Second); err != nil {+ t.Fatalf("re-enrolled credential does not verify under v2: %v", err)+ }+ })++ t.Run("dropping the previous key refuses what it signed", func(t *testing.T) {+ writeOperatorKeyFile(t, keyFile, v2)+ if err := hub.Close(); err != nil {+ t.Fatalf("hub.Close: %v", err)+ }+ hub = startHub(t, t.TempDir())+ t.Cleanup(func() { _ = hub.Close() })+ assertKeysOnWire(t, controlPlaneURL, pubOf(v2))+ 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)+ }+ 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)+ }+ })+}++func newOperatorEd25519(t *testing.T) ed25519.PrivateKey {+ t.Helper()+ _, priv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatalf("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) {+ t.Helper()+ var data []byte+ for _, k := range keys {+ der, err := x509.MarshalPKCS8PrivateKey(k)+ if err != nil {+ t.Fatalf("MarshalPKCS8PrivateKey: %v", err)+ }+ data = append(data, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})...)+ }+ tmp := path + ".tmp"+ if err := os.WriteFile(tmp, data, 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Rename(tmp, path); err != nil {+ t.Fatal(err)+ }+}++// assertKeysOnWire checks that /keys publishes exactly want.+func assertKeysOnWire(t *testing.T, controlPlaneURL string, want ...ed25519.PublicKey) {+ t.Helper()+ resp, err := http.Get(controlPlaneURL + "/keys")+ if err != nil {+ t.Fatalf("GET /keys: %v", err)+ }+ body, err := io.ReadAll(resp.Body)+ _ = resp.Body.Close()+ if err != nil {+ t.Fatalf("read /keys: %v", err)+ }+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("GET /keys = %d: %s", resp.StatusCode, body)+ }+ var keys api.KeysResponse+ if err := proto.Unmarshal(body, &keys); err != nil {+ t.Fatalf("Unmarshal KeysResponse: %v", err)+ }+ got := map[string]bool{}+ for _, k := range keys.PublicKeys {+ got[string(k)] = true+ }+ if len(got) != len(want) {+ t.Fatalf("/keys publishes %d keys, want %d", len(got), len(want))+ }+ for _, w := range want {+ if !got[string(w)] {+ t.Fatalf("/keys is missing a key the operator's file holds")+ }+ }+}++func newOperatorKeysTestNode(t *testing.T, ctx context.Context, bootstrapTokenPath string) *node.AgentMeshNode {+ t.Helper()+ nodeStore, err := node.NewStore(t.TempDir())+ if err != nil {+ t.Fatalf("node.NewStore: %v", err)+ }+ t.Cleanup(func() { _ = nodeStore.Close() })+ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)+ if err != nil {+ t.Fatalf("GenerateKeyPair: %v", err)+ }+ // The CLI persists the node key; a credential refresh signs with it.+ privBytes, err := crypto.MarshalPrivateKey(priv)+ if err != nil {+ t.Fatalf("MarshalPrivateKey: %v", err)+ }+ if err := nodeStore.SaveKey(privBytes); err != nil {+ t.Fatalf("SaveKey: %v", err)+ }+ meshNode, err := node.NewAgentMeshNode(node.Options{+ PrivKey: priv,+ Store: nodeStore,+ ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},+ AllowLoopback: true,+ RequiredRole: api.RoleNode,+ BootstrapTokenPath: bootstrapTokenPath,+ })+ if err != nil {+ t.Fatalf("NewAgentMeshNode: %v", err)+ }+ if err := meshNode.Start(ctx); err != nil {+ t.Fatalf("node.Start: %v", err)+ }+ t.Cleanup(func() {+ if meshNode.Host != nil {+ _ = meshNode.Host.Close()+ }+ })+ return meshNode+}