Skip to content

Agent Mesh

Implement zero-config binary role enrollment validation and enforcement

Antonio Ojeaeddfc71e4f77
diff --git a/.github/k8s/sam-box-canary-template.yaml b/.github/k8s/sam-box-canary-template.yaml
index 29885943..72187570 100644
--- a/.github/k8s/sam-box-canary-template.yaml
+++ b/.github/k8s/sam-box-canary-template.yaml
@@ -16,6 +16,12 @@ data:
kind: Bearer
value: real-upstream-secret-123
---
+apiVersion: v1
+kind: ServiceAccount
+metadata:
+ name: sam-box-sa
+ namespace: sam-canary-${ENV_NAME}
+---
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -31,7 +37,7 @@ spec:
labels:
app: box-canary-${ENV_NAME}
spec:
- serviceAccountName: sam-node-sa
+ serviceAccountName: sam-box-sa
initContainers:
- name: init-nano-init
image: ghcr.io/google/sam-nano-init:${IMAGE_TAG}
diff --git a/.github/k8s/sam-control-plane-template.yaml b/.github/k8s/sam-control-plane-template.yaml
index b8a6c8f2..cce2db6b 100644
--- a/.github/k8s/sam-control-plane-template.yaml
+++ b/.github/k8s/sam-control-plane-template.yaml
@@ -153,6 +153,8 @@ data:
bindings:
- members: ["user:system:serviceaccount:sam-canary-${ENV_NAME}:sam-node-sa"]
role: "sam-canary"
+ - members: ["user:system:serviceaccount:sam-canary-${ENV_NAME}:sam-box-sa"]
+ role: "sam:role:sambox"
- members: ["group:routers", "user:system:serviceaccount:${NAMESPACE}:sam-router-sa"]
role: "sam:role:router"
- members: ["sam:system:authenticated"]
@@ -163,6 +165,11 @@ data:
- "*"
allowed_targets:
- "*"
+ "sam:role:sambox":
+ allowed_services:
+ - "*"
+ allowed_targets:
+ - "*"
"sam:role:router":
allowed_services:
- "*"
diff --git a/api/datalog.go b/api/datalog.go
index 1f422de3..47322f78 100644
--- a/api/datalog.go
+++ b/api/datalog.go
@@ -94,6 +94,7 @@ const (
// Standard role values
RoleRouter = "sam:role:router"
RoleNode = "sam:role:node"
+ RoleSamBox = "sam:role:sambox"
// FactUser defines the subject (username/userID) claim extracted from the OIDC token.
// Contains: biscuit.String(username)
diff --git a/api/sam.pb.go b/api/sam.pb.go
index 6cad9686..e6577797 100644
--- a/api/sam.pb.go
+++ b/api/sam.pb.go
@@ -375,6 +375,7 @@ type EnrollRequest struct {
Jwt string `protobuf:"bytes,1,opt,name=jwt,proto3" json:"jwt,omitempty"`
PeerId string `protobuf:"bytes,2,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`
PublicKey []byte `protobuf:"bytes,3,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"`
+ RequestedRole string `protobuf:"bytes,4,opt,name=requested_role,json=requestedRole,proto3" json:"requested_role,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -430,6 +431,13 @@ func (x *EnrollRequest) GetPublicKey() []byte {
return nil
}
+func (x *EnrollRequest) GetRequestedRole() string {
+ if x != nil {
+ return x.RequestedRole
+ }
+ return ""
+}
+
type EnrollResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
BiscuitToken []byte `protobuf:"bytes,1,opt,name=biscuit_token,json=biscuitToken,proto3" json:"biscuit_token,omitempty"`
@@ -506,18 +514,63 @@ func (x *EnrollResponse) GetExpiration() int64 {
return 0
}
+type EnrollmentStatusRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ PeerId string `protobuf:"bytes,1,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *EnrollmentStatusRequest) Reset() {
+ *x = EnrollmentStatusRequest{}
+ mi := &file_api_sam_proto_msgTypes[5]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *EnrollmentStatusRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*EnrollmentStatusRequest) ProtoMessage() {}
+
+func (x *EnrollmentStatusRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[5]
+ 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 EnrollmentStatusRequest.ProtoReflect.Descriptor instead.
+func (*EnrollmentStatusRequest) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{5}
+}
+
+func (x *EnrollmentStatusRequest) GetPeerId() string {
+ if x != nil {
+ return x.PeerId
+ }
+ return ""
+}
+
type BootstrapEnrollRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
BootstrapToken string `protobuf:"bytes,1,opt,name=bootstrap_token,json=bootstrapToken,proto3" json:"bootstrap_token,omitempty"`
PeerId string `protobuf:"bytes,2,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`
PublicKey []byte `protobuf:"bytes,3,opt,name=public_key,json=publicKey,proto3" json:"public_key,omitempty"`
+ RequestedRole string `protobuf:"bytes,4,opt,name=requested_role,json=requestedRole,proto3" json:"requested_role,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *BootstrapEnrollRequest) Reset() {
*x = BootstrapEnrollRequest{}
- mi := &file_api_sam_proto_msgTypes[5]
+ mi := &file_api_sam_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -529,7 +582,7 @@ func (x *BootstrapEnrollRequest) String() string {
func (*BootstrapEnrollRequest) ProtoMessage() {}
func (x *BootstrapEnrollRequest) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[5]
+ mi := &file_api_sam_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -542,7 +595,7 @@ func (x *BootstrapEnrollRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use BootstrapEnrollRequest.ProtoReflect.Descriptor instead.
func (*BootstrapEnrollRequest) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{5}
+ return file_api_sam_proto_rawDescGZIP(), []int{6}
}
func (x *BootstrapEnrollRequest) GetBootstrapToken() string {
@@ -566,6 +619,13 @@ func (x *BootstrapEnrollRequest) GetPublicKey() []byte {
return nil
}
+func (x *BootstrapEnrollRequest) GetRequestedRole() string {
+ if x != nil {
+ return x.RequestedRole
+ }
+ return ""
+}
+
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"`
@@ -581,7 +641,7 @@ type BootstrapEnrollResponse struct {
func (x *BootstrapEnrollResponse) Reset() {
*x = BootstrapEnrollResponse{}
- mi := &file_api_sam_proto_msgTypes[6]
+ mi := &file_api_sam_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -593,7 +653,7 @@ func (x *BootstrapEnrollResponse) String() string {
func (*BootstrapEnrollResponse) ProtoMessage() {}
func (x *BootstrapEnrollResponse) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[6]
+ mi := &file_api_sam_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -606,7 +666,7 @@ func (x *BootstrapEnrollResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use BootstrapEnrollResponse.ProtoReflect.Descriptor instead.
func (*BootstrapEnrollResponse) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{6}
+ return file_api_sam_proto_rawDescGZIP(), []int{7}
}
func (x *BootstrapEnrollResponse) GetStatus() EnrollmentStatus {
@@ -658,50 +718,6 @@ func (x *BootstrapEnrollResponse) GetExpiration() int64 {
return 0
}
-type EnrollmentStatusRequest struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- PeerId string `protobuf:"bytes,1,opt,name=peer_id,json=peerId,proto3" json:"peer_id,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
-}
-
-func (x *EnrollmentStatusRequest) Reset() {
- *x = EnrollmentStatusRequest{}
- mi := &file_api_sam_proto_msgTypes[7]
- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
- ms.StoreMessageInfo(mi)
-}
-
-func (x *EnrollmentStatusRequest) String() string {
- return protoimpl.X.MessageStringOf(x)
-}
-
-func (*EnrollmentStatusRequest) ProtoMessage() {}
-
-func (x *EnrollmentStatusRequest) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[7]
- 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 EnrollmentStatusRequest.ProtoReflect.Descriptor instead.
-func (*EnrollmentStatusRequest) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{7}
-}
-
-func (x *EnrollmentStatusRequest) GetPeerId() string {
- if x != nil {
- return x.PeerId
- }
- return ""
-}
-
type ServiceInfo struct {
state protoimpl.MessageState `protogen:"open.v1"`
Type ServiceType `protobuf:"varint,1,opt,name=type,proto3,enum=sam.v1.ServiceType" json:"type,omitempty"`
@@ -1609,12 +1625,13 @@ const file_api_sam_proto_rawDesc = "" +
"\x04Type\x12\n" +
"\n" +
"\x06BANNED\x10\x00\x12\x10\n" +
- "\fKEY_ROTATION\x10\x01\"Y\n" +
+ "\fKEY_ROTATION\x10\x01\"\x80\x01\n" +
"\rEnrollRequest\x12\x10\n" +
"\x03jwt\x18\x01 \x01(\tR\x03jwt\x12\x17\n" +
"\apeer_id\x18\x02 \x01(\tR\x06peerId\x12\x1d\n" +
"\n" +
- "public_key\x18\x03 \x01(\fR\tpublicKey\"\xc5\x01\n" +
+ "public_key\x18\x03 \x01(\fR\tpublicKey\x12%\n" +
+ "\x0erequested_role\x18\x04 \x01(\tR\rrequestedRole\"\xc5\x01\n" +
"\x0eEnrollResponse\x12#\n" +
"\rbiscuit_token\x18\x01 \x01(\fR\fbiscuitToken\x12#\n" +
"\rerror_message\x18\x02 \x01(\tR\ferrorMessage\x12$\n" +
@@ -1622,12 +1639,15 @@ const file_api_sam_proto_rawDesc = "" +
"\rhub_addresses\x18\x04 \x03(\tR\fhubAddresses\x12\x1e\n" +
"\n" +
"expiration\x18\x05 \x01(\x03R\n" +
- "expiration\"y\n" +
+ "expiration\"2\n" +
+ "\x17EnrollmentStatusRequest\x12\x17\n" +
+ "\apeer_id\x18\x01 \x01(\tR\x06peerId\"\xa0\x01\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\"\xb4\x02\n" +
+ "public_key\x18\x03 \x01(\fR\tpublicKey\x12%\n" +
+ "\x0erequested_role\x18\x04 \x01(\tR\rrequestedRole\"\xb4\x02\n" +
"\x17BootstrapEnrollResponse\x120\n" +
"\x06status\x18\x01 \x01(\x0e2\x18.sam.v1.EnrollmentStatusR\x06status\x12#\n" +
"\rbiscuit_token\x18\x02 \x01(\fR\fbiscuitToken\x122\n" +
@@ -1637,9 +1657,7 @@ const file_api_sam_proto_rawDesc = "" +
"\rhub_addresses\x18\x06 \x03(\tR\fhubAddresses\x12\x1e\n" +
"\n" +
"expiration\x18\a \x01(\x03R\n" +
- "expiration\"2\n" +
- "\x17EnrollmentStatusRequest\x12\x17\n" +
- "\apeer_id\x18\x01 \x01(\tR\x06peerId\"l\n" +
+ "expiration\"l\n" +
"\vServiceInfo\x12'\n" +
"\x04type\x18\x01 \x01(\x0e2\x13.sam.v1.ServiceTypeR\x04type\x12\x12\n" +
"\x04name\x18\x02 \x01(\tR\x04name\x12 \n" +
@@ -1733,9 +1751,9 @@ var file_api_sam_proto_goTypes = []any{
(*MeshEvent)(nil), // 5: sam.v1.MeshEvent
(*EnrollRequest)(nil), // 6: sam.v1.EnrollRequest
(*EnrollResponse)(nil), // 7: sam.v1.EnrollResponse
- (*BootstrapEnrollRequest)(nil), // 8: sam.v1.BootstrapEnrollRequest
- (*BootstrapEnrollResponse)(nil), // 9: sam.v1.BootstrapEnrollResponse
- (*EnrollmentStatusRequest)(nil), // 10: sam.v1.EnrollmentStatusRequest
+ (*EnrollmentStatusRequest)(nil), // 8: sam.v1.EnrollmentStatusRequest
+ (*BootstrapEnrollRequest)(nil), // 9: sam.v1.BootstrapEnrollRequest
+ (*BootstrapEnrollResponse)(nil), // 10: sam.v1.BootstrapEnrollResponse
(*ServiceInfo)(nil), // 11: sam.v1.ServiceInfo
(*CommandBackend)(nil), // 12: sam.v1.CommandBackend
(*RegisterServiceRequest)(nil), // 13: sam.v1.RegisterServiceRequest
diff --git a/api/sam.proto b/api/sam.proto
index b1940a21..e5200af2 100644
--- a/api/sam.proto
+++ b/api/sam.proto
@@ -47,6 +47,7 @@ message EnrollRequest {
string jwt = 1;
string peer_id = 2;
bytes public_key = 3;
+ string requested_role = 4;
}
message EnrollResponse {
@@ -57,6 +58,10 @@ message EnrollResponse {
int64 expiration = 5;
}
+message EnrollmentStatusRequest {
+ string peer_id = 1;
+}
+
enum EnrollmentStatus {
ENROLLMENT_STATUS_UNSPECIFIED = 0;
ENROLLMENT_STATUS_PENDING = 1;
@@ -68,6 +73,7 @@ message BootstrapEnrollRequest {
string bootstrap_token = 1;
string peer_id = 2;
bytes public_key = 3;
+ string requested_role = 4;
}
message BootstrapEnrollResponse {
@@ -80,9 +86,7 @@ message BootstrapEnrollResponse {
int64 expiration = 7; // Populated only if APPROVED
}
-message EnrollmentStatusRequest {
- string peer_id = 1;
-}
+
enum ServiceType {
SERVICE_TYPE_UNSPECIFIED = 0;
diff --git a/cmd/sam-box/main.go b/cmd/sam-box/main.go
index 523c52e6..7e0f92df 100644
--- a/cmd/sam-box/main.go
+++ b/cmd/sam-box/main.go
@@ -219,6 +219,7 @@ func main() {
AutoRelayBootDelay: autoRelayBootDelayFlag,
AutoRelayBackoff: autoRelayBackoffFlag,
HubConnectTimeout: hubConnectTimeoutFlag,
+ RequiredRole: api.RoleSamBox,
})
if err != nil {
logger.Fatalf("Failed to initialize mesh node: %v", err)
@@ -272,6 +273,7 @@ func main() {
AutoRelayBootDelay: autoRelayBootDelayFlag,
AutoRelayBackoff: autoRelayBackoffFlag,
HubConnectTimeout: hubConnectTimeoutFlag,
+ RequiredRole: api.RoleSamBox,
})
if err != nil {
logger.Fatalf("Failed to initialize node for enrollment: %v", err)
@@ -447,6 +449,7 @@ func main() {
AutoRelayBootDelay: 0 * time.Second,
AutoRelayBackoff: 3 * time.Second,
HubConnectTimeout: hubConnectTimeoutFlag,
+ RequiredRole: api.RoleSamBox,
})
if err != nil {
logger.Fatalf("Failed to initialize node for enrollment: %v", err)
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index 1dd78e4b..7bb58369 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -227,6 +227,7 @@ func main() {
AutoRelayBootDelay: autoRelayBootDelayFlag,
AutoRelayBackoff: autoRelayBackoffFlag,
HubConnectTimeout: hubConnectTimeoutFlag,
+ RequiredRole: api.RoleNode,
DHTProviderAddrTTL: dhtProviderAddrTTLFlag,
DHTMaxRecordAge: dhtMaxRecordAgeFlag,
DHTLookupLimit: dhtLookupLimitFlag,
@@ -290,6 +291,7 @@ func main() {
AutoRelayBootDelay: autoRelayBootDelayFlag,
AutoRelayBackoff: autoRelayBackoffFlag,
HubConnectTimeout: hubConnectTimeoutFlag,
+ RequiredRole: api.RoleNode,
DHTProviderAddrTTL: dhtProviderAddrTTLFlag,
DHTMaxRecordAge: dhtMaxRecordAgeFlag,
DHTLookupLimit: dhtLookupLimitFlag,
@@ -350,6 +352,7 @@ func main() {
AutoRelayBootDelay: autoRelayBootDelayFlag,
AutoRelayBackoff: autoRelayBackoffFlag,
HubConnectTimeout: hubConnectTimeoutFlag,
+ RequiredRole: api.RoleNode,
})
if err != nil {
logger.Fatalf("Failed to initialize node after enrollment: %v", err)
@@ -508,6 +511,7 @@ func main() {
AutoRelayBootDelay: 0 * time.Second,
AutoRelayBackoff: 3 * time.Second,
HubConnectTimeout: hubConnectTimeoutFlag,
+ RequiredRole: api.RoleNode,
})
if err != nil {
logger.Fatalf("Failed to initialize node for enrollment: %v", err)
diff --git a/development/kind/10-control-plane.yaml b/development/kind/10-control-plane.yaml
index 1a849d2b..65533a42 100644
--- a/development/kind/10-control-plane.yaml
+++ b/development/kind/10-control-plane.yaml
@@ -139,6 +139,8 @@ data:
role: "sam-admin"
- members: ["user:system:serviceaccount:${NAMESPACE}:local-node-sa"]
role: "sam-admin"
+ - members: ["user:system:serviceaccount:${NAMESPACE}:sam-box-sa"]
+ role: "sam:role:sambox"
- members: ["group:routers", "user:system:serviceaccount:${NAMESPACE}:sam-router-sa"]
role: "sam:role:router"
roles:
@@ -147,6 +149,11 @@ data:
- "*"
allowed_targets:
- "*"
+ "sam:role:sambox":
+ allowed_services:
+ - "*"
+ allowed_targets:
+ - "*"
"sam:role:router":
allowed_services:
- "*"
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index 59b138c8..9628682a 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -344,26 +344,23 @@ func (s *Server) HandleRegister(w http.ResponseWriter, r *http.Request) {
return
}
+ if req.RequestedRole == "" {
+ http.Error(w, "requested_role must be specified", http.StatusBadRequest)
+ return
+ }
+
// Mint token
biscuitExpiry := time.Now().Add(api.BiscuitTokenTTL)
- biscuitData, resolvedRoles, err := identity.MintBiscuitToken(privKey, claims, token, pID, policy, biscuitExpiry)
+ biscuitData, _, err := identity.MintBiscuitToken(privKey, claims, token, pID, policy, biscuitExpiry, req.RequestedRole)
if err != nil {
logger.Errorw("Biscuit minting failed", "peer_id", req.PeerId, "error", err)
- http.Error(w, "Failed to mint biscuit: "+err.Error(), http.StatusInternalServerError)
+ http.Error(w, "Failed to mint biscuit: "+err.Error(), http.StatusForbidden)
return
}
// Session TTL is 90 days for OIDC interactive enrollment
sessionExpiresAt := time.Now().Add(api.OIDCSessionTTL)
-
- // Determine primary role from resolved roles
- primaryRole := api.RoleNode
- for _, r := range resolvedRoles {
- if strings.HasPrefix(r, "sam:role:") {
- primaryRole = r
- break
- }
- }
+ primaryRole := req.RequestedRole
claimsBytes, err := json.Marshal(claims)
if err != nil {
@@ -540,7 +537,7 @@ func (s *Server) HandleRefresh(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
- bBytes, _, err := identity.MintBiscuitToken(privKey, claims, nil, pID, policy, biscuitExpiry)
+ bBytes, _, err := identity.MintBiscuitToken(privKey, claims, nil, pID, policy, biscuitExpiry, nodeRecord.Role)
if err != nil {
logger.Errorf("Failed to mint refreshed token for node %s: %v", nodeRecord.PeerID, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
@@ -893,6 +890,17 @@ func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {
return
}
+ if req.RequestedRole == "" {
+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "requested_role must be specified")
+ return
+ }
+
+ if req.RequestedRole != tokenRecord.Role {
+ logger.Warnw("Requested role does not match bootstrap token role", "peer_id", req.PeerId, "requested", req.RequestedRole, "token_role", tokenRecord.Role)
+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, fmt.Sprintf("requested role %q does not match bootstrap token role %q", req.RequestedRole, tokenRecord.Role))
+ return
+ }
+
pID, err := peer.Decode(req.PeerId)
if err != nil {
http.Error(w, "Invalid Peer ID", http.StatusBadRequest)
diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.go
index 366d5ac7..81fb0a87 100644
--- a/internal/controlplane/server_test.go
+++ b/internal/controlplane/server_test.go
@@ -253,9 +253,10 @@ func TestNodeAndRouterRegistrationFlow(t *testing.T) {
nodePubKeyBytes, _ := crypto.MarshalPublicKey(privNode.GetPublic())
enrollNodeReq := &api.EnrollRequest{
- Jwt: nodeJWT,
- PeerId: nodePeer.String(),
- PublicKey: nodePubKeyBytes,
+ Jwt: nodeJWT,
+ PeerId: nodePeer.String(),
+ PublicKey: nodePubKeyBytes,
+ RequestedRole: api.RoleNode,
}
reqData, _ := proto.Marshal(enrollNodeReq)
@@ -295,9 +296,10 @@ func TestNodeAndRouterRegistrationFlow(t *testing.T) {
routerPubKeyBytes, _ := crypto.MarshalPublicKey(privRouter.GetPublic())
enrollRouterReq := &api.EnrollRequest{
- Jwt: routerJWT,
- PeerId: routerPeer.String(),
- PublicKey: routerPubKeyBytes,
+ Jwt: routerJWT,
+ PeerId: routerPeer.String(),
+ PublicKey: routerPubKeyBytes,
+ RequestedRole: api.RoleRouter,
}
reqData, _ = proto.Marshal(enrollRouterReq)
@@ -504,6 +506,7 @@ func TestEnrollmentWorkflow(t *testing.T) {
BootstrapToken: tokenDetails.Token,
PeerId: pID.String(),
PublicKey: pubBytes,
+ RequestedRole: api.RoleRouter,
}
enrollReqData, _ := proto.Marshal(enrollReq)
@@ -631,6 +634,7 @@ func TestEnrollmentWorkflow(t *testing.T) {
BootstrapToken: tokenDetails.Token, // use remaining usage
PeerId: pID2.String(),
PublicKey: pubBytes2,
+ RequestedRole: api.RoleRouter,
}
enrollReqData2, _ := proto.Marshal(enrollReq2)
@@ -690,9 +694,10 @@ func TestTokenRefreshAndRevocation(t *testing.T) {
nodePubKeyBytes, _ := crypto.MarshalPublicKey(pubNode)
enrollNodeReq := &api.EnrollRequest{
- Jwt: nodeJWT,
- PeerId: nodePeer.String(),
- PublicKey: nodePubKeyBytes,
+ Jwt: nodeJWT,
+ PeerId: nodePeer.String(),
+ PublicKey: nodePubKeyBytes,
+ RequestedRole: api.RoleNode,
}
reqData, _ := proto.Marshal(enrollNodeReq)
@@ -827,9 +832,10 @@ func TestNodeProactiveTokenRefresh(t *testing.T) {
// Enroll via registration endpoint
nodePubKeyBytes, _ := crypto.MarshalPublicKey(pubNode)
enrollNodeReq := &api.EnrollRequest{
- Jwt: nodeJWT,
- PeerId: nodePeer.String(),
- PublicKey: nodePubKeyBytes,
+ Jwt: nodeJWT,
+ PeerId: nodePeer.String(),
+ PublicKey: nodePubKeyBytes,
+ RequestedRole: api.RoleNode,
}
reqData, _ := proto.Marshal(enrollNodeReq)
diff --git a/internal/identity/biscuit.go b/internal/identity/biscuit.go
index 3e7078dd..aaadf9d6 100644
--- a/internal/identity/biscuit.go
+++ b/internal/identity/biscuit.go
@@ -31,17 +31,37 @@ import (
"github.com/libp2p/go-libp2p/core/peer"
)
-// // MintBiscuitToken generates a signed Biscuit token for a peer with policy rules based on JWT claims.
-func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token *oidc.IDToken, remotePeer peer.ID, policy *api.PolicyConfig, biscuitExpiry time.Time) ([]byte, []string, error) {
+// MintBiscuitToken generates a signed Biscuit token for a peer with policy rules based on JWT claims.
+//
+// Role Authorization Rationale:
+// The system has two distinct kinds of roles:
+// 1. Capability Roles (prefixed with "sam:role:"): These authorize the client's binary startup role
+// (e.g., sam:role:node, sam:role:router, sam:role:sambox) under Zero Trust.
+// 2. Custom Access Roles (all other roles): These define authorization permissions for custom
+// services and targets (e.g., restricted-role).
+//
+// When enrolling:
+// - The client binary must explicitly request a single capability role (requestedRole).
+// - We verify if the client's OIDC identity is authorized to claim that requested capability role:
+// - If the user has explicitly mapped capability roles (from policy/claims), they must only request one of those.
+// - If the user has no capability roles mapped, they are allowed to request the standard fallback role ("sam:role:node").
+// - Once authorized, the generated Biscuit is minted with:
+// - The requested capability role (enforcing least privilege).
+// - All other custom access roles mapped to the identity (so they preserve their resource permissions).
+func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token *oidc.IDToken, remotePeer peer.ID, policy *api.PolicyConfig, biscuitExpiry time.Time, requestedRole string) ([]byte, []string, error) {
if claims == nil {
return nil, nil, fmt.Errorf("claims cannot be nil")
}
+ if requestedRole == "" {
+ return nil, nil, fmt.Errorf("requested_role must be specified")
+ }
oidcRoles := toStringSlice(claims["roles"])
oidcGroups := toStringSlice(claims["groups"])
oidcSub, _ := claims["sub"].(string)
oidcEmail, _ := claims["email"].(string)
+ // Resolve all roles assigned to this identity by policy bindings or direct OIDC roles.
resolvedRoles := make(map[string]bool)
if policy != nil {
for _, b := range policy.Bindings {
@@ -55,8 +75,7 @@ func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token
if len(parts) != 2 {
continue
}
- prefix := parts[0]
- value := parts[1]
+ prefix, value := parts[0], parts[1]
switch prefix {
case api.FactGroup:
@@ -88,29 +107,40 @@ func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token
}
}
- roles := make([]string, 0, len(resolvedRoles))
- for role := range resolvedRoles {
- roles = append(roles, role)
- }
+ // Categorize resolved roles into Capability roles (sam:role:*) and Custom Access roles.
+ var hasCapabilityRoles bool
+ var customAccessRoles []string
- // Ensure all tokens have a defined sam:role. If no custom role is resolved,
- // assign the default node role: sam:role:node.
- hasSamRole := false
- for _, r := range roles {
+ for r := range resolvedRoles {
if strings.HasPrefix(r, "sam:role:") {
- hasSamRole = true
- break
+ hasCapabilityRoles = true
+ } else {
+ customAccessRoles = append(customAccessRoles, r)
}
}
- if !hasSamRole {
- roles = append(roles, api.RoleNode)
+
+ // Verify that the requested capability role is authorized.
+ isAuthorized := false
+ if resolvedRoles[requestedRole] {
+ isAuthorized = true
+ } else if requestedRole == api.RoleNode && !hasCapabilityRoles {
+ // Default fallback capability if no capability roles are explicitly assigned.
+ isAuthorized = true
+ }
+
+ if !isAuthorized {
+ return nil, nil, fmt.Errorf("requested role %q is not authorized for this identity", requestedRole)
}
- biscuitBytes, err := mintBiscuit(signingKey, remotePeer, roles, biscuitExpiry, policy, claims)
+ // Assemble final roles: the single requested capability role + all custom access roles.
+ finalRoles := []string{requestedRole}
+ finalRoles = append(finalRoles, customAccessRoles...)
+
+ biscuitBytes, err := mintBiscuit(signingKey, remotePeer, finalRoles, biscuitExpiry, policy, claims)
if err != nil {
return nil, nil, err
}
- return biscuitBytes, roles, nil
+ return biscuitBytes, finalRoles, nil
}
func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []string, expiration time.Time, policy *api.PolicyConfig, claims jwt.MapClaims) ([]byte, error) {
@@ -531,3 +561,31 @@ func VerifyAndExtractPeerID(trustedPublicKeys []ed25519.PublicKey, biscuitData [
return pID, nil
}
+
+// VerifyBiscuitRole checks that the biscuit is signed by the hub's public key
+// and contains the specified role fact.
+func VerifyBiscuitRole(biscuitData []byte, hubPubKey ed25519.PublicKey, expectedRole string) error {
+ b, err := biscuit.Unmarshal(biscuitData)
+ if err != nil {
+ return fmt.Errorf("malformed biscuit: %w", err)
+ }
+
+ authorizer, err := b.Authorizer(hubPubKey)
+ if err != nil {
+ return fmt.Errorf("failed to create authorizer: %w", err)
+ }
+
+ authorizer.AddCheck(biscuit.Check{Queries: []biscuit.Rule{
+ {
+ Body: []biscuit.Predicate{
+ {Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(expectedRole)}},
+ },
+ },
+ }})
+ authorizer.AddPolicy(api.AllowIfTruePolicy)
+
+ if err := authorizer.Authorize(); err != nil {
+ return fmt.Errorf("biscuit lacks expected role %q: %w", expectedRole, err)
+ }
+ return nil
+}
diff --git a/internal/identity/biscuit_test.go b/internal/identity/biscuit_test.go
index 36255c31..1bf9c05f 100644
--- a/internal/identity/biscuit_test.go
+++ b/internal/identity/biscuit_test.go
@@ -70,7 +70,7 @@ func TestMintBiscuitToken(t *testing.T) {
claims1 := jwt.MapClaims{
"roles": []any{"admin"},
}
- biscuitData1, _, err := MintBiscuitToken(priv, claims1, token, dummyPeer, policy, token.Expiry)
+ biscuitData1, _, err := MintBiscuitToken(priv, claims1, token, dummyPeer, policy, token.Expiry, "admin")
if err != nil {
t.Fatal(err)
}
@@ -104,7 +104,7 @@ func TestMintBiscuitToken(t *testing.T) {
claims2 := jwt.MapClaims{
"groups": []any{"system:serviceaccounts:sam-canary"},
}
- biscuitData2, _, err := MintBiscuitToken(priv, claims2, token, dummyPeer, policy, token.Expiry)
+ biscuitData2, _, err := MintBiscuitToken(priv, claims2, token, dummyPeer, policy, token.Expiry, "canary-role")
if err != nil {
t.Fatal(err)
}
@@ -135,7 +135,7 @@ func TestMintBiscuitToken(t *testing.T) {
"groups": []any{"unknown-group"},
"roles": []any{"undefined-role"},
}
- biscuitData3, _, err := MintBiscuitToken(priv, claims3, token, dummyPeer, policy, token.Expiry)
+ biscuitData3, _, err := MintBiscuitToken(priv, claims3, token, dummyPeer, policy, token.Expiry, api.RoleNode)
if err != nil {
t.Fatal(err)
}
@@ -164,7 +164,7 @@ func TestMintBiscuitToken(t *testing.T) {
claims4 := jwt.MapClaims{
"sub": "system:serviceaccount:sam-canary:sam-node-sa",
}
- biscuitData4, _, err := MintBiscuitToken(priv, claims4, token, dummyPeer, policy, token.Expiry)
+ biscuitData4, _, err := MintBiscuitToken(priv, claims4, token, dummyPeer, policy, token.Expiry, "canary-role")
if err != nil {
t.Fatal(err)
}
@@ -231,7 +231,7 @@ func TestVerifyBiscuit_Expiration(t *testing.T) {
"roles": []any{"admin"},
}
- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, &api.PolicyConfig{}, token.Expiry)
+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, &api.PolicyConfig{}, token.Expiry, api.RoleNode)
if err != nil {
t.Fatalf("MintBiscuitToken failed: %v", err)
}
@@ -283,7 +283,7 @@ func TestMintBiscuitToken_ClaimsTranslation(t *testing.T) {
"groups": []any{"beta-testers", "engineering"},
}
- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, policy, token.Expiry)
+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, policy, token.Expiry, "developer-role")
if err != nil {
t.Fatalf("Failed to mint biscuit: %v", err)
}
@@ -426,22 +426,27 @@ func TestMintBiscuitToken_VariousClaimsTypes(t *testing.T) {
claims["groups"] = tt.groupsClaim
}
- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, policy, token.Expiry)
- if err != nil {
- t.Fatalf("MintBiscuitToken failed: %v", err)
+ rolesToTest := tt.expectedRoles
+ if len(rolesToTest) == 0 {
+ rolesToTest = []string{api.RoleNode}
}
- b, err := biscuit.Unmarshal(biscuitData)
- if err != nil {
- t.Fatalf("Unmarshal biscuit failed: %v", err)
- }
+ for _, r := range rolesToTest {
+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, policy, token.Expiry, r)
+ if err != nil {
+ t.Fatalf("MintBiscuitToken failed for role %s: %v", r, err)
+ }
- authorizer, err := b.Authorizer(pub, biscuit.WithWorldOptions(datalog.WithMaxDuration(500*time.Millisecond)))
- if err != nil {
- t.Fatalf("Authorizer failed: %v", err)
- }
+ b, err := biscuit.Unmarshal(biscuitData)
+ if err != nil {
+ t.Fatalf("Unmarshal biscuit failed: %v", err)
+ }
+
+ authorizer, err := b.Authorizer(pub, biscuit.WithWorldOptions(datalog.WithMaxDuration(500*time.Millisecond)))
+ if err != nil {
+ t.Fatalf("Authorizer failed: %v", err)
+ }
- for _, r := range tt.expectedRoles {
authorizer.AddCheck(biscuit.Check{Queries: []biscuit.Rule{
{
Body: []biscuit.Predicate{
@@ -449,27 +454,27 @@ func TestMintBiscuitToken_VariousClaimsTypes(t *testing.T) {
},
},
}})
- }
- for _, g := range tt.expectedGroups {
- authorizer.AddCheck(biscuit.Check{Queries: []biscuit.Rule{
- {
- Body: []biscuit.Predicate{
- {Name: "group", IDs: []biscuit.Term{biscuit.String(g)}},
+ for _, g := range tt.expectedGroups {
+ authorizer.AddCheck(biscuit.Check{Queries: []biscuit.Rule{
+ {
+ Body: []biscuit.Predicate{
+ {Name: "group", IDs: []biscuit.Term{biscuit.String(g)}},
+ },
},
- },
- }})
- }
+ }})
+ }
- authorizer.AddPolicy(biscuit.Policy{Queries: []biscuit.Rule{
- {
- Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},
- Body: []biscuit.Predicate{},
- },
- }, Kind: biscuit.PolicyKindAllow})
+ authorizer.AddPolicy(biscuit.Policy{Queries: []biscuit.Rule{
+ {
+ Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},
+ Body: []biscuit.Predicate{},
+ },
+ }, Kind: biscuit.PolicyKindAllow})
- if err := authorizer.Authorize(); err != nil {
- t.Errorf("Verification failed for case: %v\nWorld:\n%s", err, authorizer.PrintWorld())
+ if err := authorizer.Authorize(); err != nil {
+ t.Errorf("Verification failed for case %s, role %s: %v\nWorld:\n%s", tt.name, r, err, authorizer.PrintWorld())
+ }
}
})
}
@@ -498,7 +503,7 @@ func TestVerifyBiscuit_Concurrent(t *testing.T) {
"roles": []any{"admin"},
}
- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, &api.PolicyConfig{}, token.Expiry)
+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, &api.PolicyConfig{}, token.Expiry, api.RoleNode)
if err != nil {
t.Fatalf("MintBiscuitToken failed: %v", err)
}
@@ -556,7 +561,7 @@ func TestMintBiscuitToken_ErrorAggregation(t *testing.T) {
"roles": []any{"admin"},
}
- _, _, err = MintBiscuitToken(priv, claims, token, dummyPeer, policy, token.Expiry)
+ _, _, err = MintBiscuitToken(priv, claims, token, dummyPeer, policy, token.Expiry, "admin")
if err == nil {
t.Fatal("Expected MintBiscuitToken to fail on custom datalog syntax errors, got nil error")
}
@@ -608,7 +613,7 @@ func TestMintBiscuitToken_FactDeduplication(t *testing.T) {
"sub": "user-1",
}
- biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, policy, token.Expiry)
+ biscuitData, _, err := MintBiscuitToken(priv, claims, token, dummyPeer, policy, token.Expiry, "role-a")
if err != nil {
t.Fatalf("MintBiscuitToken failed with duplicate facts: %v", err)
}
@@ -723,3 +728,77 @@ func TestMintBootstrapBiscuitToken(t *testing.T) {
t.Errorf("Expected custom node role service checks to succeed: %v", err)
}
}
+
+func TestMintBiscuitToken_RoleAuthorizationValidation(t *testing.T) {
+ _, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ privNode, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dummyPeer, _ := peer.IDFromPrivateKey(privNode)
+
+ token := &oidc.IDToken{
+ Expiry: time.Now().Add(1 * time.Hour),
+ }
+
+ // Policy defining bindings for custom capability roles
+ policy := &api.PolicyConfig{
+ Bindings: []api.Binding{
+ {Role: "sam:role:sambox", Members: []string{"user:sambox-user"}},
+ {Role: "custom-access-role", Members: []string{"user:sambox-user"}},
+ },
+ Roles: map[string]api.RolePolicy{
+ "sam:role:sambox": {},
+ "custom-access-role": {},
+ },
+ }
+
+ // 1. User has no mapped capability roles.
+ // Can request default "sam:role:node", but not "sam:role:router".
+ claimsUnmapped := jwt.MapClaims{"sub": "unmapped-user"}
+ _, _, err = MintBiscuitToken(priv, claimsUnmapped, token, dummyPeer, policy, token.Expiry, api.RoleNode)
+ if err != nil {
+ t.Errorf("expected unmapped user allowed to request default role %q, got: %v", api.RoleNode, err)
+ }
+ _, _, err = MintBiscuitToken(priv, claimsUnmapped, token, dummyPeer, policy, token.Expiry, api.RoleRouter)
+ if err == nil {
+ t.Errorf("expected unmapped user NOT allowed to request unauthorized role %q", api.RoleRouter)
+ }
+
+ // 2. User has mapped capability role "sam:role:sambox" and custom access role "custom-access-role".
+ // Can request "sam:role:sambox", but cannot request default "sam:role:node" or "sam:role:router".
+ claimsMapped := jwt.MapClaims{"sub": "sambox-user"}
+ _, finalRoles, err := MintBiscuitToken(priv, claimsMapped, token, dummyPeer, policy, token.Expiry, api.RoleSamBox)
+ if err != nil {
+ t.Errorf("expected mapped user allowed to request authorized role %q, got: %v", api.RoleSamBox, err)
+ }
+ // Check that custom access role is also preserved in final roles
+ hasCustomRole := false
+ for _, r := range finalRoles {
+ if r == "custom-access-role" {
+ hasCustomRole = true
+ }
+ }
+ if !hasCustomRole {
+ t.Errorf("expected custom access role to be preserved in final roles, got: %v", finalRoles)
+ }
+
+ _, _, err = MintBiscuitToken(priv, claimsMapped, token, dummyPeer, policy, token.Expiry, api.RoleNode)
+ if err == nil {
+ t.Errorf("expected mapped user NOT allowed to bypass map by requesting default role %q", api.RoleNode)
+ }
+ _, _, err = MintBiscuitToken(priv, claimsMapped, token, dummyPeer, policy, token.Expiry, api.RoleRouter)
+ if err == nil {
+ t.Errorf("expected mapped user NOT allowed to request unauthorized role %q", api.RoleRouter)
+ }
+
+ // 3. Requested role cannot be empty
+ _, _, err = MintBiscuitToken(priv, claimsMapped, token, dummyPeer, policy, token.Expiry, "")
+ if err == nil {
+ t.Error("expected MintBiscuitToken to reject empty requested_role")
+ }
+}
diff --git a/internal/node/enroll.go b/internal/node/enroll.go
index 44d31a0f..1274d371 100644
--- a/internal/node/enroll.go
+++ b/internal/node/enroll.go
@@ -25,6 +25,7 @@ import (
"time"
"github.com/google/sam/api"
+ "github.com/google/sam/internal/identity"
golog "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/multiformats/go-multiaddr"
@@ -63,9 +64,10 @@ func (n *SamNode) Enroll(ctx context.Context, hubURL string, jwt string) error {
}
req := &api.EnrollRequest{
- Jwt: jwt,
- PeerId: n.Host.ID().String(),
- PublicKey: pubBytes,
+ Jwt: jwt,
+ PeerId: n.Host.ID().String(),
+ PublicKey: pubBytes,
+ RequestedRole: n.config.RequiredRole,
}
data, err := proto.Marshal(req)
if err != nil {
@@ -124,6 +126,12 @@ func (n *SamNode) Enroll(ctx context.Context, hubURL string, jwt string) error {
return fmt.Errorf("received invalid hub public key size: %d bytes (expected %d)", len(enrollResp.HubPublicKey), ed25519.PublicKeySize)
}
+ if n.config.RequiredRole != "" {
+ if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, ed25519.PublicKey(enrollResp.HubPublicKey), n.config.RequiredRole); err != nil {
+ return fmt.Errorf("enrolled biscuit token lacks required role %q: %w", n.config.RequiredRole, err)
+ }
+ }
+
if err := n.Store.SaveIdentity(enrollResp.BiscuitToken); err != nil {
return fmt.Errorf("failed to save identity: %v", err)
}
@@ -180,6 +188,7 @@ func (n *SamNode) EnrollBootstrap(ctx context.Context, hubURL string, bootstrapT
BootstrapToken: bootstrapToken,
PeerId: n.Host.ID().String(),
PublicKey: pubBytes,
+ RequestedRole: n.config.RequiredRole,
}
data, err := proto.Marshal(req)
if err != nil {
@@ -298,6 +307,10 @@ func (n *SamNode) EnrollBootstrap(ctx context.Context, hubURL string, bootstrapT
return fmt.Errorf("received invalid hub public key size: %d bytes", len(enrollResp.HubPublicKey))
}
+ if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, ed25519.PublicKey(enrollResp.HubPublicKey), n.config.RequiredRole); err != nil {
+ return fmt.Errorf("enrolled biscuit token lacks required role %q: %w", n.config.RequiredRole, err)
+ }
+
if err := n.Store.SaveIdentity(enrollResp.BiscuitToken); err != nil {
return fmt.Errorf("failed to save identity: %v", err)
}
diff --git a/internal/node/node.go b/internal/node/node.go
index f115d01c..7ecc0f74 100644
--- a/internal/node/node.go
+++ b/internal/node/node.go
@@ -265,6 +265,15 @@ func NewSamNode(cfg Options) (*SamNode, error) {
// Start initializes the libp2p host, DHT, connects to the hub, and starts runtime components.
func (n *SamNode) Start(ctx context.Context) error {
+ if biscuitBytes := n.GetIdentity(); len(biscuitBytes) > 0 {
+ hubPubKeyBytes, _, err := n.Store.LoadHubConfig()
+ if err == nil && len(hubPubKeyBytes) > 0 {
+ if err := identity.VerifyBiscuitRole(biscuitBytes, ed25519.PublicKey(hubPubKeyBytes), n.config.RequiredRole); err != nil {
+ return fmt.Errorf("loaded identity fails role requirement %q: %w", n.config.RequiredRole, err)
+ }
+ }
+ }
+
// Layer 2: Attach the Bouncer (Gater)
gater := &nodeConnGate{node: n}
diff --git a/internal/node/options.go b/internal/node/options.go
index 108eeb3d..40519148 100644
--- a/internal/node/options.go
+++ b/internal/node/options.go
@@ -19,6 +19,7 @@ import (
"fmt"
"time"
+ "github.com/google/sam/api"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/multiformats/go-multiaddr"
)
@@ -55,6 +56,8 @@ type Options struct {
DHTMaxRecordAge time.Duration
DHTLookupLimit int
DiscoveryConcurrency int
+ // RequiredRole restricts enrollment and startup to only accept tokens containing this role.
+ RequiredRole string
}
// Default applies default values to Options if they are not specified.
@@ -92,6 +95,9 @@ func (o *Options) Default() {
if len(o.ListenAddrs) == 0 {
o.ListenAddrs = []string{"/ip4/0.0.0.0/udp/5001/quic-v1", "/ip4/0.0.0.0/tcp/5002"}
}
+ if o.RequiredRole == "" {
+ o.RequiredRole = api.RoleNode
+ }
}
// Validate verifies that the required options are provided and valid.
@@ -102,5 +108,8 @@ func (o *Options) Validate() error {
if o.Store == nil {
return fmt.Errorf("store is required")
}
+ if o.RequiredRole == "" {
+ return fmt.Errorf("RequiredRole must be specified")
+ }
return nil
}
diff --git a/internal/node/static_service_test.go b/internal/node/static_service_test.go
index d45bc46f..d1c8cdfc 100644
--- a/internal/node/static_service_test.go
+++ b/internal/node/static_service_test.go
@@ -99,8 +99,32 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {
return
}
+ bBuilder := biscuit.NewBuilder(cpPriv)
+ _ = bBuilder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactNode,
+ IDs: []biscuit.Term{biscuit.String(req.PeerId)},
+ }})
+ _ = bBuilder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactRole,
+ IDs: []biscuit.Term{biscuit.String(api.RoleNode)},
+ }})
+ _ = bBuilder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactExpiration,
+ IDs: []biscuit.Term{biscuit.Date(time.Now().Add(24 * time.Hour))},
+ }})
+ bTok, err := bBuilder.Build()
+ if err != nil {
+ http.Error(w, "Failed to build biscuit", http.StatusInternalServerError)
+ return
+ }
+ biscuitBytes, err := bTok.Serialize()
+ if err != nil {
+ http.Error(w, "Failed to serialize biscuit", http.StatusInternalServerError)
+ return
+ }
+
resp := &api.EnrollResponse{
- BiscuitToken: []byte("mock-biscuit-token"),
+ BiscuitToken: biscuitBytes,
HubPublicKey: cpPub,
HubAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},
}
diff --git a/internal/router/config.go b/internal/router/config.go
index d3b21152..176e0a68 100644
--- a/internal/router/config.go
+++ b/internal/router/config.go
@@ -17,6 +17,8 @@ package router
import (
"fmt"
"time"
+
+ "github.com/google/sam/api"
)
// Options holds configuration details for the sam-router.
@@ -37,6 +39,8 @@ type Options struct {
LogVerbose bool
DHTProviderAddrTTL time.Duration
DHTMaxRecordAge time.Duration
+ // RequiredRole restricts enrollment and startup to only accept tokens containing this role.
+ RequiredRole string
}
// Default sets default values for options.
@@ -59,6 +63,9 @@ func (o *Options) Default() {
if o.BiscuitTimeout <= 0 {
o.BiscuitTimeout = 100 * time.Millisecond
}
+ if o.RequiredRole == "" {
+ o.RequiredRole = api.RoleRouter
+ }
}
// Validate ensures options are valid.
diff --git a/internal/router/router.go b/internal/router/router.go
index e2b7b3ba..68fb6e0f 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -288,9 +288,10 @@ func (r *Router) enroll(peerID peer.ID) error {
}
req := &api.EnrollRequest{
- Jwt: r.config.OIDCToken,
- PeerId: peerID.String(),
- PublicKey: pubBytes,
+ Jwt: r.config.OIDCToken,
+ PeerId: peerID.String(),
+ PublicKey: pubBytes,
+ RequestedRole: r.config.RequiredRole,
}
data, err := proto.Marshal(req)
if err != nil {
@@ -325,6 +326,10 @@ func (r *Router) enroll(peerID peer.ID) error {
r.trustedPublicKeys = []ed25519.PublicKey{enrollResp.HubPublicKey}
r.keysMu.Unlock()
+ if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, enrollResp.HubPublicKey, r.config.RequiredRole); err != nil {
+ return fmt.Errorf("enrolled biscuit token lacks required role %q: %w", r.config.RequiredRole, err)
+ }
+
return nil
}
@@ -339,6 +344,7 @@ func (r *Router) enrollBootstrap(peerID peer.ID) error {
BootstrapToken: r.config.BootstrapToken,
PeerId: peerID.String(),
PublicKey: pubBytes,
+ RequestedRole: r.config.RequiredRole,
}
data, err := proto.Marshal(req)
if err != nil {
@@ -442,6 +448,10 @@ func (r *Router) enrollBootstrap(peerID peer.ID) error {
r.trustedPublicKeys = []ed25519.PublicKey{enrollResp.HubPublicKey}
r.keysMu.Unlock()
+ if err := identity.VerifyBiscuitRole(enrollResp.BiscuitToken, enrollResp.HubPublicKey, r.config.RequiredRole); err != nil {
+ return fmt.Errorf("enrolled biscuit token lacks required role %q: %w", r.config.RequiredRole, err)
+ }
+
logger.Infof("Router bootstrap enrollment approved! Biscuit received.")
return nil
}
@@ -747,7 +757,7 @@ func (r *Router) performMutualAuth(s network.Stream) error {
return fmt.Errorf("failed to verify peer router biscuit: %w", err)
}
- // Enforce role("router"), role("router-role") or role("bootstrap") inside the biscuit
+ // Enforce required role inside the biscuit
authorizer, err := b.Authorizer(trustedKeys[0])
if err != nil {
return fmt.Errorf("authorizer instantiation failed: %w", err)
@@ -756,7 +766,7 @@ func (r *Router) performMutualAuth(s network.Stream) error {
authorizer.AddCheck(biscuit.Check{Queries: []biscuit.Rule{
{
Body: []biscuit.Predicate{
- {Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(api.RoleRouter)}},
+ {Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(r.config.RequiredRole)}},
},
},
}})
diff --git a/internal/router/router_test.go b/internal/router/router_test.go
index 125475a2..a73389bd 100644
--- a/internal/router/router_test.go
+++ b/internal/router/router_test.go
@@ -229,9 +229,10 @@ func TestRouterIntegration(t *testing.T) {
t.Fatal(err)
}
enrollNodeReq := &api.EnrollRequest{
- Jwt: nodeJWT,
- PeerId: nodePeerID.String(),
- PublicKey: nodePubKeyBytes,
+ Jwt: nodeJWT,
+ PeerId: nodePeerID.String(),
+ PublicKey: nodePubKeyBytes,
+ RequestedRole: api.RoleNode,
}
reqData, _ := proto.Marshal(enrollNodeReq)
resp, err := client.Post(cpURL+"/register", "application/x-protobuf", bytes.NewReader(reqData))
diff --git a/mobile/sam-node-ffi/ffi/ffi_test.go b/mobile/sam-node-ffi/ffi/ffi_test.go
index b760210e..f202b025 100644
--- a/mobile/sam-node-ffi/ffi/ffi_test.go
+++ b/mobile/sam-node-ffi/ffi/ffi_test.go
@@ -58,45 +58,7 @@ func TestMobileFFILifecycle(t *testing.T) {
println("--- MOCK HUB: received auth stream connection")
defer func() { _ = s.Close() }()
- // Mint a valid Biscuit token signed by CP key and bound to mock hub's Peer ID
- builder := biscuit.NewBuilder(cpPrivKey)
- if err := builder.AddAuthorityFact(biscuit.Fact{
- Predicate: biscuit.Predicate{
- Name: "node",
- IDs: []biscuit.Term{biscuit.String(hubHost.ID().String())},
- },
- }); err != nil {
- println("--- MOCK HUB: failed to add node fact:", err.Error())
- return
- }
- if err := builder.AddAuthorityFact(biscuit.Fact{
- Predicate: biscuit.Predicate{
- Name: api.FactRole,
- IDs: []biscuit.Term{biscuit.String(api.RoleRouter)},
- },
- }); err != nil {
- println("--- MOCK HUB: failed to add role fact:", err.Error())
- return
- }
- if err := builder.AddAuthorityFact(biscuit.Fact{
- Predicate: biscuit.Predicate{
- Name: api.FactExpiration,
- IDs: []biscuit.Term{biscuit.Date(time.Now().Add(time.Hour))},
- },
- }); err != nil {
- println("--- MOCK HUB: failed to add expiration fact:", err.Error())
- return
- }
- b, err := builder.Build()
- if err != nil {
- println("--- MOCK HUB: failed to build biscuit:", err.Error())
- return
- }
- biscuitBytes, err := b.Serialize()
- if err != nil {
- println("--- MOCK HUB: failed to serialize biscuit:", err.Error())
- return
- }
+ biscuitBytes := mintMockBiscuit(t, hubHost.ID().String(), cpPrivKey, api.RoleRouter)
resp := &api.AuthResponse{
Success: true,
@@ -117,8 +79,9 @@ func TestMobileFFILifecycle(t *testing.T) {
var req api.EnrollRequest
_ = proto.Unmarshal(body, &req)
+ biscuitBytes := mintMockBiscuit(t, req.PeerId, cpPrivKey, api.RoleNode)
resp := &api.EnrollResponse{
- BiscuitToken: []byte("mock-biscuit-token"),
+ BiscuitToken: biscuitBytes,
HubPublicKey: cpPubKey,
HubAddresses: []string{hubHost.Addrs()[0].String() + "/p2p/" + hubHost.ID().String()},
}
@@ -173,3 +136,40 @@ func TestMobileFFILifecycle(t *testing.T) {
t.Fatalf("StopNode failed: %v", err)
}
}
+
+func mintMockBiscuit(t *testing.T, peerID string, priv ed25519.PrivateKey, role string) []byte {
+ builder := biscuit.NewBuilder(priv)
+ if err := builder.AddAuthorityFact(biscuit.Fact{
+ Predicate: biscuit.Predicate{
+ Name: "node",
+ IDs: []biscuit.Term{biscuit.String(peerID)},
+ },
+ }); err != nil {
+ t.Fatalf("failed to add node fact: %v", err)
+ }
+ if err := builder.AddAuthorityFact(biscuit.Fact{
+ Predicate: biscuit.Predicate{
+ Name: api.FactRole,
+ IDs: []biscuit.Term{biscuit.String(role)},
+ },
+ }); err != nil {
+ t.Fatalf("failed to add role fact: %v", err)
+ }
+ if err := builder.AddAuthorityFact(biscuit.Fact{
+ Predicate: biscuit.Predicate{
+ Name: api.FactExpiration,
+ IDs: []biscuit.Term{biscuit.Date(time.Now().Add(time.Hour))},
+ },
+ }); err != nil {
+ t.Fatalf("failed to add expiration fact: %v", err)
+ }
+ b, err := builder.Build()
+ if err != nil {
+ t.Fatalf("failed to build biscuit: %v", err)
+ }
+ biscuitBytes, err := b.Serialize()
+ if err != nil {
+ t.Fatalf("failed to serialize biscuit: %v", err)
+ }
+ return biscuitBytes
+}
diff --git a/site/content/docs/user/control-plane-configuration.md b/site/content/docs/user/control-plane-configuration.md
index 042c0159..a4273533 100644
--- a/site/content/docs/user/control-plane-configuration.md
+++ b/site/content/docs/user/control-plane-configuration.md
@@ -96,6 +96,26 @@ bindings:
role: "developer-role"
```
+### 3.1 Binary Capability Roles (Zero Trust)
+To enforce the principle of least privilege, the Sovereign Agent Mesh implements binary-level capability authorization. Every binary connecting to the mesh must request its specific target role during enrollment:
+- `sam-node` requests `sam:role:node` (Default agent capability)
+- `sam-box` requests `sam:role:sambox` (Secure Gateway sidecar)
+- `sam-router` requests `sam:role:router` (P2P routing and relay service)
+
+The Hub control plane validates that the enrolling client is authorized for the requested role before issuing the Biscuit identity token:
+1. **Node Fallback**: By default, any successfully authenticated OIDC identity or generic bootstrap token can claim the `sam:role:node` role.
+2. **Explicit Bindings**: The higher-privilege capability roles `sam:role:router` and `sam:role:sambox` must be explicitly authorized to the user/service account by mapping the role name in `policies.yaml` bindings. For example:
+
+```yaml
+bindings:
+ - members: ["group:mesh-routers"]
+ role: "sam:role:router"
+ - members: ["user:gateway-pod-sa"]
+ role: "sam:role:sambox"
+```
+
+If a binary requests a capability role it is not authorized for, enrollment fails immediately. If a client attempts to start using a token that lacks its binary's required role, startup aborts.
+
---
## 4. Bootstrapping Example
diff --git a/tests/integration/fallback_test.go b/tests/integration/fallback_test.go
index 3a2cedbb..674b60bd 100644
--- a/tests/integration/fallback_test.go
+++ b/tests/integration/fallback_test.go
@@ -93,7 +93,7 @@ func TestSelfHealingHTTPFallback(t *testing.T) {
writer := msgio.NewVarintWriter(s)
resp := &api.AuthResponse{
Success: true,
- Biscuit: createMockBiscuitToken(t, newH.ID().String(), priv),
+ Biscuit: createMockBiscuitToken(t, newH.ID().String(), priv, api.RoleRouter),
}
respBytes, _ := proto.Marshal(resp)
_ = writer.WriteMsg(respBytes)
@@ -155,7 +155,7 @@ func TestSelfHealingHTTPFallback(t *testing.T) {
}
resp := &api.EnrollResponse{
- BiscuitToken: createMockBiscuitToken(t, enrollReq.PeerId, priv),
+ BiscuitToken: createMockBiscuitToken(t, enrollReq.PeerId, priv, api.RoleNode),
HubPublicKey: pub,
HubAddresses: []string{addr},
}
diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.go
index 48753146..1ebd9479 100644
--- a/tests/integration/minimal_helpers_test.go
+++ b/tests/integration/minimal_helpers_test.go
@@ -232,7 +232,7 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {
writer := msgio.NewVarintWriter(s)
resp := &api.AuthResponse{
Success: true,
- Biscuit: createMockBiscuitToken(t, h.ID().String(), priv),
+ Biscuit: createMockBiscuitToken(t, h.ID().String(), priv, api.RoleRouter),
}
respBytes, _ := proto.Marshal(resp)
_ = writer.WriteMsg(respBytes)
@@ -263,7 +263,7 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {
}
resp := &api.EnrollResponse{
- BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv),
+ BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv, api.RoleNode),
HubPublicKey: pub,
HubAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},
}
@@ -313,7 +313,7 @@ func startMockLibp2pHubWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, st
writer := msgio.NewVarintWriter(s)
resp := &api.AuthResponse{
Success: true,
- Biscuit: createMockBiscuitToken(t, h.ID().String(), priv),
+ Biscuit: createMockBiscuitToken(t, h.ID().String(), priv, api.RoleRouter),
}
respBytes, _ := proto.Marshal(resp)
_ = writer.WriteMsg(respBytes)
@@ -363,7 +363,7 @@ func startMockLibp2pHubWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, st
}
resp := &api.EnrollResponse{
- BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv),
+ BiscuitToken: createMockBiscuitToken(t, req.PeerId, priv, api.RoleNode),
HubPublicKey: pub,
HubAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},
}
@@ -388,7 +388,7 @@ func startMockLibp2pHubWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, st
return h.ID(), httpServer.URL
}
-func createMockBiscuitToken(t *testing.T, peerID string, priv ed25519.PrivateKey) []byte {
+func createMockBiscuitToken(t *testing.T, peerID string, priv ed25519.PrivateKey, role string) []byte {
builder := biscuit.NewBuilder(priv)
err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})
if err != nil {
@@ -403,9 +403,12 @@ func createMockBiscuitToken(t *testing.T, peerID string, priv ed25519.PrivateKey
t.Fatalf("failed to add FactExpiration fact: %v", err)
}
+ if role == "" {
+ role = api.RoleRouter
+ }
err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
Name: api.FactRole,
- IDs: []biscuit.Term{biscuit.String(api.RoleRouter)},
+ IDs: []biscuit.Term{biscuit.String(role)},
}})
if err != nil {
t.Fatalf("failed to add role fact: %v", err)
diff --git a/tests/integration/multimaster_test.go b/tests/integration/multimaster_test.go
index 4b4bf62e..822803e0 100644
--- a/tests/integration/multimaster_test.go
+++ b/tests/integration/multimaster_test.go
@@ -279,9 +279,10 @@ func enrollClientOnControlPlane(t *testing.T, cpPort int, clientID peer.ID, pubB
t.Helper()
req := &api.EnrollRequest{
- Jwt: jwtToken,
- PeerId: clientID.String(),
- PublicKey: pubBytes,
+ Jwt: jwtToken,
+ PeerId: clientID.String(),
+ PublicKey: pubBytes,
+ RequestedRole: api.RoleNode,
}
reqBytes, err := proto.Marshal(req)
if err != nil {
diff --git a/tests/integration/proxy_test.go b/tests/integration/proxy_test.go
index 56afff77..b5085d45 100644
--- a/tests/integration/proxy_test.go
+++ b/tests/integration/proxy_test.go
@@ -16,6 +16,8 @@ package integration_test
import (
"context"
+ "crypto/ed25519"
+ "crypto/rand"
"encoding/json"
"os"
"path/filepath"
@@ -47,13 +49,15 @@ func TestSamNodeRunWithStoredIdentity(t *testing.T) {
if err != nil {
return err
}
- // The following constants are mock values used for testing.
- // 'mock-biscuit-token' is a dummy token string.
- // 'mock-hub-pub-key' is a dummy public key string.
- if err := b.Put([]byte("identity_biscuit"), []byte("mock-biscuit-token")); err != nil {
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ return err
+ }
+ biscuitBytes := createMockBiscuitToken(t, "12D3KooWRHDt3Ajd1t7YikBXyK2Uw1wrJwEX88XbwJhHh1XtBNkx", priv, "sam:role:node")
+ if err := b.Put([]byte("identity_biscuit"), biscuitBytes); err != nil {
return err
}
- if err := b.Put([]byte("hub_public_key"), []byte("mock-hub-pub-key")); err != nil {
+ if err := b.Put([]byte("hub_public_key"), pub); err != nil {
return err
}
addrsData, _ := json.Marshal([]string{"/ip4/127.0.0.1/tcp/4002/p2p/Qm..."})