From 63887e838807b78622cc2d7ff8de2654bff9fa08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ersin=20KO=C3=87?= Date: Wed, 25 Nov 2026 21:59:13 +0200 Subject: [PATCH 1/2] controlplane: keep a catalog report written while the GC sweep runs pruneCatalog picked the reports to drop from a snapshot taken before it listed the admitted nodes, then deleted them from the live map. A node whose session had lapsed could enroll again and report between the list and the delete, and lose its fresh report until its next push. Drop only an entry that is still the one the snapshot saw, and log the one kept. --- internal/controlplane/node_gc.go | 18 +++++--- internal/controlplane/node_gc_test.go | 63 +++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 5 deletions(-) diff --git a/internal/controlplane/node_gc.go b/internal/controlplane/node_gc.go index 3723e34f5..22e42742b 100644 --- a/internal/controlplane/node_gc.go +++ b/internal/controlplane/node_gc.go @@ -184,12 +184,20 @@ func (s *Server) pruneCatalog(now time.Time) { } dropped := 0 s.catalogMu.Lock() - for peerID := range snap { - if _, ok := keep[peerID]; !ok { - delete(s.catalog, peerID) - logger.Debugw("Dropped service report of a node no longer admitted", "peer_id", peerID) - dropped++ + for peerID, seen := range snap { + if _, ok := keep[peerID]; ok { + continue } + // A report written since the snapshot came from a node admitted + // when it reported, after the list was read: it is not this + // sweep's to drop. + if cur, ok := s.catalog[peerID]; ok && !cur.ReportedAt.Equal(seen.ReportedAt) { + logger.Debugw("Kept service report written during the sweep", "peer_id", peerID) + continue + } + delete(s.catalog, peerID) + logger.Debugw("Dropped service report of a node no longer admitted", "peer_id", peerID) + dropped++ } remaining := len(s.catalog) s.catalogMu.Unlock() diff --git a/internal/controlplane/node_gc_test.go b/internal/controlplane/node_gc_test.go index b8573556b..a3cb8cdd3 100644 --- a/internal/controlplane/node_gc_test.go +++ b/internal/controlplane/node_gc_test.go @@ -300,3 +300,66 @@ func TestGCExpiredNodesDefaultsRetention(t *testing.T) { t.Fatalf("after a sweep with the default retention got %+v, want only recent", nodes) } } + +// listHookStore runs afterList once, after ListNodes has read the table and +// before its caller sees the result. +type listHookStore struct { + storage.Store + afterList func() +} + +func (s *listHookStore) ListNodes(ctx context.Context, filter storage.NodeFilter) ([]storage.EnrolledNode, error) { + nodes, err := s.Store.ListNodes(ctx, filter) + if hook := s.afterList; hook != nil { + s.afterList = nil + hook() + } + return nodes, err +} + +// A node whose session lapsed enrolls again and reports its services while +// the sweep is between listing the admitted nodes and pruning: its new +// report belongs to an admitted node and must survive the sweep, which only +// forgets the reports it saw before it listed. +func TestPruneCatalogKeepsAReportWrittenDuringTheSweep(t *testing.T) { + base := newMetricsTestStore(t) + store := &listHookStore{Store: base} + ctx := context.Background() + now := time.Now() + enroll := func(id string, expiresAt time.Time) { + t.Helper() + if err := base.EnrollNode(ctx, &storage.EnrolledNode{ + PeerID: id, PublicKey: []byte("pub"), Biscuit: []byte("b"), Role: api.RoleNode, + EnrollmentType: "OIDC", EnrolledAt: now.Add(-time.Hour), ExpiresAt: expiresAt, + }); err != nil { + t.Fatalf("enroll %s: %v", id, err) + } + } + enroll("lapsed", now.Add(-time.Minute)) + + srv, err := NewServer(Options{DriverName: "sqlite", DataSourceName: "unused", OIDCIssuer: "https://issuer"}, store) + if err != nil { + t.Fatal(err) + } + defer func() { _ = srv.Close() }() + srv.catalog["lapsed"] = nodeCatalogEntry{ReportedAt: now.Add(-time.Hour)} + srv.catalog["gone"] = nodeCatalogEntry{ReportedAt: now.Add(-time.Hour)} + + fresh := now.Add(time.Second) + store.afterList = func() { + enroll("lapsed", now.Add(time.Hour)) + srv.catalogMu.Lock() + srv.catalog["lapsed"] = nodeCatalogEntry{ReportedAt: fresh} + srv.catalogMu.Unlock() + } + + srv.pruneCatalog(now) + + snap := srv.catalogSnapshot() + if entry, ok := snap["lapsed"]; !ok || !entry.ReportedAt.Equal(fresh) { + t.Fatalf("report of the re-admitted node after the sweep: present=%v reported_at=%s, want the report written at %s", ok, entry.ReportedAt, fresh) + } + if _, ok := snap["gone"]; ok { + t.Fatal("the sweep kept the report of a node that is not enrolled") + } +} From b7a765274c5d26e2070c38e9258866d1360116dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ersin=20KO=C3=87?= Date: Wed, 25 Nov 2026 21:59:14 +0200 Subject: [PATCH 2/2] controlplane: refuse an operator key file with a damaged PEM block pem.Decode skips a block whose body or BEGIN/END line is damaged and returns the next one, so a damaged first key left the second key signing, and a file read mid-write lost its last block, all without an error. The file is now refused unless every block it marks decodes, so a reload keeps the keys in use and counts the failure, as documented. Reading the keyring back after an install no longer turns a read error into an empty valid_after list: the failure is logged with its error. --- internal/controlplane/signingkeys.go | 43 ++++++---- internal/controlplane/signingkeys_log_test.go | 84 +++++++++++++++++++ internal/controlplane/signingkeys_test.go | 34 ++++++++ 3 files changed, 147 insertions(+), 14 deletions(-) create mode 100644 internal/controlplane/signingkeys_log_test.go diff --git a/internal/controlplane/signingkeys.go b/internal/controlplane/signingkeys.go index a688d2f57..1c7d3b77c 100644 --- a/internal/controlplane/signingkeys.go +++ b/internal/controlplane/signingkeys.go @@ -15,6 +15,7 @@ package controlplane import ( + "bytes" "context" "crypto/ecdsa" "crypto/ed25519" @@ -81,7 +82,9 @@ func loadOperatorSigningKeys(path string) (*operatorSigningKeys, error) { func parseOperatorSigningKeys(path string, data []byte) (*operatorSigningKeys, error) { var err error keys := &operatorSigningKeys{} + decoded := 0 for block, rest := pem.Decode(data); block != nil; block, rest = pem.Decode(rest) { + decoded++ var parsed any switch block.Type { case "PRIVATE KEY": @@ -106,6 +109,14 @@ 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) } } + // pem.Decode skips a block whose body does not decode, or whose BEGIN + // or END line is damaged, and returns the next one: a damaged first key + // would leave the next key signing. Every block the file marks must + // decode. + begun, ended := bytes.Count(data, []byte("-----BEGIN ")), bytes.Count(data, []byte("-----END ")) + if marked := max(begun, ended); marked != decoded { + return nil, fmt.Errorf("signing keys %s: %d of %d PEM blocks do not decode (damaged or truncated)", path, marked-decoded, marked) + } // 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 { @@ -150,13 +161,12 @@ func reconcileEd25519Keyring(ctx context.Context, store storage.Store, keys []ed if err := store.SetKeyring(ctx, current, verifying, gracePeriod); err != nil { return fmt.Errorf("set signing keys: %w", err) } - logKeyringChange("ed25519", keyPairFingerprints(before), func() []string { - after, err := store.GetAllValidKeys(ctx) - if err != nil { - return nil - } - return keyPairFingerprints(after) - }(), keyFingerprint(current.Public)) + after, err := store.GetAllValidKeys(ctx) + if err != nil { + logKeyringUnread("ed25519", keyFingerprint(current.Public), err) + return nil + } + logKeyringChange("ed25519", keyPairFingerprints(before), keyPairFingerprints(after), keyFingerprint(current.Public)) return nil } @@ -197,13 +207,12 @@ func reconcileES256Keyring(ctx context.Context, store storage.Store, keys []*ecd if err := store.SetOIDCKeyring(ctx, current, verifying, gracePeriod); err != nil { return fmt.Errorf("set ES256 keys: %w", err) } - logKeyringChange("es256", oidcKids(before), func() []string { - after, err := store.GetAllValidOIDCKeys(ctx) - if err != nil { - return nil - } - return oidcKids(after) - }(), current.Kid) + after, err := store.GetAllValidOIDCKeys(ctx) + if err != nil { + logKeyringUnread("es256", current.Kid, err) + return nil + } + logKeyringChange("es256", oidcKids(before), oidcKids(after), current.Kid) return nil } @@ -234,6 +243,12 @@ func logKeyringChange(algorithm string, before, after []string, signing string) logger.Infow("Operator signing keys installed", "algorithm", algorithm, "signing", signing, "valid_before", before, "valid_after", after) } +// logKeyringUnread says that the keys were installed but the keyring could +// not be read back, instead of reporting a keyring it did not read. +func logKeyringUnread(algorithm, signing string, err error) { + logger.Warnw("Operator signing keys installed; the keyring could not be read back to log the valid keys", "algorithm", algorithm, "signing", signing, "error", err) +} + // 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_log_test.go b/internal/controlplane/signingkeys_log_test.go new file mode 100644 index 000000000..f141fcd69 --- /dev/null +++ b/internal/controlplane/signingkeys_log_test.go @@ -0,0 +1,84 @@ +// 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 controlplane + +import ( + "context" + "crypto/ed25519" + "errors" + "strings" + "testing" + "time" + + golog "github.com/ipfs/go-log/v2" + + "github.com/google/agentmesh/internal/logging" + "github.com/google/agentmesh/internal/storage" +) + +// keyringReadFailStore fails GetAllValidKeys from its failFrom'th call on. +type keyringReadFailStore struct { + storage.Store + calls int + failFrom int +} + +var errKeyringRead = errors.New("keyring read failed") + +func (s *keyringReadFailStore) GetAllValidKeys(ctx context.Context) ([]storage.KeyPair, error) { + s.calls++ + if s.calls >= s.failFrom { + return nil, errKeyringRead + } + return s.Store.GetAllValidKeys(ctx) +} + +// When the keyring cannot be read back after an install, the failure is +// logged with its error instead of an install line listing no valid keys. +func TestReconcileKeyringLogsAFailedReadBack(t *testing.T) { + prev := golog.GetConfig() + logging.Setup(logging.Options{RingBuffer: true}) + t.Cleanup(func() { golog.SetupLogging(prev) }) + ctx := context.Background() + base, err := storage.NewSQLStore("sqlite", ":memory:") + if err != nil { + t.Fatalf("NewSQLStore: %v", err) + } + t.Cleanup(func() { _ = base.Close() }) + + first, second := newEd25519(t), newEd25519(t) + if err := reconcileEd25519Keyring(ctx, base, []ed25519.PrivateKey{first}, time.Hour); err != nil { + t.Fatalf("install the first key: %v", err) + } + // Call 1 is the read before SetKeyring, call 2 the read after it. + store := &keyringReadFailStore{Store: base, failFrom: 2} + if err := reconcileEd25519Keyring(ctx, store, []ed25519.PrivateKey{second, first}, time.Hour); err != nil { + t.Fatalf("install the second key: %v", err) + } + + secondFP := keyFingerprint(second.Public().(ed25519.PublicKey)) + logged := false + for _, line := range logging.RecentLogs() { + if strings.Contains(line, errKeyringRead.Error()) && strings.Contains(line, secondFP) { + logged = true + } + if strings.Contains(line, "Operator signing keys installed\t") && strings.Contains(line, secondFP) { + t.Fatalf("install line %q claims a keyring that was not read", line) + } + } + if !logged { + t.Fatalf("no log line names the failed read back (%v) for signing key %s", errKeyringRead, secondFP) + } +} diff --git a/internal/controlplane/signingkeys_test.go b/internal/controlplane/signingkeys_test.go index 63b141d62..8f01dec1b 100644 --- a/internal/controlplane/signingkeys_test.go +++ b/internal/controlplane/signingkeys_test.go @@ -140,6 +140,40 @@ func TestLoadOperatorSigningKeys(t *testing.T) { } }) + // pem.Decode skips a block whose body does not decode and returns the + // next one; the file must be refused, not loaded with the next key + // signing in place of the damaged one. + t.Run("damaged block is refused", func(t *testing.T) { + damaged := pemPKCS8(t, edA) + damaged[strings.IndexByte(string(damaged), '\n')+5] = '*' + keys, err := loadOperatorSigningKeys(writeKeyFile(t, damaged, pemPKCS8(t, edB), pemPKCS8(t, ecA))) + if err == nil { + t.Fatalf("loadOperatorSigningKeys loaded %d Ed25519 key(s) from a file whose first block is damaged, want a refusal", len(keys.ed25519)) + } + if !strings.Contains(err.Error(), "do not decode") { + t.Fatalf("err = %v, want a refusal naming the blocks that do not decode", err) + } + }) + + t.Run("damaged BEGIN line is refused", func(t *testing.T) { + damaged := pemPKCS8(t, edA)[1:] // "----BEGIN PRIVATE KEY-----" + keys, err := loadOperatorSigningKeys(writeKeyFile(t, damaged, pemPKCS8(t, edB), pemPKCS8(t, ecA))) + if err == nil { + t.Fatalf("loadOperatorSigningKeys loaded %d Ed25519 key(s) from a file whose first BEGIN line is damaged, want a refusal", len(keys.ed25519)) + } + if !strings.Contains(err.Error(), "do not decode") { + t.Fatalf("err = %v, want a refusal naming the blocks that do not decode", err) + } + }) + + t.Run("truncated block is refused", func(t *testing.T) { + whole := pemPKCS8(t, edB) + _, err := loadOperatorSigningKeys(writeKeyFile(t, pemPKCS8(t, edA), pemPKCS8(t, ecA), whole[:len(whole)/2])) + if err == nil || !strings.Contains(err.Error(), "do not decode") { + t.Fatalf("err = %v, want a refusal naming the blocks that do not decode", err) + } + }) + 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 Ed25519 key") {