Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
controlplane: identity bans, token spending and IdP roles (audit PR 3)
Antonio Ojeacbd1e4971f83
diff --git a/api/datalog.go b/api/datalog.goindex b10e2ca6..36f479e2 100644--- a/api/datalog.go+++ b/api/datalog.go@@ -88,8 +88,20 @@ const (// FactRole defines a custom SAM role assigned to the user or node.// Contains: biscuit.String(roleName)// Example Datalog: allow if role("mesh-member")+ //+ // Only the control plane mints it, from mesh policy bindings. It must+ // never be derived from an OIDC claim: role("sam:role:router") is what+ // makes a router, and an issuer's "roles" claim is the issuer's word, not+ // the mesh operator's. See FactIdpRole.FactRole = "role"+ // FactIdpRole carries the OIDC "roles" claim as the issuer emitted it.+ // Contains: biscuit.String(roleName)+ // Example Datalog: allow if idp_role("platform-team")+ // Bind it to a mesh role in policy (member "idp_role:platform-team"),+ // or target it ("idp_role:platform-team"); it grants nothing by itself.+ FactIdpRole = "idp_role"+// FactRight defines the cryptographically signed capability/right.// Contains: biscuit.String(rightName)// Example Datalog: allow if right("relay")@@ -264,7 +276,20 @@ var oidcClaimToFact = map[string]string{"sub": FactUser,"email": FactEmail,"groups": FactGroup,- "roles": FactRole,+ "roles": FactIdpRole,+}++// BindingMemberPrefixes are the fact names a policy binding member or an+// allowed_targets entry may name: the peer itself plus every OIDC claim the+// control plane mints. FactRole is deliberately absent: a binding on it would+// grant a mesh role from a mesh role.+func BindingMemberPrefixes() []string {+ names := []string{FactNode}+ for _, fact := range OIDCClaimToFact() {+ names = append(names, fact)+ }+ sort.Strings(names)+ return names}// OIDCClaimToFact returns a copy of the OIDC claims to Biscuit facts map.diff --git a/api/datalog_test.go b/api/datalog_test.goindex 778984a2..1f784ed5 100644--- a/api/datalog_test.go+++ b/api/datalog_test.go@@ -360,12 +360,22 @@ func TestOIDCClaimToFact(t *testing.T) {"sub": FactUser,"email": FactEmail,"groups": FactGroup,- "roles": FactRole,+ "roles": FactIdpRole,}if !reflect.DeepEqual(facts, want) {t.Errorf("OIDCClaimToFact() = %v, want %v", facts, want)}+ // role() is minted from mesh policy only. An issuer whose "roles" claim+ // landed there could name sam:role:router and become a router.+ for claim, fact := range facts {+ if fact == FactRole {+ t.Errorf("claim %q maps to the mesh role fact %q", claim, FactRole)+ }+ }+ if p := BindingMemberPrefixes(); slices.Contains(p, FactRole) || !slices.Contains(p, FactIdpRole) || !slices.Contains(p, FactNode) {+ t.Errorf("BindingMemberPrefixes() = %v; want idp_role and node, not role", p)+ }// Verify that modifying the returned map does not mutate the internal map.facts["new_claim"] = "new_fact"diff --git a/cmd/sam-control-plane/main.go b/cmd/sam-control-plane/main.goindex 5ab2e1d5..62b281d9 100644--- a/cmd/sam-control-plane/main.go+++ b/cmd/sam-control-plane/main.go@@ -16,6 +16,7 @@ package mainimport ("context"+ "fmt""os""os/signal""strings"@@ -27,6 +28,7 @@ import ("github.com/google/sam/internal/secrets""github.com/google/sam/internal/storage"golog "github.com/ipfs/go-log/v2"+ "github.com/libp2p/go-libp2p/core/peer""github.com/spf13/cobra")@@ -170,16 +172,31 @@ func main() {}var peerIDFlag string+ // setBan is the CLI counterpart of POST /admin/revoke and+ // POST /admin/nodes/{peer}/unban: same canonicalization, same node and+ // identity halves. A raw --peer used to match zero rows and still print+ // "Successfully banned".+ setBan := func(ctx context.Context, rawPeer string, banned bool) error {+ pID, err := peer.Decode(rawPeer)+ if err != nil {+ return fmt.Errorf("invalid peer ID %q: %w", rawPeer, err)+ }+ store, err := storage.NewSQLStore(dbDriver, dbDSN)+ if err != nil {+ return fmt.Errorf("failed to initialize database store: %w", err)+ }+ defer store.Close() //nolint:errcheck+ node, err := store.GetNode(ctx, pID.String())+ if err != nil {+ return fmt.Errorf("node %s: %w", pID, err)+ }+ return controlplane.SetNodeBan(ctx, store, node, banned)+ }banCmd := &cobra.Command{Use: "ban",- Short: "Ban a node peer ID",+ Short: "Ban a node peer ID and the identity that enrolled it",Run: func(cmd *cobra.Command, args []string) {- store, err := storage.NewSQLStore(dbDriver, dbDSN)- if err != nil {- logger.Fatalf("Failed to initialize database store: %v", err)- }- defer store.Close() //nolint:errcheck- if err := store.SetNodeBanned(cmd.Context(), peerIDFlag, true); err != nil {+ if err := setBan(cmd.Context(), peerIDFlag, true); err != nil {logger.Fatalf("Failed to ban node: %v", err)}logger.Infof("Successfully banned node %s", peerIDFlag)@@ -190,14 +207,9 @@ func main() {unbanCmd := &cobra.Command{Use: "unban",- Short: "Unban a node peer ID",+ Short: "Unban a node peer ID and the identity that enrolled it",Run: func(cmd *cobra.Command, args []string) {- store, err := storage.NewSQLStore(dbDriver, dbDSN)- if err != nil {- logger.Fatalf("Failed to initialize database store: %v", err)- }- defer store.Close() //nolint:errcheck- if err := store.SetNodeBanned(cmd.Context(), peerIDFlag, false); err != nil {+ if err := setBan(cmd.Context(), peerIDFlag, false); err != nil {logger.Fatalf("Failed to unban node: %v", err)}logger.Infof("Successfully unbanned node %s", peerIDFlag)diff --git a/internal/controlplane/identity_lifecycle_test.go b/internal/controlplane/identity_lifecycle_test.gonew file mode 100644index 00000000..441a6d14--- /dev/null+++ b/internal/controlplane/identity_lifecycle_test.go@@ -0,0 +1,589 @@+// 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"+ "crypto/ed25519"+ "encoding/json"+ "io"+ "net/http"+ "slices"+ "strconv"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/biscuit-auth/biscuit-go/v2"+ "github.com/google/sam/api"+ "github.com/google/sam/internal/identity"+ "github.com/google/sam/internal/storage"+ "github.com/libp2p/go-libp2p/core/crypto"+ "github.com/libp2p/go-libp2p/core/peer"+ "google.golang.org/protobuf/proto"+)++// lifecycleHarness is a control plane with an open node binding, an admin+// token and auto-approve on, plus the request helpers these tests share.+type lifecycleHarness struct {+ t *testing.T+ srv *Server+ store storage.Store+ baseURL string+ mintToken func(map[string]interface{}) string+ client *http.Client+}++func newLifecycleHarness(t *testing.T) *lifecycleHarness {+ t.Helper()+ issuer, mintToken := startCustomMockOIDC(t)+ srv, store, baseURL := setupTestServer(t, issuer)+ t.Cleanup(func() {+ _ = srv.Close()+ _ = store.Close()+ })+ srv.config.AdminToken = "super-secret-admin-token"+ srv.config.AutoApproveEnrollment = true+ if err := store.SaveMeshPolicy(context.Background(),+ []*api.PolicyRole{{Name: api.RoleNode, AllowedServices: []string{"*"}, AllowedTargets: []string{"*"}}},+ []*api.PolicyBinding{{Role: api.RoleNode, Members: []string{api.SystemAuthenticated}}}); err != nil {+ t.Fatal(err)+ }+ return &lifecycleHarness{t: t, srv: srv, store: store, baseURL: baseURL, mintToken: mintToken, client: &http.Client{Timeout: 5 * time.Second}}+}++// do sends an authenticated request and returns status and body.+func (h *lifecycleHarness) do(method, path, bearer string, body []byte, contentType string) (int, []byte) {+ h.t.Helper()+ req, err := http.NewRequest(method, h.baseURL+path, bytes.NewReader(body))+ if err != nil {+ h.t.Fatal(err)+ }+ if bearer != "" {+ req.Header.Set("Authorization", "Bearer "+bearer)+ }+ if contentType != "" {+ req.Header.Set("Content-Type", contentType)+ }+ resp, err := h.client.Do(req)+ if err != nil {+ h.t.Fatalf("%s %s: %v", method, path, err)+ }+ defer func() { _ = resp.Body.Close() }()+ respBody, err := io.ReadAll(resp.Body)+ if err != nil {+ h.t.Fatal(err)+ }+ return resp.StatusCode, respBody+}++// register enrolls an OIDC identity with a fresh key via /register.+func (h *lifecycleHarness) register(sub string) (crypto.PrivKey, peer.ID) {+ h.t.Helper()+ priv, id := newTestKey(h.t)+ pub, err := crypto.MarshalPublicKey(priv.GetPublic())+ if err != nil {+ h.t.Fatal(err)+ }+ ts, sig := registerPoP(h.t, priv, id.String())+ data, err := proto.Marshal(&api.EnrollRequest{+ Jwt: h.mintToken(map[string]interface{}{"sub": sub}), PeerId: id.String(), PublicKey: pub,+ RequestedRole: api.RoleNode, Timestamp: ts, ChallengeSignature: sig,+ })+ if err != nil {+ h.t.Fatal(err)+ }+ if status, body := h.do(http.MethodPost, "/register", "", data, "application/x-protobuf"); status != http.StatusOK {+ h.t.Fatalf("/register for %s: %d %s", sub, status, body)+ }+ return priv, id+}++// userToken mints a bootstrap token as an OIDC user via /user/bootstrap-tokens.+func (h *lifecycleHarness) userToken(sub string, body string) (int, map[string]any) {+ h.t.Helper()+ status, respBody := h.do(http.MethodPost, "/user/bootstrap-tokens", h.mintToken(map[string]interface{}{"sub": sub}), []byte(body), "application/json")+ var out map[string]any+ _ = json.Unmarshal(respBody, &out)+ return status, out+}++// enroll drives POST /enroll with a fresh key and returns the response status.+func (h *lifecycleHarness) enroll(token string) (api.EnrollmentStatus, int, string) {+ h.t.Helper()+ priv, id := newTestKey(h.t)+ pub, err := crypto.MarshalPublicKey(priv.GetPublic())+ if err != nil {+ h.t.Fatal(err)+ }+ ts, sig := enrollPoP(h.t, priv, id.String())+ data, err := proto.Marshal(&api.BootstrapEnrollRequest{+ BootstrapToken: token, PeerId: id.String(), PublicKey: pub, RequestedRole: api.RoleNode,+ Timestamp: ts, ChallengeSignature: sig,+ })+ if err != nil {+ h.t.Fatal(err)+ }+ status, body := h.do(http.MethodPost, "/enroll", "", data, "application/x-protobuf")+ var resp api.BootstrapEnrollResponse+ if status == http.StatusOK {+ if err := proto.Unmarshal(body, &resp); err != nil {+ h.t.Fatal(err)+ }+ }+ return resp.Status, status, resp.ErrorMessage+}++func (h *lifecycleHarness) revoke(id peer.ID) {+ h.t.Helper()+ data, err := proto.Marshal(&api.TokenRevokeRequest{PeerId: id.String()})+ if err != nil {+ h.t.Fatal(err)+ }+ if status, body := h.do(http.MethodPost, "/admin/revoke", "super-secret-admin-token", data, "application/x-protobuf"); status != http.StatusOK {+ h.t.Fatalf("/admin/revoke: %d %s", status, body)+ }+}++// M17: a banned OIDC identity could not /register again, but its still-valid+// ID token passed authenticateUser, so it minted itself a bootstrap token and+// re-enrolled a fresh device. The ban has to hold on every surface the ID+// token can drive, and a token minted before the ban has to stop working.+func TestIdentityBanCoversUserSurfaceAndOwnedTokens(t *testing.T) {+ h := newLifecycleHarness(t)+ ctx := context.Background()+ const sub = "victim-turned-attacker"+ userJWT := h.mintToken(map[string]interface{}{"sub": sub})++ // The identity logs in (user row exists), enrolls a node and mints a+ // bootstrap token while still in good standing.+ if status, body := h.do(http.MethodGet, "/user/status", userJWT, nil, ""); status != http.StatusOK {+ t.Fatalf("/user/status before ban: %d %s", status, body)+ }+ _, nodeID := h.register(sub)+ status, minted := h.userToken(sub, `{"role":"sam:role:node","max_usages":5}`)+ if status != http.StatusCreated {+ t.Fatalf("token before ban: %d %v", status, minted)+ }+ preBanToken, _ := minted["token"].(string)++ h.revoke(nodeID)+ banned, err := h.store.IsIdentityBanned(ctx, h.srv.config.OIDCIssuer+"|"+sub)+ if err != nil || !banned {+ t.Fatalf("identity not banned after revoke: banned=%v err=%v", banned, err)+ }++ t.Run("user surface refuses the banned identity", func(t *testing.T) {+ for _, tc := range []struct{ method, path string }{+ {http.MethodGet, "/user/status"},+ {http.MethodPost, "/user/bootstrap-tokens"},+ {http.MethodPost, "/user/revoke?id=" + nodeID.String()},+ } {+ status, body := h.do(tc.method, tc.path, userJWT, []byte(`{"role":"sam:role:node"}`), "application/json")+ if status != http.StatusForbidden {+ t.Errorf("%s %s with a banned identity: got %d (%s), want 403", tc.method, tc.path, status, body)+ }+ }+ })++ t.Run("token minted before the ban enrolls nothing", func(t *testing.T) {+ enrollStatus, httpStatus, msg := h.enroll(preBanToken)+ if httpStatus != http.StatusOK || enrollStatus != api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED {+ t.Fatalf("enroll with a banned owner's token: http %d, status %v (%s); want REJECTED", httpStatus, enrollStatus, msg)+ }+ if !strings.Contains(msg, "owner is banned") {+ t.Errorf("rejection reason = %q, want the owner ban", msg)+ }+ })++ t.Run("a queued approval is refused too", func(t *testing.T) {+ h.srv.config.AutoApproveEnrollment = false+ t.Cleanup(func() { h.srv.config.AutoApproveEnrollment = true })+ // Another user's token, queued, then that user is banned.+ const other = "queued-then-banned"+ _, otherNode := h.register(other)+ status, minted := h.userToken(other, `{"role":"sam:role:node","max_usages":1}`)+ if status != http.StatusCreated {+ t.Fatalf("token: %d %v", status, minted)+ }+ otherToken, _ := minted["token"].(string)+ if enrollStatus, httpStatus, msg := h.enroll(otherToken); httpStatus != http.StatusOK || enrollStatus != api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING {+ t.Fatalf("queue: http %d, status %v (%s); want PENDING", httpStatus, enrollStatus, msg)+ }+ h.revoke(otherNode)++ reqs, err := h.store.ListEnrollmentRequests(ctx)+ if err != nil {+ t.Fatal(err)+ }+ var pendingID string+ for _, r := range reqs {+ if r.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING {+ pendingID = r.ID+ }+ }+ if pendingID == "" {+ t.Fatal("no pending request found")+ }+ status, body := h.do(http.MethodPost, "/admin/enrollments/"+pendingID+"/approve", "super-secret-admin-token", nil, "")+ if status != http.StatusForbidden {+ t.Errorf("approve with a banned owner: got %d (%s), want 403", status, body)+ }+ })++ t.Run("unban lifts both halves", func(t *testing.T) {+ status, body := h.do(http.MethodPost, "/admin/nodes/"+nodeID.String()+"/unban", "super-secret-admin-token", nil, "")+ if status != http.StatusNoContent {+ t.Fatalf("unban: got %d (%s), want 204", status, body)+ }+ if banned, err := h.store.IsIdentityBanned(ctx, h.srv.config.OIDCIssuer+"|"+sub); err != nil || banned {+ t.Errorf("identity still banned after unban: banned=%v err=%v", banned, err)+ }+ if node, err := h.store.GetNode(ctx, nodeID.String()); err != nil || node.Banned {+ t.Errorf("node still banned after unban: err=%v", err)+ }+ if status, body := h.do(http.MethodGet, "/user/status", userJWT, nil, ""); status != http.StatusOK {+ t.Errorf("/user/status after unban: %d %s", status, body)+ }+ })+}++// M3: the usage cap was read-then-increment across two round trips, so+// concurrent enrollments on a 1-use token could all pass the read.+func TestBootstrapTokenUsageCapHoldsUnderConcurrency(t *testing.T) {+ h := newLifecycleHarness(t)+ status, minted := h.userToken("issuer-of-one", `{"role":"sam:role:node","max_usages":1}`)+ if status != http.StatusCreated {+ t.Fatalf("token: %d %v", status, minted)+ }+ token, _ := minted["token"].(string)++ const attempts = 12+ var wg sync.WaitGroup+ results := make(chan api.EnrollmentStatus, attempts)+ for i := 0; i < attempts; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ enrollStatus, httpStatus, _ := h.enroll(token)+ if httpStatus == http.StatusOK {+ results <- enrollStatus+ } else if httpStatus != http.StatusTooManyRequests {+ t.Errorf("unexpected http status %d", httpStatus)+ }+ }()+ }+ wg.Wait()+ close(results)++ approved := 0+ for s := range results {+ if s == api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {+ approved+++ }+ }+ if approved != 1 {+ t.Errorf("%d enrollments approved on a 1-use token, want exactly 1", approved)+ }+ tok, err := h.store.GetBootstrapToken(context.Background(), minted["id"].(string))+ if err != nil {+ t.Fatal(err)+ }+ if tok.UsagesCount != 1 {+ t.Errorf("usages_count = %d, want 1", tok.UsagesCount)+ }+}++// M3 (approve arm) and L35: approve re-checks the token and writes the node+// record before the request becomes APPROVED; a second approve or reject of+// the same request is a 409, not a second biscuit.+func TestApproveRechecksTokenAndResolvesOnce(t *testing.T) {+ h := newLifecycleHarness(t)+ h.srv.config.AutoApproveEnrollment = false+ ctx := context.Background()++ queue := func(maxUsages int) (tokenID, requestID string) {+ t.Helper()+ status, minted := h.userToken("queuer", `{"role":"sam:role:node","max_usages":`+strconv.Itoa(maxUsages)+`}`)+ if status != http.StatusCreated {+ t.Fatalf("token: %d %v", status, minted)+ }+ if enrollStatus, httpStatus, msg := h.enroll(minted["token"].(string)); httpStatus != http.StatusOK || enrollStatus != api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING {+ t.Fatalf("queue: http %d, status %v (%s)", httpStatus, enrollStatus, msg)+ }+ reqs, err := h.store.ListEnrollmentRequests(ctx)+ if err != nil {+ t.Fatal(err)+ }+ for _, r := range reqs {+ if r.TokenID == minted["id"].(string) && r.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING {+ return r.TokenID, r.ID+ }+ }+ t.Fatal("pending request not found")+ return "", ""+ }+ approve := func(id string) (int, string) {+ t.Helper()+ status, body := h.do(http.MethodPost, "/admin/enrollments/"+id+"/approve", "super-secret-admin-token", nil, "")+ return status, string(body)+ }++ t.Run("revoked since queued", func(t *testing.T) {+ tokenID, reqID := queue(1)+ if err := h.store.RevokeBootstrapToken(ctx, tokenID); err != nil {+ t.Fatal(err)+ }+ if status, body := approve(reqID); status != http.StatusGone {+ t.Errorf("approve with a revoked token: got %d (%s), want 410", status, body)+ }+ req, err := h.store.GetEnrollmentRequestByID(ctx, reqID)+ if err != nil {+ t.Fatal(err)+ }+ if req.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING || len(req.BiscuitToken) != 0 {+ t.Errorf("request was resolved despite the revoked token: %+v", req)+ }+ })++ t.Run("second resolution is a conflict", func(t *testing.T) {+ _, reqID := queue(5)+ if status, body := approve(reqID); status != http.StatusOK {+ t.Fatalf("first approve: %d %s", status, body)+ }+ if status, body := approve(reqID); status != http.StatusConflict {+ t.Errorf("second approve: got %d (%s), want 409", status, body)+ }+ if status, body := h.do(http.MethodPost, "/admin/enrollments/"+reqID+"/reject", "super-secret-admin-token", nil, ""); status != http.StatusConflict {+ t.Errorf("reject after approve: got %d (%s), want 409", status, body)+ }+ req, err := h.store.GetEnrollmentRequestByID(ctx, reqID)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := h.store.GetNode(ctx, req.PeerID); err != nil {+ t.Errorf("approved request has no node record behind it: %v", err)+ }+ })++ t.Run("exhausted since queued", func(t *testing.T) {+ // Two requests queued on a 1-use token: only one approval can land.+ status, minted := h.userToken("queuer", `{"role":"sam:role:node","max_usages":1}`)+ if status != http.StatusCreated {+ t.Fatalf("token: %d %v", status, minted)+ }+ var ids []string+ for i := 0; i < 2; i++ {+ if _, httpStatus, _ := h.enroll(minted["token"].(string)); httpStatus != http.StatusOK {+ t.Fatalf("queue %d: http %d", i, httpStatus)+ }+ }+ reqs, err := h.store.ListEnrollmentRequests(ctx)+ if err != nil {+ t.Fatal(err)+ }+ for _, r := range reqs {+ if r.TokenID == minted["id"].(string) {+ ids = append(ids, r.ID)+ }+ }+ if len(ids) != 2 {+ t.Fatalf("queued %d requests, want 2", len(ids))+ }+ if status, body := approve(ids[0]); status != http.StatusOK {+ t.Fatalf("first approve: %d %s", status, body)+ }+ if status, body := approve(ids[1]); status != http.StatusGone {+ t.Errorf("approve past the cap: got %d (%s), want 410", status, body)+ }+ })+}++// L9: a non-admin's token is bounded in lifetime and width.+func TestUserBootstrapTokenCeilings(t *testing.T) {+ h := newLifecycleHarness(t)+ for name, body := range map[string]string{+ "ttl": `{"role":"sam:role:node","ttl_hours":` + strconv.Itoa(userTokenMaxTTLHours+1) + `}`,+ "usages": `{"role":"sam:role:node","max_usages":` + strconv.Itoa(userTokenMaxUsages+1) + `}`,+ } {+ if status, resp := h.userToken("greedy", body); status != http.StatusBadRequest {+ t.Errorf("%s over the ceiling: got %d %v, want 400", name, status, resp)+ }+ }+ if status, resp := h.userToken("modest", `{"role":"sam:role:node","ttl_hours":`+strconv.Itoa(userTokenMaxTTLHours)+`,"max_usages":`+strconv.Itoa(userTokenMaxUsages)+`}`); status != http.StatusCreated {+ t.Errorf("at the ceiling: got %d %v, want 201", status, resp)+ }+ // Admins are not bounded.+ status, body := h.do(http.MethodPost, "/user/bootstrap-tokens", "super-secret-admin-token",+ []byte(`{"role":"sam:role:router","ttl_hours":`+strconv.Itoa(userTokenMaxTTLHours*10)+`,"max_usages":`+strconv.Itoa(userTokenMaxUsages*10)+`}`), "application/json")+ if status != http.StatusCreated {+ t.Errorf("admin over the user ceiling: got %d (%s), want 201", status, body)+ }+}++// L11: /user/status must not hand out live biscuits or key material, and+// mesh-wide state (policy, routers) is admin-only.+func TestUserStatusTrimsCredentialsAndMeshState(t *testing.T) {+ h := newLifecycleHarness(t)+ const sub = "status-user"+ h.register(sub)++ status, body := h.do(http.MethodGet, "/user/status", h.mintToken(map[string]interface{}{"sub": sub}), nil, "")+ if status != http.StatusOK {+ t.Fatalf("/user/status: %d %s", status, body)+ }+ for _, leaked := range []string{`"Biscuit"`, `"PublicKey"`, `"ClaimsJSON"`, `"policy_json"`, `"active_routers"`} {+ if bytes.Contains(body, []byte(leaked)) {+ t.Errorf("non-admin /user/status carries %s", leaked)+ }+ }+ var resp struct {+ Nodes []map[string]any `json:"enrolled_nodes"`+ }+ if err := json.Unmarshal(body, &resp); err != nil {+ t.Fatal(err)+ }+ if len(resp.Nodes) != 0 {+ // The node was OIDC-enrolled with no owner; a user sees only nodes it+ // owns. What matters is the shape when present, checked as admin.+ t.Errorf("non-owner sees %d nodes", len(resp.Nodes))+ }++ status, body = h.do(http.MethodGet, "/user/status", "super-secret-admin-token", nil, "")+ if status != http.StatusOK {+ t.Fatalf("admin /user/status: %d %s", status, body)+ }+ for _, leaked := range []string{`"Biscuit"`, `"PublicKey"`} {+ if bytes.Contains(body, []byte(leaked)) {+ t.Errorf("admin /user/status carries %s", leaked)+ }+ }+ for _, wanted := range []string{`"policy_json"`, `"active_routers"`, `"ClaimsJSON"`, `"PeerID"`} {+ if !bytes.Contains(body, []byte(wanted)) {+ t.Errorf("admin /user/status lacks %s", wanted)+ }+ }+}++// M9: an email the issuer marks unverified resolves no binding and is not+// minted; two issuers sharing a subject do not share a user.+func TestUnverifiedEmailAndIssuerCollision(t *testing.T) {+ h := newLifecycleHarness(t)+ ctx := context.Background()+ if err := h.store.SaveMeshPolicy(ctx,+ []*api.PolicyRole{{Name: api.RoleNode}, {Name: "by-email", AllowedServices: []string{"*"}}},+ []*api.PolicyBinding{+ {Role: api.RoleNode, Members: []string{api.SystemAuthenticated}},+ {Role: "by-email", Members: []string{"email:[email protected]"}},+ }); err != nil {+ t.Fatal(err)+ }+ cpPriv, cpPub, err := h.store.GetCurrentKey(ctx)+ if err != nil {+ t.Fatal(err)+ }+ _ = cpPriv+ _ = cpPub++ mintedRoles := func(claims map[string]interface{}) []string {+ t.Helper()+ priv, id := newTestKey(t)+ pub, err := crypto.MarshalPublicKey(priv.GetPublic())+ if err != nil {+ t.Fatal(err)+ }+ ts, sig := registerPoP(t, priv, id.String())+ claims["sub"] = id.String() // distinct subjects, so only the email can bind+ data, err := proto.Marshal(&api.EnrollRequest{+ Jwt: h.mintToken(claims), PeerId: id.String(), PublicKey: pub,+ RequestedRole: api.RoleNode, Timestamp: ts, ChallengeSignature: sig,+ })+ if err != nil {+ t.Fatal(err)+ }+ status, body := h.do(http.MethodPost, "/register", "", data, "application/x-protobuf")+ if status != http.StatusOK {+ t.Fatalf("/register: %d %s", status, body)+ }+ var resp api.EnrollResponse+ if err := proto.Unmarshal(body, &resp); err != nil {+ t.Fatal(err)+ }+ var roles []string+ for _, r := range []string{api.RoleNode, "by-email"} {+ if authorityHasFact(t, resp.BiscuitToken, api.FactRole+`("`+r+`")`) {+ roles = append(roles, r)+ }+ }+ return roles+ }++ verified := mintedRoles(map[string]interface{}{"email": "[email protected]", "email_verified": true})+ if !slices.Contains(verified, "by-email") {+ t.Errorf("verified email did not resolve its binding: roles=%v", verified)+ }+ unverified := mintedRoles(map[string]interface{}{"email": "[email protected]", "email_verified": false})+ if slices.Contains(unverified, "by-email") {+ t.Errorf("email the issuer marked unverified resolved a binding: roles=%v", unverified)+ }++ // Issuer collision: a user row from issuer A, then the same sub from+ // issuer B. The second issuer is unknown to the control plane so its+ // token is refused before the user lookup; simulate the collision at the+ // store level, the way a second configured issuer would produce it.+ const sub = "shared-sub"+ if err := h.store.SaveUser(ctx, &storage.User{ID: sub, Issuer: "https://other-idp.example", Email: "[email protected]", Role: "user", CreatedAt: time.Now()}); err != nil {+ t.Fatal(err)+ }+ status, body := h.do(http.MethodGet, "/user/status", h.mintToken(map[string]interface{}{"sub": sub}), nil, "")+ if status != http.StatusUnauthorized {+ t.Errorf("same subject from another issuer: got %d (%s), want 401", status, body)+ }+}++// M2: a mesh with no policy roles used to mint every node an unrestricted+// token. Now it mints the role and nothing else.+func TestNoPolicyMintsNoGrants(t *testing.T) {+ _, cpPriv, err := ed25519.GenerateKey(nil)+ if err != nil {+ t.Fatal(err)+ }+ _, id := newTestKey(t)+ data, err := identity.MintBootstrapBiscuitToken(cpPriv, id, api.RoleNode, time.Now().Add(time.Hour), nil, nil)+ if err != nil {+ t.Fatal(err)+ }+ for _, open := range []string{api.FactGrantedServiceAllTypes, api.FactTargetUnrestricted} {+ if authorityHasFact(t, data, open+"(") {+ t.Errorf("token minted under an empty policy carries %s()", open)+ }+ }+ if !authorityHasFact(t, data, api.FactRole+`("`+api.RoleNode+`")`) {+ t.Error("token lacks its role fact")+ }+}++// authorityHasFact reports whether the token's authority block prints the+// given Datalog text (Biscuit.Code lists appended blocks only).+func authorityHasFact(t *testing.T, token []byte, text string) bool {+ t.Helper()+ b, err := biscuit.Unmarshal(token)+ if err != nil {+ t.Fatal(err)+ }+ return strings.Contains(b.String(), text)+}diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex 21063266..75ffa531 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -66,6 +66,10 @@ const (// for storage.EnrolledNode.AutonomousRecovery. Admin-console only: the// node-facing side of #367 is TokenRefreshRequest.peer_id in sam.proto.adminNodeActionAutonomousRecovery = "autonomous-recovery"++ // adminNodeActionUnban is the action segment of+ // POST /admin/nodes/{peer_id}/unban, the inverse of POST /admin/revoke.+ adminNodeActionUnban = "unban")// Server implements the SAM Control Plane web app.@@ -384,9 +388,12 @@ func (s *Server) HandleReadyz(w http.ResponseWriter, r *http.Request) {}if s.store != nil {if err := s.store.Ping(r.Context()); err != nil {+ // The DSN, host names and driver errors are operator material; the+ // probe is unauthenticated.+ logger.Errorf("Readiness probe: database unreachable: %v", err)w.Header().Set("Content-Type", "application/json")w.WriteHeader(http.StatusServiceUnavailable)- _, _ = fmt.Fprintf(w, `{"status":"error","message":%q}`, err.Error())+ _, _ = w.Write([]byte(`{"status":"error","message":"database unavailable"}`))return}}@@ -502,6 +509,11 @@ func (s *Server) HandleRegister(w http.ResponseWriter, r *http.Request) {http.Error(w, "JWT validation failed: "+err.Error(), http.StatusUnauthorized)return}+ // An email the issuer marks unverified must not resolve bindings or be+ // minted as an email() fact.+ if verifiedEmail(claims) == "" {+ delete(claims, "email")+ }pID, err := peer.Decode(req.PeerId)if err != nil {@@ -1122,34 +1134,31 @@ func (s *Server) HandlePolicies(w http.ResponseWriter, r *http.Request) {// Simple HTTP admin methods for policiesswitch r.Method {case http.MethodGet:- // Nodes need to fetch policies using their Biscuit token, Admins use OIDC/Bootstrap- isAdmin := false- user, err := s.authenticateUser(r)- if err == nil && user.Role == "admin" {- isAdmin = true- }-+ // Nodes fetch policies with their biscuit, admins with the admin token+ // or an ID token. The biscuit is tried first: running OIDC+ // verification on a biscuit logs a failure and would auto-register+ // whoever's ID token lands here.isNode := false- if !isAdmin {- // Try checking if it's a valid node biscuit- authHeader := r.Header.Get("Authorization")- if strings.HasPrefix(authHeader, "Bearer ") {- biscuitBytes, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Bearer "))- if err == nil {- trustedKeys, err := s.store.GetAllValidPublicKeys(r.Context())- if err == nil {- 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.CheckAdmission(time.Now()) == nil {- isNode = true- }+ if authHeader := r.Header.Get("Authorization"); strings.HasPrefix(authHeader, "Bearer ") {+ if biscuitBytes, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Bearer ")); err == nil {+ if trustedKeys, err := s.store.GetAllValidPublicKeys(r.Context()); err == nil {+ if peerID, err := identity.VerifyAndExtractPeerID(trustedKeys, biscuitBytes, s.config.BiscuitTimeout); err == nil {+ nodeRecord, nodeErr := s.store.GetNode(r.Context(), peerID.String())+ if nodeErr == nil && nodeRecord != nil && nodeRecord.CheckAdmission(time.Now()) == nil {+ isNode = true}}}}}+ isAdmin := false+ if !isNode {+ if user, err := s.authenticateUser(r); err == nil && user.Role == "admin" {+ isAdmin = true+ }+ }+if !isAdmin && !isNode {http.Error(w, "Unauthorized: Admin or Node authentication required", http.StatusUnauthorized)return@@ -1331,6 +1340,17 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {return}+ // A token is only as welcome as the identity that minted it.+ if banned, err := s.tokenOwnerBanned(ctx, tokenRecord); err != nil {+ logger.Errorf("Failed to check token owner ban: %v", err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ } else if banned {+ logger.Warnw("Bootstrap token from a banned identity used", "peer_id", req.PeerId, "token_id", tokenRecord.ID, "owner", tokenRecord.OwnerID)+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Bootstrap token owner is banned")+ return+ }+if req.RequestedRole == "" {s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "requested_role must be specified")return@@ -1395,7 +1415,7 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {if existingReq.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {biscuitToken, resolvedAt, refreshErr := s.remintApprovedBootstrapBiscuit(ctx, existingReq, tokenRecord)if refreshErr != nil {- if errors.Is(refreshErr, storage.ErrNodeBanned) || errors.Is(refreshErr, storage.ErrNodeSessionExpired) || errors.Is(refreshErr, errBootstrapRoleMismatch) {+ if errors.Is(refreshErr, storage.ErrNodeBanned) || errors.Is(refreshErr, storage.ErrNodeSessionExpired) || errors.Is(refreshErr, errBootstrapRoleMismatch) || errors.Is(refreshErr, storage.ErrBootstrapTokenUnusable) {logger.Warnw("Refused bootstrap re-enrollment", "peer_id", req.PeerId, "error", refreshErr)s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Enrollment no longer valid: "+refreshErr.Error())return@@ -1461,6 +1481,18 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Label not permitted: "+err.Error())return}+ // Spend the usage before anything is minted or written: the read+ // above is advisory, this is the gate concurrent enrollments race on.+ if err := s.store.ConsumeBootstrapTokenUsage(ctx, tokenRecord.ID, time.Now()); err != nil {+ if errors.Is(err, storage.ErrBootstrapTokenUnusable) {+ logger.Warnw("Bootstrap token no longer usable at enrollment", "peer_id", canonical, "token_id", tokenRecord.ID)+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Bootstrap token expired, revoked or exhausted")+ return+ }+ logger.Errorf("Failed to consume token usage: %v", err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ }biscuitBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, tokenRecord.Role, time.Now().Add(s.config.BiscuitTTL), policyRoles, req.Labels)if err != nil {logger.Errorf("Failed to mint bootstrap biscuit: %v", err)@@ -1474,12 +1506,8 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {enrollReq.ResolvedAt = &tNowenrollReq.ResolvedBy = "auto-approver"- if err := s.store.CreateEnrollmentRequest(ctx, enrollReq); err != nil {- logger.Errorf("Failed to save enrollment request: %v", err)- http.Error(w, "Internal server error", http.StatusInternalServerError)- return- }-+ // Node record first: an approved request with no node behind it hands+ // out a biscuit that /admin/revoke cannot find (see approve).nodeRecord := &storage.EnrolledNode{PeerID: canonical,PublicKey: req.PublicKey,@@ -1498,8 +1526,10 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {return}- if err := s.store.IncrementBootstrapTokenUsage(ctx, tokenRecord.ID); err != nil {- logger.Errorf("Failed to increment token usage: %v", err)+ if err := s.store.CreateEnrollmentRequest(ctx, enrollReq); err != nil {+ logger.Errorf("Failed to save enrollment request: %v", err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return}resp, err := s.buildApprovedBootstrapEnrollResponse(ctx, biscuitBytes, enrollReq.ResolvedAt)@@ -1642,6 +1672,11 @@ func (s *Server) HandleEnrollStatus(w http.ResponseWriter, r *http.Request) {s.writeEnrollResponse(w, resp)}+// errIdentityBanned is authenticateUser's answer for a valid ID token whose+// issuer|subject has been banned. Callers map it to 403, not 401: the token+// is fine, the identity is not welcome.+var errIdentityBanned = errors.New("identity is banned")+func (s *Server) authenticateUser(r *http.Request) (*storage.User, error) {authHeader := r.Header.Get("Authorization")if !strings.HasPrefix(authHeader, "Bearer ") {@@ -1678,13 +1713,26 @@ func (s *Server) authenticateUser(r *http.Request) (*storage.User, error) {if sub == "" {return nil, errors.New("token subject (sub) claim is empty")}- email, _ := claims["email"].(string)+ iss, _ := claims["iss"].(string)+ email := verifiedEmail(claims)++ // A revoked node bans the identity behind it (banNode), and that has to+ // hold on every surface the identity can drive with its ID token, or it+ // mints itself a bootstrap token and re-enrolls a fresh device.+ if banned, err := s.store.IsIdentityBanned(ctx, oidcIdentityKey(claims)); err != nil {+ return nil, fmt.Errorf("failed to check identity ban: %w", err)+ } else if banned {+ logger.Warnw("Banned identity presented a valid ID token", "identity", oidcIdentityKey(claims))+ return nil, errIdentityBanned+ }// Fetch or auto-register useruser, err := s.store.GetUser(ctx, sub)- if err == storage.ErrNotFound {+ switch {+ case err == storage.ErrNotFound:user = &storage.User{ID: sub,+ Issuer: iss,Email: email,Role: "user",CreatedAt: time.Now(),@@ -1692,18 +1740,56 @@ func (s *Server) authenticateUser(r *http.Request) (*storage.User, error) {if err := s.store.SaveUser(ctx, user); err != nil {return nil, fmt.Errorf("failed to register user: %w", err)}- logger.Infow("Auto-registered new OIDC user", "id", sub, "email", email)- } else if err != nil {+ logger.Infow("Auto-registered new OIDC user", "id", sub, "issuer", iss, "email", email)+ case err != nil:return nil, fmt.Errorf("failed to get user: %w", err)+ case user.Issuer == "":+ // Row from before issuers were recorded: adopt this one.+ user.Issuer = iss+ if err := s.store.SaveUser(ctx, user); err != nil {+ return nil, fmt.Errorf("failed to record user issuer: %w", err)+ }+ case user.Issuer != iss:+ // Users are keyed on the subject alone; two issuers handing out the+ // same subject would otherwise share one account and its nodes.+ logger.Warnw("ID token subject collides with a user from another issuer", "sub", sub, "issuer", iss, "user_issuer", user.Issuer)+ return nil, errors.New("subject is registered under a different issuer")}return user, nil}-func (s *Server) checkAdminAuth(w http.ResponseWriter, r *http.Request) bool {+// verifiedEmail returns the email claim unless the issuer marked it+// unverified. Absent email_verified is kept (many issuers never emit it and+// several emit no email at all); an explicit false is not an identity.+func verifiedEmail(claims jwt.MapClaims) string {+ if v, ok := claims["email_verified"].(bool); ok && !v {+ return ""+ }+ email, _ := claims["email"].(string)+ return email+}++// requireUser authenticates the caller for a user- or admin-facing route and+// writes the failure itself. Internal failures are logged, not echoed: the+// body says only whether the caller is unauthenticated or banned.+func (s *Server) requireUser(w http.ResponseWriter, r *http.Request) (*storage.User, bool) {user, err := s.authenticateUser(r)- if err != nil {- http.Error(w, "Unauthorized: "+err.Error(), http.StatusUnauthorized)+ if err == nil {+ return user, true+ }+ if errors.Is(err, errIdentityBanned) {+ http.Error(w, "Forbidden: identity is banned", http.StatusForbidden)+ return nil, false+ }+ logger.Debugf("User authentication failed: %v", err)+ http.Error(w, "Unauthorized", http.StatusUnauthorized)+ return nil, false+}++func (s *Server) checkAdminAuth(w http.ResponseWriter, r *http.Request) bool {+ user, ok := s.requireUser(w, r)+ if !ok {return false}if user.Role != "admin" {@@ -1902,7 +1988,11 @@ func (s *Server) HandleAdminEnrollmentAction(w http.ResponseWriter, r *http.RequadminIdentity := "admin"if action == "reject" {- err = s.store.UpdateEnrollmentRequest(ctx, id, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, nil, adminIdentity)+ err = s.store.ResolveEnrollmentRequest(ctx, id, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, nil, adminIdentity)+ if errors.Is(err, storage.ErrEnrollmentAlreadyResolved) {+ http.Error(w, "Enrollment request is already resolved", http.StatusConflict)+ return+ }if err != nil {logger.Errorf("Failed to reject enrollment: %v", err)http.Error(w, "Internal server error", http.StatusInternalServerError)@@ -1921,6 +2011,29 @@ func (s *Server) HandleAdminEnrollmentAction(w http.ResponseWriter, r *http.Requreturn}+ // The token was checked when the request was queued; it may have been+ // revoked, expired or run out since, and its owner may have been+ // banned. Approval is where it is spent, so it is re-checked here.+ switch {+ case tokenRecord.IsRevoked():+ http.Error(w, "Bootstrap token has been revoked since this request was queued", http.StatusGone)+ return+ case time.Now().After(tokenRecord.ExpiresAt):+ http.Error(w, "Bootstrap token has expired since this request was queued", http.StatusGone)+ return+ case tokenRecord.UsagesCount >= tokenRecord.MaxUsages:+ http.Error(w, "Bootstrap token has no usages left", http.StatusGone)+ return+ }+ if banned, err := s.tokenOwnerBanned(ctx, tokenRecord); err != nil {+ logger.Errorf("Failed to check token owner ban: %v", err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ } else if banned {+ http.Error(w, "Bootstrap token owner is banned", http.StatusForbidden)+ return+ }+pID, err := peer.Decode(enrollReq.PeerID)if err != nil {http.Error(w, "Invalid Peer ID stored in request", http.StatusInternalServerError)@@ -1928,8 +2041,6 @@ func (s *Server) HandleAdminEnrollmentAction(w http.ResponseWriter, r *http.Requ}canonical := pID.String()- // No policy fetch needed.-privKey, _, err := s.store.GetCurrentKey(ctx)if err != nil {logger.Errorf("Failed to retrieve signing key: %v", err)@@ -1954,20 +2065,29 @@ func (s *Server) HandleAdminEnrollmentAction(w http.ResponseWriter, r *http.Requreturn}- biscuitBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, tokenRecord.Role, time.Now().Add(s.config.BiscuitTTL), policyRoles, enrollReq.Labels)- if err != nil {- logger.Errorf("Failed to mint bootstrap biscuit: %v", err)+ // The atomic gate; the checks above only give a better message.+ if err := s.store.ConsumeBootstrapTokenUsage(ctx, tokenRecord.ID, time.Now()); err != nil {+ if errors.Is(err, storage.ErrBootstrapTokenUnusable) {+ http.Error(w, "Bootstrap token expired, revoked or exhausted", http.StatusGone)+ return+ }+ logger.Errorf("Failed to consume token usage: %v", err)http.Error(w, "Internal server error", http.StatusInternalServerError)return}- err = s.store.UpdateEnrollmentRequest(ctx, id, api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED, biscuitBytes, adminIdentity)+ biscuitBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, tokenRecord.Role, time.Now().Add(s.config.BiscuitTTL), policyRoles, enrollReq.Labels)if err != nil {- logger.Errorf("Failed to approve enrollment request in DB: %v", err)+ logger.Errorf("Failed to mint bootstrap biscuit: %v", err)http.Error(w, "Internal server error", http.StatusInternalServerError)return}+ // Node record before the request flips to APPROVED. The other order+ // left a window where /enroll/status handed out a biscuit for a node+ // that did not exist: routers accepted it and /admin/revoke could not+ // find it. A node row with a still-pending request is the harmless+ // failure: the enrollee keeps polling and the admin can retry.nodeRecord := &storage.EnrolledNode{PeerID: canonical,PublicKey: enrollReq.PublicKey,@@ -1986,8 +2106,15 @@ func (s *Server) HandleAdminEnrollmentAction(w http.ResponseWriter, r *http.Requreturn}- if err := s.store.IncrementBootstrapTokenUsage(ctx, tokenRecord.ID); err != nil {- logger.Errorf("Failed to increment token usage: %v", err)+ err = s.store.ResolveEnrollmentRequest(ctx, id, api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED, biscuitBytes, adminIdentity)+ if errors.Is(err, storage.ErrEnrollmentAlreadyResolved) {+ http.Error(w, "Enrollment request is already resolved", http.StatusConflict)+ return+ }+ if err != nil {+ logger.Errorf("Failed to approve enrollment request in DB: %v", err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return}w.WriteHeader(http.StatusOK)@@ -2013,7 +2140,7 @@ func (s *Server) HandleAdminNodeAction(w http.ResponseWriter, r *http.Request) {}parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/admin/nodes/"), "/")- if len(parts) != 2 || parts[1] != adminNodeActionAutonomousRecovery {+ if len(parts) != 2 {http.Error(w, "Not found", http.StatusNotFound)return}@@ -2022,6 +2149,36 @@ func (s *Server) HandleAdminNodeAction(w http.ResponseWriter, r *http.Request) {http.Error(w, "Invalid Peer ID", http.StatusBadRequest)return}+ canonical := pID.String()++ switch parts[1] {+ case adminNodeActionUnban:+ // The inverse of /admin/revoke: lifts the device-key ban and the+ // identity ban together, so the human behind the node can enroll+ // again. Until this existed an identity ban was permanent short of+ // editing the database.+ node, err := s.store.GetNode(r.Context(), canonical)+ if err == storage.ErrNotFound {+ http.Error(w, "Node not found", http.StatusNotFound)+ return+ } else if err != nil {+ logger.Errorf("Failed to retrieve node %s: %v", canonical, err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ }+ if err := SetNodeBan(r.Context(), s.store, node, false); err != nil {+ logger.Errorf("Failed to unban node %s: %v", canonical, err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ }+ logger.Infow("Node and identity unbanned", "peer_id", canonical)+ w.WriteHeader(http.StatusNoContent)+ return+ case adminNodeActionAutonomousRecovery:+ default:+ http.Error(w, "Not found", http.StatusNotFound)+ return+ }var req struct {Enabled bool `json:"enabled"`@@ -2033,7 +2190,6 @@ func (s *Server) HandleAdminNodeAction(w http.ResponseWriter, r *http.Request) {}defer func() { _ = r.Body.Close() }()- canonical := pID.String()err = s.store.SetNodeAutonomousRecovery(r.Context(), canonical, req.Enabled)if err == storage.ErrNotFound {http.Error(w, "Node not found", http.StatusNotFound)@@ -2165,6 +2321,14 @@ func (s *Server) remintApprovedBootstrapBiscuit(ctx context.Context, existingReqreturn nil, nil, err}+ // Re-minting consumes a use of the bootstrap token, the same as the+ // original enrollment did - it is the operator's lever on how many times+ // this can happen, per #367/#368. Spent before minting: an exhausted,+ // expired or revoked token re-mints nothing.+ if err := s.store.ConsumeBootstrapTokenUsage(ctx, tokenRecord.ID, time.Now()); err != nil {+ return nil, nil, fmt.Errorf("bootstrap token cannot re-mint for %s: %w", pID, err)+ }+privKey, _, err := s.store.GetCurrentKey(ctx)if err != nil {return nil, nil, fmt.Errorf("failed to retrieve signing key: %w", err)@@ -2193,19 +2357,26 @@ func (s *Server) remintApprovedBootstrapBiscuit(ctx context.Context, existingReqreturn nil, nil, fmt.Errorf("failed to persist refreshed node record: %w", err)}- // Re-minting consumes a use of the bootstrap token, the same as the- // original enrollment did - it is the operator's lever on how many times- // this can happen, per #367/#368. A failure here only means the usage- // counter under-counts; it must not block the peer from getting its- // (already persisted) fresh biscuit.- if err := s.store.IncrementBootstrapTokenUsage(ctx, tokenRecord.ID); err != nil {- logger.Errorf("Failed to increment bootstrap token usage on re-mint for %s: %v", pID, err)- }-resolvedAt := time.Now()return biscuitBytes, &resolvedAt, nil}+// tokenOwnerBanned reports whether the identity that minted a bootstrap+// token has since been banned. Admin-minted tokens have no owner.+func (s *Server) tokenOwnerBanned(ctx context.Context, tok *storage.BootstrapToken) (bool, error) {+ if tok.OwnerID == "" {+ return false, nil+ }+ owner, err := s.store.GetUser(ctx, tok.OwnerID)+ if err == storage.ErrNotFound {+ return false, nil+ }+ if err != nil {+ return false, err+ }+ return s.store.IsIdentityBanned(ctx, owner.IdentityKey())+}+func (s *Server) buildApprovedBootstrapEnrollResponse(ctx context.Context, biscuitToken []byte, resolvedAt *time.Time) (*api.BootstrapEnrollResponse, error) {_, pubKey, err := s.store.GetCurrentKey(ctx)if err != nil {@@ -2241,64 +2412,38 @@ func (s *Server) HandleUserStatus(w http.ResponseWriter, r *http.Request) {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)return}- user, err := s.authenticateUser(r)- if err != nil {- http.Error(w, "Unauthorized: "+err.Error(), http.StatusUnauthorized)+ user, ok := s.requireUser(w, r)+ if !ok {return}ctx := r.Context()- routers, err := s.store.GetActiveRouters(ctx)- if err != nil {- logger.Errorf("Failed to get active routers: %v", err)- http.Error(w, "Internal server error", http.StatusInternalServerError)- return- }+ isAdmin := user.Role == "admin"- nodes := []storage.EnrolledNode{}- if user.Role == "admin" {- nodes, err = s.store.ListNodes(ctx)- } else {- allNodes, err := s.store.ListNodes(ctx)- if err == nil {- for _, n := range allNodes {- if n.OwnerID == user.ID {- nodes = append(nodes, n)- }- }- }- }+ allNodes, err := s.store.ListNodes(ctx)if err != nil {logger.Errorf("Failed to list nodes: %v", err)http.Error(w, "Internal server error", http.StatusInternalServerError)return}-- tokens := []storage.BootstrapToken{}- allTokens, err := s.store.ListBootstrapTokens(ctx)- if err == nil {- for _, t := range allTokens {- if t.OwnerID == user.ID || user.Role == "admin" {- tokens = append(tokens, t)- }+ nodes := []enrolledNodeView{}+ for _, n := range allNodes {+ if isAdmin || n.OwnerID == user.ID {+ nodes = append(nodes, viewEnrolledNode(n, isAdmin))}}++ allTokens, err := s.store.ListBootstrapTokens(ctx)if err != nil {logger.Errorf("Failed to list bootstrap tokens: %v", err)http.Error(w, "Internal server error", http.StatusInternalServerError)return}-- roles, bindings, err := s.store.GetMeshPolicy(r.Context())- if err != nil {- logger.Errorf("Failed to list policy: %v", err)- }-- var policyJSON string- if rendered, err := marshalPolicyJSON(roles, bindings); err == nil {- policyJSON = rendered- } else {- logger.Errorf("Failed to render policy: %v", err)+ tokens := []storage.BootstrapToken{}+ for _, t := range allTokens {+ if isAdmin || t.OwnerID == user.ID {+ tokens = append(tokens, t)+ }}resp := map[string]any{@@ -2307,10 +2452,30 @@ func (s *Server) HandleUserStatus(w http.ResponseWriter, r *http.Request) {"email": user.Email,"role": user.Role,},- "active_routers": routers,"enrolled_nodes": nodes,"bootstrap_tokens": tokens,- "policy_json": policyJSON,+ }++ // The mesh policy and the router fleet describe the whole mesh, not the+ // caller's nodes; they are admin material.+ if isAdmin {+ routers, err := s.store.GetActiveRouters(ctx)+ if err != nil {+ logger.Errorf("Failed to get active routers: %v", err)+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ return+ }+ resp["active_routers"] = routers++ roles, bindings, err := s.store.GetMeshPolicy(ctx)+ if err != nil && err != storage.ErrNotFound {+ logger.Errorf("Failed to list policy: %v", err)+ }+ if rendered, err := marshalPolicyJSON(roles, bindings); err == nil {+ resp["policy_json"] = rendered+ } else {+ logger.Errorf("Failed to render policy: %v", err)+ }}w.Header().Set("Content-Type", "application/json")@@ -2318,10 +2483,50 @@ func (s *Server) HandleUserStatus(w http.ResponseWriter, r *http.Request) {_ = json.NewEncoder(w).Encode(resp)}+// enrolledNodeView is what status endpoints return for a node: the record+// minus its live credential and key material. ClaimsJSON is admin-only.+type enrolledNodeView struct {+ PeerID string `json:"PeerID"`+ Role string `json:"Role"`+ EnrollmentType string `json:"EnrollmentType"`+ ClaimsJSON string `json:"ClaimsJSON,omitempty"`+ OwnerID string `json:"OwnerID"`+ Labels map[string]string `json:"Labels"`+ EnrolledAt time.Time `json:"EnrolledAt"`+ ExpiresAt time.Time `json:"ExpiresAt"`+ Banned bool `json:"Banned"`+ AutonomousRecovery bool `json:"AutonomousRecovery"`+}++func viewEnrolledNode(n storage.EnrolledNode, withClaims bool) enrolledNodeView {+ v := enrolledNodeView{+ PeerID: n.PeerID,+ Role: n.Role,+ EnrollmentType: n.EnrollmentType,+ OwnerID: n.OwnerID,+ Labels: n.Labels,+ EnrolledAt: n.EnrolledAt,+ ExpiresAt: n.ExpiresAt,+ Banned: n.Banned,+ AutonomousRecovery: n.AutonomousRecovery,+ }+ if withClaims {+ v.ClaimsJSON = n.ClaimsJSON+ }+ return v+}++// Ceilings on what a non-admin may mint for itself: a token is a standing+// invitation into the mesh, and these bound how long and how wide one+// user's invitation can be.+const (+ userTokenMaxTTLHours = 7 * 24+ userTokenMaxUsages = 10+)+func (s *Server) HandleUserBootstrapTokens(w http.ResponseWriter, r *http.Request) {- user, err := s.authenticateUser(r)- if err != nil {- http.Error(w, "Unauthorized: "+err.Error(), http.StatusUnauthorized)+ user, ok := s.requireUser(w, r)+ if !ok {return}@@ -2374,6 +2579,16 @@ func (s *Server) HandleUserBootstrapTokens(w http.ResponseWriter, r *http.Requesif req.MaxUsages <= 0 {req.MaxUsages = 1}+ if user.Role != "admin" {+ if req.TTLHours > userTokenMaxTTLHours {+ http.Error(w, fmt.Sprintf("ttl_hours may not exceed %d for non-admin users", userTokenMaxTTLHours), http.StatusBadRequest)+ return+ }+ if req.MaxUsages > userTokenMaxUsages {+ http.Error(w, fmt.Sprintf("max_usages may not exceed %d for non-admin users", userTokenMaxUsages), http.StatusBadRequest)+ return+ }+ }randBytes := make([]byte, 16)if _, err := rand.Read(randBytes); err != nil {@@ -2434,9 +2649,8 @@ func (s *Server) resolveTokenOwner(ctx context.Context, caller *storage.User, re}func (s *Server) HandleUserRevoke(w http.ResponseWriter, r *http.Request) {- user, err := s.authenticateUser(r)- if err != nil {- http.Error(w, "Unauthorized: "+err.Error(), http.StatusUnauthorized)+ user, ok := s.requireUser(w, r)+ if !ok {return}@@ -2507,10 +2721,22 @@ func oidcIdentityKey(claims jwt.MapClaims) string {// banNode bans the device key and, when the record carries OIDC claims, the// enrolled identity behind it, so the ban survives keypair regeneration.func (s *Server) banNode(ctx context.Context, node *storage.EnrolledNode) error {- if err := s.store.SetNodeBanned(ctx, node.PeerID, true); err != nil {+ if err := SetNodeBan(ctx, s.store, node, true); err != nil {return err}s.dropCatalogEntry(node.PeerID)+ return nil+}++// SetNodeBan bans or unbans a node and, when its record carries OIDC claims,+// the identity behind it. The one place both halves are toggled together,+// for the HTTP handlers and the CLI alike: a ban that names only the peer id+// is shed with a new keypair, and an unban that lifts only the peer id leaves+// the human locked out of /register.+func SetNodeBan(ctx context.Context, store storage.Store, node *storage.EnrolledNode, banned bool) error {+ if err := store.SetNodeBanned(ctx, node.PeerID, banned); err != nil {+ return err+ }if node.ClaimsJSON == "" {return nil}@@ -2519,7 +2745,7 @@ func (s *Server) banNode(ctx context.Context, node *storage.EnrolledNode) errorreturn fmt.Errorf("stored claims for %s are unreadable: %w", node.PeerID, err)}if key := oidcIdentityKey(claims); key != "" {- return s.store.SetIdentityBanned(ctx, key, true)+ return store.SetIdentityBanned(ctx, key, banned)}return nil}@@ -2700,12 +2926,9 @@ func validatePolicyConfig(req *api.PolicyConfigUpdateRequest) error {return fmt.Errorf("policy config would allow a single identity (via overlapping bindings) to accumulate up to %d Datalog facts across all roles, exceeding the safe budget of %d; biscuit-go's authorizer rejects tokens/checks beyond ~1000 world facts, so requests would start failing at authorization time instead of at config validation. Reduce the number of roles, grants, or custom_datalog entries", factBudget, maxIdentityFactBudget)}- validPrefixes := map[string]bool{- api.FactNode: true,- api.FactGroup: true,- api.FactUser: true,- api.FactEmail: true,- api.FactRole: true,+ validPrefixes := make(map[string]bool)+ for _, p := range api.BindingMemberPrefixes() {+ validPrefixes[p] = true}for _, b := range req.Bindings {diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.goindex e8cfef47..e0f85ae1 100644--- a/internal/controlplane/server_test.go+++ b/internal/controlplane/server_test.go@@ -30,6 +30,7 @@ import ("os""path/filepath""reflect"+ "slices""strconv""strings""sync/atomic"@@ -2310,12 +2311,18 @@ func TestResolveRolesAndRoleImpersonationProtection(t *testing.T) {bindings := []*api.PolicyBinding{{Role: api.RoleRouter,- Members: []string{"group:routers", "role:oidc-router-role"},+ Members: []string{"group:routers", "idp_role:oidc-router-role"},},{Role: api.RoleSamBox,Members: []string{"user:sambox-admin-sub"},},+ {+ // A binding on the mesh role fact itself: must never resolve from a+ // claim, or an issuer emitting roles: ["sam:role:router"] gets in.+ Role: "legacy-role-prefix",+ Members: []string{"role:oidc-router-role"},+ },}t.Run("OIDC claims role is not blindly trusted without explicit binding", func(t *testing.T) {@@ -2331,20 +2338,17 @@ func TestResolveRolesAndRoleImpersonationProtection(t *testing.T) {}})- t.Run("Explicit role mapping in binding grants capability role", func(t *testing.T) {+ t.Run("Explicit idp_role mapping in binding grants capability role", func(t *testing.T) {claims := jwt.MapClaims{"sub": "router-sub","roles": []string{"oidc-router-role"},}roles := resolveRoles("peer-123", claims, bindings)- hasRouter := false- for _, r := range roles {- if r == api.RoleRouter {- hasRouter = true- }+ if !slices.Contains(roles, api.RoleRouter) {+ t.Errorf("Expected role %q to be granted via explicit idp_role binding mapping", api.RoleRouter)}- if !hasRouter {- t.Errorf("Expected role %q to be granted via explicit role binding mapping", api.RoleRouter)+ if slices.Contains(roles, "legacy-role-prefix") {+ t.Errorf("a role: member resolved from the IdP roles claim; the claim must only feed idp_role")}})diff --git a/internal/identity/biscuit.go b/internal/identity/biscuit.goindex a7acf6bc..73247c39 100644--- a/internal/identity/biscuit.go+++ b/internal/identity/biscuit.go@@ -231,8 +231,6 @@ func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []stri}}- hasTargets := false- hasServices := falsesort.Strings(roles)var errs []error// Collected across every matched role and merged into Set facts once below: a token's@@ -266,22 +264,12 @@ func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []stri}}); err != nil {errs = append(errs, fmt.Errorf("failed to add target unrestricted: %w", err))}- hasTargets = true- hasServices = truecontinue}if pr, ok := rolesMap[role]; ok {- if len(pr.AllowedServices) > 0 {- hasServices = true- allServices = append(allServices, pr.AllowedServices...)- }-- if len(pr.AllowedTargets) > 0 {- hasTargets = true- allTargets = append(allTargets, pr.AllowedTargets...)- }-+ allServices = append(allServices, pr.AllowedServices...)+ allTargets = append(allTargets, pr.AllowedTargets...)allAgents = append(allAgents, pr.AllowedAgents...)for _, customEntry := range pr.CustomDatalog {@@ -323,22 +311,10 @@ func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []stri}}- if !hasServices && len(policyRoles) == 0 {- if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactGrantedServiceAllTypes,- IDs: []biscuit.Term{},- }}); err != nil {- errs = append(errs, fmt.Errorf("failed to add fallback service fact: %w", err))- }- }- if !hasTargets && len(policyRoles) == 0 {- if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactTargetUnrestricted,- IDs: []biscuit.Term{},- }}); err != nil {- errs = append(errs, fmt.Errorf("failed to add fallback target fact: %w", err))- }- }+ // No policy means no grants. A mesh with no roles defined used to mint+ // every non-router an unrestricted token; a fresh control plane, or one+ // whose policy was wiped, was the most permissive configuration there+ // is. Deny by default: the operator posts a policy, then nodes can talk.if len(errs) > 0 {return nil, fmt.Errorf("biscuit policy validation failed: %w", errors.Join(errs...))diff --git a/internal/node/policy.go b/internal/node/policy.goindex 720a60b8..112a4c7c 100644--- a/internal/node/policy.go+++ b/internal/node/policy.go@@ -25,6 +25,15 @@ import (func BuildPolicyRules(roles []*api.PolicyRole, bindings []*api.PolicyBinding) []biscuit.Rule {var rules []biscuit.Rule+ // A binding member becomes the body of a rule that grants a mesh role,+ // so only facts the control plane attests in the authority block may+ // appear there: agent() is the caller's own claim, and role() would+ // grant a role from a role.+ allowedMemberPrefix := make(map[string]bool)+ for _, p := range api.BindingMemberPrefixes() {+ allowedMemberPrefix[p] = true+ }+for _, b := range bindings {if b == nil {continue@@ -41,7 +50,7 @@ func BuildPolicyRules(roles []*api.PolicyRole, bindings []*api.PolicyBinding) []continue}parts := strings.SplitN(m, ":", 2)- if len(parts) == 2 {+ if len(parts) == 2 && allowedMemberPrefix[parts[0]] {memberType := parts[0]memberVal := parts[1]rules = append(rules, biscuit.Rule{diff --git a/internal/storage/round_trip_test.go b/internal/storage/round_trip_test.goindex 8fff469c..83b0d033 100644--- a/internal/storage/round_trip_test.go+++ b/internal/storage/round_trip_test.go@@ -398,6 +398,7 @@ func TestUserRoundTripsEveryField(t *testing.T) {want := &User{ID: "user-1",+ Issuer: "https://idp.example",Email: "[email protected]",Role: "admin",CreatedAt: time.Now().Add(-time.Hour),diff --git a/internal/storage/sql_store.go b/internal/storage/sql_store.goindex ca362b02..913cde99 100644--- a/internal/storage/sql_store.go+++ b/internal/storage/sql_store.go@@ -437,6 +437,20 @@ var migrations = []migration{`ALTER TABLE bootstrap_tokens ADD COLUMN autonomous_recovery BOOLEAN DEFAULT FALSE NOT NULL`,},},+ {+ // Identity bans are keyed on issuer|subject; a user row keyed on the+ // bare subject could not be matched against them, so the surfaces a+ // user drives with an ID token (bootstrap tokens, revocation) did not+ // see the ban. Empty for rows from before this migration until the+ // user next logs in.+ version: 11,+ postgres: []string{+ `ALTER TABLE users ADD COLUMN IF NOT EXISTS issuer VARCHAR(512) DEFAULT '' NOT NULL`,+ },+ sqlite: []string{+ `ALTER TABLE users ADD COLUMN issuer TEXT DEFAULT '' NOT NULL`,+ },+ },}func (s *SQLStore) initSchema() error {@@ -785,8 +799,18 @@ func (s *SQLStore) GetNode(ctx context.Context, peerID string) (*EnrolledNode, e// SetNodeBanned implements Store.func (s *SQLStore) SetNodeBanned(ctx context.Context, peerID string, banned bool) error {query := s.rebind(`UPDATE nodes SET banned = ? WHERE peer_id = ?`)- _, err := s.db.ExecContext(ctx, query, banned, peerID)- return err+ res, err := s.db.ExecContext(ctx, query, banned, peerID)+ if err != nil {+ return err+ }+ n, err := res.RowsAffected()+ if err != nil {+ return err+ }+ if n == 0 {+ return ErrNotFound+ }+ return nil}// SetNodeAutonomousRecovery implements Store.@@ -1156,12 +1180,21 @@ func (s *SQLStore) GetBootstrapToken(ctx context.Context, id string) (*Bootstrapreturn &t, nil}-// IncrementBootstrapTokenUsage increments usage count.-func (s *SQLStore) IncrementBootstrapTokenUsage(ctx context.Context, id string) error {- query := `UPDATE bootstrap_tokens SET usages_count = usages_count + 1 WHERE id = ?`- _, err := s.db.ExecContext(ctx, s.rebind(query), id)+// ConsumeBootstrapTokenUsage implements Store. The validity conditions live+// in the WHERE clause so the check and the increment are one statement.+func (s *SQLStore) ConsumeBootstrapTokenUsage(ctx context.Context, id string, now time.Time) error {+ query := `UPDATE bootstrap_tokens SET usages_count = usages_count + 1+ WHERE id = ? AND usages_count < max_usages AND revoked_at IS NULL AND expires_at > ?`+ res, err := s.db.ExecContext(ctx, s.rebind(query), id, now.Unix())if err != nil {- return fmt.Errorf("failed to increment usage: %w", err)+ return fmt.Errorf("failed to consume token usage: %w", err)+ }+ n, err := res.RowsAffected()+ if err != nil {+ return fmt.Errorf("failed to consume token usage: %w", err)+ }+ if n == 0 {+ return ErrBootstrapTokenUnusable}return nil}@@ -1314,6 +1347,31 @@ func (s *SQLStore) UpdateEnrollmentRequest(ctx context.Context, id string, statureturn nil}+// ResolveEnrollmentRequest implements Store.+func (s *SQLStore) ResolveEnrollmentRequest(ctx context.Context, id string, status api.EnrollmentStatus, biscuit []byte, resolvedBy string) error {+ query := `UPDATE enrollment_requests SET status = ?, biscuit_token = ?, resolved_at = ?, resolved_by = ?+ WHERE id = ? AND status = ?`+ res, err := s.db.ExecContext(ctx, s.rebind(query),+ int(status),+ biscuit,+ time.Now().Unix(),+ resolvedBy,+ id,+ int(api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING),+ )+ if err != nil {+ return fmt.Errorf("failed to resolve enrollment request: %w", err)+ }+ n, err := res.RowsAffected()+ if err != nil {+ return fmt.Errorf("failed to resolve enrollment request: %w", err)+ }+ if n == 0 {+ return ErrEnrollmentAlreadyResolved+ }+ return nil+}+// ListNodes retrieves all enrolled nodes.func (s *SQLStore) ListNodes(ctx context.Context) ([]EnrolledNode, error) {query := s.rebind(`SELECT peer_id, public_key, biscuit_token, role, enrollment_type, claims_json, owner_id, labels_json, enrolled_at, expires_at, banned, autonomous_recovery FROM nodes ORDER BY enrolled_at DESC`)@@ -1432,18 +1490,19 @@ func (s *SQLStore) SaveUser(ctx context.Context, user *User) error {var query stringif s.isPostgres() {query = s.rebind(`- INSERT INTO users (id, email, role, created_at)- VALUES (?, ?, ?, ?)- ON CONFLICT (id) DO UPDATE SET email = EXCLUDED.email, role = EXCLUDED.role`)+ INSERT INTO users (id, issuer, email, role, created_at)+ VALUES (?, ?, ?, ?, ?)+ ON CONFLICT (id) DO UPDATE SET issuer = EXCLUDED.issuer, email = EXCLUDED.email, role = EXCLUDED.role`)} else {query = s.rebind(`- INSERT INTO users (id, email, role, created_at)- VALUES (?, ?, ?, ?)- ON CONFLICT (id) DO UPDATE SET email = excluded.email, role = excluded.role`)+ INSERT INTO users (id, issuer, email, role, created_at)+ VALUES (?, ?, ?, ?, ?)+ ON CONFLICT (id) DO UPDATE SET issuer = excluded.issuer, email = excluded.email, role = excluded.role`)}_, err := s.db.ExecContext(ctx, query,user.ID,+ user.Issuer,user.Email,user.Role,user.CreatedAt.Unix(),@@ -1453,11 +1512,12 @@ func (s *SQLStore) SaveUser(ctx context.Context, user *User) error {// GetUser retrieves a user by ID.func (s *SQLStore) GetUser(ctx context.Context, id string) (*User, error) {- query := s.rebind(`SELECT id, email, role, created_at FROM users WHERE id = ?`)+ query := s.rebind(`SELECT id, issuer, email, role, created_at FROM users WHERE id = ?`)var user Uservar created int64err := s.db.QueryRowContext(ctx, query, id).Scan(&user.ID,+ &user.Issuer,&user.Email,&user.Role,&created,@@ -1474,7 +1534,7 @@ func (s *SQLStore) GetUser(ctx context.Context, id string) (*User, error) {// ListUsers retrieves all registered users.func (s *SQLStore) ListUsers(ctx context.Context) ([]User, error) {- query := `SELECT id, email, role, created_at FROM users`+ query := `SELECT id, issuer, email, role, created_at FROM users`rows, err := s.db.QueryContext(ctx, query)if err != nil {return nil, err@@ -1487,6 +1547,7 @@ func (s *SQLStore) ListUsers(ctx context.Context) ([]User, error) {var created int64if err := rows.Scan(&user.ID,+ &user.Issuer,&user.Email,&user.Role,&created,diff --git a/internal/storage/sql_store_test.go b/internal/storage/sql_store_test.goindex 4cde3f69..7471c0e9 100644--- a/internal/storage/sql_store_test.go+++ b/internal/storage/sql_store_test.go@@ -83,12 +83,12 @@ func TestSQLiteFilesAreOwnerOnly(t *testing.T) {func TestSQLiteFilePath(t *testing.T) {cases := map[string]string{- "keys.db": "keys.db",+ "keys.db": "keys.db","/data/keys.db?_pragma=busy_timeout(5)": "/data/keys.db",- "file:/data/keys.db?mode=rwc": "/data/keys.db",- ":memory:": "",- "file::memory:?cache=shared": "",- "": "",+ "file:/data/keys.db?mode=rwc": "/data/keys.db",+ ":memory:": "",+ "file::memory:?cache=shared": "",+ "": "",}for dsn, want := range cases {if got := sqliteFilePath(dsn); got != want {@@ -587,10 +587,13 @@ func TestBootstrapTokensAndEnrollmentRequestsOps(t *testing.T) {t.Errorf("retrieved token mismatch: %+v", ret)}- if err := store.IncrementBootstrapTokenUsage(ctx, tok.ID); err != nil {- t.Fatalf("failed to increment usage: %v", err)+ if err := store.ConsumeBootstrapTokenUsage(ctx, tok.ID, time.Now()); err != nil {+ t.Fatalf("failed to consume usage: %v", err)+ }+ ret2, err := store.GetBootstrapToken(ctx, tok.ID)+ if err != nil {+ t.Fatal(err)}- ret2, _ := store.GetBootstrapToken(ctx, tok.ID)if ret2.UsagesCount != 1 {t.Errorf("expected usage count 1, got %d", ret2.UsagesCount)}@@ -650,3 +653,113 @@ func TestBootstrapTokensAndEnrollmentRequestsOps(t *testing.T) {t.Errorf("updated request details mismatch: %+v", updatedReq)}}++// The usage cap used to be read-then-increment, so N concurrent enrollments+// on a 1-use token could all pass the read. The consume is now one statement+// that also refuses expired and revoked tokens.+func TestConsumeBootstrapTokenUsageIsAtomicAndGated(t *testing.T) {+ store := newTestStore(t)+ defer func() { _ = store.Close() }()+ ctx := context.Background()+ now := time.Now()++ save := func(id string, max int, expiresAt time.Time) {+ t.Helper()+ if err := store.SaveBootstrapToken(ctx, &BootstrapToken{+ ID: id, TokenHash: "h-" + id, Role: "sam:role:node", MaxUsages: max,+ CreatedAt: now, ExpiresAt: expiresAt,+ }); err != nil {+ t.Fatal(err)+ }+ }++ t.Run("cap under concurrency", func(t *testing.T) {+ save("cap", 3, now.Add(time.Hour))+ const attempts = 20+ var wg sync.WaitGroup+ var ok atomic.Int32+ for i := 0; i < attempts; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ err := store.ConsumeBootstrapTokenUsage(ctx, "cap", now)+ switch err {+ case nil:+ ok.Add(1)+ case ErrBootstrapTokenUnusable:+ default:+ t.Errorf("unexpected error: %v", err)+ }+ }()+ }+ wg.Wait()+ if ok.Load() != 3 {+ t.Errorf("%d of %d concurrent consumes succeeded on a 3-use token, want exactly 3", ok.Load(), attempts)+ }+ tok, err := store.GetBootstrapToken(ctx, "cap")+ if err != nil {+ t.Fatal(err)+ }+ if tok.UsagesCount != 3 {+ t.Errorf("usages_count = %d, want 3", tok.UsagesCount)+ }+ })++ t.Run("expired", func(t *testing.T) {+ save("expired", 5, now.Add(-time.Minute))+ if err := store.ConsumeBootstrapTokenUsage(ctx, "expired", now); err != ErrBootstrapTokenUnusable {+ t.Errorf("err = %v, want ErrBootstrapTokenUnusable", err)+ }+ })++ t.Run("revoked", func(t *testing.T) {+ save("revoked", 5, now.Add(time.Hour))+ if err := store.RevokeBootstrapToken(ctx, "revoked"); err != nil {+ t.Fatal(err)+ }+ if err := store.ConsumeBootstrapTokenUsage(ctx, "revoked", now); err != ErrBootstrapTokenUnusable {+ t.Errorf("err = %v, want ErrBootstrapTokenUnusable", err)+ }+ })++ t.Run("unknown", func(t *testing.T) {+ if err := store.ConsumeBootstrapTokenUsage(ctx, "nope", now); err != ErrBootstrapTokenUnusable {+ t.Errorf("err = %v, want ErrBootstrapTokenUnusable", err)+ }+ })+}++// Two admins acting on one pending request: only the first resolution lands.+func TestResolveEnrollmentRequestOnlyWhilePending(t *testing.T) {+ store := newTestStore(t)+ defer func() { _ = store.Close() }()+ ctx := context.Background()++ if err := store.SaveBootstrapToken(ctx, &BootstrapToken{+ ID: "tok", TokenHash: "h", Role: "sam:role:node", MaxUsages: 1,+ CreatedAt: time.Now(), ExpiresAt: time.Now().Add(time.Hour),+ }); err != nil {+ t.Fatal(err)+ }+ if err := store.CreateEnrollmentRequest(ctx, &EnrollmentRequest{+ ID: "req", PeerID: "peer", PublicKey: []byte("pk"), TokenID: "tok",+ Status: api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING, CreatedAt: time.Now(),+ }); err != nil {+ t.Fatal(err)+ }++ if err := store.ResolveEnrollmentRequest(ctx, "req", api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED, []byte("b1"), "admin-1"); err != nil {+ t.Fatalf("first resolution: %v", err)+ }+ err := store.ResolveEnrollmentRequest(ctx, "req", api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, nil, "admin-2")+ if err != ErrEnrollmentAlreadyResolved {+ t.Fatalf("second resolution: err = %v, want ErrEnrollmentAlreadyResolved", err)+ }+ got, err := store.GetEnrollmentRequestByID(ctx, "req")+ if err != nil {+ t.Fatal(err)+ }+ if got.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED || got.ResolvedBy != "admin-1" || !bytes.Equal(got.BiscuitToken, []byte("b1")) {+ t.Errorf("losing resolution overwrote the request: %+v", got)+ }+}diff --git a/internal/storage/storage.go b/internal/storage/storage.goindex 72e5d79e..46554fdc 100644--- a/internal/storage/storage.go+++ b/internal/storage/storage.go@@ -30,6 +30,16 @@ var (// stops being servable. See EnrolledNode.CheckAdmission.ErrNodeBanned = errors.New("node is banned")ErrNodeSessionExpired = errors.New("node session expired")++ // ErrBootstrapTokenUnusable is returned by ConsumeBootstrapTokenUsage when+ // the token is expired, revoked or has no usages left. One error for the+ // three so a caller cannot tell them apart after the fact and race one.+ ErrBootstrapTokenUnusable = errors.New("bootstrap token is expired, revoked or exhausted")++ // ErrEnrollmentAlreadyResolved is returned by ResolveEnrollmentRequest+ // when the request is no longer pending: someone else approved or+ // rejected it first.+ ErrEnrollmentAlreadyResolved = errors.New("enrollment request is already resolved"))// KeyPair holds cryptographic key information.@@ -51,12 +61,21 @@ type RouterLease struct {// User represents a human identity in the mesh.type User struct {+ // ID is the OIDC subject. Issuer is the OIDC issuer it came from: the+ // pair is what an identity ban is keyed on (see SetIdentityBanned), and+ // two issuers may hand out the same subject to different people.ID string+ Issuer stringEmail stringRole stringCreatedAt time.Time}+// IdentityKey is the "issuer|subject" form identity bans are keyed on.+func (u *User) IdentityKey() string {+ return u.Issuer + "|" + u.ID+}+// EnrolledNode represents a node enrolled in the mesh.type EnrolledNode struct {PeerID string@@ -188,7 +207,8 @@ type Store interface {// GetNode retrieves node enrollment details.GetNode(ctx context.Context, peerID string) (*EnrolledNode, error)- // SetNodeBanned updates the banned status of a node.+ // SetNodeBanned updates the banned status of a node. ErrNotFound if no+ // node has that peer ID.SetNodeBanned(ctx context.Context, peerID string, banned bool) error// IsNodeBanned checks if a node is currently banned.@@ -230,8 +250,12 @@ type Store interface {// GetBootstrapToken retrieves a bootstrap token by its ID (sha256 hash).GetBootstrapToken(ctx context.Context, id string) (*BootstrapToken, error)- // IncrementBootstrapTokenUsage increments the usage count of a token.- IncrementBootstrapTokenUsage(ctx context.Context, id string) error+ // ConsumeBootstrapTokenUsage spends one usage of a token, atomically+ // with the check that a usage is left and that the token is neither+ // expired (as of now) nor revoked. ErrBootstrapTokenUnusable when it is+ // not: a read-then-increment would let concurrent enrollments overshoot+ // max_usages.+ ConsumeBootstrapTokenUsage(ctx context.Context, id string, now time.Time) error// RevokeBootstrapToken soft-revokes a token by setting its RevokedAt, so// HandleEnroll refuses it even though it may still be within its TTL and@@ -255,6 +279,11 @@ type Store interface {// UpdateEnrollmentRequest updates status, resolved details, and stored Biscuit of a request.UpdateEnrollmentRequest(ctx context.Context, id string, status api.EnrollmentStatus, biscuit []byte, resolvedBy string) error+ // ResolveEnrollmentRequest is UpdateEnrollmentRequest for a request that+ // must still be pending: two admins acting on the same request cannot+ // both succeed. ErrEnrollmentAlreadyResolved if it was not pending.+ ResolveEnrollmentRequest(ctx context.Context, id string, status api.EnrollmentStatus, biscuit []byte, resolvedBy string) error+// ListNodes retrieves all enrolled nodes.ListNodes(ctx context.Context) ([]EnrolledNode, error)diff --git a/site/content/docs/development/policy.md b/site/content/docs/development/policy.mdindex e8d71043..3d6851aa 100644--- a/site/content/docs/development/policy.md+++ b/site/content/docs/development/policy.md@@ -75,7 +75,7 @@ allow if group("engineering");Admins manage central permissions dynamically via the Control Plane REST API. The policy database defines a set of **Roles** and **Bindings**.* **Roles**: Define specific capabilities (allowed destinations and services).- * `allowed_targets`: Defines which logical groups or specific peers a user can route messages to, analogous to Active Directory security groups. Target definitions must be formatted as resolved facts (e.g., `group:<name>`, `user:<sub-id>`, `email:<email>`, `role:<role-name>`, or `node:<peer-id>`). *Note: These are evaluated dynamically at the destination node using its own identity (see Section 3.1).*+ * `allowed_targets`: Defines which logical groups or specific peers a user can route messages to, analogous to Active Directory security groups. Target definitions must be formatted as resolved facts (e.g., `group:<name>`, `user:<sub-id>`, `email:<email>`, `idp_role:<role-name>` for the issuer's `roles` claim, or `node:<peer-id>`). *Note: These are evaluated dynamically at the destination node using its own identity (see Section 3.1).** `allowed_agents`: The agent namespaces a node with this role can act for, such as `*.prod.acme.example`. When a node forwards a request for a sandboxed agent, it sends the agent's name alongside the token (see `internal/node/agent.go`). The receiving node accepts that name only if it matches one of these namespaces, and a node with no grant cannot name any agent. You can also use `agent:<id>` as a binding member to give a role to a named agent, but that is only as reliable as the namespace grant held by the node making the claim.* `allowed_services`: Defines the application-level tools or endpoints a user can access. Services use a strict `type://name` convention (e.g., `mcp://db-agent` or `inference://openrouter`).* **Strict Namespaces**: There are no implicit fallbacks. `system://...` is used for internal services, `mcp://...` for node services, `inference://...` for AI models, etc. Service names must be valid domain labels (e.g. `value1.value2.value3`).diff --git a/site/content/docs/user/control-plane-configuration.md b/site/content/docs/user/control-plane-configuration.mdindex 7d97da49..ac7510e8 100644--- a/site/content/docs/user/control-plane-configuration.md+++ b/site/content/docs/user/control-plane-configuration.md@@ -56,7 +56,7 @@ The Router is a dedicated GossipSub helper that maintains stable network addressThe Control Plane dynamically issues permissions inside the Biscuit token based on identity claims (users or groups) mapped to specific roles in the database.The policy defines what endpoints and services agents are permitted to use:-* **`allowed_targets`**: Restricts which logical endpoints the agent can route connections to. Use resolved Biscuit facts: `group:<name>`, `user:<sub-id>`, `email:<email>`, `role:<role-name>`, or `node:<peer-id>`.+* **`allowed_targets`**: Restricts which logical endpoints the agent can route connections to. Use resolved Biscuit facts: `group:<name>`, `user:<sub-id>`, `email:<email>`, `idp_role:<role-name>` (the issuer's `roles` claim), or `node:<peer-id>`. Mesh roles (`role(...)`) are never a target or a binding member: they are what bindings grant, and an issuer must not be able to hand one out by emitting it as a claim.* **`allowed_services`**: Restricts the application-level services the agent can invoke. Services are prefixed by their protocol type and URI scheme (e.g., `mcp://local-shell-tools` or `inference://openrouter`). Wildcards are supported (e.g., `mcp://*`). The service is deliberately the unit of authorization: a grant offers the service's whole tool surface, so publish different privilege tiers as different services (e.g. `mcp://db-reader` vs `mcp://db-writer`) rather than expecting the mesh to filter tools inside one backend.* **`allowed_agents`**: The agent namespaces a node with this role can use. When a node forwards a request for a sandboxed agent, it sends the agent's name with it. The receiving node accepts that name only if it falls inside one of these namespaces. A node with no `allowed_agents` grant cannot name any agent. Accepted patterns are `*.prod.acme.example`, `acme.*`, an exact ID such as `reviewer-7.prod.acme.example`, or `*` for any agent.* **`allowed_labels`**: The labels a node with this role may declare when it enrolls, as `*`, `key=*` or `key=value`. A node sends its own labels in its enrollment request, so this is what decides which of them the control plane is willing to sign into `label()` facts. A role granting none means a node holding it can declare none. Peers gate on those facts with `required_labels`, so a node that could declare anything could satisfy any such requirement.@@ -85,7 +85,7 @@ Admins manage policies by sending a JSON payload to the `/policies` endpoint.},{"name": "admin-role",- "allowed_targets": ["group:all-nodes", "role:admin"],+ "allowed_targets": ["group:all-nodes", "idp_role:admin"],"allowed_services": ["mcp://*", "inference://*", "system://*"]}],@@ -239,7 +239,10 @@ Administrators can immediately revoke any active session to disable a node's abi"peer_id": "12D3KooW..."}```-* **Enforcement**: Revoked nodes are marked as banned in the database. When the node next attempts a proactive `/refresh` handshake, the request is denied with a `403 Forbidden` status, and the node's local daemon immediately terminates.+* **Enforcement**: Revoked nodes are marked as banned in the database. When the node next attempts a proactive `/refresh` handshake, the request is denied with a `403 Forbidden` status, and the node's local daemon immediately terminates. When the node was enrolled through OIDC, the identity behind it (`issuer|subject`) is banned as well: it can no longer `/register` a fresh keypair, use the `/user/*` API, or enroll anything with bootstrap tokens it minted earlier, and a queued enrollment on such a token is refused at approval.+* **Lifting a ban**: `POST /admin/nodes/{peer_id}/unban` reverses both halves (node and identity). The `sam-control-plane admin ban|unban --peer` commands do the same directly against the database.++Bootstrap tokens are spent atomically: a token's `max_usages` holds under concurrent enrollments, an approval re-checks that the token is still valid and unspent, and a pending request can be resolved exactly once. A Control Plane with no mesh policy mints Biscuits that carry the role and no grants at all; nothing is reachable until an administrator posts a policy.---diff --git a/tests/integration/policy_permutations_test.go b/tests/integration/policy_permutations_test.goindex b8064db6..6ae838df 100644--- a/tests/integration/policy_permutations_test.go+++ b/tests/integration/policy_permutations_test.go@@ -107,6 +107,11 @@ func TestPolicyPermutations(t *testing.T) {- name: role-directallowed_services: ["mcp://test-role"]allowed_targets: ["group:compute"]+ # Same shape as role-direct but with no idp_role binding: an issuer's+ # roles claim naming it must grant nothing.+ - name: role-unbound+ allowed_services: ["mcp://test-unbound"]+ allowed_targets: ["group:compute"]- name: adminallowed_services: ["*"]allowed_targets: ["*:*"]@@ -120,6 +125,8 @@ bindings:members: ["group:eng-team"]- role: role-nodemembers: ["user:node-user"]+ - role: role-direct+ members: ["idp_role:role-direct"]- role: adminmembers: ["user:admin-user"]- role: admin@@ -226,11 +233,19 @@ services:expectAllow: true,},{- name: "Fact roles: role(role-direct)",+ name: "Fact idp_role bound: idp_role(role-direct) -> role(role-direct)",jwtClaims: map[string]interface{}{"sub": "some-id", "roles": []string{"role-direct"}},targetSvc: "mcp://test-role",expectAllow: true,},+ {+ // The issuer's roles claim used to be minted as role() itself, so+ // naming any mesh role in it granted that role with no binding.+ name: "Fact idp_role unbound: roles claim does not mint a mesh role",+ jwtClaims: map[string]interface{}{"sub": "some-id", "roles": []string{"role-unbound"}},+ targetSvc: "mcp://test-unbound",+ expectAllow: false,+ },{name: "Fact node: node(peerID)",jwtClaims: map[string]interface{}{"sub": "node-user"},@@ -251,13 +266,8 @@ services:apiTokenA := "tokenA"apiPortA := getFreePort(t)- if r, ok := tt.jwtClaims["roles"]; ok {- if stringSlice, ok := r.([]string); ok {- tt.jwtClaims["roles"] = append(stringSlice, api.RoleNode)- }- } else {- tt.jwtClaims["roles"] = []string{api.RoleNode}- }+ // The seat comes from the sam:system:authenticated binding above,+ // never from a roles claim naming sam:role:node.jwtA := mintToken(tt.jwtClaims)cmdA := exec.Command(nodeBin, "run",