Skip to content
Open
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
18 changes: 13 additions & 5 deletions internal/controlplane/node_gc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
63 changes: 63 additions & 0 deletions internal/controlplane/node_gc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
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
84 changes: 84 additions & 0 deletions internal/controlplane/signingkeys_log_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
34 changes: 34 additions & 0 deletions internal/controlplane/signingkeys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand Down
Loading