Skip to content

Agent Mesh

controlplane: gate policy reads on the same admission rules as refresh

Antonio Ojea5d0a93969fca
diff --git a/internal/controlplane/policies_admission_test.go b/internal/controlplane/policies_admission_test.go
new file mode 100644
index 00000000..51cf7332
--- /dev/null
+++ b/internal/controlplane/policies_admission_test.go
@@ -0,0 +1,136 @@
+// 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 (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "io"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/google/sam/api"
+ "github.com/libp2p/go-libp2p/core/crypto"
+ "github.com/libp2p/go-libp2p/core/peer"
+ "google.golang.org/protobuf/proto"
+)
+
+// TestPoliciesRequiresAnAdmissibleNode pins that reading mesh policy applies the
+// same admission rules as refreshing a token. The GET handler used to accept any
+// node record that was not explicitly banned, so a node whose OIDC session had
+// lapsed kept reading roles, bindings and allowed targets until an operator
+// banned it by hand. Passive expiry is the backstop that has to work on its own.
+func TestPoliciesRequiresAnAdmissibleNode(t *testing.T) {
+ issuer, mintToken := startCustomMockOIDC(t)
+ srv, store, baseURL := setupTestServer(t, issuer)
+ defer func() {
+ _ = srv.Close()
+ _ = store.Close()
+ }()
+
+ ctx := context.Background()
+ client := &http.Client{Timeout: 5 * time.Second}
+
+ privNode, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ nodePeer, err := peer.IDFromPrivateKey(privNode)
+ if err != nil {
+ t.Fatal(err)
+ }
+ nodePubKeyBytes, err := crypto.MarshalPublicKey(privNode.GetPublic())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ enrollReq := &api.EnrollRequest{
+ Jwt: mintToken(map[string]interface{}{"sub": "node-alice", "groups": []string{"users"}}),
+ PeerId: nodePeer.String(),
+ PublicKey: nodePubKeyBytes,
+ RequestedRole: api.RoleNode,
+ }
+ reqData, err := proto.Marshal(enrollReq)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ resp, err := client.Post(baseURL+"/register", "application/x-protobuf", bytes.NewReader(reqData))
+ if err != nil {
+ t.Fatalf("node /register failed: %v", err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("node /register status %s (body: %s)", resp.Status, body)
+ }
+
+ var enrollResp api.EnrollResponse
+ if err := proto.Unmarshal(body, &enrollResp); err != nil {
+ t.Fatalf("failed to unmarshal EnrollResponse: %v", err)
+ }
+
+ getPolicies := func(t *testing.T) int {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodGet, baseURL+"/policies", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(enrollResp.BiscuitToken))
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("GET /policies failed: %v", err)
+ }
+ _ = resp.Body.Close()
+ return resp.StatusCode
+ }
+
+ // The token is the same throughout; only the node record changes, so any
+ // difference below comes from the admission check and not from the biscuit.
+ if got := getPolicies(t); got != http.StatusOK {
+ t.Fatalf("freshly enrolled node got status %d, want %d", got, http.StatusOK)
+ }
+
+ expireSession := func(t *testing.T, at time.Time) {
+ t.Helper()
+ record, err := store.GetNode(ctx, nodePeer.String())
+ if err != nil {
+ t.Fatalf("GetNode: %v", err)
+ }
+ record.ExpiresAt = at
+ if err := store.EnrollNode(ctx, record); err != nil {
+ t.Fatalf("EnrollNode: %v", err)
+ }
+ }
+
+ expireSession(t, time.Now().Add(-time.Hour))
+ if got := getPolicies(t); got != http.StatusUnauthorized {
+ t.Errorf("node with a lapsed session got status %d, want %d", got, http.StatusUnauthorized)
+ }
+
+ expireSession(t, time.Now().Add(time.Hour))
+ if got := getPolicies(t); got != http.StatusOK {
+ t.Errorf("node with a renewed session got status %d, want %d", got, http.StatusOK)
+ }
+
+ if err := store.SetNodeBanned(ctx, nodePeer.String(), true); err != nil {
+ t.Fatalf("SetNodeBanned: %v", err)
+ }
+ if got := getPolicies(t); got != http.StatusUnauthorized {
+ t.Errorf("banned node got status %d, want %d", got, http.StatusUnauthorized)
+ }
+}
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index 5b428233..9737c908 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -648,14 +648,12 @@ func (s *Server) HandleRefresh(w http.ResponseWriter, r *http.Request) {
return
}
- if nodeRecord.Banned {
- logger.Warnw("Banned node attempted refresh", "peer_id", pID.String())
- http.Error(w, "Node is banned", http.StatusForbidden)
- return
- }
-
- // Check session expiry (OIDC 90 days expiration)
- if !nodeRecord.ExpiresAt.IsZero() && time.Now().After(nodeRecord.ExpiresAt) {
+ if err := nodeRecord.CheckAdmission(time.Now()); err != nil {
+ if errors.Is(err, storage.ErrNodeBanned) {
+ logger.Warnw("Banned node attempted refresh", "peer_id", pID.String())
+ http.Error(w, "Node is banned", http.StatusForbidden)
+ return
+ }
logger.Warnw("Session expired for node", "peer_id", pID.String(), "expires_at", nodeRecord.ExpiresAt)
http.Error(w, "Session expired, please re-enroll interactively", http.StatusUnauthorized)
return
@@ -944,7 +942,7 @@ func (s *Server) HandlePolicies(w http.ResponseWriter, r *http.Request) {
peerID, err := identity.VerifyAndExtractPeerID(trustedKeys, biscuitBytes, s.config.BiscuitTimeout)
if err == nil {
nodeRecord, nodeErr := s.store.GetNode(r.Context(), peerID.String())
- if nodeErr == nil && nodeRecord != nil && !nodeRecord.Banned {
+ if nodeErr == nil && nodeRecord != nil && nodeRecord.CheckAdmission(time.Now()) == nil {
isNode = true
}
}
diff --git a/internal/storage/node_admission_test.go b/internal/storage/node_admission_test.go
new file mode 100644
index 00000000..cc99ebd3
--- /dev/null
+++ b/internal/storage/node_admission_test.go
@@ -0,0 +1,67 @@
+// 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 storage
+
+import (
+ "errors"
+ "testing"
+ "time"
+)
+
+func TestEnrolledNodeCheckAdmission(t *testing.T) {
+ now := time.Date(2026, 8, 26, 12, 0, 0, 0, time.UTC)
+
+ tests := []struct {
+ name string
+ node EnrolledNode
+ want error
+ }{
+ {
+ name: "session still open",
+ node: EnrolledNode{ExpiresAt: now.Add(time.Hour)},
+ },
+ {
+ // Bootstrap enrollments carry no session, so a zero time must not
+ // read as "expired at the epoch".
+ name: "no session expiry recorded",
+ node: EnrolledNode{},
+ },
+ {
+ name: "banned",
+ node: EnrolledNode{Banned: true, ExpiresAt: now.Add(time.Hour)},
+ want: ErrNodeBanned,
+ },
+ {
+ name: "session lapsed",
+ node: EnrolledNode{ExpiresAt: now.Add(-time.Second)},
+ want: ErrNodeSessionExpired,
+ },
+ {
+ // A ban is the more actionable of the two, so it wins.
+ name: "banned and lapsed",
+ node: EnrolledNode{Banned: true, ExpiresAt: now.Add(-time.Hour)},
+ want: ErrNodeBanned,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := tt.node.CheckAdmission(now)
+ if !errors.Is(err, tt.want) {
+ t.Errorf("CheckAdmission() = %v, want %v", err, tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/storage/storage.go b/internal/storage/storage.go
index ac5e24ba..f1ee555d 100644
--- a/internal/storage/storage.go
+++ b/internal/storage/storage.go
@@ -25,6 +25,11 @@ import (
var (
ErrNotFound = errors.New("not found")
+
+ // ErrNodeBanned and ErrNodeSessionExpired are the two ways an enrolled node
+ // stops being servable. See EnrolledNode.CheckAdmission.
+ ErrNodeBanned = errors.New("node is banned")
+ ErrNodeSessionExpired = errors.New("node session expired")
)
// KeyPair holds cryptographic key information.
@@ -69,6 +74,21 @@ type EnrolledNode struct {
Banned bool
}
+// CheckAdmission reports whether the control plane may still serve this node.
+// Enrollment is bounded by two independent conditions, an explicit ban and the
+// end of the OIDC session, and every path that acts on an enrolled node has to
+// apply both: checking only Banned lets a node whose session lapsed keep
+// reading mesh state until someone bans it by hand.
+func (n *EnrolledNode) CheckAdmission(now time.Time) error {
+ if n.Banned {
+ return ErrNodeBanned
+ }
+ if !n.ExpiresAt.IsZero() && now.After(n.ExpiresAt) {
+ return ErrNodeSessionExpired
+ }
+ return nil
+}
+
// BootstrapToken represents a pre-shared token for node enrollment.
type BootstrapToken struct {
ID string