Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
controlplane: one proof-of-possession rule for the whole enrollment surface
Antonio Ojea4caac8d0e6cd
diff --git a/api/network.go b/api/network.goindex 459b0bc3..40a8ac99 100644--- a/api/network.go+++ b/api/network.go@@ -75,14 +75,31 @@ const (TokenRefreshCheckInterval = 10 * time.Minute)+// EnrollChallenge is the payload a bootstrap enrollee signs to prove+// possession of the private half of BootstrapEnrollRequest.public_key at+// POST /enroll, carried in that message's timestamp/challenge_signature+// fields. Binding the peer ID keeps a captured signature useless for any+// other peer; the domain prefix keeps it useless at any other endpoint.+func EnrollChallenge(peerID string, ts int64) []byte {+ return []byte("sam:enroll:" + peerID + ":" + strconv.FormatInt(ts, 10))+}+// EnrollStatusChallenge is the payload a bootstrap enrollee signs to prove// possession of the key it submitted at /enroll when polling-// GET /enroll/status: the signature travels in the `sig` query parameter-// (unpadded base64url) alongside `ts` (unix milliseconds). The domain prefix-// keeps the signature from doubling as a /refresh challenge, which signs the-// bare timestamp.-func EnrollStatusChallenge(ts int64) []byte {- return []byte("sam:enroll-status:" + strconv.FormatInt(ts, 10))+// GET /enroll/status. ts is unix milliseconds; the signature travels in the+// HeaderChallengeSignature header (unpadded base64url) alongside+// HeaderChallengeTimestamp.+func EnrollStatusChallenge(peerID string, ts int64) []byte {+ return []byte("sam:enroll-status:" + peerID + ":" + strconv.FormatInt(ts, 10))+}++// RefreshChallenge is the payload an enrolled peer signs to prove possession+// of its identity key at POST /refresh, carried in TokenRefreshRequest's+// timestamp/challenge_signature fields alongside the expiring biscuit. Same+// shape as the other enrollment challenges: peer- and endpoint-bound, so a+// captured signature is useless anywhere else.+func RefreshChallenge(peerID string, ts int64) []byte {+ return []byte("sam:refresh:" + peerID + ":" + strconv.FormatInt(ts, 10))}// ============================================================================@@ -98,6 +115,14 @@ const (// are forwarded to backend services.HeaderSamBiscuit = "X-Sam-Biscuit"+ // HeaderChallengeTimestamp and HeaderChallengeSignature carry the signed+ // freshness challenge on GET /enroll/status: unix milliseconds and an+ // unpadded base64url signature over EnrollStatusChallenge. Headers rather+ // than query parameters, so the signature never lands in access logs,+ // where it would be replayable for its freshness window.+ HeaderChallengeTimestamp = "X-Sam-Challenge-Ts"+ HeaderChallengeSignature = "X-Sam-Challenge-Sig"+// HeaderPeerID carries the authenticated libp2p peer ID of the caller.// The mesh ingress handler stamps it after authorization succeeds,// overwriting any inbound value, so backend services get verified callerdiff --git a/api/sam.pb.go b/api/sam.pb.goindex 5e081c40..4c1280ef 100644--- a/api/sam.pb.go+++ b/api/sam.pb.go@@ -552,9 +552,17 @@ type BootstrapEnrollRequest struct {RequestedRole string `protobuf:"bytes,4,opt,name=requested_role,json=requestedRole,proto3" json:"requested_role,omitempty"`// Operator-declared labels; the admin approving the enrollment attests// them (see EnrollRequest.labels).- Labels map[string]string `protobuf:"bytes,5,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ Labels map[string]string `protobuf:"bytes,5,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`+ // Proof of possession of public_key's private half: timestamp is unix+ // milliseconds and challenge_signature signs the UTF-8 bytes of+ // "sam:enroll:<peer_id>:<timestamp>". Required, and peer_id must be+ // derived from public_key: this is what entitles a repeated POST /enroll+ // to re-fetch an existing enrollment's biscuit, so a bootstrap token+ // alone must never satisfy it.+ Timestamp int64 `protobuf:"varint,6,opt,name=timestamp,proto3" json:"timestamp,omitempty"`+ ChallengeSignature []byte `protobuf:"bytes,7,opt,name=challenge_signature,json=challengeSignature,proto3" json:"challenge_signature,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *BootstrapEnrollRequest) Reset() {@@ -622,11 +630,26 @@ func (x *BootstrapEnrollRequest) GetLabels() map[string]string {return nil}+func (x *BootstrapEnrollRequest) GetTimestamp() int64 {+ if x != nil {+ return x.Timestamp+ }+ return 0+}++func (x *BootstrapEnrollRequest) GetChallengeSignature() []byte {+ if x != nil {+ return x.ChallengeSignature+ }+ return nil+}+// BootstrapEnrollResponse answers POST /enroll and GET /enroll/status.// Polling GET /enroll/status requires proof of possession of the key-// submitted at /enroll: alongside `peer_id`, the caller sends the query-// parameters `ts` (unix milliseconds) and `sig` (unpadded base64url-// signature over the UTF-8 bytes of "sam:enroll-status:<ts>").+// submitted at /enroll: alongside the `peer_id` query parameter, the caller+// sends the X-Sam-Challenge-Ts header (unix milliseconds) and the+// X-Sam-Challenge-Sig header (unpadded base64url signature over the UTF-8+// bytes of "sam:enroll-status:<peer_id>:<ts>").type BootstrapEnrollResponse struct {state protoimpl.MessageState `protogen:"open.v1"`Status EnrollmentStatus `protobuf:"varint,1,opt,name=status,proto3,enum=sam.v1.EnrollmentStatus" json:"status,omitempty"`@@ -1683,7 +1706,10 @@ func (x *KeysResponse) GetPublicKeys() [][]byte {type TokenRefreshRequest struct {state protoimpl.MessageState `protogen:"open.v1"`- // Signature over the decimal string form of timestamp, made with the node key.+ // Signature with the node key over the UTF-8 bytes of+ // "sam:refresh:<peer_id>:<timestamp>", where peer_id is the one bound in+ // the presented biscuit. Peer- and endpoint-bound so a captured signature+ // verifies nowhere else.ChallengeSignature []byte `protobuf:"bytes,1,opt,name=challenge_signature,json=challengeSignature,proto3" json:"challenge_signature,omitempty"`// Unix milliseconds. Must be within the control plane's freshness window.Timestamp int64 `protobuf:"varint,2,opt,name=timestamp,proto3" json:"timestamp,omitempty"`@@ -2896,14 +2922,16 @@ const file_api_sam_proto_rawDesc = "" +"\x10router_addresses\x18\x04 \x03(\tR\x0frouterAddresses\x12\x1e\n" +"\n" +"expiration\x18\x05 \x01(\x03R\n" +- "expiration\"\x9f\x02\n" ++ "expiration\"\xee\x02\n" +"\x16BootstrapEnrollRequest\x12'\n" +"\x0fbootstrap_token\x18\x01 \x01(\tR\x0ebootstrapToken\x12\x17\n" +"\apeer_id\x18\x02 \x01(\tR\x06peerId\x12\x1d\n" +"\n" +"public_key\x18\x03 \x01(\fR\tpublicKey\x12%\n" +"\x0erequested_role\x18\x04 \x01(\tR\rrequestedRole\x12B\n" +- "\x06labels\x18\x05 \x03(\v2*.sam.v1.BootstrapEnrollRequest.LabelsEntryR\x06labels\x1a9\n" ++ "\x06labels\x18\x05 \x03(\v2*.sam.v1.BootstrapEnrollRequest.LabelsEntryR\x06labels\x12\x1c\n" ++ "\ttimestamp\x18\x06 \x01(\x03R\ttimestamp\x12/\n" ++ "\x13challenge_signature\x18\a \x01(\fR\x12challengeSignature\x1a9\n" +"\vLabelsEntry\x12\x10\n" +"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xcd\x02\n" +diff --git a/api/sam.proto b/api/sam.protoindex f7886d54..9ae07c1f 100644--- a/api/sam.proto+++ b/api/sam.proto@@ -85,13 +85,22 @@ message BootstrapEnrollRequest {// Operator-declared labels; the admin approving the enrollment attests// them (see EnrollRequest.labels).map<string, string> labels = 5;+ // Proof of possession of public_key's private half: timestamp is unix+ // milliseconds and challenge_signature signs the UTF-8 bytes of+ // "sam:enroll:<peer_id>:<timestamp>". Required, and peer_id must be+ // derived from public_key: this is what entitles a repeated POST /enroll+ // to re-fetch an existing enrollment's biscuit, so a bootstrap token+ // alone must never satisfy it.+ int64 timestamp = 6;+ bytes challenge_signature = 7;}// BootstrapEnrollResponse answers POST /enroll and GET /enroll/status.// Polling GET /enroll/status requires proof of possession of the key-// submitted at /enroll: alongside `peer_id`, the caller sends the query-// parameters `ts` (unix milliseconds) and `sig` (unpadded base64url-// signature over the UTF-8 bytes of "sam:enroll-status:<ts>").+// submitted at /enroll: alongside the `peer_id` query parameter, the caller+// sends the X-Sam-Challenge-Ts header (unix milliseconds) and the+// X-Sam-Challenge-Sig header (unpadded base64url signature over the UTF-8+// bytes of "sam:enroll-status:<peer_id>:<ts>").message BootstrapEnrollResponse {EnrollmentStatus status = 1;bytes biscuit_token = 2; // Populated only if APPROVED@@ -221,7 +230,10 @@ message KeysResponse {}message TokenRefreshRequest {- // Signature over the decimal string form of timestamp, made with the node key.+ // Signature with the node key over the UTF-8 bytes of+ // "sam:refresh:<peer_id>:<timestamp>", where peer_id is the one bound in+ // the presented biscuit. Peer- and endpoint-bound so a captured signature+ // verifies nowhere else.bytes challenge_signature = 1;// Unix milliseconds. Must be within the control plane's freshness window.int64 timestamp = 2;diff --git a/internal/controlplane/approval_labels_test.go b/internal/controlplane/approval_labels_test.goindex 173ea160..5e0c0459 100644--- a/internal/controlplane/approval_labels_test.go+++ b/internal/controlplane/approval_labels_test.go@@ -96,12 +96,19 @@ func TestApprovalRefusesLabelsTheRoleDoesNotGrant(t *testing.T) {t.Fatal(err)}+ enrollTS := time.Now().UnixMilli()+ enrollSig, err := priv.Sign(api.EnrollChallenge(pID.String(), enrollTS))+ if err != nil {+ t.Fatal(err)+ }enrollData, err := proto.Marshal(&api.BootstrapEnrollRequest{- BootstrapToken: tokenDetails.Token,- PeerId: pID.String(),- PublicKey: pubBytes,- RequestedRole: api.RoleNode,- Labels: labels,+ BootstrapToken: tokenDetails.Token,+ PeerId: pID.String(),+ PublicKey: pubBytes,+ RequestedRole: api.RoleNode,+ Labels: labels,+ Timestamp: enrollTS,+ ChallengeSignature: enrollSig,})if err != nil {t.Fatal(err)diff --git a/internal/controlplane/biscuit_ttl_test.go b/internal/controlplane/biscuit_ttl_test.goindex 77d1127d..c4bad393 100644--- a/internal/controlplane/biscuit_ttl_test.go+++ b/internal/controlplane/biscuit_ttl_test.go@@ -119,7 +119,11 @@ func refreshNode(t *testing.T, cpURL string, priv crypto.PrivKey, currentBiscuitt.Helper()timestamp := time.Now().UnixMilli()- sig, err := priv.Sign([]byte(fmt.Sprintf("%d", timestamp)))+ pid, err := peer.IDFromPrivateKey(priv)+ if err != nil {+ t.Fatal(err)+ }+ sig, err := priv.Sign(api.RefreshChallenge(pid.String(), timestamp))if err != nil {t.Fatal(err)}diff --git a/internal/controlplane/server.go b/internal/controlplane/server.goindex 4e2a4a46..75aa64e8 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -678,24 +678,9 @@ func (s *Server) HandleRefresh(w http.ResponseWriter, r *http.Request) {return}- const refreshChallengeMaxAge = 5 * time.Minute- if req.Timestamp <= 0 {- http.Error(w, "missing or invalid timestamp", http.StatusBadRequest)- return- }- challengeTime := time.UnixMilli(req.Timestamp)- now := time.Now()- if now.Sub(challengeTime) > refreshChallengeMaxAge || challengeTime.Sub(now) > refreshChallengeMaxAge {- logger.Warnw("Stale or invalid challenge timestamp", "peer_id", nodeRecord.PeerID, "timestamp", req.Timestamp)- http.Error(w, "stale or invalid challenge timestamp", http.StatusUnauthorized)- return- }-- challengeData := []byte(fmt.Sprintf("%d", req.Timestamp))- ok, err := pubKey.Verify(challengeData, req.ChallengeSignature)- if err != nil || !ok {- logger.Warnw("Challenge signature verification failed", "peer_id", nodeRecord.PeerID, "error", err)- http.Error(w, "Challenge signature verification failed", http.StatusUnauthorized)+ if err := verifyFreshChallenge(pubKey, api.RefreshChallenge(nodeRecord.PeerID, req.Timestamp), req.Timestamp, req.ChallengeSignature); err != nil {+ logger.Warnw("Refresh challenge verification failed", "peer_id", nodeRecord.PeerID, "error", err)+ http.Error(w, "Challenge verification failed: "+err.Error(), http.StatusUnauthorized)return}@@ -1197,6 +1182,26 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {return}+ // Proof of possession: peer_id must be the submitted key's own, and the+ // caller must hold its private half. This gates the existing-request+ // branch below — a bootstrap token alone must not re-fetch another+ // peer's biscuit.+ enrolleeKey, err := crypto.UnmarshalPublicKey(req.PublicKey)+ if err != nil {+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Invalid public key")+ return+ }+ if !pID.MatchesPublicKey(enrolleeKey) {+ logger.Warnw("Enrollment peer_id does not match public_key", "peer_id", req.PeerId)+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "peer_id is not derived from public_key")+ return+ }+ if err := verifyFreshChallenge(enrolleeKey, api.EnrollChallenge(req.PeerId, req.Timestamp), req.Timestamp, req.ChallengeSignature); err != nil {+ logger.Warnw("Enroll challenge verification failed", "peer_id", req.PeerId, "error", err)+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Invalid enrollment challenge: "+err.Error())+ return+ }+// 2. Check for existing enrollment requestexistingReq, err := s.store.GetEnrollmentRequest(ctx, req.PeerId)if err == nil {@@ -1324,18 +1329,40 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {s.writeEnrollResponse(w, resp)}-// enrollStatusChallengeMaxAge bounds the freshness window of the signed-// /enroll/status challenge, mirroring the /refresh handshake.-const enrollStatusChallengeMaxAge = 5 * time.Minute+// challengeMaxAge bounds the freshness window of every signed timestamp+// challenge on the enrollment surface (/enroll, /enroll/status, /refresh).+const challengeMaxAge = 5 * time.Minute++// verifyFreshChallenge checks a signed timestamp challenge: ts must be within+// challengeMaxAge of now and sig must verify over payload with pub. The+// payload (built by api.EnrollChallenge, api.EnrollStatusChallenge or+// api.RefreshChallenge) binds the peer and the endpoint, so a signature+// captured from one request verifies nowhere else.+func verifyFreshChallenge(pub crypto.PubKey, payload []byte, ts int64, sig []byte) error {+ if ts <= 0 {+ return errors.New("missing or invalid challenge timestamp")+ }+ challengeTime := time.UnixMilli(ts)+ now := time.Now()+ if now.Sub(challengeTime) > challengeMaxAge || challengeTime.Sub(now) > challengeMaxAge {+ return errors.New("stale or invalid challenge timestamp")+ }+ ok, err := pub.Verify(payload, sig)+ if err != nil || !ok {+ return errors.New("challenge signature verification failed")+ }+ return nil+}// HandleEnrollStatus HTTP GET `/enroll/status`//// The approved response carries the enrollee's Biscuit, so polling requires-// proof of possession of the key submitted at /enroll: `ts` (unix-// milliseconds) and `sig` (unpadded base64url signature over-// api.EnrollStatusChallenge(ts)) must accompany `peer_id`. Every failure-// mode after the freshness check answers a uniform 401 so the endpoint is not-// a peer-ID existence oracle for anonymous callers.+// proof of possession of the key submitted at /enroll: the+// api.HeaderChallengeTimestamp header (unix milliseconds) and the+// api.HeaderChallengeSignature header (unpadded base64url signature over+// api.EnrollStatusChallenge) must accompany `peer_id`. Every failure mode+// after the header parse answers a uniform 401 so the endpoint is not a+// peer-ID existence oracle for anonymous callers.func (s *Server) HandleEnrollStatus(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)@@ -1353,20 +1380,10 @@ func (s *Server) HandleEnrollStatus(w http.ResponseWriter, r *http.Request) {return}- ts, err := strconv.ParseInt(r.URL.Query().Get("ts"), 10, 64)- if err != nil || ts <= 0 {- http.Error(w, "Missing or invalid ts parameter: signed challenge required", http.StatusUnauthorized)- return- }- sig, err := base64.RawURLEncoding.DecodeString(r.URL.Query().Get("sig"))- if err != nil || len(sig) == 0 {- http.Error(w, "Missing or invalid sig parameter: signed challenge required", http.StatusUnauthorized)- return- }- challengeTime := time.UnixMilli(ts)- now := time.Now()- if now.Sub(challengeTime) > enrollStatusChallengeMaxAge || challengeTime.Sub(now) > enrollStatusChallengeMaxAge {- http.Error(w, "stale or invalid challenge timestamp", http.StatusUnauthorized)+ ts, tsErr := strconv.ParseInt(r.Header.Get(api.HeaderChallengeTimestamp), 10, 64)+ sig, sigErr := base64.RawURLEncoding.DecodeString(r.Header.Get(api.HeaderChallengeSignature))+ if tsErr != nil || sigErr != nil || len(sig) == 0 {+ http.Error(w, "Missing or invalid challenge headers: signed challenge required", http.StatusUnauthorized)return}@@ -1387,9 +1404,8 @@ func (s *Server) HandleEnrollStatus(w http.ResponseWriter, r *http.Request) {http.Error(w, "Unauthorized", http.StatusUnauthorized)return}- ok, err := pubKey.Verify(api.EnrollStatusChallenge(ts), sig)- if err != nil || !ok {- logger.Warnw("Enroll status challenge verification failed", "peer_id", peerID)+ if err := verifyFreshChallenge(pubKey, api.EnrollStatusChallenge(peerID, ts), ts, sig); err != nil {+ logger.Warnw("Enroll status challenge verification failed", "peer_id", peerID, "error", err)http.Error(w, "Unauthorized", http.StatusUnauthorized)return}diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.goindex 3286b4ea..263553ac 100644--- a/internal/controlplane/server_test.go+++ b/internal/controlplane/server_test.go@@ -21,7 +21,6 @@ import ("crypto/rsa""encoding/base64""encoding/json"- "fmt""io""math/big""net/http"@@ -796,11 +795,14 @@ func TestEnrollmentWorkflow(t *testing.T) {pubBytes, _ := crypto.MarshalPublicKey(pubNode)// 2. Submit Enrollment Request (Mode B -> PENDING)+ enrollTS, enrollSig := enrollPoP(t, privNode, pID.String())enrollReq := &api.BootstrapEnrollRequest{- BootstrapToken: tokenDetails.Token,- PeerId: pID.String(),- PublicKey: pubBytes,- RequestedRole: api.RoleRouter,+ BootstrapToken: tokenDetails.Token,+ PeerId: pID.String(),+ PublicKey: pubBytes,+ RequestedRole: api.RoleRouter,+ Timestamp: enrollTS,+ ChallengeSignature: enrollSig,}enrollReqData, _ := proto.Marshal(enrollReq)@@ -824,7 +826,7 @@ func TestEnrollmentWorkflow(t *testing.T) {}// 3. Poll Enrollment Status -> PENDING (signed by the enrollee's key)- resp, err = client.Get(signedEnrollStatusURL(t, baseURL, privNode, pID.String(), time.Now().UnixMilli()))+ resp, err = client.Do(signedEnrollStatusRequest(t, baseURL, privNode, pID.String(), time.Now().UnixMilli()))if err != nil {t.Fatalf("failed to get status: %v", err)}@@ -866,7 +868,7 @@ func TestEnrollmentWorkflow(t *testing.T) {_ = resp.Body.Close()// 5. Poll Status -> APPROVED & Validate Biscuit- resp, err = client.Get(signedEnrollStatusURL(t, baseURL, privNode, pID.String(), time.Now().UnixMilli()))+ resp, err = client.Do(signedEnrollStatusRequest(t, baseURL, privNode, pID.String(), time.Now().UnixMilli()))if err != nil {t.Fatal(err)}@@ -924,11 +926,14 @@ func TestEnrollmentWorkflow(t *testing.T) {pID2, _ := peer.IDFromPrivateKey(privNode2)pubBytes2, _ := crypto.MarshalPublicKey(pubNode2)+ enrollTS2, enrollSig2 := enrollPoP(t, privNode2, pID2.String())enrollReq2 := &api.BootstrapEnrollRequest{- BootstrapToken: tokenDetails.Token, // use remaining usage- PeerId: pID2.String(),- PublicKey: pubBytes2,- RequestedRole: api.RoleRouter,+ BootstrapToken: tokenDetails.Token, // use remaining usage+ PeerId: pID2.String(),+ PublicKey: pubBytes2,+ RequestedRole: api.RoleRouter,+ Timestamp: enrollTS2,+ ChallengeSignature: enrollSig2,}enrollReqData2, _ := proto.Marshal(enrollReq2)@@ -949,24 +954,41 @@ func TestEnrollmentWorkflow(t *testing.T) {}}-// signedEnrollStatusURL builds a /enroll/status URL carrying the-// proof-of-possession challenge signed by priv.-func signedEnrollStatusURL(t *testing.T, baseURL string, priv crypto.PrivKey, peerID string, ts int64) string {+// signedEnrollStatusRequest builds a GET /enroll/status request carrying the+// proof-of-possession challenge headers signed by priv.+func signedEnrollStatusRequest(t *testing.T, baseURL string, priv crypto.PrivKey, peerID string, ts int64) *http.Request {t.Helper()- sig, err := priv.Sign(api.EnrollStatusChallenge(ts))+ sig, err := priv.Sign(api.EnrollStatusChallenge(peerID, ts))if err != nil {t.Fatalf("failed to sign enroll status challenge: %v", err)}- return baseURL + "/enroll/status?peer_id=" + peerID +- "&ts=" + strconv.FormatInt(ts, 10) +- "&sig=" + base64.RawURLEncoding.EncodeToString(sig)+ req, err := http.NewRequest(http.MethodGet, baseURL+"/enroll/status?peer_id="+peerID, nil)+ if err != nil {+ t.Fatalf("failed to build enroll status request: %v", err)+ }+ req.Header.Set(api.HeaderChallengeTimestamp, strconv.FormatInt(ts, 10))+ req.Header.Set(api.HeaderChallengeSignature, base64.RawURLEncoding.EncodeToString(sig))+ return req+}++// enrollPoP returns the timestamp/challenge_signature pair proving possession+// of priv for a POST /enroll as peerID.+func enrollPoP(t *testing.T, priv crypto.PrivKey, peerID string) (int64, []byte) {+ t.Helper()+ ts := time.Now().UnixMilli()+ sig, err := priv.Sign(api.EnrollChallenge(peerID, ts))+ if err != nil {+ t.Fatalf("failed to sign enroll challenge: %v", err)+ }+ return ts, sig}-// TestEnrollStatusRequiresProofOfPossession pins the fix for-// GHSA-hp3x-79wr-rx66: /enroll/status must never reveal an enrollment's-// status or its biscuit to a caller that cannot sign with the key submitted-// at /enroll.-func TestEnrollStatusRequiresProofOfPossession(t *testing.T) {+// TestBootstrapEnrollmentRequiresProofOfPossession pins the fix for+// GHSA-hp3x-79wr-rx66 on both bootstrap endpoints: neither GET /enroll/status+// nor a repeated POST /enroll may reveal an enrollment's status or biscuit to+// a caller that cannot sign with the enrollee's key — holding a valid+// bootstrap token is not enough.+func TestBootstrapEnrollmentRequiresProofOfPossession(t *testing.T) {issuer, _ := startCustomMockOIDC(t)srv, store, baseURL := setupTestServer(t, issuer)defer func() {@@ -978,7 +1000,7 @@ func TestEnrollStatusRequiresProofOfPossession(t *testing.T) {client := &http.Client{Timeout: 5 * time.Second}- adminReqBody := []byte(`{"role": "sam:role:router", "ttl_hours": 2, "max_usages": 1, "description": "PoP test"}`)+ adminReqBody := []byte(`{"role": "sam:role:router", "ttl_hours": 2, "max_usages": 2, "description": "PoP test"}`)req, _ := http.NewRequest("POST", baseURL+"/admin/bootstrap-tokens", bytes.NewBuffer(adminReqBody))req.Header.Set("Content-Type", "application/json")req.Header.Set("Authorization", "Bearer super-secret-admin-token")@@ -1002,11 +1024,14 @@ func TestEnrollStatusRequiresProofOfPossession(t *testing.T) {pID, _ := peer.IDFromPrivateKey(priv)pubBytes, _ := crypto.MarshalPublicKey(pub)+ enrollTS, enrollSig := enrollPoP(t, priv, pID.String())enrollData, _ := proto.Marshal(&api.BootstrapEnrollRequest{- BootstrapToken: tokenDetails.Token,- PeerId: pID.String(),- PublicKey: pubBytes,- RequestedRole: api.RoleRouter,+ BootstrapToken: tokenDetails.Token,+ PeerId: pID.String(),+ PublicKey: pubBytes,+ RequestedRole: api.RoleRouter,+ Timestamp: enrollTS,+ ChallengeSignature: enrollSig,})resp, err = client.Post(baseURL+"/enroll", "application/x-protobuf", bytes.NewReader(enrollData))if err != nil {@@ -1020,20 +1045,21 @@ func TestEnrollStatusRequiresProofOfPossession(t *testing.T) {t.Fatalf("expected auto-approved enrollment with biscuit, got %v", enrollResp.Status)}- otherKey, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)+ otherKey, otherPub, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)if err != nil {t.Fatal(err)}otherPID, _ := peer.IDFromPrivateKey(otherKey)- denied := map[string]string{- "anonymous poll": baseURL + "/enroll/status?peer_id=" + pID.String(),- "wrong key": signedEnrollStatusURL(t, baseURL, otherKey, pID.String(), time.Now().UnixMilli()),- "stale timestamp": signedEnrollStatusURL(t, baseURL, priv, pID.String(), time.Now().Add(-6*time.Minute).UnixMilli()),- "unknown peer": signedEnrollStatusURL(t, baseURL, otherKey, otherPID.String(), time.Now().UnixMilli()),+ anonReq, _ := http.NewRequest(http.MethodGet, baseURL+"/enroll/status?peer_id="+pID.String(), nil)+ denied := map[string]*http.Request{+ "anonymous poll": anonReq,+ "wrong key": signedEnrollStatusRequest(t, baseURL, otherKey, pID.String(), time.Now().UnixMilli()),+ "stale timestamp": signedEnrollStatusRequest(t, baseURL, priv, pID.String(), time.Now().Add(-6*time.Minute).UnixMilli()),+ "unknown peer": signedEnrollStatusRequest(t, baseURL, otherKey, otherPID.String(), time.Now().UnixMilli()),}- for name, u := range denied {- resp, err := client.Get(u)+ for name, dr := range denied {+ resp, err := client.Do(dr)if err != nil {t.Fatalf("%s: request failed: %v", name, err)}@@ -1048,7 +1074,7 @@ func TestEnrollStatusRequiresProofOfPossession(t *testing.T) {}// Positive control: the enrollee itself still collects its biscuit.- resp, err = client.Get(signedEnrollStatusURL(t, baseURL, priv, pID.String(), time.Now().UnixMilli()))+ resp, err = client.Do(signedEnrollStatusRequest(t, baseURL, priv, pID.String(), time.Now().UnixMilli()))if err != nil {t.Fatal(err)}@@ -1064,6 +1090,136 @@ func TestEnrollStatusRequiresProofOfPossession(t *testing.T) {if statusResp.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED || !bytes.Equal(statusResp.BiscuitToken, enrollResp.BiscuitToken) {t.Fatalf("signed poll did not return the approved biscuit: %v", statusResp.Status)}++ // POST /enroll is gated the same way: the existing-enrollment branch+ // re-serves the stored biscuit, so a bootstrap token holder who is not+ // the peer must never reach it.+ postEnroll := func(name string, payload []byte) *api.BootstrapEnrollResponse {+ t.Helper()+ resp, err := client.Post(baseURL+"/enroll", "application/x-protobuf", bytes.NewReader(payload))+ if err != nil {+ t.Fatalf("%s: POST /enroll failed: %v", name, err)+ }+ body, _ := io.ReadAll(resp.Body)+ _ = resp.Body.Close()+ var r api.BootstrapEnrollResponse+ _ = proto.Unmarshal(body, &r)+ return &r+ }++ otherPubBytes, _ := crypto.MarshalPublicKey(otherPub)+ crossTS, crossSig := enrollPoP(t, otherKey, pID.String())+ for name, payload := range map[string]*api.BootstrapEnrollRequest{+ "cross-peer re-fetch with wrong key": {+ BootstrapToken: tokenDetails.Token,+ PeerId: pID.String(),+ PublicKey: pubBytes,+ RequestedRole: api.RoleRouter,+ Timestamp: crossTS,+ ChallengeSignature: crossSig,+ },+ "peer_id not derived from public_key": {+ BootstrapToken: tokenDetails.Token,+ PeerId: pID.String(),+ PublicKey: otherPubBytes,+ RequestedRole: api.RoleRouter,+ Timestamp: crossTS,+ ChallengeSignature: crossSig,+ },+ "missing challenge": {+ BootstrapToken: tokenDetails.Token,+ PeerId: pID.String(),+ PublicKey: pubBytes,+ RequestedRole: api.RoleRouter,+ },+ } {+ data, _ := proto.Marshal(payload)+ r := postEnroll(name, data)+ if r.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED {+ t.Errorf("%s: expected REJECTED, got %v", name, r.Status)+ }+ if len(r.BiscuitToken) != 0 {+ t.Errorf("%s: response leaked a biscuit", name)+ }+ }++ // The enrollee itself retries POST /enroll idempotently.+ retryTS, retrySig := enrollPoP(t, priv, pID.String())+ retryData, _ := proto.Marshal(&api.BootstrapEnrollRequest{+ BootstrapToken: tokenDetails.Token,+ PeerId: pID.String(),+ PublicKey: pubBytes,+ RequestedRole: api.RoleRouter,+ Timestamp: retryTS,+ ChallengeSignature: retrySig,+ })+ r := postEnroll("enrollee retry", retryData)+ if r.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED || !bytes.Equal(r.BiscuitToken, enrollResp.BiscuitToken) {+ t.Fatalf("enrollee retry did not return its own biscuit: %v", r.Status)+ }++ // Domain separation: a signature captured from one endpoint must verify+ // nowhere else, even signed by the right key within the freshness window.+ crossEndpointTS := time.Now().UnixMilli()+ statusSig, err := priv.Sign(api.EnrollStatusChallenge(pID.String(), crossEndpointTS))+ if err != nil {+ t.Fatal(err)+ }+ replayData, _ := proto.Marshal(&api.BootstrapEnrollRequest{+ BootstrapToken: tokenDetails.Token,+ PeerId: pID.String(),+ PublicKey: pubBytes,+ RequestedRole: api.RoleRouter,+ Timestamp: crossEndpointTS,+ ChallengeSignature: statusSig, // valid /enroll/status signature, wrong endpoint+ })+ if r := postEnroll("cross-endpoint replay", replayData); r.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED || len(r.BiscuitToken) != 0 {+ t.Errorf("an /enroll/status signature was accepted at /enroll: %v", r.Status)+ }++ enrollSigForStatus, err := priv.Sign(api.EnrollChallenge(pID.String(), crossEndpointTS))+ if err != nil {+ t.Fatal(err)+ }+ statusReplay, _ := http.NewRequest(http.MethodGet, baseURL+"/enroll/status?peer_id="+pID.String(), nil)+ statusReplay.Header.Set(api.HeaderChallengeTimestamp, strconv.FormatInt(crossEndpointTS, 10))+ statusReplay.Header.Set(api.HeaderChallengeSignature, base64.RawURLEncoding.EncodeToString(enrollSigForStatus))+ resp, err = client.Do(statusReplay)+ if err != nil {+ t.Fatal(err)+ }+ _ = resp.Body.Close()+ if resp.StatusCode != http.StatusUnauthorized {+ t.Errorf("an /enroll signature was accepted at /enroll/status: %s", resp.Status)+ }+}++// TestEnrollStatusRateLimited pins that /enroll/status shares the enrollment+// rate limit: the advisory's PoC relied on polling it without bound.+func TestEnrollStatusRateLimited(t *testing.T) {+ issuer, _ := startCustomMockOIDC(t)+ srv, store, baseURL := setupTestServer(t, issuer)+ defer func() {+ _ = srv.Close()+ _ = store.Close()+ }()++ client := &http.Client{Timeout: 5 * time.Second}+ limited := false+ for i := 0; i < EnrollBurst+10; i++ {+ resp, err := client.Get(baseURL + "/enroll/status?peer_id=unknown")+ if err != nil {+ t.Fatalf("request %d failed: %v", i, err)+ }+ _ = resp.Body.Close()+ if resp.StatusCode == http.StatusTooManyRequests {+ limited = true+ break+ }+ }+ if !limited {+ t.Fatalf("no 429 after %d rapid /enroll/status requests", EnrollBurst+10)+ }}// enrollRefreshTestNode enrolls a bootstrap node directly in the store and@@ -1119,7 +1275,11 @@ func enrollRefreshTestNode(t *testing.T, ctx context.Context, store storage.Storfunc signedRefreshRequest(t *testing.T, priv crypto.PrivKey, timestamp int64) []byte {t.Helper()- sig, err := priv.Sign([]byte(fmt.Sprintf("%d", timestamp)))+ pid, err := peer.IDFromPrivateKey(priv)+ if err != nil {+ t.Fatalf("IDFromPrivateKey: %v", err)+ }+ sig, err := priv.Sign(api.RefreshChallenge(pid.String(), timestamp))if err != nil {t.Fatalf("Sign: %v", err)}@@ -1179,8 +1339,10 @@ func TestHandleRefresh_TimestampFreshness(t *testing.T) {{"stale", func() int64 { return time.Now().Add(-2 * time.Hour).UnixMilli() }, http.StatusUnauthorized},{"far future", func() int64 { return time.Now().Add(2 * time.Hour).UnixMilli() }, http.StatusUnauthorized},{"seconds instead of milliseconds", func() int64 { return time.Now().Unix() }, http.StatusUnauthorized},- {"zero", func() int64 { return 0 }, http.StatusBadRequest},- {"negative", func() int64 { return -1 }, http.StatusBadRequest},+ // Absent and malformed timestamps are authentication failures like+ // every other bad challenge: one uniform 401, no oracle.+ {"zero", func() int64 { return 0 }, http.StatusUnauthorized},+ {"negative", func() int64 { return -1 }, http.StatusUnauthorized},}for _, tc := range cases {@@ -1301,8 +1463,8 @@ func TestTokenRefreshAndRevocation(t *testing.T) {// 2. Perform refreshtimestamp := time.Now().UnixMilli()- challengeData := []byte(fmt.Sprintf("%d", timestamp))- challengeSig, err := privNode.Sign(challengeData)+ refreshPID, _ := peer.IDFromPrivateKey(privNode)+ challengeSig, err := privNode.Sign(api.RefreshChallenge(refreshPID.String(), timestamp))if err != nil {t.Fatalf("failed to generate challenge signature: %v", err)}@@ -1980,11 +2142,14 @@ func TestBootstrapTokenOwnerPropagatesToNode(t *testing.T) {pID, _ := peer.IDFromPrivateKey(privNode)pubBytes, _ := crypto.MarshalPublicKey(pubNode)+ ownerTS, ownerSig := enrollPoP(t, privNode, pID.String())enrollData, _ := proto.Marshal(&api.BootstrapEnrollRequest{- BootstrapToken: tokenDetails.Token,- PeerId: pID.String(),- PublicKey: pubBytes,- RequestedRole: api.RoleNode,+ BootstrapToken: tokenDetails.Token,+ PeerId: pID.String(),+ PublicKey: pubBytes,+ RequestedRole: api.RoleNode,+ Timestamp: ownerTS,+ ChallengeSignature: ownerSig,})resp, err = client.Post(baseURL+"/enroll", "application/x-protobuf", bytes.NewBuffer(enrollData))if err != nil {diff --git a/internal/node/enroll.go b/internal/node/enroll.goindex b1c432fc..44d73609 100644--- a/internal/node/enroll.go+++ b/internal/node/enroll.go@@ -223,12 +223,20 @@ func (n *SamNode) EnrollBootstrap(ctx context.Context, controlPlaneURL string, breturn fmt.Errorf("failed to marshal public key: %w", err)}+ enrollTS := time.Now().UnixMilli()+ enrollSig, err := n.config.PrivKey.Sign(api.EnrollChallenge(n.Host.ID().String(), enrollTS))+ if err != nil {+ return fmt.Errorf("failed to sign enrollment challenge: %w", err)+ }+req := &api.BootstrapEnrollRequest{- BootstrapToken: bootstrapToken,- PeerId: n.Host.ID().String(),- PublicKey: pubBytes,- RequestedRole: n.config.RequiredRole,- Labels: n.config.Labels, // validated at startup+ BootstrapToken: bootstrapToken,+ PeerId: n.Host.ID().String(),+ PublicKey: pubBytes,+ RequestedRole: n.config.RequiredRole,+ Labels: n.config.Labels, // validated at startup+ Timestamp: enrollTS,+ ChallengeSignature: enrollSig,}data, err := proto.Marshal(req)if err != nil {@@ -283,6 +291,8 @@ func (n *SamNode) EnrollBootstrap(ctx context.Context, controlPlaneURL string, bu = u.JoinPath("enroll", "status")q := u.Query()q.Set("peer_id", n.Host.ID().String())+ u.RawQuery = q.Encode()+ statusURL := u.String()ticker := time.NewTicker(2 * time.Second)defer ticker.Stop()@@ -295,17 +305,16 @@ func (n *SamNode) EnrollBootstrap(ctx context.Context, controlPlaneURL string, b// Prove possession of the enrollment key on every poll; the// control plane returns the biscuit only to the enrollee.ts := time.Now().UnixMilli()- sig, err := n.config.PrivKey.Sign(api.EnrollStatusChallenge(ts))+ sig, err := n.config.PrivKey.Sign(api.EnrollStatusChallenge(n.Host.ID().String(), ts))if err != nil {return fmt.Errorf("failed to sign enrollment status challenge: %w", err)}- q.Set("ts", strconv.FormatInt(ts, 10))- q.Set("sig", base64.RawURLEncoding.EncodeToString(sig))- u.RawQuery = q.Encode()- hReq, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)+ hReq, err := http.NewRequestWithContext(ctx, http.MethodGet, statusURL, nil)if err != nil {return fmt.Errorf("failed to create status request: %w", err)}+ hReq.Header.Set(api.HeaderChallengeTimestamp, strconv.FormatInt(ts, 10))+ hReq.Header.Set(api.HeaderChallengeSignature, base64.RawURLEncoding.EncodeToString(sig))hResp, err := client.Do(hReq)if err != nil {diff --git a/internal/node/node.go b/internal/node/node.goindex 28daa019..d802f4f4 100644--- a/internal/node/node.go+++ b/internal/node/node.go@@ -1045,10 +1045,13 @@ func (n *SamNode) RefreshEnrollment(ctx context.Context) error {return fmt.Errorf("corrupted private key: %w", err)}- // 3. Generate challenge signature over current timestamp+ // 3. Sign the peer-bound refresh challengetimestamp := time.Now().UnixMilli()- challengeData := []byte(fmt.Sprintf("%d", timestamp))- sig, err := privKey.Sign(challengeData)+ peerID, err := peer.IDFromPrivateKey(privKey)+ if err != nil {+ return fmt.Errorf("failed to derive peer ID from private key: %w", err)+ }+ sig, err := privKey.Sign(api.RefreshChallenge(peerID.String(), timestamp))if err != nil {return fmt.Errorf("failed to generate signature: %w", err)}diff --git a/internal/router/router.go b/internal/router/router.goindex e70d68c3..cc23fa2f 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -342,11 +342,19 @@ func (r *Router) enrollBootstrap(peerID peer.ID) error {return fmt.Errorf("failed to marshal router public key: %w", err)}+ enrollTS := time.Now().UnixMilli()+ enrollSig, err := r.privKey.Sign(api.EnrollChallenge(peerID.String(), enrollTS))+ if err != nil {+ return fmt.Errorf("failed to sign enrollment challenge: %w", err)+ }+req := &api.BootstrapEnrollRequest{- BootstrapToken: r.config.BootstrapToken,- PeerId: peerID.String(),- PublicKey: pubBytes,- RequestedRole: r.config.RequiredRole,+ BootstrapToken: r.config.BootstrapToken,+ PeerId: peerID.String(),+ PublicKey: pubBytes,+ RequestedRole: r.config.RequiredRole,+ Timestamp: enrollTS,+ ChallengeSignature: enrollSig,}data, err := proto.Marshal(req)if err != nil {@@ -389,6 +397,8 @@ func (r *Router) enrollBootstrap(peerID peer.ID) error {u = u.JoinPath("enroll", "status")q := u.Query()q.Set("peer_id", peerID.String())+ u.RawQuery = q.Encode()+ statusURL := u.String()ticker := time.NewTicker(2 * time.Second)defer ticker.Stop()@@ -401,17 +411,16 @@ func (r *Router) enrollBootstrap(peerID peer.ID) error {// Prove possession of the enrollment key on every poll; the// control plane returns the biscuit only to the enrollee.ts := time.Now().UnixMilli()- sig, err := r.privKey.Sign(api.EnrollStatusChallenge(ts))+ sig, err := r.privKey.Sign(api.EnrollStatusChallenge(peerID.String(), ts))if err != nil {return fmt.Errorf("failed to sign enrollment status challenge: %w", err)}- q.Set("ts", strconv.FormatInt(ts, 10))- q.Set("sig", base64.RawURLEncoding.EncodeToString(sig))- u.RawQuery = q.Encode()- req, err := http.NewRequestWithContext(r.ctx, http.MethodGet, u.String(), nil)+ req, err := http.NewRequestWithContext(r.ctx, http.MethodGet, statusURL, nil)if err != nil {return fmt.Errorf("failed to create status request: %w", err)}+ req.Header.Set(api.HeaderChallengeTimestamp, strconv.FormatInt(ts, 10))+ req.Header.Set(api.HeaderChallengeSignature, base64.RawURLEncoding.EncodeToString(sig))statusResp, err := client.Do(req)if err != nil {logger.Warnf("failed to poll enrollment status: %v", err)@@ -1051,10 +1060,13 @@ func (r *Router) RefreshEnrollment(ctx context.Context) error {return fmt.Errorf("router not enrolled (no biscuit)")}- // 1. Generate challenge signature over current timestamp+ // 1. Sign the peer-bound refresh challengetimestamp := time.Now().UnixMilli()- challengeData := []byte(fmt.Sprintf("%d", timestamp))- sig, err := r.privKey.Sign(challengeData)+ peerID, err := peer.IDFromPrivateKey(r.privKey)+ if err != nil {+ return fmt.Errorf("failed to derive peer ID from private key: %w", err)+ }+ sig, err := r.privKey.Sign(api.RefreshChallenge(peerID.String(), timestamp))if err != nil {return fmt.Errorf("failed to generate signature: %w", err)}diff --git a/site/content/docs/user/control-plane-configuration.md b/site/content/docs/user/control-plane-configuration.mdindex 2a254eca..e5041b9b 100644--- a/site/content/docs/user/control-plane-configuration.md+++ b/site/content/docs/user/control-plane-configuration.md@@ -169,9 +169,11 @@ To enforce centralized access control without sacrificing offline verification pNodes and Routers run a background task that periodically checks the remaining Biscuit expiration:* **Check Interval**: Every 10 minutes (`api.TokenRefreshCheckInterval`).* **Threshold**: When the remaining token lifespan is less than 20% of its initial TTL (~4.8 hours remaining), the daemon proactively trades the expiring Biscuit for a fresh one.-* **Challenge Handshake**: The client signs a current timestamp using its private key and sends it to the Control Plane `/refresh` endpoint along with its expiring Biscuit in the `Authorization: Bearer <token>` header. The Control Plane verifies the signature against the registered node's public key in the database before issuing a new Biscuit.+* **Challenge Handshake**: The client signs a peer- and endpoint-bound timestamp challenge (`sam:refresh:<peer_id>:<unix-millis>`) with its private key and sends it to the Control Plane `/refresh` endpoint along with its expiring Biscuit in the `Authorization: Bearer <token>` header. The Control Plane verifies the signature against the registered node's public key in the database before issuing a new Biscuit.-The bootstrap polling endpoint is guarded by the same proof of possession: `GET /enroll/status` answers only when the caller signs a current timestamp with the key it submitted at `/enroll` (sent as the `ts` and `sig` query parameters). Anything else — no signature, a stale timestamp, another key, an unknown peer — receives a uniform `401`, so an approved enrollment's Biscuit is only ever released to the enrollee itself.+The bootstrap surface requires the same proof of possession end to end. `POST /enroll` carries a signed timestamp challenge in the request body (`timestamp`/`challenge_signature`, and `peer_id` must be derived from the submitted `public_key`), so a bootstrap token alone can never mint — or re-fetch — another peer's Biscuit. `GET /enroll/status` answers only when the caller signs the peer-bound challenge with that same key, sent in the `X-Sam-Challenge-Ts` and `X-Sam-Challenge-Sig` headers (headers rather than query parameters, so signatures stay out of access logs). Anything else — no signature, a stale timestamp, another key, an unknown peer — receives a uniform `401`, so an approved enrollment's Biscuit is only ever released to the enrollee itself.++All three challenges share one shape — the UTF-8 bytes of `sam:<endpoint>:<peer_id>:<unix-millis>` (`sam:enroll:…`, `sam:enroll-status:…`, `sam:refresh:…`), signed by the peer's identity key and accepted within a ±5-minute freshness window. Binding the peer and the endpoint into the signed payload means a signature captured from any one request verifies nowhere else.### Administrative Revocation