Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions internal/controlplane/node_gc.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,12 +184,26 @@ 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
}
cur, ok := s.catalog[peerID]
if !ok {
// Evicted meanwhile, by a ban: not this sweep's drop.
logger.Debugw("Service report already dropped during the sweep", "peer_id", peerID)
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.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()
Expand Down
109 changes: 109 additions & 0 deletions internal/controlplane/node_gc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@ import (
"testing"
"time"

golog "github.com/ipfs/go-log/v2"

dto "github.com/prometheus/client_model/go"

"github.com/google/agentmesh/api"
"github.com/google/agentmesh/internal/logging"
"github.com/google/agentmesh/internal/storage"
)

Expand Down Expand Up @@ -300,3 +303,109 @@ 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")
}
}

// A report evicted while the sweep runs (a ban drops it at once) is gone
// before the sweep gets to it, so the sweep does not count it as one it
// dropped.
func TestPruneCatalogCountsOnlyTheReportsItDrops(t *testing.T) {
prev := golog.GetConfig()
logging.Setup(logging.Options{RingBuffer: true})
t.Cleanup(func() { golog.SetupLogging(prev) })
store := &listHookStore{Store: newMetricsTestStore(t)}
now := time.Now()
srv, err := NewServer(Options{DriverName: "sqlite", DataSourceName: "unused", OIDCIssuer: "https://issuer"}, store)
if err != nil {
t.Fatal(err)
}
defer func() { _ = srv.Close() }()
srv.catalog["gone"] = nodeCatalogEntry{ReportedAt: now.Add(-time.Hour)}
srv.catalog["banned"] = nodeCatalogEntry{ReportedAt: now.Add(-time.Hour)}
store.afterList = func() {
srv.catalogMu.Lock()
delete(srv.catalog, "banned")
srv.catalogMu.Unlock()
}

// The ring buffer is shared by the process: only lines this sweep wrote count.
earlier := make(map[string]bool)
for _, line := range logging.RecentLogs() {
earlier[line] = true
}
srv.pruneCatalog(now)

var summaries []string
for _, line := range logging.RecentLogs() {
if !earlier[line] && strings.Contains(line, "service reports of nodes no longer admitted") {
summaries = append(summaries, line)
}
}
if len(summaries) != 1 || !strings.Contains(summaries[0], "Dropped 1 service reports") {
t.Fatalf("sweep summary lines %q, want one that counts the 1 report the sweep dropped", summaries)
}
if n := len(srv.catalogSnapshot()); n != 0 {
t.Fatalf("catalog after the sweep has %d entries, want 0", n)
}
}
43 changes: 29 additions & 14 deletions internal/controlplane/signingkeys.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package controlplane

import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/ed25519"
Expand Down Expand Up @@ -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":
Expand All @@ -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 {
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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) {
Expand Down
119 changes: 119 additions & 0 deletions internal/controlplane/signingkeys_log_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// 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/ecdsa"
"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 and GetAllValidOIDCKeys from
// their failFrom'th call on, each counted on its own.
type keyringReadFailStore struct {
storage.Store
calls, oidcCalls 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)
}

func (s *keyringReadFailStore) GetAllValidOIDCKeys(ctx context.Context) ([]storage.OIDCKeyPair, error) {
s.oidcCalls++
if s.oidcCalls >= s.failFrom {
return nil, errKeyringRead
}
return s.Store.GetAllValidOIDCKeys(ctx)
}

// When a 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) })

for _, tc := range []struct {
name string
// install puts the first key in place, then installs the second in
// front of it through store, and returns the second key's id.
install func(t *testing.T, base, store storage.Store) string
}{
{"ed25519", func(t *testing.T, base, store storage.Store) string {
first, second := newEd25519(t), newEd25519(t)
if err := reconcileEd25519Keyring(context.Background(), base, []ed25519.PrivateKey{first}, time.Hour); err != nil {
t.Fatalf("install the first key: %v", err)
}
if err := reconcileEd25519Keyring(context.Background(), store, []ed25519.PrivateKey{second, first}, time.Hour); err != nil {
t.Fatalf("install the second key: %v", err)
}
return keyFingerprint(second.Public().(ed25519.PublicKey))
}},
{"es256", func(t *testing.T, base, store storage.Store) string {
first, second := newP256(t), newP256(t)
if err := reconcileES256Keyring(context.Background(), base, []*ecdsa.PrivateKey{first}, time.Hour); err != nil {
t.Fatalf("install the first key: %v", err)
}
if err := reconcileES256Keyring(context.Background(), store, []*ecdsa.PrivateKey{second, first}, time.Hour); err != nil {
t.Fatalf("install the second key: %v", err)
}
pub, err := second.PublicKey.Bytes()
if err != nil {
t.Fatalf("encode the second key: %v", err)
}
return es256Kid(pub)
}},
} {
t.Run(tc.name, func(t *testing.T) {
base, err := storage.NewSQLStore("sqlite", ":memory:")
if err != nil {
t.Fatalf("NewSQLStore: %v", err)
}
t.Cleanup(func() { _ = base.Close() })
// Call 1 is the read before the keyring is set, call 2 the read after it.
signing := tc.install(t, base, &keyringReadFailStore{Store: base, failFrom: 2})

logged := false
for _, line := range logging.RecentLogs() {
if strings.Contains(line, errKeyringRead.Error()) && strings.Contains(line, signing) {
logged = true
}
if strings.Contains(line, "Operator signing keys installed ") && strings.Contains(line, signing) {
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, signing)
}
})
}
}
Loading
Loading