Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
feat(node): expose authenticated identity evidence
Rhein1 / Agoragentic170abada32c8
diff --git a/api/sam.pb.go b/api/sam.pb.goindex 43998b02..8ae00da2 100644--- a/api/sam.pb.go+++ b/api/sam.pb.go@@ -2638,6 +2638,190 @@ func (x *AgentStatusResponse) GetError() string {return ""}+type IdentityEvidenceResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ PeerId string `protobuf:"bytes,1,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`+ Biscuit []byte `protobuf:"bytes,2,opt,name=biscuit,proto3" json:"biscuit,omitempty"`+ BiscuitExpiresAt int64 `protobuf:"varint,3,opt,name=biscuit_expires_at,json=biscuitExpiresAt,proto3" json:"biscuit_expires_at,omitempty"`+ ControlPlaneUrl string `protobuf:"bytes,4,opt,name=control_plane_url,json=controlPlaneUrl,proto3" json:"control_plane_url,omitempty"`+ TrustedControlPlaneKeys [][]byte `protobuf:"bytes,5,rep,name=trusted_control_plane_keys,json=trustedControlPlaneKeys,proto3" json:"trusted_control_plane_keys,omitempty"` // Ed25519 SPKI DER+ CheckedAt int64 `protobuf:"varint,6,opt,name=checked_at,json=checkedAt,proto3" json:"checked_at,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *IdentityEvidenceResponse) Reset() {+ *x = IdentityEvidenceResponse{}+ mi := &file_api_sam_proto_msgTypes[39]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *IdentityEvidenceResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*IdentityEvidenceResponse) ProtoMessage() {}++func (x *IdentityEvidenceResponse) ProtoReflect() protoreflect.Message {+ mi := &file_api_sam_proto_msgTypes[39]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use IdentityEvidenceResponse.ProtoReflect.Descriptor instead.+func (*IdentityEvidenceResponse) Descriptor() ([]byte, []int) {+ return file_api_sam_proto_rawDescGZIP(), []int{39}+}++func (x *IdentityEvidenceResponse) GetPeerId() string {+ if x != nil {+ return x.PeerId+ }+ return ""+}++func (x *IdentityEvidenceResponse) GetBiscuit() []byte {+ if x != nil {+ return x.Biscuit+ }+ return nil+}++func (x *IdentityEvidenceResponse) GetBiscuitExpiresAt() int64 {+ if x != nil {+ return x.BiscuitExpiresAt+ }+ return 0+}++func (x *IdentityEvidenceResponse) GetControlPlaneUrl() string {+ if x != nil {+ return x.ControlPlaneUrl+ }+ return ""+}++func (x *IdentityEvidenceResponse) GetTrustedControlPlaneKeys() [][]byte {+ if x != nil {+ return x.TrustedControlPlaneKeys+ }+ return nil+}++func (x *IdentityEvidenceResponse) GetCheckedAt() int64 {+ if x != nil {+ return x.CheckedAt+ }+ return 0+}++type PeerEvidenceResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ PeerId string `protobuf:"bytes,1,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`+ Biscuit []byte `protobuf:"bytes,2,opt,name=biscuit,proto3" json:"biscuit,omitempty"`+ VerifyingKey []byte `protobuf:"bytes,3,opt,name=verifying_key,json=verifyingKey,proto3" json:"verifying_key,omitempty"` // Ed25519 SPKI DER, member of the trusted set+ Roles []string `protobuf:"bytes,4,rep,name=roles,proto3" json:"roles,omitempty"`+ 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"`+ Expiration int64 `protobuf:"varint,6,opt,name=expiration,proto3" json:"expiration,omitempty"`+ RevocationIds []string `protobuf:"bytes,7,rep,name=revocation_ids,json=revocationIds,proto3" json:"revocation_ids,omitempty"` // hex+ CheckedAt int64 `protobuf:"varint,8,opt,name=checked_at,json=checkedAt,proto3" json:"checked_at,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *PeerEvidenceResponse) Reset() {+ *x = PeerEvidenceResponse{}+ mi := &file_api_sam_proto_msgTypes[40]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *PeerEvidenceResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*PeerEvidenceResponse) ProtoMessage() {}++func (x *PeerEvidenceResponse) ProtoReflect() protoreflect.Message {+ mi := &file_api_sam_proto_msgTypes[40]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use PeerEvidenceResponse.ProtoReflect.Descriptor instead.+func (*PeerEvidenceResponse) Descriptor() ([]byte, []int) {+ return file_api_sam_proto_rawDescGZIP(), []int{40}+}++func (x *PeerEvidenceResponse) GetPeerId() string {+ if x != nil {+ return x.PeerId+ }+ return ""+}++func (x *PeerEvidenceResponse) GetBiscuit() []byte {+ if x != nil {+ return x.Biscuit+ }+ return nil+}++func (x *PeerEvidenceResponse) GetVerifyingKey() []byte {+ if x != nil {+ return x.VerifyingKey+ }+ return nil+}++func (x *PeerEvidenceResponse) GetRoles() []string {+ if x != nil {+ return x.Roles+ }+ return nil+}++func (x *PeerEvidenceResponse) GetLabels() map[string]string {+ if x != nil {+ return x.Labels+ }+ return nil+}++func (x *PeerEvidenceResponse) GetExpiration() int64 {+ if x != nil {+ return x.Expiration+ }+ return 0+}++func (x *PeerEvidenceResponse) GetRevocationIds() []string {+ if x != nil {+ return x.RevocationIds+ }+ return nil+}++func (x *PeerEvidenceResponse) GetCheckedAt() int64 {+ if x != nil {+ return x.CheckedAt+ }+ return 0+}+var File_api_sam_proto protoreflect.FileDescriptorconst file_api_sam_proto_rawDesc = "" +@@ -2836,7 +3020,30 @@ const file_api_sam_proto_rawDesc = "" +"\x15credential_expires_at\x18\x04 \x01(\x03R\x13credentialExpiresAt\"X\n" +"\x13AgentStatusResponse\x12+\n" +"\x06agents\x18\x01 \x03(\v2\x13.sam.v1.AgentStatusR\x06agents\x12\x14\n" +- "\x05error\x18\x02 \x01(\tR\x05error*\x94\x01\n" ++ "\x05error\x18\x02 \x01(\tR\x05error\"\x83\x02\n" ++ "\x18IdentityEvidenceResponse\x12\x17\n" ++ "\apeer_id\x18\x01 \x01(\tR\x06peerId\x12\x18\n" ++ "\abiscuit\x18\x02 \x01(\fR\abiscuit\x12,\n" ++ "\x12biscuit_expires_at\x18\x03 \x01(\x03R\x10biscuitExpiresAt\x12*\n" ++ "\x11control_plane_url\x18\x04 \x01(\tR\x0fcontrolPlaneUrl\x12;\n" ++ "\x1atrusted_control_plane_keys\x18\x05 \x03(\fR\x17trustedControlPlaneKeys\x12\x1d\n" ++ "\n" ++ "checked_at\x18\x06 \x01(\x03R\tcheckedAt\"\xe7\x02\n" ++ "\x14PeerEvidenceResponse\x12\x17\n" ++ "\apeer_id\x18\x01 \x01(\tR\x06peerId\x12\x18\n" ++ "\abiscuit\x18\x02 \x01(\fR\abiscuit\x12#\n" ++ "\rverifying_key\x18\x03 \x01(\fR\fverifyingKey\x12\x14\n" ++ "\x05roles\x18\x04 \x03(\tR\x05roles\x12@\n" ++ "\x06labels\x18\x05 \x03(\v2(.sam.v1.PeerEvidenceResponse.LabelsEntryR\x06labels\x12\x1e\n" ++ "\n" ++ "expiration\x18\x06 \x01(\x03R\n" ++ "expiration\x12%\n" ++ "\x0erevocation_ids\x18\a \x03(\tR\rrevocationIds\x12\x1d\n" ++ "\n" ++ "checked_at\x18\b \x01(\x03R\tcheckedAt\x1a9\n" ++ "\vLabelsEntry\x12\x10\n" ++ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" ++ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01*\x94\x01\n" +"\x10EnrollmentStatus\x12!\n" +"\x1dENROLLMENT_STATUS_UNSPECIFIED\x10\x00\x12\x1d\n" +"\x19ENROLLMENT_STATUS_PENDING\x10\x01\x12\x1e\n" +@@ -2860,7 +3067,7 @@ func file_api_sam_proto_rawDescGZIP() []byte {}var file_api_sam_proto_enumTypes = make([]protoimpl.EnumInfo, 3)-var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 43)+var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 46)var file_api_sam_proto_goTypes = []any{(EnrollmentStatus)(0), // 0: sam.v1.EnrollmentStatus(ServiceType)(0), // 1: sam.v1.ServiceType@@ -2904,22 +3111,25 @@ var file_api_sam_proto_goTypes = []any{(*AgentStatusRequest)(nil), // 39: sam.v1.AgentStatusRequest(*AgentStatus)(nil), // 40: sam.v1.AgentStatus(*AgentStatusResponse)(nil), // 41: sam.v1.AgentStatusResponse- nil, // 42: sam.v1.EnrollRequest.LabelsEntry- nil, // 43: sam.v1.BootstrapEnrollRequest.LabelsEntry- nil, // 44: sam.v1.CommandBackend.EnvEntry- nil, // 45: sam.v1.ServiceAnnounce.LabelsEntry+ (*IdentityEvidenceResponse)(nil), // 42: sam.v1.IdentityEvidenceResponse+ (*PeerEvidenceResponse)(nil), // 43: sam.v1.PeerEvidenceResponse+ nil, // 44: sam.v1.EnrollRequest.LabelsEntry+ nil, // 45: sam.v1.BootstrapEnrollRequest.LabelsEntry+ nil, // 46: sam.v1.CommandBackend.EnvEntry+ nil, // 47: sam.v1.ServiceAnnounce.LabelsEntry+ nil, // 48: sam.v1.PeerEvidenceResponse.LabelsEntry}var file_api_sam_proto_depIdxs = []int32{2, // 0: sam.v1.MeshEvent.type:type_name -> sam.v1.MeshEvent.Type- 42, // 1: sam.v1.EnrollRequest.labels:type_name -> sam.v1.EnrollRequest.LabelsEntry- 43, // 2: sam.v1.BootstrapEnrollRequest.labels:type_name -> sam.v1.BootstrapEnrollRequest.LabelsEntry+ 44, // 1: sam.v1.EnrollRequest.labels:type_name -> sam.v1.EnrollRequest.LabelsEntry+ 45, // 2: sam.v1.BootstrapEnrollRequest.labels:type_name -> sam.v1.BootstrapEnrollRequest.LabelsEntry0, // 3: sam.v1.BootstrapEnrollResponse.status:type_name -> sam.v1.EnrollmentStatus1, // 4: sam.v1.ServiceInfo.type:type_name -> sam.v1.ServiceType- 44, // 5: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry+ 46, // 5: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry10, // 6: sam.v1.RegisterServiceRequest.service:type_name -> sam.v1.ServiceInfo11, // 7: sam.v1.RegisterServiceRequest.command:type_name -> sam.v1.CommandBackend1, // 8: sam.v1.ServiceAnnounce.type:type_name -> sam.v1.ServiceType- 45, // 9: sam.v1.ServiceAnnounce.labels:type_name -> sam.v1.ServiceAnnounce.LabelsEntry+ 47, // 9: sam.v1.ServiceAnnounce.labels:type_name -> sam.v1.ServiceAnnounce.LabelsEntry18, // 10: sam.v1.PolicyConfigGetResponse.roles:type_name -> sam.v1.PolicyRole19, // 11: sam.v1.PolicyConfigGetResponse.bindings:type_name -> sam.v1.PolicyBinding18, // 12: sam.v1.PolicyConfigUpdateRequest.roles:type_name -> sam.v1.PolicyRole@@ -2931,11 +3141,12 @@ var file_api_sam_proto_depIdxs = []int32{32, // 18: sam.v1.AgentAttachRequest.bundle:type_name -> sam.v1.AgentBundle31, // 19: sam.v1.AgentStatus.ingress:type_name -> sam.v1.AgentIngress40, // 20: sam.v1.AgentStatusResponse.agents:type_name -> sam.v1.AgentStatus- 21, // [21:21] is the sub-list for method output_type- 21, // [21:21] is the sub-list for method input_type- 21, // [21:21] is the sub-list for extension type_name- 21, // [21:21] is the sub-list for extension extendee- 0, // [0:21] is the sub-list for field type_name+ 48, // 21: sam.v1.PeerEvidenceResponse.labels:type_name -> sam.v1.PeerEvidenceResponse.LabelsEntry+ 22, // [22:22] is the sub-list for method output_type+ 22, // [22:22] is the sub-list for method input_type+ 22, // [22:22] is the sub-list for extension type_name+ 22, // [22:22] is the sub-list for extension extendee+ 0, // [0:22] is the sub-list for field type_name}func init() { file_api_sam_proto_init() }@@ -2953,7 +3164,7 @@ func file_api_sam_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_sam_proto_rawDesc), len(file_api_sam_proto_rawDesc)),NumEnums: 3,- NumMessages: 43,+ NumMessages: 46,NumExtensions: 0,NumServices: 0,},diff --git a/api/sam.proto b/api/sam.protoindex d956ed72..b84ecbe5 100644--- a/api/sam.proto+++ b/api/sam.proto@@ -345,5 +345,35 @@ message AgentStatusResponse {string error = 2;}+// ============================================================================+// Identity Evidence API+// ============================================================================+//+// Read-only owner/control-plane material served by the node sidecar on+// GET /sam/identity and GET /sam/peer/{peer_id}/evidence. Only reachable+// over the filesystem-protected Unix socket or verified mTLS. A 200 asserts+// the node verified the biscuit, its PeerID binding, and revocation state at+// checked_at; independent verifiers recompute from the raw biscuit and keys.++message IdentityEvidenceResponse {+ string peer_id = 1;+ bytes biscuit = 2;+ int64 biscuit_expires_at = 3;+ string control_plane_url = 4;+ repeated bytes trusted_control_plane_keys = 5; // Ed25519 SPKI DER+ int64 checked_at = 6;+}++message PeerEvidenceResponse {+ string peer_id = 1;+ bytes biscuit = 2;+ bytes verifying_key = 3; // Ed25519 SPKI DER, member of the trusted set+ repeated string roles = 4;+ map<string, string> labels = 5;+ int64 expiration = 6;+ repeated string revocation_ids = 7; // hex+ int64 checked_at = 8;+}+diff --git a/internal/node/identity_evidence.go b/internal/node/identity_evidence.gonew file mode 100644index 00000000..bdf37876--- /dev/null+++ b/internal/node/identity_evidence.go@@ -0,0 +1,405 @@+// 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 node++import (+ "bytes"+ "crypto/ed25519"+ "crypto/x509"+ "encoding/hex"+ "fmt"+ "net/http"+ "sort"+ "strings"+ "time"++ "github.com/biscuit-auth/biscuit-go/v2"+ "github.com/google/sam/api"+ "github.com/google/sam/internal/identity"+ "github.com/libp2p/go-libp2p/core/peer"+ "google.golang.org/protobuf/encoding/protojson"+ "google.golang.org/protobuf/proto"+)++type trustedKeySnapshot struct {+ Key ed25519.PublicKey+ SPKIDER []byte+}++func snapshotControlPlaneKey(key ed25519.PublicKey) (trustedKeySnapshot, error) {+ if len(key) != ed25519.PublicKeySize {+ return trustedKeySnapshot{}, fmt.Errorf("invalid Ed25519 key size %d", len(key))+ }+ keyCopy := append(ed25519.PublicKey(nil), key...)+ der, err := x509.MarshalPKIXPublicKey(keyCopy)+ if err != nil {+ return trustedKeySnapshot{}, fmt.Errorf("marshal Ed25519 SPKI: %w", err)+ }+ return trustedKeySnapshot{+ Key: keyCopy,+ SPKIDER: der,+ }, nil+}++func (n *SamNode) trustedKeySnapshot() ([]trustedKeySnapshot, error) {+ n.keysMu.RLock()+ trusted := append([]TrustedKey(nil), n.trustedKeys...)+ n.keysMu.RUnlock()++ snapshots := make([]trustedKeySnapshot, 0, len(trusted))+ for _, candidate := range trusted {+ snapshot, err := snapshotControlPlaneKey(candidate.Key)+ if err != nil {+ return nil, err+ }+ snapshots = append(snapshots, snapshot)+ }+ sort.Slice(snapshots, func(i, j int) bool {+ return bytes.Compare(snapshots[i].SPKIDER, snapshots[j].SPKIDER) < 0+ })+ return snapshots, nil+}++func keysFromSnapshot(snapshots []trustedKeySnapshot) []ed25519.PublicKey {+ keys := make([]ed25519.PublicKey, 0, len(snapshots))+ for _, snapshot := range snapshots {+ keys = append(keys, snapshot.Key)+ }+ return keys+}++func findSelectedKey(snapshots []trustedKeySnapshot, selected ed25519.PublicKey) (trustedKeySnapshot, bool) {+ for _, snapshot := range snapshots {+ if snapshot.Key.Equal(selected) {+ return snapshot, true+ }+ }+ return trustedKeySnapshot{}, false+}++func (n *SamNode) stillTrustsKey(selected trustedKeySnapshot) bool {+ current, err := n.trustedKeySnapshot()+ if err != nil {+ return false+ }+ for _, candidate := range current {+ if candidate.Key.Equal(selected.Key) {+ return true+ }+ }+ return false+}++func requireIdentityEvidenceTransport(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if !fromLocalSocket(r) && (r.TLS == nil || len(r.TLS.VerifiedChains) == 0) {+ writeEvidenceError(w, http.StatusForbidden, "Strong transport required")+ return+ }+ next.ServeHTTP(w, r)+ })+}++func writeEvidenceProtoJSON(w http.ResponseWriter, status int, value proto.Message) {+ body, err := protojson.Marshal(value)+ if err != nil {+ logger.Errorf("[IdentityEvidence] Failed to encode response: %v", err)+ writeEvidenceError(w, http.StatusInternalServerError, "Failed to encode response")+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.Header().Set("Cache-Control", "no-store")+ w.Header().Set("X-Content-Type-Options", "nosniff")+ w.WriteHeader(status)+ if _, err := w.Write(body); err != nil {+ logger.Errorf("[IdentityEvidence] Failed to write response: %v", err)+ }+}++func writeEvidenceError(w http.ResponseWriter, status int, message string) {+ w.Header().Set("Cache-Control", "no-store")+ http.Error(w, message, status)+}++func handleIdentityEvidenceNotFound(w http.ResponseWriter, _ *http.Request) {+ writeEvidenceError(w, http.StatusNotFound, "Not found")+}++func handleIdentityEvidence(n *SamNode, w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ w.Header().Set("Allow", http.MethodGet)+ writeEvidenceError(w, http.StatusMethodNotAllowed, "Method not allowed")+ return+ }+ if n != nil && n.Host != nil && n.peerIsRevoked(n.Host.ID()) {+ writeEvidenceError(w, http.StatusForbidden, "Local identity is revoked")+ return+ }+ response, err := n.buildIdentityEvidence(time.Now().UTC())+ if err != nil {+ logger.Warnf("[IdentityEvidence] Local identity unavailable: %v", err)+ writeEvidenceError(w, http.StatusServiceUnavailable, "Identity evidence unavailable")+ return+ }+ writeEvidenceProtoJSON(w, http.StatusOK, response)+}++func handlePeerEvidence(n *SamNode, w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ w.Header().Set("Allow", http.MethodGet)+ writeEvidenceError(w, http.StatusMethodNotAllowed, "Method not allowed")+ return+ }+ const prefix = "/sam/peer/"+ remainder := strings.TrimPrefix(r.URL.Path, prefix)+ parts := strings.Split(remainder, "/")+ if len(parts) != 2 || parts[0] == "" || parts[1] != "evidence" {+ writeEvidenceError(w, http.StatusNotFound, "Not found")+ return+ }+ requestedPeer, err := peer.Decode(parts[0])+ if err != nil || requestedPeer.String() != parts[0] {+ writeEvidenceError(w, http.StatusBadRequest, "Invalid peer ID")+ return+ }+ if n.peerIsRevoked(requestedPeer) {+ writeEvidenceError(w, http.StatusForbidden, "Peer is revoked")+ return+ }++ observation, err := n.fetchPeerBiscuitEvidence(r.Context(), requestedPeer)+ if err != nil {+ logger.Warnf("[IdentityEvidence] Peer evidence fetch failed for %s: %v", requestedPeer, err)+ writeEvidenceError(w, http.StatusBadGateway, "Failed to fetch peer evidence")+ return+ }+ response, err := n.buildPeerEvidence(requestedPeer, observation, time.Now().UTC())+ if err != nil {+ logger.Warnf("[IdentityEvidence] Peer evidence verification failed for %s: %v", requestedPeer, err)+ writeEvidenceError(w, http.StatusUnprocessableEntity, "Peer evidence is unverifiable")+ return+ }+ writeEvidenceProtoJSON(w, http.StatusOK, response)+}++func trustedControlPlaneKeysUnavailable(err error, snapshots []trustedKeySnapshot) error {+ if err != nil {+ return fmt.Errorf("trusted control-plane keys unavailable: %w", err)+ }+ if len(snapshots) == 0 {+ return fmt.Errorf("trusted control-plane keys unavailable")+ }+ return nil+}++func (n *SamNode) buildIdentityEvidence(checkedAt time.Time) (*api.IdentityEvidenceResponse, error) {+ if n == nil || n.Host == nil || n.Store == nil {+ return nil, fmt.Errorf("node identity store is unavailable")+ }+ biscuitBytes := n.GetIdentity()+ if len(biscuitBytes) == 0 {+ return nil, fmt.Errorf("node is not enrolled")+ }+ snapshots, err := n.trustedKeySnapshot()+ if unavailable := trustedControlPlaneKeysUnavailable(err, snapshots); unavailable != nil {+ return nil, unavailable+ }+ b, selectedKey, err := identity.VerifyBiscuitAndGetKey(biscuitBytes, n.Host.ID(), keysFromSnapshot(snapshots), n.BiscuitTimeout)+ if err != nil {+ return nil, err+ }+ selected, ok := findSelectedKey(snapshots, selectedKey)+ if !ok {+ return nil, fmt.Errorf("selected verification key is not in the trusted snapshot")+ }+ claims, err := extractBiscuitClaims(b, selectedKey, n.BiscuitTimeout, checkedAt)+ if err != nil {+ return nil, err+ }+ if claims.PeerID != n.Host.ID().String() || n.peerIsRevoked(n.Host.ID()) || !n.stillTrustsKey(selected) {+ return nil, fmt.Errorf("local peer binding, revocation, or trust state changed during verification")+ }+ controlPlaneURL, err := n.Store.LoadControlPlaneURL()+ if err != nil {+ return nil, fmt.Errorf("control-plane URL unavailable: %w", err)+ }+ keyEvidence := make([][]byte, 0, len(snapshots))+ for _, snapshot := range snapshots {+ keyEvidence = append(keyEvidence, append([]byte(nil), snapshot.SPKIDER...))+ }+ return &api.IdentityEvidenceResponse{+ PeerId: n.Host.ID().String(),+ Biscuit: append([]byte(nil), biscuitBytes...),+ BiscuitExpiresAt: claims.Expiration.Unix(),+ ControlPlaneUrl: controlPlaneURL,+ TrustedControlPlaneKeys: keyEvidence,+ CheckedAt: checkedAt.Unix(),+ }, nil+}++func (n *SamNode) buildPeerEvidence(requested peer.ID, observation peerBiscuitObservation, checkedAt time.Time) (*api.PeerEvidenceResponse, error) {+ if requested == "" || observation.ConnectionPeer == "" || requested != observation.ConnectionPeer {+ return nil, fmt.Errorf("requested and connection PeerIDs differ")+ }+ snapshots, err := n.trustedKeySnapshot()+ if unavailable := trustedControlPlaneKeysUnavailable(err, snapshots); unavailable != nil {+ return nil, unavailable+ }+ b, selectedKey, err := identity.VerifyBiscuitAndGetKey(observation.Biscuit, observation.ConnectionPeer, keysFromSnapshot(snapshots), n.BiscuitTimeout)+ if err != nil {+ return nil, err+ }+ selected, ok := findSelectedKey(snapshots, selectedKey)+ if !ok {+ return nil, fmt.Errorf("selected verification key is not in the trusted snapshot")+ }+ claims, err := extractBiscuitClaims(b, selectedKey, n.BiscuitTimeout, checkedAt)+ if err != nil {+ return nil, err+ }+ if claims.PeerID != requested.String() || n.peerIsRevoked(requested) || !n.stillTrustsKey(selected) {+ return nil, fmt.Errorf("peer binding, revocation, or trust state changed during verification")+ }++ revocationIDs := make([]string, 0, len(b.RevocationIds()))+ for _, id := range b.RevocationIds() {+ revocationIDs = append(revocationIDs, hex.EncodeToString(id))+ }+ return &api.PeerEvidenceResponse{+ PeerId: requested.String(),+ Biscuit: append([]byte(nil), observation.Biscuit...),+ VerifyingKey: append([]byte(nil), selected.SPKIDER...),+ Roles: append([]string(nil), claims.Roles...),+ Labels: claims.Labels,+ Expiration: claims.Expiration.Unix(),+ RevocationIds: revocationIDs,+ CheckedAt: checkedAt.Unix(),+ }, nil+}++func (n *SamNode) peerIsRevoked(peerID peer.ID) bool {+ if n.revokedPeers != nil && n.revokedPeers.Contains(peerID.String()) {+ return true+ }+ return n.Store != nil && n.Store.IsBanned(peerID)+}++type biscuitClaims struct {+ PeerID string+ Roles []string+ Labels map[string]string+ Expiration time.Time+}++func extractBiscuitClaims(b *biscuit.Biscuit, key ed25519.PublicKey, timeout time.Duration, checkedAt time.Time) (biscuitClaims, error) {+ authorizer, err := b.Authorizer(key, identity.AuthorizerOptions(timeout)...)+ if err != nil {+ return biscuitClaims{}, err+ }+ authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactTime,+ IDs: []biscuit.Term{biscuit.Date(checkedAt)},+ }})+ authorizer.AddCheck(api.ControlPlaneStaticTimeCheck)+ authorizer.AddPolicy(api.AllowIfTruePolicy)+ if err := authorizer.Authorize(); err != nil {+ return biscuitClaims{}, err+ }++ peerIDs, err := queryStringFacts(authorizer, api.FactNode)+ if err != nil || len(peerIDs) != 1 {+ return biscuitClaims{}, fmt.Errorf("expected exactly one node fact")+ }+ roles, err := queryStringFacts(authorizer, api.FactRole)+ if err != nil {+ return biscuitClaims{}, err+ }+ labels, err := queryLabelFacts(authorizer)+ if err != nil {+ return biscuitClaims{}, err+ }+ expiration, err := queryExpiration(authorizer)+ if err != nil {+ return biscuitClaims{}, err+ }+ sort.Strings(roles)+ return biscuitClaims{PeerID: peerIDs[0], Roles: roles, Labels: labels, Expiration: expiration.UTC()}, nil+}++func queryStringFacts(authorizer biscuit.Authorizer, factName string) ([]string, error) {+ facts, err := authorizer.Query(biscuit.Rule{+ Head: biscuit.Predicate{Name: "q", IDs: []biscuit.Term{biscuit.Variable("v")}},+ Body: []biscuit.Predicate{{Name: factName, IDs: []biscuit.Term{biscuit.Variable("v")}}},+ })+ if err != nil {+ return nil, err+ }+ values := make([]string, 0, len(facts))+ for _, fact := range facts {+ if len(fact.IDs) != 1 {+ return nil, fmt.Errorf("unexpected %s fact shape", factName)+ }+ value, ok := fact.IDs[0].(biscuit.String)+ if !ok {+ return nil, fmt.Errorf("unexpected %s fact type", factName)+ }+ values = append(values, string(value))+ }+ return values, nil+}++func queryLabelFacts(authorizer biscuit.Authorizer) (map[string]string, error) {+ facts, err := authorizer.Query(biscuit.Rule{+ Head: biscuit.Predicate{Name: "q", IDs: []biscuit.Term{biscuit.Variable("k"), biscuit.Variable("v")}},+ Body: []biscuit.Predicate{{Name: api.FactLabel, IDs: []biscuit.Term{biscuit.Variable("k"), biscuit.Variable("v")}}},+ })+ if err != nil {+ return nil, err+ }+ labels := make(map[string]string, len(facts))+ for _, fact := range facts {+ if len(fact.IDs) != 2 {+ return nil, fmt.Errorf("unexpected label fact shape")+ }+ key, keyOK := fact.IDs[0].(biscuit.String)+ value, valueOK := fact.IDs[1].(biscuit.String)+ if !keyOK || !valueOK {+ return nil, fmt.Errorf("unexpected label fact type")+ }+ if previous, exists := labels[string(key)]; exists && previous != string(value) {+ return nil, fmt.Errorf("conflicting attested label %q", key)+ }+ labels[string(key)] = string(value)+ }+ return labels, nil+}++func queryExpiration(authorizer biscuit.Authorizer) (time.Time, error) {+ facts, err := authorizer.Query(biscuit.Rule{+ Head: biscuit.Predicate{Name: "q", IDs: []biscuit.Term{biscuit.Variable("t")}},+ Body: []biscuit.Predicate{{Name: api.FactExpiration, IDs: []biscuit.Term{biscuit.Variable("t")}}},+ })+ if err != nil {+ return time.Time{}, err+ }+ if len(facts) != 1 || len(facts[0].IDs) != 1 {+ return time.Time{}, fmt.Errorf("expected exactly one expiration fact")+ }+ expiration, ok := facts[0].IDs[0].(biscuit.Date)+ if !ok {+ return time.Time{}, fmt.Errorf("unexpected expiration fact type")+ }+ return time.Time(expiration), nil+}diff --git a/internal/node/identity_evidence_http_test.go b/internal/node/identity_evidence_http_test.gonew file mode 100644index 00000000..ab203bbc--- /dev/null+++ b/internal/node/identity_evidence_http_test.go@@ -0,0 +1,176 @@+// 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 node++import (+ "io"+ "net/http"+ "net/http/httptest"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/libp2p/go-libp2p"+)++func TestIdentityEvidenceRoutesHaveOwnMetricClass(t *testing.T) {+ for _, path := range []string{+ "/sam/identity",+ "/sam/identity/",+ "/sam/identity/extra",+ "/sam/peer/12D3KooWpeer/evidence",+ } {+ if got := classifyRoute(path); got != "identity-evidence" {+ t.Errorf("classifyRoute(%q) = %q, want %q", path, got, "identity-evidence")+ }+ }+}++func TestIdentityEvidenceTrailingSlashReturnsNotFound(t *testing.T) {+ node := &SamNode{+ BiscuitTimeout: 500 * time.Millisecond,+ services: NewServiceRegistry(&fakeDHT{}),+ }+ socketPath := filepath.Join(t.TempDir(), "sam.sock")++ srv, err := StartSidecarServer(node, "", socketPath, "", "", "", "")+ if err != nil {+ t.Fatalf("start socket-only sidecar: %v", err)+ }+ defer func() { _ = srv.Close() }()++ client := waitForSocket(t, socketPath)+ resp, err := client.Get("http://localhost/sam/identity/")+ if err != nil {+ t.Fatalf("GET /sam/identity/: %v", err)+ }+ defer func() { _ = resp.Body.Close() }()+ body, err := io.ReadAll(resp.Body)+ if err != nil {+ t.Fatalf("read response: %v", err)+ }+ if resp.StatusCode != http.StatusNotFound {+ t.Fatalf("status = %d, body = %q, want %d", resp.StatusCode, body, http.StatusNotFound)+ }+ if got := strings.TrimSpace(string(body)); got != "Not found" {+ t.Fatalf("body = %q, want %q", got, "Not found")+ }+}++func TestHandleIdentityEvidenceRejectsRevokedLocalPeer(t *testing.T) {+ node, _, _ := newIdentityEvidenceTestNode(t, nil)+ node.revokedPeers.Add(node.Host.ID().String(), time.Now().Unix())++ recorder := httptest.NewRecorder()+ handleIdentityEvidence(node, recorder, localSocketRequest(http.MethodGet, "/sam/identity"))++ if recorder.Code != http.StatusForbidden {+ t.Fatalf("status = %d, body = %q, want %d", recorder.Code, recorder.Body.String(), http.StatusForbidden)+ }+ if got := strings.TrimSpace(recorder.Body.String()); got != "Local identity is revoked" {+ t.Fatalf("body = %q, want %q", got, "Local identity is revoked")+ }+ if got := recorder.Header().Get("Cache-Control"); got != "no-store" {+ t.Fatalf("Cache-Control = %q, want %q", got, "no-store")+ }+}++func TestHandlePeerEvidenceErrorContract(t *testing.T) {+ node, _, _ := newIdentityEvidenceTestNode(t, nil)+ provider, err := libp2p.New()+ if err != nil {+ t.Fatalf("create provider host: %v", err)+ }+ t.Cleanup(func() { _ = provider.Close() })++ validPath := "/sam/peer/" + provider.ID().String() + "/evidence"+ tests := []struct {+ name string+ method string+ path string+ setup func()+ cleanup func()+ wantStatus int+ wantBody string+ wantAllow string+ }{+ {+ name: "bad peer ID",+ method: http.MethodGet,+ path: "/sam/peer/not-a-peer/evidence",+ wantStatus: http.StatusBadRequest,+ wantBody: "Invalid peer ID",+ },+ {+ name: "pre-fetch revoked",+ method: http.MethodGet,+ path: validPath,+ setup: func() {+ node.revokedPeers.Add(provider.ID().String(), time.Now().Unix())+ },+ cleanup: func() {+ node.revokedPeers.Remove(provider.ID().String())+ },+ wantStatus: http.StatusForbidden,+ wantBody: "Peer is revoked",+ },+ {+ name: "non-GET",+ method: http.MethodPost,+ path: validPath,+ wantStatus: http.StatusMethodNotAllowed,+ wantBody: "Method not allowed",+ wantAllow: http.MethodGet,+ },+ {+ name: "wrong path shape",+ method: http.MethodGet,+ path: "/sam/peer/" + provider.ID().String(),+ wantStatus: http.StatusNotFound,+ wantBody: "Not found",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if tc.setup != nil {+ tc.setup()+ }+ if tc.cleanup != nil {+ defer tc.cleanup()+ }++ recorder := httptest.NewRecorder()+ handlePeerEvidence(node, recorder, httptest.NewRequest(tc.method, tc.path, nil))++ if recorder.Code != tc.wantStatus {+ t.Fatalf("status = %d, body = %q, want %d", recorder.Code, recorder.Body.String(), tc.wantStatus)+ }+ if got := strings.TrimSpace(recorder.Body.String()); got != tc.wantBody {+ t.Fatalf("body = %q, want %q", got, tc.wantBody)+ }+ if got := recorder.Header().Get("Cache-Control"); got != "no-store" {+ t.Fatalf("Cache-Control = %q, want %q", got, "no-store")+ }+ if got := recorder.Header().Get("Content-Type"); got != "text/plain; charset=utf-8" {+ t.Fatalf("Content-Type = %q, want text/plain", got)+ }+ if got := recorder.Header().Get("Allow"); got != tc.wantAllow {+ t.Fatalf("Allow = %q, want %q", got, tc.wantAllow)+ }+ })+ }+}diff --git a/internal/node/identity_evidence_test.go b/internal/node/identity_evidence_test.gonew file mode 100644index 00000000..21e691f3--- /dev/null+++ b/internal/node/identity_evidence_test.go@@ -0,0 +1,217 @@+// 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 node++import (+ "bytes"+ "context"+ "crypto/ed25519"+ "crypto/rand"+ "crypto/tls"+ "crypto/x509"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/google/sam/api"+ "github.com/google/sam/internal/identity"+ lru "github.com/hashicorp/golang-lru/v2"+ "github.com/libp2p/go-libp2p"+ "google.golang.org/protobuf/encoding/protojson"+)++func newIdentityEvidenceTestNode(t *testing.T, labels map[string]string) (*SamNode, ed25519.PrivateKey, time.Time) {+ t.Helper()+ host, err := libp2p.New()+ if err != nil {+ t.Fatalf("create libp2p host: %v", err)+ }+ t.Cleanup(func() { _ = host.Close() })+ controlPlanePublic, controlPlanePrivate, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatalf("generate control-plane key: %v", err)+ }+ expiresAt := time.Now().UTC().Add(time.Hour).Truncate(time.Second)+ biscuitBytes, err := identity.MintBootstrapBiscuitToken(controlPlanePrivate, host.ID(), api.RoleNode, expiresAt, nil, labels)+ if err != nil {+ t.Fatalf("mint identity biscuit: %v", err)+ }+ store, err := NewStore(t.TempDir())+ if err != nil {+ t.Fatalf("create store: %v", err)+ }+ t.Cleanup(func() { _ = store.Close() })+ if err := store.SaveIdentity(biscuitBytes); err != nil {+ t.Fatalf("save identity: %v", err)+ }+ if err := store.SaveControlPlaneURL("https://cp.example"); err != nil {+ t.Fatalf("save control-plane URL: %v", err)+ }+ revokedPeers, err := lru.New[string, int64](16)+ if err != nil {+ t.Fatalf("create revocation cache: %v", err)+ }+ node := &SamNode{+ Host: host,+ Store: store,+ trustedKeys: []TrustedKey{{Key: controlPlanePublic, ReceivedAt: time.Now().UTC().Add(-time.Minute)}},+ revokedPeers: revokedPeers,+ BiscuitTimeout: time.Second,+ }+ node.SetIdentityCache(biscuitBytes)+ return node, controlPlanePrivate, expiresAt+}++func localSocketRequest(method, target string) *http.Request {+ request := httptest.NewRequest(method, target, nil)+ return request.WithContext(context.WithValue(request.Context(), localSocketContextKey{}, true))+}++func TestIdentityEvidenceRequiresStrongTransport(t *testing.T) {+ node, _, _ := newIdentityEvidenceTestNode(t, nil)+ handler := requireIdentityEvidenceTransport(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handleIdentityEvidence(node, w, r)+ }))++ plainRecorder := httptest.NewRecorder()+ handler.ServeHTTP(plainRecorder, httptest.NewRequest(http.MethodGet, "/sam/identity", nil))+ if plainRecorder.Code != http.StatusForbidden {+ t.Fatalf("plain TCP status = %d, want %d", plainRecorder.Code, http.StatusForbidden)+ }+ if got := plainRecorder.Header().Get("Content-Type"); got != "text/plain; charset=utf-8" {+ t.Fatalf("plain TCP content type = %q, want text/plain", got)+ }++ socketRecorder := httptest.NewRecorder()+ handler.ServeHTTP(socketRecorder, localSocketRequest(http.MethodGet, "/sam/identity"))+ if socketRecorder.Code != http.StatusOK {+ t.Fatalf("socket status = %d, body = %s", socketRecorder.Code, socketRecorder.Body.String())+ }++ mtlsRequest := httptest.NewRequest(http.MethodGet, "/sam/identity", nil)+ mtlsRequest.TLS = &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{{}}}}+ mtlsRecorder := httptest.NewRecorder()+ handler.ServeHTTP(mtlsRecorder, mtlsRequest)+ if mtlsRecorder.Code != http.StatusOK {+ t.Fatalf("mTLS status = %d, body = %s", mtlsRecorder.Code, mtlsRecorder.Body.String())+ }+}++func TestIdentityEvidenceReturnsVerifiableClosedResponse(t *testing.T) {+ node, _, expiresAt := newIdentityEvidenceTestNode(t, map[string]string{"region": "us-east-1"})+ recorder := httptest.NewRecorder()+ handleIdentityEvidence(node, recorder, localSocketRequest(http.MethodGet, "/sam/identity"))+ if recorder.Code != http.StatusOK {+ t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body.String())+ }+ var response api.IdentityEvidenceResponse+ if err := protojson.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if response.PeerId != node.Host.ID().String() || len(response.Biscuit) == 0 {+ t.Fatalf("unexpected identity response: peer=%q biscuit=%d", response.PeerId, len(response.Biscuit))+ }+ if response.BiscuitExpiresAt != expiresAt.Unix() || len(response.TrustedControlPlaneKeys) != 1 {+ t.Fatalf("unexpected expiry or key set: expiry=%d keys=%d", response.BiscuitExpiresAt, len(response.TrustedControlPlaneKeys))+ }+ parsedKey, err := x509.ParsePKIXPublicKey(response.TrustedControlPlaneKeys[0])+ if err != nil {+ t.Fatalf("parse SPKI: %v", err)+ }+ publicKey, ok := parsedKey.(ed25519.PublicKey)+ if !ok || !publicKey.Equal(node.trustedKeys[0].Key) {+ t.Fatalf("trusted control-plane key is not the enrolled key")+ }+ if response.CheckedAt <= 0 || response.CheckedAt > response.BiscuitExpiresAt {+ t.Fatalf("invalid checked/expiry timestamps: checked=%d expiry=%d", response.CheckedAt, response.BiscuitExpiresAt)+ }+}++func TestBuildIdentityEvidenceFailsClosedWhenLocalPeerIsRevoked(t *testing.T) {+ node, _, _ := newIdentityEvidenceTestNode(t, nil)+ node.revokedPeers.Add(node.Host.ID().String(), time.Now().Unix())++ if _, err := node.buildIdentityEvidence(time.Now().UTC()); err == nil {+ t.Fatal("revoked local peer must not produce identity evidence")+ }+}++func TestBuildPeerEvidenceBindsRequestedConnectionAndBiscuitPeers(t *testing.T) {+ node, controlPlanePrivate, expiresAt := newIdentityEvidenceTestNode(t, nil)+ provider, err := libp2p.New()+ if err != nil {+ t.Fatalf("create provider host: %v", err)+ }+ t.Cleanup(func() { _ = provider.Close() })+ providerBiscuit, err := identity.MintBootstrapBiscuitToken(controlPlanePrivate, provider.ID(), api.RoleNode, expiresAt, nil, map[string]string{"region": "us-east-1"})+ if err != nil {+ t.Fatalf("mint provider biscuit: %v", err)+ }+ response, err := node.buildPeerEvidence(provider.ID(), peerBiscuitObservation{+ Biscuit: providerBiscuit,+ ConnectionPeer: provider.ID(),+ }, time.Now().UTC())+ if err != nil {+ t.Fatalf("build peer evidence: %v", err)+ }+ if response.PeerId != provider.ID().String() || !bytes.Equal(response.Biscuit, providerBiscuit) {+ t.Fatalf("unexpected peer binding: %+v", response)+ }+ if response.Labels["region"] != "us-east-1" || len(response.RevocationIds) == 0 {+ t.Fatalf("missing attestation or revocation evidence: %+v", response)+ }+ if response.Expiration != expiresAt.Unix() || response.CheckedAt <= 0 || response.CheckedAt > response.Expiration {+ t.Fatalf("invalid checked/expiry timestamps: checked=%d expiry=%d", response.CheckedAt, response.Expiration)+ }+ parsedKey, err := x509.ParsePKIXPublicKey(response.VerifyingKey)+ if err != nil {+ t.Fatalf("parse verifying key SPKI: %v", err)+ }+ publicKey, ok := parsedKey.(ed25519.PublicKey)+ if !ok || !publicKey.Equal(node.trustedKeys[0].Key) {+ t.Fatalf("peer evidence verifying key is not in the trusted set")+ }+}++func TestBuildPeerEvidenceFailsClosedOnBindingRevocationAndKeyRotation(t *testing.T) {+ node, controlPlanePrivate, expiresAt := newIdentityEvidenceTestNode(t, nil)+ provider, _ := libp2p.New()+ t.Cleanup(func() { _ = provider.Close() })+ other, _ := libp2p.New()+ t.Cleanup(func() { _ = other.Close() })+ providerBiscuit, err := identity.MintBootstrapBiscuitToken(controlPlanePrivate, provider.ID(), api.RoleNode, expiresAt, nil, nil)+ if err != nil {+ t.Fatalf("mint provider biscuit: %v", err)+ }+ observation := peerBiscuitObservation{Biscuit: providerBiscuit, ConnectionPeer: provider.ID()}+ if _, err := node.buildPeerEvidence(other.ID(), observation, time.Now().UTC()); err == nil {+ t.Fatalf("requested/connection mismatch must fail closed")+ }++ node.revokedPeers.Add(provider.ID().String(), time.Now().Unix())+ if _, err := node.buildPeerEvidence(provider.ID(), observation, time.Now().UTC()); err == nil {+ t.Fatalf("revoked peer must fail closed")+ }+ node.revokedPeers.Remove(provider.ID().String())++ newPublic, _, _ := ed25519.GenerateKey(rand.Reader)+ node.keysMu.Lock()+ node.trustedKeys = []TrustedKey{{Key: newPublic, ReceivedAt: time.Now().UTC()}}+ node.keysMu.Unlock()+ if _, err := node.buildPeerEvidence(provider.ID(), observation, time.Now().UTC()); err == nil {+ t.Fatalf("untrusted signing key must fail closed")+ }+}diff --git a/internal/node/labels_gate.go b/internal/node/labels_gate.goindex f85e9b0c..33d78478 100644--- a/internal/node/labels_gate.go+++ b/internal/node/labels_gate.go@@ -123,42 +123,65 @@ func (n *SamNode) checkPeerLabels(providerBiscuit []byte, peerID peer.ID, requir// fetchPeerBiscuit obtains the peer's control-plane-minted identity via the// mutual auth handshake on AuthProtocolID, authenticating with our own.func (n *SamNode) fetchPeerBiscuit(ctx context.Context, peerID peer.ID) ([]byte, error) {+ observation, err := n.fetchPeerBiscuitEvidence(ctx, peerID)+ if err != nil {+ return nil, err+ }+ return observation.Biscuit, nil+}++type peerBiscuitObservation struct {+ Biscuit []byte+ ConnectionPeer peer.ID+}++// fetchPeerBiscuitEvidence is the uncached form used by the local evidence API.+// It preserves the PeerID authenticated by the libp2p stream separately from+// the requested target so callers can fail closed on any binding mismatch.+func (n *SamNode) fetchPeerBiscuitEvidence(ctx context.Context, peerID peer.ID) (peerBiscuitObservation, error) {ourBiscuit := n.GetIdentity()if ourBiscuit == nil {- return nil, fmt.Errorf("missing node identity")+ return peerBiscuitObservation{}, fmt.Errorf("missing node identity")}dialCtx, cancel := context.WithTimeout(ctx, labelGateDialTimeout)defer cancel()s, err := n.Host.NewStream(dialCtx, peerID, api.AuthProtocolID)if err != nil {- return nil, fmt.Errorf("failed to open auth stream: %w", err)+ return peerBiscuitObservation{}, fmt.Errorf("failed to open auth stream: %w", err)}defer func() { _ = s.Close() }()_ = s.SetDeadline(time.Now().Add(labelGateDialTimeout))+ connectionPeer := s.Conn().RemotePeer()+ if connectionPeer != peerID {+ return peerBiscuitObservation{}, fmt.Errorf("authenticated connection peer %s does not match requested peer %s", connectionPeer, peerID)+ }authBytes, err := proto.Marshal(&api.AuthFrame{Biscuit: ourBiscuit})if err != nil {- return nil, fmt.Errorf("marshal auth frame: %w", err)+ return peerBiscuitObservation{}, fmt.Errorf("marshal auth frame: %w", err)}writer := msgio.NewVarintWriter(s)if err := writer.WriteMsg(authBytes); err != nil {- return nil, fmt.Errorf("write auth frame: %w", err)+ return peerBiscuitObservation{}, fmt.Errorf("write auth frame: %w", err)}reader := msgio.NewVarintReaderSize(s, 1024*64)msg, err := reader.ReadMsg()if err != nil {- return nil, fmt.Errorf("read auth response (peer may predate mutual auth): %w", err)+ return peerBiscuitObservation{}, fmt.Errorf("read auth response (peer may predate mutual auth): %w", err)}defer reader.ReleaseMsg(msg)var resp api.AuthResponseif err := proto.Unmarshal(msg, &resp); err != nil {- return nil, fmt.Errorf("invalid auth response: %w", err)+ return peerBiscuitObservation{}, fmt.Errorf("invalid auth response: %w", err)}if !resp.Success {- return nil, fmt.Errorf("auth rejected: %s", resp.Error)+ return peerBiscuitObservation{}, fmt.Errorf("auth rejected: %s", resp.Error)}- return resp.Biscuit, nil+ return peerBiscuitObservation{+ Biscuit: resp.Biscuit,+ ConnectionPeer: connectionPeer,+ }, nil}diff --git a/internal/node/sidecar.go b/internal/node/sidecar.goindex ef3fee4f..1065127d 100644--- a/internal/node/sidecar.go+++ b/internal/node/sidecar.go@@ -62,6 +62,17 @@ func StartSidecarServer(node *SamNode, addr, socketPath, token, certFile, keyFilhandleDiscoverService(node, w, r)}))))+ // Identity evidence is local owner/control-plane material, not an agent tool.+ // Require a channel that authenticates the sidecar back to the caller: the+ // filesystem-protected Unix socket, or verified mTLS when TCP is unavoidable.+ mux.Handle("/sam/identity", withAuth(token, true, requireIdentityEvidenceTransport(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handleIdentityEvidence(node, w, r)+ }))))+ mux.Handle("/sam/identity/", withAuth(token, true, requireIdentityEvidenceTransport(http.HandlerFunc(handleIdentityEvidenceNotFound))))+ mux.Handle("/sam/peer/", withAuth(token, true, requireIdentityEvidenceTransport(withMeshConnection(node, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handlePeerEvidence(node, w, r)+ })))))+// Mount Egress Proxy. allowAuthorizationFallback=false is required here: this// handler forwards Authorization to the destination service, so it must never// also accept it as the local gate credential (would leak the sidecar token off-node).diff --git a/internal/node/sidecar_metrics.go b/internal/node/sidecar_metrics.goindex 58767451..9e8b6629 100644--- a/internal/node/sidecar_metrics.go+++ b/internal/node/sidecar_metrics.go@@ -67,6 +67,8 @@ func classifyRoute(path string) string {switch {case path == "/healthz", path == "/readyz", path == "/metrics":return "health"+ case path == "/sam/identity", strings.HasPrefix(path, "/sam/identity/"), strings.HasPrefix(path, "/sam/peer/"):+ return "identity-evidence"case strings.HasPrefix(path, "/sam/service/"):return "service-registry"case strings.HasPrefix(path, "/sam/"):diff --git a/tests/integration/identity_evidence_test.go b/tests/integration/identity_evidence_test.gonew file mode 100644index 00000000..60a5e188--- /dev/null+++ b/tests/integration/identity_evidence_test.go@@ -0,0 +1,149 @@+// 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 integration_test++import (+ "context"+ "io"+ "net"+ "net/http"+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/google/sam/api"+ "google.golang.org/protobuf/encoding/protojson"+ "google.golang.org/protobuf/proto"+)++// TestIdentityEvidenceOperatorFlow exercises the same owner-side sequence as+// an external receipt verifier: trust the local Unix socket, identify this+// node, connect to an exact peer, and collect fresh independently verifiable+// peer evidence before any provider request.+func TestIdentityEvidenceOperatorFlow(t *testing.T) {+ nodeBin := buildBinary(t, "./cmd/sam-node")+ _, controlPlaneURL := startMockRouter(t)++ ownerHome := t.TempDir()+ providerHome := t.TempDir()+ socketDir, err := os.MkdirTemp("", "sam-evidence-")+ if err != nil {+ t.Fatalf("create short socket directory: %v", err)+ }+ t.Cleanup(func() { _ = os.RemoveAll(socketDir) })+ ownerSocket := filepath.Join(socketDir, "owner.sock")++ _ = startBackgroundNode(t, nodeBin, controlPlaneURL, ownerHome,+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",+ "--listen", "/ip4/127.0.0.1/tcp/0",+ "--discovery-interval", "100ms",+ "--socket-path", ownerSocket,+ )+ _ = startBackgroundNode(t, nodeBin, controlPlaneURL, providerHome,+ "--listen", "/ip4/127.0.0.1/udp/0/quic-v1",+ "--listen", "/ip4/127.0.0.1/tcp/0",+ "--discovery-interval", "100ms",+ )++ ownerAPI := waitForMCPAddr(t, filepath.Join(ownerHome, "node.log"))+ providerAPI := waitForMCPAddr(t, filepath.Join(providerHome, "node.log"))+ waitForAPI(t, ownerAPI)+ waitForAPI(t, providerAPI)++ providerAddr := waitForPeerInfoInLog(t, filepath.Join(providerHome, "node.log"))+ providerPeerID := getPeerIDFromAddr(providerAddr)+ if providerPeerID == "" {+ t.Fatalf("provider address %q has no PeerID", providerAddr)+ }+ callMCP(t, ownerAPI, "connect_peer", map[string]any{"peer_addr": providerAddr})++ client := identityEvidenceSocketClient(ownerSocket)+ waitForIdentityEvidenceSocket(t, client)++ var local api.IdentityEvidenceResponse+ getIdentityEvidenceJSON(t, client, "/sam/identity", &local)+ if local.PeerId == "" || len(local.Biscuit) == 0 || len(local.TrustedControlPlaneKeys) == 0 {+ t.Fatalf("local identity evidence is incomplete: peer=%q biscuit=%d keys=%d", local.PeerId, len(local.Biscuit), len(local.TrustedControlPlaneKeys))+ }+ if local.ControlPlaneUrl != controlPlaneURL {+ t.Fatalf("control plane URL = %q, want %q", local.ControlPlaneUrl, controlPlaneURL)+ }++ var remote api.PeerEvidenceResponse+ getIdentityEvidenceJSON(t, client, "/sam/peer/"+url.PathEscape(providerPeerID.String())+"/evidence", &remote)+ if remote.PeerId != providerPeerID.String() || len(remote.Biscuit) == 0 || len(remote.VerifyingKey) == 0 {+ t.Fatalf("remote handshake evidence is incomplete: peer=%q biscuit=%d key=%d", remote.PeerId, len(remote.Biscuit), len(remote.VerifyingKey))+ }+}++func identityEvidenceSocketClient(socketPath string) *http.Client {+ return &http.Client{+ Transport: &http.Transport{+ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {+ return (&net.Dialer{}).DialContext(ctx, "unix", socketPath)+ },+ },+ CheckRedirect: func(_ *http.Request, _ []*http.Request) error {+ return http.ErrUseLastResponse+ },+ Timeout: 5 * time.Second,+ }+}++func waitForIdentityEvidenceSocket(t *testing.T, client *http.Client) {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ resp, err := client.Get("http://localhost/healthz")+ if err == nil {+ _ = resp.Body.Close()+ if resp.StatusCode == http.StatusOK {+ return+ }+ }+ time.Sleep(50 * time.Millisecond)+ }+ t.Fatal("timeout waiting for owner Unix socket")+}++func getIdentityEvidenceJSON(t *testing.T, client *http.Client, path string, target proto.Message) {+ t.Helper()+ request, err := http.NewRequest(http.MethodGet, "http://localhost"+path, nil)+ if err != nil {+ t.Fatalf("build evidence request: %v", err)+ }+ resp, err := client.Do(request)+ if err != nil {+ t.Fatalf("GET %s over owner socket: %v", path, err)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusOK {+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))+ t.Fatalf("GET %s status = %d, body = %q", path, resp.StatusCode, body)+ }+ if !strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") || resp.Header.Get("Cache-Control") != "no-store" {+ t.Fatalf("GET %s returned unsafe response headers: %v", path, resp.Header)+ }+ body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))+ if err != nil {+ t.Fatalf("read response from %s: %v", path, err)+ }+ if err := protojson.Unmarshal(body, target); err != nil {+ t.Fatalf("decode closed response from %s: %v", path, err)+ }+}