Skip to content

Agent Mesh

feat(headless): support bootstrap token enrollment for sam-router

Antonio Ojea94357b0eb850
diff --git a/.github/k8s/sam-control-plane-template.yaml b/.github/k8s/sam-control-plane-template.yaml
index a98c9e1a..ab33eb1a 100644
--- a/.github/k8s/sam-control-plane-template.yaml
+++ b/.github/k8s/sam-control-plane-template.yaml
@@ -137,8 +137,8 @@ data:
- members: ["user:system:serviceaccount:sam-canary-${ENV_NAME}:sam-node-sa"]
role: "sam-canary"
- members: ["group:routers", "user:system:serviceaccount:${NAMESPACE}:sam-router-sa"]
- role: "router-role"
- - members: ["system:authenticated"]
+ role: "sam:role:router"
+ - members: ["sam:system:authenticated"]
role: "public-mesh"
roles:
sam-canary:
@@ -146,7 +146,7 @@ data:
- "*"
allowed_targets:
- "*"
- router-role:
+ "sam:role:router":
allowed_services:
- "*"
allowed_targets:
diff --git a/api/datalog.go b/api/datalog.go
index 5023fe66..1f422de3 100644
--- a/api/datalog.go
+++ b/api/datalog.go
@@ -80,9 +80,20 @@ const (
// Example Datalog: allow if role("mesh-member")
FactRole = "role"
+ // FactRight defines the cryptographically signed capability/right.
+ // Contains: biscuit.String(rightName)
+ // Example Datalog: allow if right("relay")
+ FactRight = "right"
+
+ // RightRelay defines the transport relaying/bridging right.
+ RightRelay = "relay"
+
+ // RightServiceInvoke defines the edge service invocation right.
+ RightServiceInvoke = "service:invoke"
+
// Standard role values
- RoleRouter = "router"
- RoleBootstrap = "bootstrap"
+ RoleRouter = "sam:role:router"
+ RoleNode = "sam:role:node"
// FactUser defines the subject (username/userID) claim extracted from the OIDC token.
// Contains: biscuit.String(username)
diff --git a/api/network.go b/api/network.go
index 0bb41245..c6479341 100644
--- a/api/network.go
+++ b/api/network.go
@@ -83,7 +83,7 @@ const (
const (
// SystemNamespace is the namespace reserved for built-in mesh services and protocols.
- SystemNamespace = "system"
+ SystemNamespace = "sam:system"
// CatalogTarget is the special system service name used to retrieve tool catalogs.
// In policy rules, it must be referred to explicitly as: system://sam.catalog
diff --git a/api/policy.go b/api/policy.go
index 1fb94c73..11a5a505 100644
--- a/api/policy.go
+++ b/api/policy.go
@@ -16,7 +16,7 @@ package api
const (
// SystemAuthenticated is a special member string representing any authenticated user.
- SystemAuthenticated = "system:authenticated"
+ SystemAuthenticated = "sam:system:authenticated"
)
var (
diff --git a/api/sam.pb.go b/api/sam.pb.go
index ed3224ad..2024bb83 100644
--- a/api/sam.pb.go
+++ b/api/sam.pb.go
@@ -35,6 +35,58 @@ const (
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
+type EnrollmentStatus int32
+
+const (
+ EnrollmentStatus_ENROLLMENT_STATUS_UNSPECIFIED EnrollmentStatus = 0
+ EnrollmentStatus_ENROLLMENT_STATUS_PENDING EnrollmentStatus = 1
+ EnrollmentStatus_ENROLLMENT_STATUS_APPROVED EnrollmentStatus = 2
+ EnrollmentStatus_ENROLLMENT_STATUS_REJECTED EnrollmentStatus = 3
+)
+
+// Enum value maps for EnrollmentStatus.
+var (
+ EnrollmentStatus_name = map[int32]string{
+ 0: "ENROLLMENT_STATUS_UNSPECIFIED",
+ 1: "ENROLLMENT_STATUS_PENDING",
+ 2: "ENROLLMENT_STATUS_APPROVED",
+ 3: "ENROLLMENT_STATUS_REJECTED",
+ }
+ EnrollmentStatus_value = map[string]int32{
+ "ENROLLMENT_STATUS_UNSPECIFIED": 0,
+ "ENROLLMENT_STATUS_PENDING": 1,
+ "ENROLLMENT_STATUS_APPROVED": 2,
+ "ENROLLMENT_STATUS_REJECTED": 3,
+ }
+)
+
+func (x EnrollmentStatus) Enum() *EnrollmentStatus {
+ p := new(EnrollmentStatus)
+ *p = x
+ return p
+}
+
+func (x EnrollmentStatus) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (EnrollmentStatus) Descriptor() protoreflect.EnumDescriptor {
+ return file_api_sam_proto_enumTypes[0].Descriptor()
+}
+
+func (EnrollmentStatus) Type() protoreflect.EnumType {
+ return &file_api_sam_proto_enumTypes[0]
+}
+
+func (x EnrollmentStatus) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use EnrollmentStatus.Descriptor instead.
+func (EnrollmentStatus) EnumDescriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{0}
+}
+
type ServiceType int32
const (
@@ -68,11 +120,11 @@ func (x ServiceType) String() string {
}
func (ServiceType) Descriptor() protoreflect.EnumDescriptor {
- return file_api_sam_proto_enumTypes[0].Descriptor()
+ return file_api_sam_proto_enumTypes[1].Descriptor()
}
func (ServiceType) Type() protoreflect.EnumType {
- return &file_api_sam_proto_enumTypes[0]
+ return &file_api_sam_proto_enumTypes[1]
}
func (x ServiceType) Number() protoreflect.EnumNumber {
@@ -81,7 +133,7 @@ func (x ServiceType) Number() protoreflect.EnumNumber {
// Deprecated: Use ServiceType.Descriptor instead.
func (ServiceType) EnumDescriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{0}
+ return file_api_sam_proto_rawDescGZIP(), []int{1}
}
type MeshEvent_Type int32
@@ -114,11 +166,11 @@ func (x MeshEvent_Type) String() string {
}
func (MeshEvent_Type) Descriptor() protoreflect.EnumDescriptor {
- return file_api_sam_proto_enumTypes[1].Descriptor()
+ return file_api_sam_proto_enumTypes[2].Descriptor()
}
func (MeshEvent_Type) Type() protoreflect.EnumType {
- return &file_api_sam_proto_enumTypes[1]
+ return &file_api_sam_proto_enumTypes[2]
}
func (x MeshEvent_Type) Number() protoreflect.EnumNumber {
@@ -446,6 +498,202 @@ func (x *EnrollResponse) GetExpiration() int64 {
return 0
}
+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"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *BootstrapEnrollRequest) Reset() {
+ *x = BootstrapEnrollRequest{}
+ mi := &file_api_sam_proto_msgTypes[5]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *BootstrapEnrollRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BootstrapEnrollRequest) ProtoMessage() {}
+
+func (x *BootstrapEnrollRequest) 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 BootstrapEnrollRequest.ProtoReflect.Descriptor instead.
+func (*BootstrapEnrollRequest) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{5}
+}
+
+func (x *BootstrapEnrollRequest) GetBootstrapToken() string {
+ if x != nil {
+ return x.BootstrapToken
+ }
+ return ""
+}
+
+func (x *BootstrapEnrollRequest) GetPeerId() string {
+ if x != nil {
+ return x.PeerId
+ }
+ return ""
+}
+
+func (x *BootstrapEnrollRequest) GetPublicKey() []byte {
+ if x != nil {
+ return x.PublicKey
+ }
+ return nil
+}
+
+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"`
+ BiscuitToken []byte `protobuf:"bytes,2,opt,name=biscuit_token,json=biscuitToken,proto3" json:"biscuit_token,omitempty"` // Populated only if APPROVED
+ PollIntervalSeconds int32 `protobuf:"varint,3,opt,name=poll_interval_seconds,json=pollIntervalSeconds,proto3" json:"poll_interval_seconds,omitempty"` // Recommended polling wait time
+ ErrorMessage string `protobuf:"bytes,4,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`
+ HubPublicKey []byte `protobuf:"bytes,5,opt,name=hub_public_key,json=hubPublicKey,proto3" json:"hub_public_key,omitempty"` // Populated only if APPROVED
+ HubAddresses []string `protobuf:"bytes,6,rep,name=hub_addresses,json=hubAddresses,proto3" json:"hub_addresses,omitempty"` // Populated only if APPROVED
+ Expiration int64 `protobuf:"varint,7,opt,name=expiration,proto3" json:"expiration,omitempty"` // Populated only if APPROVED
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *BootstrapEnrollResponse) Reset() {
+ *x = BootstrapEnrollResponse{}
+ mi := &file_api_sam_proto_msgTypes[6]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *BootstrapEnrollResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BootstrapEnrollResponse) ProtoMessage() {}
+
+func (x *BootstrapEnrollResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_api_sam_proto_msgTypes[6]
+ 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 BootstrapEnrollResponse.ProtoReflect.Descriptor instead.
+func (*BootstrapEnrollResponse) Descriptor() ([]byte, []int) {
+ return file_api_sam_proto_rawDescGZIP(), []int{6}
+}
+
+func (x *BootstrapEnrollResponse) GetStatus() EnrollmentStatus {
+ if x != nil {
+ return x.Status
+ }
+ return EnrollmentStatus_ENROLLMENT_STATUS_UNSPECIFIED
+}
+
+func (x *BootstrapEnrollResponse) GetBiscuitToken() []byte {
+ if x != nil {
+ return x.BiscuitToken
+ }
+ return nil
+}
+
+func (x *BootstrapEnrollResponse) GetPollIntervalSeconds() int32 {
+ if x != nil {
+ return x.PollIntervalSeconds
+ }
+ return 0
+}
+
+func (x *BootstrapEnrollResponse) GetErrorMessage() string {
+ if x != nil {
+ return x.ErrorMessage
+ }
+ return ""
+}
+
+func (x *BootstrapEnrollResponse) GetHubPublicKey() []byte {
+ if x != nil {
+ return x.HubPublicKey
+ }
+ return nil
+}
+
+func (x *BootstrapEnrollResponse) GetHubAddresses() []string {
+ if x != nil {
+ return x.HubAddresses
+ }
+ return nil
+}
+
+func (x *BootstrapEnrollResponse) GetExpiration() int64 {
+ if x != nil {
+ return x.Expiration
+ }
+ 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"`
@@ -457,7 +705,7 @@ type ServiceInfo struct {
func (x *ServiceInfo) Reset() {
*x = ServiceInfo{}
- mi := &file_api_sam_proto_msgTypes[5]
+ mi := &file_api_sam_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -469,7 +717,7 @@ func (x *ServiceInfo) String() string {
func (*ServiceInfo) ProtoMessage() {}
func (x *ServiceInfo) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[5]
+ mi := &file_api_sam_proto_msgTypes[8]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -482,7 +730,7 @@ func (x *ServiceInfo) ProtoReflect() protoreflect.Message {
// Deprecated: Use ServiceInfo.ProtoReflect.Descriptor instead.
func (*ServiceInfo) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{5}
+ return file_api_sam_proto_rawDescGZIP(), []int{8}
}
func (x *ServiceInfo) GetType() ServiceType {
@@ -516,7 +764,7 @@ type CommandBackend struct {
func (x *CommandBackend) Reset() {
*x = CommandBackend{}
- mi := &file_api_sam_proto_msgTypes[6]
+ mi := &file_api_sam_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -528,7 +776,7 @@ func (x *CommandBackend) String() string {
func (*CommandBackend) ProtoMessage() {}
func (x *CommandBackend) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[6]
+ mi := &file_api_sam_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -541,7 +789,7 @@ func (x *CommandBackend) ProtoReflect() protoreflect.Message {
// Deprecated: Use CommandBackend.ProtoReflect.Descriptor instead.
func (*CommandBackend) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{6}
+ return file_api_sam_proto_rawDescGZIP(), []int{9}
}
func (x *CommandBackend) GetCommand() []string {
@@ -572,7 +820,7 @@ type RegisterServiceRequest struct {
func (x *RegisterServiceRequest) Reset() {
*x = RegisterServiceRequest{}
- mi := &file_api_sam_proto_msgTypes[7]
+ mi := &file_api_sam_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -584,7 +832,7 @@ func (x *RegisterServiceRequest) String() string {
func (*RegisterServiceRequest) ProtoMessage() {}
func (x *RegisterServiceRequest) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[7]
+ mi := &file_api_sam_proto_msgTypes[10]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -597,7 +845,7 @@ func (x *RegisterServiceRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use RegisterServiceRequest.ProtoReflect.Descriptor instead.
func (*RegisterServiceRequest) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{7}
+ return file_api_sam_proto_rawDescGZIP(), []int{10}
}
func (x *RegisterServiceRequest) GetService() *ServiceInfo {
@@ -660,7 +908,7 @@ type DiscoveredProvider struct {
func (x *DiscoveredProvider) Reset() {
*x = DiscoveredProvider{}
- mi := &file_api_sam_proto_msgTypes[8]
+ mi := &file_api_sam_proto_msgTypes[11]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -672,7 +920,7 @@ func (x *DiscoveredProvider) String() string {
func (*DiscoveredProvider) ProtoMessage() {}
func (x *DiscoveredProvider) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[8]
+ mi := &file_api_sam_proto_msgTypes[11]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -685,7 +933,7 @@ func (x *DiscoveredProvider) ProtoReflect() protoreflect.Message {
// Deprecated: Use DiscoveredProvider.ProtoReflect.Descriptor instead.
func (*DiscoveredProvider) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{8}
+ return file_api_sam_proto_rawDescGZIP(), []int{11}
}
func (x *DiscoveredProvider) GetPeerId() string {
@@ -728,7 +976,7 @@ type HubInfoResponse struct {
func (x *HubInfoResponse) Reset() {
*x = HubInfoResponse{}
- mi := &file_api_sam_proto_msgTypes[9]
+ mi := &file_api_sam_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -740,7 +988,7 @@ func (x *HubInfoResponse) String() string {
func (*HubInfoResponse) ProtoMessage() {}
func (x *HubInfoResponse) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[9]
+ mi := &file_api_sam_proto_msgTypes[12]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -753,7 +1001,7 @@ func (x *HubInfoResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use HubInfoResponse.ProtoReflect.Descriptor instead.
func (*HubInfoResponse) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{9}
+ return file_api_sam_proto_rawDescGZIP(), []int{12}
}
func (x *HubInfoResponse) GetOidcIssuer() string {
@@ -795,7 +1043,7 @@ type RouterLeaseRequest struct {
func (x *RouterLeaseRequest) Reset() {
*x = RouterLeaseRequest{}
- mi := &file_api_sam_proto_msgTypes[10]
+ mi := &file_api_sam_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -807,7 +1055,7 @@ func (x *RouterLeaseRequest) String() string {
func (*RouterLeaseRequest) ProtoMessage() {}
func (x *RouterLeaseRequest) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[10]
+ mi := &file_api_sam_proto_msgTypes[13]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -820,7 +1068,7 @@ func (x *RouterLeaseRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use RouterLeaseRequest.ProtoReflect.Descriptor instead.
func (*RouterLeaseRequest) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{10}
+ return file_api_sam_proto_rawDescGZIP(), []int{13}
}
func (x *RouterLeaseRequest) GetPeerId() string {
@@ -855,7 +1103,7 @@ type RouterLeaseResponse struct {
func (x *RouterLeaseResponse) Reset() {
*x = RouterLeaseResponse{}
- mi := &file_api_sam_proto_msgTypes[11]
+ mi := &file_api_sam_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -867,7 +1115,7 @@ func (x *RouterLeaseResponse) String() string {
func (*RouterLeaseResponse) ProtoMessage() {}
func (x *RouterLeaseResponse) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[11]
+ mi := &file_api_sam_proto_msgTypes[14]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -880,7 +1128,7 @@ func (x *RouterLeaseResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use RouterLeaseResponse.ProtoReflect.Descriptor instead.
func (*RouterLeaseResponse) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{11}
+ return file_api_sam_proto_rawDescGZIP(), []int{14}
}
func (x *RouterLeaseResponse) GetSuccess() bool {
@@ -912,7 +1160,7 @@ type PolicyConfigGetRequest struct {
func (x *PolicyConfigGetRequest) Reset() {
*x = PolicyConfigGetRequest{}
- mi := &file_api_sam_proto_msgTypes[12]
+ mi := &file_api_sam_proto_msgTypes[15]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -924,7 +1172,7 @@ func (x *PolicyConfigGetRequest) String() string {
func (*PolicyConfigGetRequest) ProtoMessage() {}
func (x *PolicyConfigGetRequest) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[12]
+ mi := &file_api_sam_proto_msgTypes[15]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -937,7 +1185,7 @@ func (x *PolicyConfigGetRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use PolicyConfigGetRequest.ProtoReflect.Descriptor instead.
func (*PolicyConfigGetRequest) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{12}
+ return file_api_sam_proto_rawDescGZIP(), []int{15}
}
type PolicyConfigGetResponse struct {
@@ -949,7 +1197,7 @@ type PolicyConfigGetResponse struct {
func (x *PolicyConfigGetResponse) Reset() {
*x = PolicyConfigGetResponse{}
- mi := &file_api_sam_proto_msgTypes[13]
+ mi := &file_api_sam_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -961,7 +1209,7 @@ func (x *PolicyConfigGetResponse) String() string {
func (*PolicyConfigGetResponse) ProtoMessage() {}
func (x *PolicyConfigGetResponse) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[13]
+ mi := &file_api_sam_proto_msgTypes[16]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -974,7 +1222,7 @@ func (x *PolicyConfigGetResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use PolicyConfigGetResponse.ProtoReflect.Descriptor instead.
func (*PolicyConfigGetResponse) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{13}
+ return file_api_sam_proto_rawDescGZIP(), []int{16}
}
func (x *PolicyConfigGetResponse) GetYamlContent() string {
@@ -993,7 +1241,7 @@ type PolicyConfigUpdateRequest struct {
func (x *PolicyConfigUpdateRequest) Reset() {
*x = PolicyConfigUpdateRequest{}
- mi := &file_api_sam_proto_msgTypes[14]
+ mi := &file_api_sam_proto_msgTypes[17]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1005,7 +1253,7 @@ func (x *PolicyConfigUpdateRequest) String() string {
func (*PolicyConfigUpdateRequest) ProtoMessage() {}
func (x *PolicyConfigUpdateRequest) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[14]
+ mi := &file_api_sam_proto_msgTypes[17]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1018,7 +1266,7 @@ func (x *PolicyConfigUpdateRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use PolicyConfigUpdateRequest.ProtoReflect.Descriptor instead.
func (*PolicyConfigUpdateRequest) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{14}
+ return file_api_sam_proto_rawDescGZIP(), []int{17}
}
func (x *PolicyConfigUpdateRequest) GetYamlContent() string {
@@ -1038,7 +1286,7 @@ type PolicyConfigUpdateResponse struct {
func (x *PolicyConfigUpdateResponse) Reset() {
*x = PolicyConfigUpdateResponse{}
- mi := &file_api_sam_proto_msgTypes[15]
+ mi := &file_api_sam_proto_msgTypes[18]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1050,7 +1298,7 @@ func (x *PolicyConfigUpdateResponse) String() string {
func (*PolicyConfigUpdateResponse) ProtoMessage() {}
func (x *PolicyConfigUpdateResponse) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[15]
+ mi := &file_api_sam_proto_msgTypes[18]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1063,7 +1311,7 @@ func (x *PolicyConfigUpdateResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use PolicyConfigUpdateResponse.ProtoReflect.Descriptor instead.
func (*PolicyConfigUpdateResponse) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{15}
+ return file_api_sam_proto_rawDescGZIP(), []int{18}
}
func (x *PolicyConfigUpdateResponse) GetSuccess() bool {
@@ -1089,7 +1337,7 @@ type KeysResponse struct {
func (x *KeysResponse) Reset() {
*x = KeysResponse{}
- mi := &file_api_sam_proto_msgTypes[16]
+ mi := &file_api_sam_proto_msgTypes[19]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -1101,7 +1349,7 @@ func (x *KeysResponse) String() string {
func (*KeysResponse) ProtoMessage() {}
func (x *KeysResponse) ProtoReflect() protoreflect.Message {
- mi := &file_api_sam_proto_msgTypes[16]
+ mi := &file_api_sam_proto_msgTypes[19]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -1114,7 +1362,7 @@ func (x *KeysResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use KeysResponse.ProtoReflect.Descriptor instead.
func (*KeysResponse) Descriptor() ([]byte, []int) {
- return file_api_sam_proto_rawDescGZIP(), []int{16}
+ return file_api_sam_proto_rawDescGZIP(), []int{19}
}
func (x *KeysResponse) GetPublicKeys() [][]byte {
@@ -1156,7 +1404,24 @@ const file_api_sam_proto_rawDesc = "" +
"\rhub_addresses\x18\x04 \x03(\tR\fhubAddresses\x12\x1e\n" +
"\n" +
"expiration\x18\x05 \x01(\x03R\n" +
- "expiration\"l\n" +
+ "expiration\"y\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" +
+ "\x17BootstrapEnrollResponse\x120\n" +
+ "\x06status\x18\x01 \x01(\x0e2\x18.sam.v1.EnrollmentStatusR\x06status\x12#\n" +
+ "\rbiscuit_token\x18\x02 \x01(\fR\fbiscuitToken\x122\n" +
+ "\x15poll_interval_seconds\x18\x03 \x01(\x05R\x13pollIntervalSeconds\x12#\n" +
+ "\rerror_message\x18\x04 \x01(\tR\ferrorMessage\x12$\n" +
+ "\x0ehub_public_key\x18\x05 \x01(\fR\fhubPublicKey\x12#\n" +
+ "\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" +
"\vServiceInfo\x12'\n" +
"\x04type\x18\x01 \x01(\x0e2\x13.sam.v1.ServiceTypeR\x04type\x12\x12\n" +
"\x04name\x18\x02 \x01(\tR\x04name\x12 \n" +
@@ -1203,7 +1468,12 @@ const file_api_sam_proto_rawDesc = "" +
"\x05error\x18\x02 \x01(\tR\x05error\"/\n" +
"\fKeysResponse\x12\x1f\n" +
"\vpublic_keys\x18\x01 \x03(\fR\n" +
- "publicKeys*]\n" +
+ "publicKeys*\x94\x01\n" +
+ "\x10EnrollmentStatus\x12!\n" +
+ "\x1dENROLLMENT_STATUS_UNSPECIFIED\x10\x00\x12\x1d\n" +
+ "\x19ENROLLMENT_STATUS_PENDING\x10\x01\x12\x1e\n" +
+ "\x1aENROLLMENT_STATUS_APPROVED\x10\x02\x12\x1e\n" +
+ "\x1aENROLLMENT_STATUS_REJECTED\x10\x03*]\n" +
"\vServiceType\x12\x1c\n" +
"\x18SERVICE_TYPE_UNSPECIFIED\x10\x00\x12\x14\n" +
"\x10SERVICE_TYPE_MCP\x10\x01\x12\x1a\n" +
@@ -1221,41 +1491,46 @@ func file_api_sam_proto_rawDescGZIP() []byte {
return file_api_sam_proto_rawDescData
}
-var file_api_sam_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
-var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 18)
+var file_api_sam_proto_enumTypes = make([]protoimpl.EnumInfo, 3)
+var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 21)
var file_api_sam_proto_goTypes = []any{
- (ServiceType)(0), // 0: sam.v1.ServiceType
- (MeshEvent_Type)(0), // 1: sam.v1.MeshEvent.Type
- (*AuthFrame)(nil), // 2: sam.v1.AuthFrame
- (*AuthResponse)(nil), // 3: sam.v1.AuthResponse
- (*MeshEvent)(nil), // 4: sam.v1.MeshEvent
- (*EnrollRequest)(nil), // 5: sam.v1.EnrollRequest
- (*EnrollResponse)(nil), // 6: sam.v1.EnrollResponse
- (*ServiceInfo)(nil), // 7: sam.v1.ServiceInfo
- (*CommandBackend)(nil), // 8: sam.v1.CommandBackend
- (*RegisterServiceRequest)(nil), // 9: sam.v1.RegisterServiceRequest
- (*DiscoveredProvider)(nil), // 10: sam.v1.DiscoveredProvider
- (*HubInfoResponse)(nil), // 11: sam.v1.HubInfoResponse
- (*RouterLeaseRequest)(nil), // 12: sam.v1.RouterLeaseRequest
- (*RouterLeaseResponse)(nil), // 13: sam.v1.RouterLeaseResponse
- (*PolicyConfigGetRequest)(nil), // 14: sam.v1.PolicyConfigGetRequest
- (*PolicyConfigGetResponse)(nil), // 15: sam.v1.PolicyConfigGetResponse
- (*PolicyConfigUpdateRequest)(nil), // 16: sam.v1.PolicyConfigUpdateRequest
- (*PolicyConfigUpdateResponse)(nil), // 17: sam.v1.PolicyConfigUpdateResponse
- (*KeysResponse)(nil), // 18: sam.v1.KeysResponse
- nil, // 19: sam.v1.CommandBackend.EnvEntry
+ (EnrollmentStatus)(0), // 0: sam.v1.EnrollmentStatus
+ (ServiceType)(0), // 1: sam.v1.ServiceType
+ (MeshEvent_Type)(0), // 2: sam.v1.MeshEvent.Type
+ (*AuthFrame)(nil), // 3: sam.v1.AuthFrame
+ (*AuthResponse)(nil), // 4: sam.v1.AuthResponse
+ (*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
+ (*ServiceInfo)(nil), // 11: sam.v1.ServiceInfo
+ (*CommandBackend)(nil), // 12: sam.v1.CommandBackend
+ (*RegisterServiceRequest)(nil), // 13: sam.v1.RegisterServiceRequest
+ (*DiscoveredProvider)(nil), // 14: sam.v1.DiscoveredProvider
+ (*HubInfoResponse)(nil), // 15: sam.v1.HubInfoResponse
+ (*RouterLeaseRequest)(nil), // 16: sam.v1.RouterLeaseRequest
+ (*RouterLeaseResponse)(nil), // 17: sam.v1.RouterLeaseResponse
+ (*PolicyConfigGetRequest)(nil), // 18: sam.v1.PolicyConfigGetRequest
+ (*PolicyConfigGetResponse)(nil), // 19: sam.v1.PolicyConfigGetResponse
+ (*PolicyConfigUpdateRequest)(nil), // 20: sam.v1.PolicyConfigUpdateRequest
+ (*PolicyConfigUpdateResponse)(nil), // 21: sam.v1.PolicyConfigUpdateResponse
+ (*KeysResponse)(nil), // 22: sam.v1.KeysResponse
+ nil, // 23: sam.v1.CommandBackend.EnvEntry
}
var file_api_sam_proto_depIdxs = []int32{
- 1, // 0: sam.v1.MeshEvent.type:type_name -> sam.v1.MeshEvent.Type
- 0, // 1: sam.v1.ServiceInfo.type:type_name -> sam.v1.ServiceType
- 19, // 2: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry
- 7, // 3: sam.v1.RegisterServiceRequest.service:type_name -> sam.v1.ServiceInfo
- 8, // 4: sam.v1.RegisterServiceRequest.command:type_name -> sam.v1.CommandBackend
- 5, // [5:5] is the sub-list for method output_type
- 5, // [5:5] is the sub-list for method input_type
- 5, // [5:5] is the sub-list for extension type_name
- 5, // [5:5] is the sub-list for extension extendee
- 0, // [0:5] is the sub-list for field type_name
+ 2, // 0: sam.v1.MeshEvent.type:type_name -> sam.v1.MeshEvent.Type
+ 0, // 1: sam.v1.BootstrapEnrollResponse.status:type_name -> sam.v1.EnrollmentStatus
+ 1, // 2: sam.v1.ServiceInfo.type:type_name -> sam.v1.ServiceType
+ 23, // 3: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry
+ 11, // 4: sam.v1.RegisterServiceRequest.service:type_name -> sam.v1.ServiceInfo
+ 12, // 5: sam.v1.RegisterServiceRequest.command:type_name -> sam.v1.CommandBackend
+ 6, // [6:6] is the sub-list for method output_type
+ 6, // [6:6] is the sub-list for method input_type
+ 6, // [6:6] is the sub-list for extension type_name
+ 6, // [6:6] is the sub-list for extension extendee
+ 0, // [0:6] is the sub-list for field type_name
}
func init() { file_api_sam_proto_init() }
@@ -1263,7 +1538,7 @@ func file_api_sam_proto_init() {
if File_api_sam_proto != nil {
return
}
- file_api_sam_proto_msgTypes[7].OneofWrappers = []any{
+ file_api_sam_proto_msgTypes[10].OneofWrappers = []any{
(*RegisterServiceRequest_TargetUrl)(nil),
(*RegisterServiceRequest_Command)(nil),
}
@@ -1272,8 +1547,8 @@ func file_api_sam_proto_init() {
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_sam_proto_rawDesc), len(file_api_sam_proto_rawDesc)),
- NumEnums: 2,
- NumMessages: 18,
+ NumEnums: 3,
+ NumMessages: 21,
NumExtensions: 0,
NumServices: 0,
},
diff --git a/api/sam.proto b/api/sam.proto
index f39c33b8..21cdbed5 100644
--- a/api/sam.proto
+++ b/api/sam.proto
@@ -56,6 +56,33 @@ message EnrollResponse {
int64 expiration = 5;
}
+enum EnrollmentStatus {
+ ENROLLMENT_STATUS_UNSPECIFIED = 0;
+ ENROLLMENT_STATUS_PENDING = 1;
+ ENROLLMENT_STATUS_APPROVED = 2;
+ ENROLLMENT_STATUS_REJECTED = 3;
+}
+
+message BootstrapEnrollRequest {
+ string bootstrap_token = 1;
+ string peer_id = 2;
+ bytes public_key = 3;
+}
+
+message BootstrapEnrollResponse {
+ EnrollmentStatus status = 1;
+ bytes biscuit_token = 2; // Populated only if APPROVED
+ int32 poll_interval_seconds = 3; // Recommended polling wait time
+ string error_message = 4;
+ bytes hub_public_key = 5; // Populated only if APPROVED
+ repeated string hub_addresses = 6; // Populated only if APPROVED
+ int64 expiration = 7; // Populated only if APPROVED
+}
+
+message EnrollmentStatusRequest {
+ string peer_id = 1;
+}
+
enum ServiceType {
SERVICE_TYPE_UNSPECIFIED = 0;
SERVICE_TYPE_MCP = 1;
diff --git a/cmd/sam-control-plane/main.go b/cmd/sam-control-plane/main.go
index ff9a595c..23e4cd22 100644
--- a/cmd/sam-control-plane/main.go
+++ b/cmd/sam-control-plane/main.go
@@ -38,8 +38,10 @@ var (
keyGracePeriod time.Duration
leaseDuration time.Duration
adminToken string
+ bootstrapToken string
insecureSkipTLSVerify bool
logLevel string
+ autoApproveEnrollment bool
)
var logger = golog.Logger("sam-control-plane-cli")
@@ -99,6 +101,9 @@ func main() {
InsecureSkipTLSVerify: insecureSkipTLSVerify,
PolicyPath: policyFile,
BiscuitTimeout: 10 * time.Second,
+ BootstrapToken: bootstrapToken,
+ AdminToken: adminToken,
+ AutoApproveEnrollment: autoApproveEnrollment,
}
srv, err := controlplane.NewServer(opts, store)
@@ -130,8 +135,10 @@ func main() {
rootCmd.Flags().DurationVar(&keyGracePeriod, "key-grace-period", 1*time.Hour, "Key grace period for rotated keys.")
rootCmd.Flags().DurationVar(&leaseDuration, "lease-duration", 15*time.Minute, "Router lease registration TTL.")
rootCmd.Flags().StringVar(&adminToken, "admin-token", "", "Token for authenticating policy REST API requests")
+ rootCmd.Flags().StringVar(&bootstrapToken, "bootstrap-token", "", "Pre-shared bootstrap token for bypassing OIDC verification")
rootCmd.Flags().BoolVar(&insecureSkipTLSVerify, "insecure-skip-tls-verify", false, "Skip TLS verification for OIDC providers")
rootCmd.Flags().StringVar(&logLevel, "log-level", "info", "Log level (debug, info, warn, error)")
+ rootCmd.Flags().BoolVar(&autoApproveEnrollment, "auto-approve-enrollment", false, "Auto-approve valid bootstrap token enrollment requests")
adminCmd := &cobra.Command{
Use: "admin",
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index 0b484afe..b052dd20 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -53,6 +53,7 @@ var (
hubAddr string
jwtFlag string
jwtPathFlag string
+ bootstrapTokenFlag string
clientIDFlag string
clientSecretFlag string
hubPublicKeyFlag string
@@ -176,7 +177,7 @@ func main() {
}
}
- if jwtStr == "" {
+ if jwtStr == "" && bootstrapTokenFlag == "" {
token, _ := store.LoadIdentity()
if len(token) == 0 {
displayHub := hubAddr
@@ -291,7 +292,11 @@ func main() {
logger.Fatalf("Failed to start node for enrollment: %v", err)
}
- err = meshNode.Enroll(enrollCtx, hubAddr, jwtStr)
+ if bootstrapTokenFlag != "" {
+ err = meshNode.EnrollBootstrap(enrollCtx, hubAddr, bootstrapTokenFlag)
+ } else {
+ err = meshNode.Enroll(enrollCtx, hubAddr, jwtStr)
+ }
if err != nil {
if teardownErr := meshNode.Teardown(); teardownErr != nil {
logger.Errorf("Teardown failed during enrollment error cleanup: %v", teardownErr)
@@ -426,18 +431,21 @@ func main() {
logger.Fatalf("Failed to discover hub info: %v", err)
}
- fmt.Printf("OIDC Issuer discovered: %s\n", hubInfo.OidcIssuer)
- fmt.Printf("Client ID discovered: %s\n", hubInfo.ClientId)
+ var jwtStr string
+ if bootstrapTokenFlag == "" {
+ fmt.Printf("OIDC Issuer discovered: %s\n", hubInfo.OidcIssuer)
+ fmt.Printf("Client ID discovered: %s\n", hubInfo.ClientId)
- logger.Info("Discovering OIDC endpoints...")
- tokenURL, authURL, err := dummyNode.DiscoverEndpoints(ctx, hubInfo.OidcIssuer)
- if err != nil {
- logger.Fatalf("Failed to discover OIDC endpoints: %v", err)
- }
+ logger.Info("Discovering OIDC endpoints...")
+ tokenURL, authURL, err := dummyNode.DiscoverEndpoints(ctx, hubInfo.OidcIssuer)
+ if err != nil {
+ logger.Fatalf("Failed to discover OIDC endpoints: %v", err)
+ }
- jwtStr, err := dummyNode.InteractiveLogin(ctx, authURL, tokenURL, hubInfo.ClientId, hubInfo.Audience, offlineAccessFlag, headlessFlag)
- if err != nil {
- logger.Fatalf("Failed to get token: %v", err)
+ jwtStr, err = dummyNode.InteractiveLogin(ctx, authURL, tokenURL, hubInfo.ClientId, hubInfo.Audience, offlineAccessFlag, headlessFlag)
+ if err != nil {
+ logger.Fatalf("Failed to get token: %v", err)
+ }
}
// Override global hubAddr with targetHub for enrollment
@@ -496,15 +504,21 @@ func main() {
logger.Fatalf("Failed to start node for enrollment: %v", err)
}
- err = meshNode.Enroll(context.Background(), targetHub, jwtStr)
+ if bootstrapTokenFlag != "" {
+ err = meshNode.EnrollBootstrap(ctx, targetHub, bootstrapTokenFlag)
+ } else {
+ err = meshNode.Enroll(ctx, targetHub, jwtStr)
+ }
if err != nil {
logger.Fatalf("Enrollment failed: %v", err)
}
if err := store.SaveHubURL(targetHub); err != nil {
logger.Warnf("Failed to save hub URL: %v", err)
}
- if err := store.SaveOIDCConfig(hubInfo.OidcIssuer, hubInfo.ClientId, hubInfo.Audience); err != nil {
- logger.Warnf("Failed to save OIDC config: %v", err)
+ if bootstrapTokenFlag == "" {
+ if err := store.SaveOIDCConfig(hubInfo.OidcIssuer, hubInfo.ClientId, hubInfo.Audience); err != nil {
+ logger.Warnf("Failed to save OIDC config: %v", err)
+ }
}
fmt.Println("Successfully joined the Sovereign Agent Mesh!")
@@ -515,6 +529,7 @@ func main() {
runCmd.Flags().StringSliceVar(&listenAddrs, "listen", []string{"/ip4/0.0.0.0/udp/5001/quic-v1", "/ip4/0.0.0.0/tcp/5002"}, "libp2p Listen Addrs")
runCmd.Flags().StringVar(&jwtFlag, "jwt", "", "Pre-fetched JWT token")
runCmd.Flags().StringVar(&jwtPathFlag, "jwt-path", "", "Path to file containing JWT token")
+ runCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")
runCmd.Flags().StringVar(&clientIDFlag, "client-id", "", "OIDC Client ID for M2M")
runCmd.Flags().StringVar(&clientSecretFlag, "client-secret", "", "OIDC Client Secret for M2M")
runCmd.Flags().StringVar(&hubPublicKeyFlag, "hub-public-key", "", "Hub Public Key (32-byte Hex)")
@@ -534,6 +549,7 @@ func main() {
joinCmd.Flags().BoolVar(&allowLoopbackFlag, "allow-loopback", false, "Allow publishing and connecting to loopback/link-local addresses")
joinCmd.Flags().DurationVar(&hubConnectTimeoutFlag, "hub-connect-timeout", node.DefaultHubConnectTimeout, "Timeout for dialing each hub address")
joinCmd.Flags().BoolVar(&offlineAccessFlag, "offline-access", false, "Request OIDC offline access/refresh token for automatic renewal")
+ joinCmd.Flags().StringVar(&bootstrapTokenFlag, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")
runCmd.Flags().StringVar(&apiTokenFlag, "api-token", "", "Static Bearer token for API authorization")
runCmd.Flags().StringVar(&tlsCertFlag, "tls-cert", "", "Path to TLS certificate for sidecar API")
runCmd.Flags().StringVar(&tlsKeyFlag, "tls-key", "", "Path to TLS key for sidecar API")
diff --git a/cmd/sam-router/main.go b/cmd/sam-router/main.go
index 989c716a..1a470ab5 100644
--- a/cmd/sam-router/main.go
+++ b/cmd/sam-router/main.go
@@ -31,6 +31,8 @@ var (
keysSyncInterval time.Duration
leaseRenewInterval time.Duration
oidcToken string
+ bootstrapToken string
+ bootstrapTokenPath string
jwtPath string
keysPath string
allowLoopback bool
@@ -63,6 +65,8 @@ func main() {
KeysSyncInterval: keysSyncInterval,
LeaseRenewInterval: leaseRenewInterval,
OIDCToken: oidcToken,
+ BootstrapToken: bootstrapToken,
+ BootstrapTokenPath: bootstrapTokenPath,
JWTPath: jwtPath,
KeysDBPath: keysPath,
AllowLoopback: allowLoopback,
@@ -91,7 +95,9 @@ func main() {
rootCmd.Flags().StringSliceVar(&externalAddrs, "external-addr", []string{}, "External addresses to announce to control plane")
rootCmd.Flags().DurationVar(&keysSyncInterval, "keys-sync-interval", 5*time.Minute, "Key synchronization polling interval")
rootCmd.Flags().DurationVar(&leaseRenewInterval, "lease-renew-interval", 300*time.Second, "Lease renewal registration interval")
- rootCmd.Flags().StringVar(&oidcToken, "oidc-token", "", "OIDC ID token or bootstrap secret token for enrollment")
+ rootCmd.Flags().StringVar(&oidcToken, "oidc-token", "", "OIDC ID token for enrollment")
+ rootCmd.Flags().StringVar(&bootstrapToken, "bootstrap-token", "", "Pre-shared bootstrap token for enrollment")
+ rootCmd.Flags().StringVar(&bootstrapTokenPath, "bootstrap-token-path", "", "Path to file containing bootstrap token for enrollment")
rootCmd.Flags().StringVar(&jwtPath, "jwt-path", "", "Path to file containing OIDC JWT token")
rootCmd.Flags().StringVar(&keysPath, "keys-path", "router.key", "Path to save/load persistent private key")
rootCmd.Flags().BoolVar(&allowLoopback, "allow-loopback", false, "Allow loopback and link-local addresses for discovery")
diff --git a/internal/controlplane/config.go b/internal/controlplane/config.go
index a9b52f3c..9ebe46eb 100644
--- a/internal/controlplane/config.go
+++ b/internal/controlplane/config.go
@@ -32,6 +32,9 @@ type Options struct {
InsecureSkipTLSVerify bool
BiscuitTimeout time.Duration
PolicyPath string // Optional: path to bootstrap policy configuration
+ BootstrapToken string // Optional: pre-shared bootstrap token for bypassing OIDC verification (e.g. for router enrollment)
+ AdminToken string // Optional: administrative bearer token for protecting policy and enrollment queue REST APIs
+ AutoApproveEnrollment bool // If true, valid bootstrap token enrollment requests are immediately approved without administrative manual gate
}
// Default sets default values for control plane options.
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index f5165d29..6ffebe94 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -18,8 +18,10 @@ import (
"context"
"crypto/ed25519"
"crypto/rand"
+ "crypto/sha256"
"crypto/tls"
"encoding/hex"
+ "encoding/json"
"errors"
"fmt"
"io"
@@ -118,6 +120,31 @@ func (s *Server) Start() error {
}
}
+ // Seed the initial command-line bootstrap token if provided
+ if s.config.BootstrapToken != "" {
+ hash := sha256.Sum256([]byte(s.config.BootstrapToken))
+ tokenID := fmt.Sprintf("%x", hash)
+ _, err := s.store.GetBootstrapToken(ctx, tokenID)
+ if err == storage.ErrNotFound {
+ logger.Infof("Seeding initial bootstrap token into database (ID: %s)...", tokenID)
+ tokenRecord := &storage.BootstrapToken{
+ ID: tokenID,
+ TokenHash: tokenID,
+ Role: api.RoleRouter,
+ MaxUsages: 10000,
+ UsagesCount: 0,
+ Description: "Command Line Seeded Token",
+ CreatedAt: time.Now(),
+ ExpiresAt: time.Now().Add(365 * 24 * time.Hour),
+ }
+ if err := s.store.SaveBootstrapToken(ctx, tokenRecord); err != nil {
+ return fmt.Errorf("failed to save initial bootstrap token: %w", err)
+ }
+ } else if err != nil {
+ return fmt.Errorf("failed to check initial bootstrap token state: %w", err)
+ }
+ }
+
// Initialize OIDC Providers
if err := s.discoverProviders(); err != nil {
return fmt.Errorf("failed OIDC discovery: %w", err)
@@ -136,6 +163,11 @@ func (s *Server) Start() error {
mux.HandleFunc("/keys", s.HandleKeys)
mux.HandleFunc("/routers/lease", s.HandleRouterLease)
mux.HandleFunc("/policies", s.HandlePolicies)
+ mux.HandleFunc("/enroll", s.HandleEnroll)
+ mux.HandleFunc("/enroll/status", s.HandleEnrollStatus)
+ mux.HandleFunc("/admin/bootstrap-tokens", s.HandleAdminBootstrapTokens)
+ mux.HandleFunc("/admin/enrollments", s.HandleAdminEnrollments)
+ mux.HandleFunc("/admin/enrollments/", s.HandleAdminEnrollmentAction)
s.httpServer = &http.Server{
Handler: mux,
@@ -472,11 +504,6 @@ func (s *Server) HandleRouterLease(w http.ResponseWriter, r *http.Request) {
{Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(api.RoleRouter)}},
},
},
- {
- Body: []biscuit.Predicate{
- {Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(api.RoleBootstrap)}},
- },
- },
}})
authorizer.AddPolicy(api.AllowIfTruePolicy)
@@ -615,3 +642,422 @@ func (s *Server) Addr() string {
}
return s.listener.Addr().String()
}
+
+func cryptoRandUUID() string {
+ b := make([]byte, 16)
+ _, _ = rand.Read(b)
+ return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
+}
+
+func (s *Server) writeEnrollResponse(w http.ResponseWriter, resp *api.BootstrapEnrollResponse) {
+ respData, err := proto.Marshal(resp)
+ if err != nil {
+ http.Error(w, "Failed to serialize response", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(respData)
+}
+
+func (s *Server) writeEnrollError(w http.ResponseWriter, status api.EnrollmentStatus, errMsg string) {
+ s.writeEnrollResponse(w, &api.BootstrapEnrollResponse{
+ Status: status,
+ ErrorMessage: errMsg,
+ })
+}
+
+// HandleEnroll HTTP POST `/enroll`
+func (s *Server) HandleEnroll(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ http.Error(w, "Failed to read body", http.StatusBadRequest)
+ return
+ }
+ defer func() { _ = r.Body.Close() }()
+
+ var req api.BootstrapEnrollRequest
+ if err := proto.Unmarshal(body, &req); err != nil {
+ http.Error(w, "Invalid request format", http.StatusBadRequest)
+ return
+ }
+
+ if !s.limiter.Allow() {
+ http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
+ return
+ }
+
+ ctx := r.Context()
+ tokenID := fmt.Sprintf("%x", sha256.Sum256([]byte(req.BootstrapToken)))
+
+ // 1. Get and validate bootstrap token
+ tokenRecord, err := s.store.GetBootstrapToken(ctx, tokenID)
+ if err == storage.ErrNotFound {
+ logger.Errorw("Invalid bootstrap token attempt", "peer_id", req.PeerId)
+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Invalid bootstrap token")
+ return
+ } else if err != nil {
+ logger.Errorf("Failed to retrieve bootstrap token: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ if time.Now().After(tokenRecord.ExpiresAt) {
+ logger.Warnw("Expired bootstrap token used", "peer_id", req.PeerId, "token_id", tokenRecord.ID)
+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Bootstrap token expired")
+ return
+ }
+
+ if tokenRecord.UsagesCount >= tokenRecord.MaxUsages {
+ logger.Warnw("Max usages exceeded for bootstrap token", "peer_id", req.PeerId, "token_id", tokenRecord.ID)
+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Bootstrap token max usages exceeded")
+ return
+ }
+
+ pID, err := peer.Decode(req.PeerId)
+ if err != nil {
+ http.Error(w, "Invalid Peer ID", http.StatusBadRequest)
+ return
+ }
+
+ // 2. Check for existing enrollment request
+ existingReq, err := s.store.GetEnrollmentRequest(ctx, req.PeerId)
+ if err == nil {
+ // Request already exists, return status
+ resp := &api.BootstrapEnrollResponse{
+ Status: existingReq.Status,
+ BiscuitToken: existingReq.BiscuitToken,
+ }
+ s.writeEnrollResponse(w, resp)
+ return
+ } else if err != storage.ErrNotFound {
+ logger.Errorf("Failed to query enrollment request: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ // 3. Create new enrollment request
+ enrollReq := &storage.EnrollmentRequest{
+ ID: cryptoRandUUID(),
+ PeerID: req.PeerId,
+ PublicKey: req.PublicKey,
+ TokenID: tokenRecord.ID,
+ Status: api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING,
+ CreatedAt: time.Now(),
+ }
+
+ // Fetch mesh policy
+ policy, err := s.store.GetPolicy(ctx)
+ if err != nil && err != storage.ErrNotFound {
+ logger.Errorf("Failed to retrieve policy: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ // Fetch current signing private key
+ privKey, _, err := s.store.GetCurrentKey(ctx)
+ if err != nil {
+ logger.Errorf("Failed to retrieve signing key: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ if s.config.AutoApproveEnrollment {
+ // Mode A: Auto-Approve
+ tokenTTL := 24 * time.Hour
+ biscuitBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, tokenRecord.Role, time.Now().Add(tokenTTL), policy)
+ if err != nil {
+ logger.Errorf("Failed to mint bootstrap biscuit: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ enrollReq.Status = api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED
+ enrollReq.BiscuitToken = biscuitBytes
+ tNow := time.Now()
+ enrollReq.ResolvedAt = &tNow
+ enrollReq.ResolvedBy = "auto-approver"
+
+ if err := s.store.CreateEnrollmentRequest(ctx, enrollReq); err != nil {
+ logger.Errorf("Failed to save enrollment request: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ if err := s.store.IncrementBootstrapTokenUsage(ctx, tokenRecord.ID); err != nil {
+ logger.Errorf("Failed to increment token usage: %v", err)
+ }
+
+ resp := &api.BootstrapEnrollResponse{
+ Status: api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED,
+ BiscuitToken: biscuitBytes,
+ }
+ s.writeEnrollResponse(w, resp)
+ return
+ }
+
+ // Mode B: Manual approval queue
+ if err := s.store.CreateEnrollmentRequest(ctx, enrollReq); err != nil {
+ logger.Errorf("Failed to save pending enrollment request: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ resp := &api.BootstrapEnrollResponse{
+ Status: api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING,
+ PollIntervalSeconds: 30,
+ }
+ s.writeEnrollResponse(w, resp)
+}
+
+// HandleEnrollStatus HTTP GET `/enroll/status`
+func (s *Server) HandleEnrollStatus(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ peerID := r.URL.Query().Get("peer_id")
+ if peerID == "" {
+ http.Error(w, "Missing peer_id parameter", http.StatusBadRequest)
+ return
+ }
+
+ ctx := r.Context()
+ enrollReq, err := s.store.GetEnrollmentRequest(ctx, peerID)
+ if err == storage.ErrNotFound {
+ s.writeEnrollError(w, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, "Enrollment request not found")
+ return
+ } else if err != nil {
+ logger.Errorf("Failed to retrieve enrollment status: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ resp := &api.BootstrapEnrollResponse{
+ Status: enrollReq.Status,
+ BiscuitToken: enrollReq.BiscuitToken,
+ }
+ if enrollReq.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING {
+ resp.PollIntervalSeconds = 30
+ }
+ s.writeEnrollResponse(w, resp)
+}
+
+func (s *Server) checkAdminAuth(w http.ResponseWriter, r *http.Request) bool {
+ if s.config.AdminToken == "" {
+ return true
+ }
+ authHeader := r.Header.Get("Authorization")
+ if !strings.HasPrefix(authHeader, "Bearer ") {
+ http.Error(w, "Unauthorized", http.StatusUnauthorized)
+ return false
+ }
+ token := strings.TrimPrefix(authHeader, "Bearer ")
+ if token != s.config.AdminToken {
+ http.Error(w, "Unauthorized", http.StatusUnauthorized)
+ return false
+ }
+ return true
+}
+
+// HandleAdminBootstrapTokens HTTP POST `/admin/bootstrap-tokens`
+func (s *Server) HandleAdminBootstrapTokens(w http.ResponseWriter, r *http.Request) {
+ if !s.checkAdminAuth(w, r) {
+ return
+ }
+
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ var req struct {
+ Role string `json:"role"`
+ TTLHours int `json:"ttl_hours"`
+ MaxUsages int `json:"max_usages"`
+ Description string `json:"description"`
+ }
+
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, "Invalid JSON body", http.StatusBadRequest)
+ return
+ }
+ defer func() { _ = r.Body.Close() }()
+
+ if req.Role == "" {
+ req.Role = api.RoleRouter
+ }
+ if req.TTLHours <= 0 {
+ req.TTLHours = 24
+ }
+ if req.MaxUsages <= 0 {
+ req.MaxUsages = 1
+ }
+
+ randBytes := make([]byte, 16)
+ if _, err := rand.Read(randBytes); err != nil {
+ http.Error(w, "Internal keygen error", http.StatusInternalServerError)
+ return
+ }
+ tokenVal := fmt.Sprintf("sam-bt-%x", randBytes)
+ tokenID := fmt.Sprintf("%x", sha256.Sum256([]byte(tokenVal)))
+
+ tokenRecord := &storage.BootstrapToken{
+ ID: tokenID,
+ TokenHash: tokenID,
+ Role: req.Role,
+ MaxUsages: req.MaxUsages,
+ UsagesCount: 0,
+ Description: req.Description,
+ CreatedAt: time.Now(),
+ ExpiresAt: time.Now().Add(time.Duration(req.TTLHours) * time.Hour),
+ }
+
+ if err := s.store.SaveBootstrapToken(r.Context(), tokenRecord); err != nil {
+ logger.Errorf("Failed to save bootstrap token: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "id": tokenRecord.ID,
+ "token": tokenVal,
+ "role": tokenRecord.Role,
+ "expires_at": tokenRecord.ExpiresAt.Format(time.RFC3339),
+ })
+}
+
+// HandleAdminEnrollments HTTP GET `/admin/enrollments`
+func (s *Server) HandleAdminEnrollments(w http.ResponseWriter, r *http.Request) {
+ if !s.checkAdminAuth(w, r) {
+ return
+ }
+
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ list, err := s.store.ListEnrollmentRequests(r.Context())
+ if err != nil {
+ logger.Errorf("Failed to list enrollment requests: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(list)
+}
+
+// HandleAdminEnrollmentAction HTTP POST `/admin/enrollments/{id}/approve` or `/admin/enrollments/{id}/reject`
+func (s *Server) HandleAdminEnrollmentAction(w http.ResponseWriter, r *http.Request) {
+ if !s.checkAdminAuth(w, r) {
+ return
+ }
+
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ path := strings.TrimPrefix(r.URL.Path, "/admin/enrollments/")
+ parts := strings.Split(path, "/")
+ if len(parts) != 2 {
+ http.Error(w, "Not found", http.StatusNotFound)
+ return
+ }
+ id := parts[0]
+ action := parts[1]
+
+ ctx := r.Context()
+ enrollReq, err := s.store.GetEnrollmentRequestByID(ctx, id)
+ if err == storage.ErrNotFound {
+ http.Error(w, "Enrollment request not found", http.StatusNotFound)
+ return
+ } else if err != nil {
+ logger.Errorf("Failed to query enrollment request: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ if enrollReq.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING {
+ http.Error(w, "Enrollment request is already resolved", http.StatusConflict)
+ return
+ }
+
+ adminIdentity := "admin"
+
+ if action == "reject" {
+ err = s.store.UpdateEnrollmentRequest(ctx, id, api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED, nil, adminIdentity)
+ if err != nil {
+ logger.Errorf("Failed to reject enrollment: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte("Enrollment rejected"))
+ return
+ }
+
+ if action == "approve" {
+ tokenRecord, err := s.store.GetBootstrapToken(ctx, enrollReq.TokenID)
+ if err != nil {
+ logger.Errorf("Failed to retrieve token for request: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ pID, err := peer.Decode(enrollReq.PeerID)
+ if err != nil {
+ http.Error(w, "Invalid Peer ID stored in request", http.StatusInternalServerError)
+ return
+ }
+
+ policy, err := s.store.GetPolicy(ctx)
+ if err != nil && err != storage.ErrNotFound {
+ logger.Errorf("Failed to retrieve policy: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ privKey, _, err := s.store.GetCurrentKey(ctx)
+ if err != nil {
+ logger.Errorf("Failed to retrieve signing key: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ biscuitBytes, err := identity.MintBootstrapBiscuitToken(privKey, pID, tokenRecord.Role, time.Now().Add(24*time.Hour), policy)
+ if err != nil {
+ logger.Errorf("Failed to mint bootstrap biscuit: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ err = s.store.UpdateEnrollmentRequest(ctx, id, api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED, biscuitBytes, adminIdentity)
+ if err != nil {
+ logger.Errorf("Failed to approve enrollment request in DB: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+
+ if err := s.store.IncrementBootstrapTokenUsage(ctx, tokenRecord.ID); err != nil {
+ logger.Errorf("Failed to increment token usage: %v", err)
+ }
+
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte("Enrollment approved"))
+ return
+ }
+
+ http.Error(w, "Invalid action", http.StatusBadRequest)
+}
diff --git a/internal/controlplane/server_test.go b/internal/controlplane/server_test.go
index a375131c..b4ecf5fc 100644
--- a/internal/controlplane/server_test.go
+++ b/internal/controlplane/server_test.go
@@ -32,6 +32,7 @@ import (
"testing"
"time"
+ "github.com/biscuit-auth/biscuit-go/v2"
"github.com/golang-jwt/jwt/v5"
"github.com/google/sam/api"
"github.com/google/sam/internal/storage"
@@ -214,11 +215,11 @@ func TestNodeAndRouterRegistrationFlow(t *testing.T) {
policy := &api.PolicyConfig{
Version: "v1alpha1",
Bindings: []api.Binding{
- {Role: "router", Members: []string{"group:routers"}},
+ {Role: api.RoleRouter, Members: []string{"group:routers"}},
{Role: "user-role", Members: []string{"group:users"}},
},
Roles: map[string]api.RolePolicy{
- "router": {
+ api.RoleRouter: {
AllowedServices: []string{"*"},
AllowedTargets: []string{"*"},
},
@@ -437,3 +438,205 @@ roles:
t.Errorf("returned policy content mismatch: %s", getResp.YamlContent)
}
}
+
+func TestEnrollmentWorkflow(t *testing.T) {
+ issuer, _ := startCustomMockOIDC(t)
+ srv, store, baseURL := setupTestServer(t, issuer)
+ defer func() {
+ _ = srv.Close()
+ _ = store.Close()
+ }()
+
+ // Configure admin token
+ srv.config.AdminToken = "super-secret-admin-token"
+
+ client := &http.Client{Timeout: 5 * time.Second}
+
+ // 1. Create Bootstrap Token (Manual Approval Gate)
+ srv.config.AutoApproveEnrollment = false
+
+ adminReqBody := []byte(`{
+ "role": "sam:role:router",
+ "ttl_hours": 2,
+ "max_usages": 2,
+ "description": "Test Mode B"
+ }`)
+
+ req, _ := http.NewRequest("POST", baseURL+"/admin/bootstrap-tokens", bytes.NewBuffer(adminReqBody))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer super-secret-admin-token")
+
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("failed to create bootstrap token: %v", err)
+ }
+ if resp.StatusCode != http.StatusCreated {
+ t.Fatalf("unexpected status creating token: %s", resp.Status)
+ }
+
+ var tokenDetails struct {
+ ID string `json:"id"`
+ Token string `json:"token"`
+ }
+ _ = json.NewDecoder(resp.Body).Decode(&tokenDetails)
+ _ = resp.Body.Close()
+
+ if tokenDetails.Token == "" || tokenDetails.ID == "" {
+ t.Fatalf("empty token details received: %+v", tokenDetails)
+ }
+
+ // Generate Client node key
+ privNode, pubNode, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pID, _ := peer.IDFromPrivateKey(privNode)
+ pubBytes, _ := pubNode.Raw()
+
+ // 2. Submit Enrollment Request (Mode B -> PENDING)
+ enrollReq := &api.BootstrapEnrollRequest{
+ BootstrapToken: tokenDetails.Token,
+ PeerId: pID.String(),
+ PublicKey: pubBytes,
+ }
+ enrollReqData, _ := proto.Marshal(enrollReq)
+
+ resp, err = client.Post(baseURL+"/enroll", "application/x-protobuf", bytes.NewBuffer(enrollReqData))
+ if err != nil {
+ t.Fatalf("failed to enroll: %v", err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("unexpected enroll status: %s", resp.Status)
+ }
+
+ body, _ := io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+
+ var enrollResp api.BootstrapEnrollResponse
+ if err := proto.Unmarshal(body, &enrollResp); err != nil {
+ t.Fatalf("failed to unmarshal enroll response: %v", err)
+ }
+ if enrollResp.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING {
+ t.Errorf("expected PENDING status, got %v", enrollResp.Status)
+ }
+
+ // 3. Poll Enrollment Status -> PENDING
+ resp, err = client.Get(baseURL + "/enroll/status?peer_id=" + pID.String())
+ if err != nil {
+ t.Fatalf("failed to get status: %v", err)
+ }
+ body, _ = io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+
+ var statusResp api.BootstrapEnrollResponse
+ _ = proto.Unmarshal(body, &statusResp)
+ if statusResp.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING {
+ t.Errorf("expected polled status to be PENDING, got %v", statusResp.Status)
+ }
+
+ // 4. Admin query list & approve
+ req, _ = http.NewRequest("GET", baseURL+"/admin/enrollments", nil)
+ req.Header.Set("Authorization", "Bearer super-secret-admin-token")
+ resp, err = client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var enrollList []storage.EnrollmentRequest
+ _ = json.NewDecoder(resp.Body).Decode(&enrollList)
+ _ = resp.Body.Close()
+
+ if len(enrollList) != 1 || enrollList[0].PeerID != pID.String() {
+ t.Fatalf("unexpected enrollments list: %+v", enrollList)
+ }
+ reqID := enrollList[0].ID
+
+ // Approve
+ req, _ = http.NewRequest("POST", baseURL+"/admin/enrollments/"+reqID+"/approve", nil)
+ req.Header.Set("Authorization", "Bearer super-secret-admin-token")
+ resp, err = client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("failed to approve enrollment: %s", resp.Status)
+ }
+ _ = resp.Body.Close()
+
+ // 5. Poll Status -> APPROVED & Validate Biscuit
+ resp, err = client.Get(baseURL + "/enroll/status?peer_id=" + pID.String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _ = io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+
+ _ = proto.Unmarshal(body, &statusResp)
+ if statusResp.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
+ t.Fatalf("expected APPROVED, got %v", statusResp.Status)
+ }
+ if len(statusResp.BiscuitToken) == 0 {
+ t.Fatalf("biscuit token is empty")
+ }
+
+ // Verify Biscuit router rights
+ _, cpPub, err := store.GetCurrentKey(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := biscuit.Unmarshal(statusResp.BiscuitToken)
+ if err != nil {
+ t.Fatalf("failed to unmarshal biscuit: %v", err)
+ }
+ authorizer, err := b.Authorizer(cpPub)
+ if err != nil {
+ t.Fatal(err)
+ }
+ checkRelay := biscuit.Check{Queries: []biscuit.Rule{
+ {
+ Body: []biscuit.Predicate{
+ {Name: api.FactRight, IDs: []biscuit.Term{biscuit.String(api.RightRelay)}},
+ },
+ },
+ }}
+ authorizer.AddCheck(checkRelay)
+ 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("biscuit validation failed: %v", err)
+ }
+
+ // 6. Test Mode A (Auto-Approve)
+ srv.config.AutoApproveEnrollment = true
+
+ // Generate new client key
+ privNode2, _, _ := crypto.GenerateKeyPair(crypto.Ed25519, -1)
+ pID2, _ := peer.IDFromPrivateKey(privNode2)
+
+ enrollReq2 := &api.BootstrapEnrollRequest{
+ BootstrapToken: tokenDetails.Token, // use remaining usage
+ PeerId: pID2.String(),
+ PublicKey: pubBytes,
+ }
+ enrollReqData2, _ := proto.Marshal(enrollReq2)
+
+ resp, err = client.Post(baseURL+"/enroll", "application/x-protobuf", bytes.NewBuffer(enrollReqData2))
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _ = io.ReadAll(resp.Body)
+ _ = resp.Body.Close()
+
+ var enrollResp2 api.BootstrapEnrollResponse
+ _ = proto.Unmarshal(body, &enrollResp2)
+ if enrollResp2.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
+ t.Errorf("expected immediate APPROVED status in Auto-Approve mode, got %v", enrollResp2.Status)
+ }
+ if len(enrollResp2.BiscuitToken) == 0 {
+ t.Error("biscuit token empty in Auto-Approve response")
+ }
+}
diff --git a/internal/identity/biscuit.go b/internal/identity/biscuit.go
index 9ce1354a..ba2bdbd0 100644
--- a/internal/identity/biscuit.go
+++ b/internal/identity/biscuit.go
@@ -31,7 +31,7 @@ import (
"github.com/libp2p/go-libp2p/core/peer"
)
-// MintBiscuitToken generates a signed Biscuit token for a peer with policy rules based on JWT claims.
+// // 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) ([]byte, error) {
if token == nil {
return nil, fmt.Errorf("token cannot be nil")
@@ -91,6 +91,28 @@ func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token
}
}
+ roles := make([]string, 0, len(resolvedRoles))
+ for role := range resolvedRoles {
+ roles = append(roles, role)
+ }
+
+ // 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 {
+ if strings.HasPrefix(r, "sam:role:") {
+ hasSamRole = true
+ break
+ }
+ }
+ if !hasSamRole {
+ roles = append(roles, api.RoleNode)
+ }
+
+ return mintBiscuit(signingKey, remotePeer, roles, token.Expiry, policy, claims)
+}
+
+func mintBiscuit(signingKey ed25519.PrivateKey, remotePeer peer.ID, roles []string, expiration time.Time, policy *api.PolicyConfig, claims jwt.MapClaims) ([]byte, error) {
builder := biscuit.NewBuilder(signingKey)
addedFacts := make(map[string]bool)
addFact := func(fact biscuit.Fact) error {
@@ -107,7 +129,7 @@ func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token
if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{
Name: api.FactExpiration,
- IDs: []biscuit.Term{biscuit.Date(token.Expiry)},
+ IDs: []biscuit.Term{biscuit.Date(expiration)},
}}); err != nil {
return nil, fmt.Errorf("failed to add expiration fact: %w", err)
}
@@ -126,16 +148,13 @@ func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token
return nil, fmt.Errorf("failed to add client_peer_id fact: %w", err)
}
- if err := translateClaimsToFacts(addFact, claims); err != nil {
- return nil, err
+ if claims != nil {
+ if err := translateClaimsToFacts(addFact, claims); err != nil {
+ return nil, err
+ }
}
- roles := make([]string, 0, len(resolvedRoles))
- for role := range resolvedRoles {
- roles = append(roles, role)
- }
sort.Strings(roles)
-
var errs []error
for _, role := range roles {
if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{
@@ -146,6 +165,22 @@ func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token
continue
}
+ if role == api.RoleRouter {
+ if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactRight,
+ IDs: []biscuit.Term{biscuit.String(api.RightRelay)},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add relay right: %w", err))
+ }
+ if err := addFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactTargetUnrestricted,
+ IDs: []biscuit.Term{},
+ }}); err != nil {
+ errs = append(errs, fmt.Errorf("failed to add target unrestricted: %w", err))
+ }
+ continue
+ }
+
if policy != nil {
if rolePolicy, ok := policy.Roles[role]; ok {
for _, svc := range rolePolicy.AllowedServices {
@@ -190,6 +225,7 @@ func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token
}
}
}
+
for _, target := range rolePolicy.AllowedTargets {
targetFact, targetVal := api.ParseServiceTarget(target)
@@ -232,6 +268,7 @@ func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token
}
}
}
+
for _, customFact := range rolePolicy.CustomDatalog {
trimmed := strings.TrimRight(strings.TrimSpace(customFact), ";")
if trimmed == "" {
@@ -291,12 +328,12 @@ func MintBiscuitToken(signingKey ed25519.PrivateKey, claims jwt.MapClaims, token
return nil, fmt.Errorf("failed to build biscuit: %w", err)
}
- biscuitData, err := t.Serialize()
+ bBytes, err := t.Serialize()
if err != nil {
return nil, fmt.Errorf("failed to serialize biscuit: %w", err)
}
- return biscuitData, nil
+ return bBytes, nil
}
// VerifyBiscuit verifies the validity of a Biscuit token.
@@ -424,3 +461,8 @@ func toStringSlice(val any) []string {
}
return nil
}
+
+// MintBootstrapBiscuitToken generates a signed Biscuit token for a peer using a bootstrap role.
+func MintBootstrapBiscuitToken(signingKey ed25519.PrivateKey, remotePeer peer.ID, role string, expiration time.Time, policy *api.PolicyConfig) ([]byte, error) {
+ return mintBiscuit(signingKey, remotePeer, []string{role}, expiration, policy, nil)
+}
diff --git a/internal/identity/biscuit_test.go b/internal/identity/biscuit_test.go
index 3dfcb85b..6f23ebc6 100644
--- a/internal/identity/biscuit_test.go
+++ b/internal/identity/biscuit_test.go
@@ -130,7 +130,7 @@ func TestMintBiscuitToken(t *testing.T) {
t.Errorf("Expected mapped role 'canary-role' to be authorized: %v", err)
}
- // Case 3: Unmapped OIDC group and undefined direct role
+ // Case 3: Unmapped OIDC group and undefined direct role -> falls back to sam:role:node
claims3 := jwt.MapClaims{
"groups": []any{"unknown-group"},
"roles": []any{"undefined-role"},
@@ -151,13 +151,13 @@ func TestMintBiscuitToken(t *testing.T) {
{
Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},
Body: []biscuit.Predicate{
- {Name: "role", IDs: []biscuit.Term{biscuit.Variable("any_role")}},
+ {Name: "role", IDs: []biscuit.Term{biscuit.String(api.RoleNode)}},
},
},
}, Kind: biscuit.PolicyKindAllow}
authorizer3.AddPolicy(rule3)
- if err := authorizer3.Authorize(); err == nil {
- t.Error("Expected authorizer to fail when checking for any roles in undefined configuration")
+ if err := authorizer3.Authorize(); err != nil {
+ t.Errorf("Expected authorizer to pass fallback role '%s', got err: %v", api.RoleNode, err)
}
// Case 4: GKE Workload Identity projected token (no groups claim, sub-based mapping)
@@ -617,3 +617,109 @@ func TestMintBiscuitToken_FactDeduplication(t *testing.T) {
t.Error("Expected valid biscuit data, got empty")
}
}
+
+func TestMintBootstrapBiscuitToken(t *testing.T) {
+ pub, 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, err := peer.IDFromPrivateKey(privNode)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ policy := &api.PolicyConfig{
+ Roles: map[string]api.RolePolicy{
+ "custom-node-role": {
+ AllowedServices: []string{"mcp:service1"},
+ },
+ },
+ }
+
+ // Case 1: Router Role
+ biscuitData1, err := MintBootstrapBiscuitToken(priv, dummyPeer, api.RoleRouter, time.Now().Add(1*time.Hour), policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ b1, err := biscuit.Unmarshal(biscuitData1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ authorizer1, err := b1.Authorizer(pub, biscuit.WithWorldOptions(datalog.WithMaxDuration(500*time.Millisecond)))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Verify right("relay") fact is present
+ checkRelay := biscuit.Check{Queries: []biscuit.Rule{
+ {
+ Body: []biscuit.Predicate{
+ {Name: api.FactRight, IDs: []biscuit.Term{biscuit.String(api.RightRelay)}},
+ },
+ },
+ }}
+ authorizer1.AddCheck(checkRelay)
+
+ // Verify target_unrestricted() fact is present
+ checkUnrestricted := biscuit.Check{Queries: []biscuit.Rule{
+ {
+ Body: []biscuit.Predicate{
+ {Name: "target_unrestricted", IDs: []biscuit.Term{}},
+ },
+ },
+ }}
+ authorizer1.AddCheck(checkUnrestricted)
+
+ authorizer1.AddPolicy(biscuit.Policy{Queries: []biscuit.Rule{
+ {
+ Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},
+ Body: []biscuit.Predicate{},
+ },
+ }, Kind: biscuit.PolicyKindAllow})
+
+ if err := authorizer1.Authorize(); err != nil {
+ t.Errorf("Expected router facts checks to succeed: %v", err)
+ }
+
+ // Case 2: Custom Node Role
+ biscuitData2, err := MintBootstrapBiscuitToken(priv, dummyPeer, "custom-node-role", time.Now().Add(1*time.Hour), policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ b2, err := biscuit.Unmarshal(biscuitData2)
+ if err != nil {
+ t.Fatal(err)
+ }
+ authorizer2, err := b2.Authorizer(pub, biscuit.WithWorldOptions(datalog.WithMaxDuration(500*time.Millisecond)))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Verify exact match service fact derived from policy
+ checkServiceExact := biscuit.Check{Queries: []biscuit.Rule{
+ {
+ Body: []biscuit.Predicate{
+ {Name: "granted_service_exact", IDs: []biscuit.Term{biscuit.String("mcp"), biscuit.String("service1")}},
+ },
+ },
+ }}
+ authorizer2.AddCheck(checkServiceExact)
+
+ authorizer2.AddPolicy(biscuit.Policy{Queries: []biscuit.Rule{
+ {
+ Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},
+ Body: []biscuit.Predicate{},
+ },
+ }, Kind: biscuit.PolicyKindAllow})
+
+ if err := authorizer2.Authorize(); err != nil {
+ t.Errorf("Expected custom node role service checks to succeed: %v", err)
+ }
+}
diff --git a/internal/node/enroll.go b/internal/node/enroll.go
index 609c8559..1ef64106 100644
--- a/internal/node/enroll.go
+++ b/internal/node/enroll.go
@@ -159,3 +159,177 @@ func (n *SamNode) Enroll(ctx context.Context, hubURL string, jwt string) error {
logger.Info("Successfully enrolled via HTTP and stored identity and hub config.")
return nil
}
+
+// EnrollBootstrap enrolls the node with the control plane using a pre-shared bootstrap token.
+// If the enrollment status is PENDING, it polls the status endpoint until approved or rejected.
+func (n *SamNode) EnrollBootstrap(ctx context.Context, hubURL string, bootstrapToken string) error {
+ pubKey := n.Host.Peerstore().PubKey(n.Host.ID())
+ pubBytes, err := crypto.MarshalPublicKey(pubKey)
+ if err != nil {
+ return fmt.Errorf("failed to marshal public key: %w", err)
+ }
+
+ req := &api.BootstrapEnrollRequest{
+ BootstrapToken: bootstrapToken,
+ PeerId: n.Host.ID().String(),
+ PublicKey: pubBytes,
+ }
+ data, err := proto.Marshal(req)
+ if err != nil {
+ return fmt.Errorf("failed to marshal bootstrap enroll request: %w", err)
+ }
+
+ if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {
+ return fmt.Errorf("hub address must be an HTTP or HTTPS URL for enrollment: %s", hubURL)
+ }
+ url := hubURL + "/enroll"
+ logger.Infof("Enrolling via Bootstrap token at %s", url)
+
+ client := &http.Client{Timeout: 30 * time.Second}
+ httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))
+ if err != nil {
+ return fmt.Errorf("failed to create HTTP request: %w", err)
+ }
+ httpReq.Header.Set("Content-Type", "application/x-protobuf")
+
+ resp, err := client.Do(httpReq)
+ if err != nil {
+ return fmt.Errorf("HTTP request failed: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("enrollment failed with status %s: %s", resp.Status, string(body))
+ }
+
+ respData, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return fmt.Errorf("failed to read response body: %w", err)
+ }
+
+ enrollResp := &api.BootstrapEnrollResponse{}
+ if err := proto.Unmarshal(respData, enrollResp); err != nil {
+ return fmt.Errorf("failed to unmarshal response: %w", err)
+ }
+
+ if enrollResp.ErrorMessage != "" {
+ return fmt.Errorf("enrollment failed: %s", enrollResp.ErrorMessage)
+ }
+
+ if enrollResp.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING {
+ logger.Infof("Enrollment is pending approval. Polling status...")
+ statusReq := &api.EnrollmentStatusRequest{
+ PeerId: n.Host.ID().String(),
+ }
+ statusData, err := proto.Marshal(statusReq)
+ if err != nil {
+ return fmt.Errorf("failed to marshal status request: %w", err)
+ }
+
+ ticker := time.NewTicker(2 * time.Second)
+ defer ticker.Stop()
+
+ pollLoop:
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-ticker.C:
+ statusURL := hubURL + "/enroll/status"
+ hReq, err := http.NewRequestWithContext(ctx, "POST", statusURL, bytes.NewReader(statusData))
+ if err != nil {
+ return fmt.Errorf("failed to create status request: %w", err)
+ }
+ hReq.Header.Set("Content-Type", "application/x-protobuf")
+
+ hResp, err := client.Do(hReq)
+ if err != nil {
+ logger.Warnf("Failed to check enrollment status: %v", err)
+ continue
+ }
+
+ if hResp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(hResp.Body)
+ _ = hResp.Body.Close()
+ logger.Warnf("Status check returned status %s: %s", hResp.Status, string(body))
+ continue
+ }
+
+ hRespData, err := io.ReadAll(hResp.Body)
+ _ = hResp.Body.Close()
+ if err != nil {
+ logger.Warnf("Failed to read status response body: %v", err)
+ continue
+ }
+
+ statusResp := &api.BootstrapEnrollResponse{}
+ if err := proto.Unmarshal(hRespData, statusResp); err != nil {
+ logger.Warnf("Failed to unmarshal status response: %v", err)
+ continue
+ }
+
+ if statusResp.ErrorMessage != "" {
+ return fmt.Errorf("enrollment failed: %s", statusResp.ErrorMessage)
+ }
+
+ if statusResp.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
+ enrollResp = statusResp
+ break pollLoop
+ } else if statusResp.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED {
+ return fmt.Errorf("enrollment was rejected by administrator")
+ }
+ }
+ }
+ }
+
+ if len(enrollResp.BiscuitToken) == 0 {
+ return fmt.Errorf("received empty biscuit token from enrollment response")
+ }
+
+ if len(enrollResp.HubPublicKey) != ed25519.PublicKeySize {
+ return fmt.Errorf("received invalid hub public key size: %d bytes", len(enrollResp.HubPublicKey))
+ }
+
+ if err := n.Store.SaveIdentity(enrollResp.BiscuitToken); err != nil {
+ return fmt.Errorf("failed to save identity: %v", err)
+ }
+ n.SetIdentityCache(enrollResp.BiscuitToken)
+
+ if err := n.Store.SaveIdentityExpiration(enrollResp.Expiration); err != nil {
+ return fmt.Errorf("failed to save identity expiration: %v", err)
+ }
+
+ if err := n.Store.SaveHubConfig(enrollResp.HubPublicKey, enrollResp.HubAddresses); err != nil {
+ return fmt.Errorf("failed to save hub config: %v", err)
+ }
+
+ n.keysMu.Lock()
+ n.trustedKeys = append(n.trustedKeys, TrustedKey{Key: ed25519.PublicKey(enrollResp.HubPublicKey), ReceivedAt: time.Now()})
+ n.keysMu.Unlock()
+
+ // Connect and Auth to hub after enrollment to join the mesh
+ var lastAuthErr error
+ var authed bool
+ for _, addrStr := range enrollResp.HubAddresses {
+ addr, err := multiaddr.NewMultiaddr(addrStr)
+ if err != nil {
+ logger.Warnf("Failed to parse hub address: %v", err)
+ continue
+ }
+ if err := n.ConnectAndAuthWithHub(ctx, addr); err != nil {
+ logger.Warnf("Failed to connect and auth with hub: %v", err)
+ lastAuthErr = err
+ } else {
+ authed = true
+ break
+ }
+ }
+
+ if !authed {
+ return fmt.Errorf("failed to connect/auth with hub after bootstrap enrollment (last error: %v)", lastAuthErr)
+ }
+
+ logger.Info("Successfully enrolled via Bootstrap token and joined mesh.")
+ return nil
+}
diff --git a/internal/node/middleware_test.go b/internal/node/middleware_test.go
index 08ce1a7b..1995cf18 100644
--- a/internal/node/middleware_test.go
+++ b/internal/node/middleware_test.go
@@ -17,6 +17,7 @@ package node
import (
"context"
"crypto/ed25519"
+ "fmt"
"io"
"os"
@@ -28,6 +29,7 @@ import (
"github.com/biscuit-auth/biscuit-go/v2/parser"
"github.com/google/sam/api"
lru "github.com/hashicorp/golang-lru/v2"
+ golog "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
@@ -97,6 +99,7 @@ func TestAuthorize(t *testing.T) {
defer func() {
_ = store.Close()
}()
+ golog.SetAllLoggers(golog.LevelDebug)
// Create a biscuit token
pub, priv, err := ed25519.GenerateKey(nil)
@@ -128,8 +131,8 @@ func TestAuthorize(t *testing.T) {
// Add fact to match baseline rule
err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "granted_service_exact",
- IDs: []biscuit.Term{biscuit.String("system"), biscuit.String("/test/proto")},
+ Name: api.FactGrantedServiceExact,
+ IDs: []biscuit.Term{biscuit.String(api.SystemNamespace), biscuit.String("/test/proto")},
}})
if err != nil {
t.Fatal(err)
@@ -179,7 +182,7 @@ func TestBaselineRules(t *testing.T) {
{
name: "Baseline Rule 1: Exact Match",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- factStr := `granted_service_exact("mcp", "test_tool")`
+ factStr := fmt.Sprintf(`%s("mcp", "test_tool")`, api.FactGrantedServiceExact)
fact, _ := parser.FromStringFact(factStr)
_ = builder.AddAuthorityFact(fact)
},
@@ -190,7 +193,7 @@ func TestBaselineRules(t *testing.T) {
{
name: "Baseline Rule 2: Global Wildcard",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- factStr := `granted_service_all_types()`
+ factStr := fmt.Sprintf(`%s()`, api.FactGrantedServiceAllTypes)
fact, _ := parser.FromStringFact(factStr)
_ = builder.AddAuthorityFact(fact)
},
@@ -202,7 +205,7 @@ func TestBaselineRules(t *testing.T) {
{
name: "Baseline Rule 4: Type Wildcard",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- factStr := `granted_service_all("mcp")`
+ factStr := fmt.Sprintf(`%s("mcp")`, api.FactGrantedServiceAll)
fact, _ := parser.FromStringFact(factStr)
_ = builder.AddAuthorityFact(fact)
},
@@ -213,7 +216,7 @@ func TestBaselineRules(t *testing.T) {
{
name: "Baseline Rule Rejection: Type Wildcard does not allow other types",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- factStr := `granted_service_all("mcp")`
+ factStr := fmt.Sprintf(`%s("mcp")`, api.FactGrantedServiceAll)
fact, _ := parser.FromStringFact(factStr)
_ = builder.AddAuthorityFact(fact)
},
@@ -224,12 +227,12 @@ func TestBaselineRules(t *testing.T) {
{
name: "Baseline Replay Check Rejection: mismatched peer ID",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- factStr := `granted_service_exact("mcp", "test_tool")`
+ factStr := fmt.Sprintf(`%s("mcp", "test_tool")`, api.FactGrantedServiceExact)
fact, _ := parser.FromStringFact(factStr)
_ = builder.AddAuthorityFact(fact)
// deliberately add a different client_peer_id than the connection peer ID
err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "client_peer_id",
+ Name: api.FactClientPeerID,
IDs: []biscuit.Term{biscuit.String("different-peer")},
}})
},
@@ -300,7 +303,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {
{
name: "Case 1 (Happy Path)",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- fact, err := parser.FromStringFact(`granted_service_exact("system", "query_db")`)
+ fact, err := parser.FromStringFact(fmt.Sprintf(`%s(%q, "query_db")`, api.FactGrantedServiceExact, api.SystemNamespace))
if err != nil {
t.Fatal(err)
}
@@ -314,7 +317,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {
{
name: "Case 2 (Unauthorized Tool)",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- fact, err := parser.FromStringFact(`granted_service_exact("system", "query_db")`)
+ fact, err := parser.FromStringFact(fmt.Sprintf(`%s(%q, "query_db")`, api.FactGrantedServiceExact, api.SystemNamespace))
if err != nil {
t.Fatal(err)
}
@@ -328,7 +331,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {
{
name: "Case 3 (Wildcard Access)",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- fact, err := parser.FromStringFact(`granted_service_all_types()`)
+ fact, err := parser.FromStringFact(fmt.Sprintf(`%s()`, api.FactGrantedServiceAllTypes))
if err != nil {
t.Fatal(err)
}
@@ -342,7 +345,7 @@ func TestEnterprisePolicyEngine(t *testing.T) {
{
name: "Case 4 (Local Attenuation Override)",
mintToken: func(t *testing.T, builder biscuit.Builder) {
- fact1, err := parser.FromStringFact(`granted_service_all_types()`)
+ fact1, err := parser.FromStringFact(fmt.Sprintf(`%s()`, api.FactGrantedServiceAllTypes))
if err != nil {
t.Fatal(err)
}
@@ -371,10 +374,10 @@ attenuation:
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
builder := biscuit.NewBuilder(priv)
- _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}})
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: api.FactTargetUnrestricted}})
err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "node",
+ Name: api.FactNode,
IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
}})
if err != nil {
@@ -383,7 +386,7 @@ attenuation:
// Add client_peer_id for replay check
err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "client_peer_id",
+ Name: api.FactClientPeerID,
IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
}})
if err != nil {
@@ -589,7 +592,7 @@ func TestMiddlewareTargetChecks(t *testing.T) {
name: "Target Check: Allowed by User Fact",
mintToken: func(t *testing.T, builder biscuit.Builder) {
_ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "granted_target_exact",
+ Name: api.FactGrantedTargetExact,
IDs: []biscuit.Term{biscuit.String("user"), biscuit.String("bob")},
}})
},
@@ -605,7 +608,7 @@ func TestMiddlewareTargetChecks(t *testing.T) {
name: "Target Check: Rejected by wrong User Fact",
mintToken: func(t *testing.T, builder biscuit.Builder) {
_ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "granted_target_exact",
+ Name: api.FactGrantedTargetExact,
IDs: []biscuit.Term{biscuit.String("user"), biscuit.String("alice")},
}})
},
@@ -621,7 +624,7 @@ func TestMiddlewareTargetChecks(t *testing.T) {
name: "Target Check: Allowed by Group Fact",
mintToken: func(t *testing.T, builder biscuit.Builder) {
_ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "granted_target_exact",
+ Name: api.FactGrantedTargetExact,
IDs: []biscuit.Term{biscuit.String("group"), biscuit.String("eng")},
}})
},
@@ -640,15 +643,15 @@ func TestMiddlewareTargetChecks(t *testing.T) {
builder := biscuit.NewBuilder(priv)
// Required basic facts
_ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "client_peer_id",
+ Name: api.FactClientPeerID,
IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
}})
_ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "node",
+ Name: api.FactNode,
IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
}})
// Allow exact service
- factStr := `granted_service_exact("mcp", "test_tool")`
+ factStr := fmt.Sprintf(`%s("mcp", "test_tool")`, api.FactGrantedServiceExact)
fact, _ := parser.FromStringFact(factStr)
_ = builder.AddAuthorityFact(fact)
diff --git a/internal/node/node.go b/internal/node/node.go
index c12252df..fe458e2c 100644
--- a/internal/node/node.go
+++ b/internal/node/node.go
@@ -783,7 +783,7 @@ func (n *SamNode) performHubAuthHandshake(s network.Stream, biscuitBytes []byte,
return false, fmt.Errorf("%w: failed to verify router biscuit: %w", ErrFatalAuth, err)
}
- // Enforce role("router"), role("router-role") or role("bootstrap") inside the biscuit
+ // Enforce role("router") inside the biscuit
authorizer, err := b.Authorizer(trustedKeys[0])
if err != nil {
return false, fmt.Errorf("authorizer instantiation failed: %w", err)
@@ -795,11 +795,6 @@ func (n *SamNode) performHubAuthHandshake(s network.Stream, biscuitBytes []byte,
{Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(api.RoleRouter)}},
},
},
- {
- Body: []biscuit.Predicate{
- {Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(api.RoleBootstrap)}},
- },
- },
}})
authorizer.AddPolicy(api.AllowIfTruePolicy)
diff --git a/internal/node/static_service_test.go b/internal/node/static_service_test.go
index 1ffc29b3..d45bc46f 100644
--- a/internal/node/static_service_test.go
+++ b/internal/node/static_service_test.go
@@ -50,7 +50,7 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {
}})
_ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
Name: api.FactRole,
- IDs: []biscuit.Term{biscuit.String("router")},
+ IDs: []biscuit.Term{biscuit.String(api.RoleRouter)},
}})
_ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
Name: api.FactExpiration,
diff --git a/internal/router/config.go b/internal/router/config.go
index 4f693bd0..e8d45767 100644
--- a/internal/router/config.go
+++ b/internal/router/config.go
@@ -27,7 +27,9 @@ type Options struct {
KeysSyncInterval time.Duration
LeaseRenewInterval time.Duration
OIDCProvider string // For OIDC enrollment
- OIDCToken string // OIDC JWT or bootstrap token for enrollment
+ OIDCToken string // OIDC JWT token for enrollment
+ BootstrapToken string // Pre-shared bootstrap token for enrollment
+ BootstrapTokenPath string // File path containing pre-shared bootstrap token
JWTPath string // File path containing OIDC JWT token
KeysDBPath string // Path to save peer private key
AllowLoopback bool
diff --git a/internal/router/router.go b/internal/router/router.go
index 8919718a..485975f5 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -131,22 +131,36 @@ func (r *Router) Start() error {
return err
}
- // 2. Enroll with Control Plane
- if r.config.OIDCToken == "" && r.config.JWTPath != "" {
- tokenData, err := os.ReadFile(r.config.JWTPath)
+ if r.config.BootstrapToken == "" && r.config.BootstrapTokenPath != "" {
+ tokenData, err := os.ReadFile(r.config.BootstrapTokenPath)
if err != nil {
- return fmt.Errorf("failed to read JWT from path %s: %w", r.config.JWTPath, err)
+ return fmt.Errorf("failed to read bootstrap token from path %s: %w", r.config.BootstrapTokenPath, err)
}
- r.config.OIDCToken = strings.TrimSpace(string(tokenData))
+ r.config.BootstrapToken = strings.TrimSpace(string(tokenData))
}
- if r.config.OIDCToken != "" {
- logger.Infof("Enrolling router %s with Control Plane at %s...", peerID, r.config.ControlPlaneURL)
- if err := r.enroll(peerID); err != nil {
- return fmt.Errorf("failed router enrollment: %w", err)
+ if r.config.BootstrapToken != "" {
+ logger.Infof("Enrolling router %s with Control Plane at %s using Bootstrap Token...", peerID, r.config.ControlPlaneURL)
+ if err := r.enrollBootstrap(peerID); err != nil {
+ return fmt.Errorf("failed router bootstrap enrollment: %w", err)
}
} else {
- logger.Warn("Router started without OIDCToken/JWTPath. Enrollment bypassed. Expecting local keys sync.")
+ if r.config.OIDCToken == "" && r.config.JWTPath != "" {
+ tokenData, err := os.ReadFile(r.config.JWTPath)
+ if err != nil {
+ return fmt.Errorf("failed to read JWT from path %s: %w", r.config.JWTPath, err)
+ }
+ r.config.OIDCToken = strings.TrimSpace(string(tokenData))
+ }
+
+ if r.config.OIDCToken != "" {
+ logger.Infof("Enrolling router %s with Control Plane at %s using OIDC Token...", peerID, r.config.ControlPlaneURL)
+ if err := r.enroll(peerID); err != nil {
+ return fmt.Errorf("failed router enrollment: %w", err)
+ }
+ } else {
+ logger.Warn("Router started without OIDCToken or BootstrapToken. Enrollment bypassed. Expecting local keys sync.")
+ }
}
// 3. Initial Keys Sync
@@ -287,6 +301,123 @@ func (r *Router) enroll(peerID peer.ID) error {
return nil
}
+func (r *Router) enrollBootstrap(peerID peer.ID) error {
+ pubKey := r.privKey.GetPublic()
+ pubBytes, err := crypto.MarshalPublicKey(pubKey)
+ if err != nil {
+ return fmt.Errorf("failed to marshal router public key: %w", err)
+ }
+
+ req := &api.BootstrapEnrollRequest{
+ BootstrapToken: r.config.BootstrapToken,
+ PeerId: peerID.String(),
+ PublicKey: pubBytes,
+ }
+ data, err := proto.Marshal(req)
+ if err != nil {
+ return err
+ }
+
+ client := &http.Client{Timeout: 30 * time.Second}
+ resp, err := client.Post(r.config.ControlPlaneURL+"/enroll", "application/x-protobuf", bytes.NewReader(data))
+ if err != nil {
+ return err
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("bootstrap enrollment request response status %s: %s", resp.Status, string(body))
+ }
+
+ respData, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return err
+ }
+
+ enrollResp := &api.BootstrapEnrollResponse{}
+ if err := proto.Unmarshal(respData, enrollResp); err != nil {
+ return fmt.Errorf("failed to unmarshal response: %w", err)
+ }
+
+ if enrollResp.ErrorMessage != "" {
+ return fmt.Errorf("enrollment failed: %s", enrollResp.ErrorMessage)
+ }
+
+ if enrollResp.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING {
+ logger.Infof("Enrollment is pending approval. Polling status...")
+ statusReq := &api.EnrollmentStatusRequest{
+ PeerId: peerID.String(),
+ }
+ statusData, err := proto.Marshal(statusReq)
+ if err != nil {
+ return fmt.Errorf("failed to marshal status request: %w", err)
+ }
+
+ ticker := time.NewTicker(2 * time.Second)
+ defer ticker.Stop()
+
+ pollLoop:
+ for {
+ select {
+ case <-r.ctx.Done():
+ return r.ctx.Err()
+ case <-ticker.C:
+ statusResp, err := client.Post(r.config.ControlPlaneURL+"/enroll/status", "application/x-protobuf", bytes.NewReader(statusData))
+ if err != nil {
+ logger.Warnf("failed to poll enrollment status: %v", err)
+ continue
+ }
+
+ if statusResp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(statusResp.Body)
+ _ = statusResp.Body.Close()
+ logger.Warnf("status poll returned code %s: %s", statusResp.Status, string(body))
+ continue
+ }
+
+ statusBody, err := io.ReadAll(statusResp.Body)
+ _ = statusResp.Body.Close()
+ if err != nil {
+ logger.Warnf("failed to read status body: %v", err)
+ continue
+ }
+
+ pollResp := &api.BootstrapEnrollResponse{}
+ if err := proto.Unmarshal(statusBody, pollResp); err != nil {
+ logger.Warnf("failed to unmarshal poll response: %v", err)
+ continue
+ }
+
+ if pollResp.ErrorMessage != "" {
+ return fmt.Errorf("enrollment rejected: %s", pollResp.ErrorMessage)
+ }
+
+ if pollResp.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
+ enrollResp = pollResp
+ break pollLoop
+ }
+ if pollResp.Status == api.EnrollmentStatus_ENROLLMENT_STATUS_REJECTED {
+ return fmt.Errorf("enrollment rejected by administrator")
+ }
+ logger.Infof("Enrollment is still pending approval...")
+ }
+ }
+ }
+
+ if enrollResp.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED {
+ return fmt.Errorf("enrollment not approved (status: %v)", enrollResp.Status)
+ }
+
+ r.biscuitToken = enrollResp.BiscuitToken
+ r.keysMu.Lock()
+ r.trustedPublicKeys = []ed25519.PublicKey{enrollResp.HubPublicKey}
+ r.keysMu.Unlock()
+
+ logger.Infof("Router bootstrap enrollment approved! Biscuit received.")
+ return nil
+}
+
func (r *Router) syncKeys() error {
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get(r.config.ControlPlaneURL + "/keys")
@@ -600,11 +731,6 @@ func (r *Router) performMutualAuth(s network.Stream) error {
{Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(api.RoleRouter)}},
},
},
- {
- Body: []biscuit.Predicate{
- {Name: api.FactRole, IDs: []biscuit.Term{biscuit.String(api.RoleBootstrap)}},
- },
- },
}})
authorizer.AddPolicy(api.AllowIfTruePolicy)
diff --git a/internal/router/router_test.go b/internal/router/router_test.go
index 6db2084e..427c4caf 100644
--- a/internal/router/router_test.go
+++ b/internal/router/router_test.go
@@ -127,11 +127,11 @@ func setupControlPlane(t *testing.T, oidcIssuer string) (*controlplane.Server, s
policy := &api.PolicyConfig{
Version: "v1alpha1",
Bindings: []api.Binding{
- {Role: "router", Members: []string{"group:routers"}},
+ {Role: api.RoleRouter, Members: []string{"group:routers"}},
{Role: "user-role", Members: []string{"group:users"}},
},
Roles: map[string]api.RolePolicy{
- "router": {
+ api.RoleRouter: {
AllowedServices: []string{"*"},
AllowedTargets: []string{"*"},
},
diff --git a/internal/storage/sql_store.go b/internal/storage/sql_store.go
index a7b7cfd8..2f8264d2 100644
--- a/internal/storage/sql_store.go
+++ b/internal/storage/sql_store.go
@@ -75,6 +75,7 @@ func (s *SQLStore) isPostgres() bool {
func (s *SQLStore) initSchema() error {
var keyringSchema, nodesSchema, routersSchema, policiesSchema string
+ var bootstrapTokensSchema, enrollmentRequestsSchema string
if s.isPostgres() {
keyringSchema = `
@@ -106,6 +107,29 @@ func (s *SQLStore) initSchema() error {
content TEXT NOT NULL,
updated_at BIGINT NOT NULL
)`
+ bootstrapTokensSchema = `
+ CREATE TABLE IF NOT EXISTS bootstrap_tokens (
+ id VARCHAR(64) PRIMARY KEY,
+ token_hash VARCHAR(64) UNIQUE NOT NULL,
+ role VARCHAR(64) NOT NULL,
+ max_usages INT NOT NULL,
+ usages_count INT NOT NULL,
+ description TEXT,
+ created_at BIGINT NOT NULL,
+ expires_at BIGINT NOT NULL
+ )`
+ enrollmentRequestsSchema = `
+ CREATE TABLE IF NOT EXISTS enrollment_requests (
+ id VARCHAR(64) PRIMARY KEY,
+ peer_id VARCHAR(255) UNIQUE NOT NULL,
+ public_key BYTEA NOT NULL,
+ token_id VARCHAR(64) REFERENCES bootstrap_tokens(id),
+ status INT NOT NULL,
+ biscuit_token BYTEA,
+ created_at BIGINT NOT NULL,
+ resolved_at BIGINT,
+ resolved_by VARCHAR(255)
+ )`
} else {
keyringSchema = `
CREATE TABLE IF NOT EXISTS keyring (
@@ -136,9 +160,32 @@ func (s *SQLStore) initSchema() error {
content TEXT NOT NULL,
updated_at BIGINT NOT NULL
)`
+ bootstrapTokensSchema = `
+ CREATE TABLE IF NOT EXISTS bootstrap_tokens (
+ id TEXT PRIMARY KEY,
+ token_hash TEXT UNIQUE NOT NULL,
+ role TEXT NOT NULL,
+ max_usages INTEGER NOT NULL,
+ usages_count INTEGER NOT NULL,
+ description TEXT,
+ created_at BIGINT NOT NULL,
+ expires_at BIGINT NOT NULL
+ )`
+ enrollmentRequestsSchema = `
+ CREATE TABLE IF NOT EXISTS enrollment_requests (
+ id TEXT PRIMARY KEY,
+ peer_id TEXT UNIQUE NOT NULL,
+ public_key BLOB NOT NULL,
+ token_id TEXT REFERENCES bootstrap_tokens(id),
+ status INTEGER NOT NULL,
+ biscuit_token BLOB,
+ created_at BIGINT NOT NULL,
+ resolved_at BIGINT,
+ resolved_by TEXT
+ )`
}
- schemas := []string{keyringSchema, nodesSchema, routersSchema, policiesSchema}
+ schemas := []string{keyringSchema, nodesSchema, routersSchema, policiesSchema, bootstrapTokensSchema, enrollmentRequestsSchema}
for _, schema := range schemas {
if _, err := s.db.Exec(schema); err != nil {
return err
@@ -403,6 +450,177 @@ func (s *SQLStore) GetPolicy(ctx context.Context) (*api.PolicyConfig, error) {
return &policy, nil
}
+// SaveBootstrapToken persists a new bootstrap token.
+func (s *SQLStore) SaveBootstrapToken(ctx context.Context, token *BootstrapToken) error {
+ query := `INSERT INTO bootstrap_tokens (id, token_hash, role, max_usages, usages_count, description, created_at, expires_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
+ _, err := s.db.ExecContext(ctx, s.rebind(query),
+ token.ID,
+ token.TokenHash,
+ token.Role,
+ token.MaxUsages,
+ token.UsagesCount,
+ token.Description,
+ token.CreatedAt.Unix(),
+ token.ExpiresAt.Unix(),
+ )
+ if err != nil {
+ return fmt.Errorf("failed to save bootstrap token: %w", err)
+ }
+ return nil
+}
+
+// GetBootstrapToken retrieves a bootstrap token by its ID.
+func (s *SQLStore) GetBootstrapToken(ctx context.Context, id string) (*BootstrapToken, error) {
+ query := `SELECT id, token_hash, role, max_usages, usages_count, description, created_at, expires_at
+ FROM bootstrap_tokens WHERE id = ?`
+ var created, expires int64
+ var t BootstrapToken
+ err := s.db.QueryRowContext(ctx, s.rebind(query), id).Scan(
+ &t.ID,
+ &t.TokenHash,
+ &t.Role,
+ &t.MaxUsages,
+ &t.UsagesCount,
+ &t.Description,
+ &created,
+ &expires,
+ )
+ if err == sql.ErrNoRows {
+ return nil, ErrNotFound
+ } else if err != nil {
+ return nil, fmt.Errorf("failed to scan bootstrap token: %w", err)
+ }
+ t.CreatedAt = time.Unix(created, 0)
+ t.ExpiresAt = time.Unix(expires, 0)
+ return &t, nil
+}
+
+// IncrementBootstrapTokenUsage increments usage count.
+func (s *SQLStore) IncrementBootstrapTokenUsage(ctx context.Context, id string) error {
+ query := `UPDATE bootstrap_tokens SET usages_count = usages_count + 1 WHERE id = ?`
+ _, err := s.db.ExecContext(ctx, s.rebind(query), id)
+ if err != nil {
+ return fmt.Errorf("failed to increment usage: %w", err)
+ }
+ return nil
+}
+
+// CreateEnrollmentRequest saves a new pending request.
+func (s *SQLStore) CreateEnrollmentRequest(ctx context.Context, req *EnrollmentRequest) error {
+ query := `INSERT INTO enrollment_requests (id, peer_id, public_key, token_id, status, biscuit_token, created_at, resolved_at, resolved_by)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
+ var resAt sql.NullInt64
+ if req.ResolvedAt != nil {
+ resAt = sql.NullInt64{Int64: req.ResolvedAt.Unix(), Valid: true}
+ }
+ _, err := s.db.ExecContext(ctx, s.rebind(query),
+ req.ID,
+ req.PeerID,
+ req.PublicKey,
+ req.TokenID,
+ int(req.Status),
+ req.BiscuitToken,
+ req.CreatedAt.Unix(),
+ resAt,
+ req.ResolvedBy,
+ )
+ if err != nil {
+ return fmt.Errorf("failed to create enrollment request: %w", err)
+ }
+ return nil
+}
+
+// GetEnrollmentRequest retrieves request by PeerID.
+func (s *SQLStore) GetEnrollmentRequest(ctx context.Context, peerID string) (*EnrollmentRequest, error) {
+ query := `SELECT id, peer_id, public_key, token_id, status, biscuit_token, created_at, resolved_at, resolved_by
+ FROM enrollment_requests WHERE peer_id = ?`
+ return s.scanEnrollmentRequest(s.db.QueryRowContext(ctx, s.rebind(query), peerID))
+}
+
+// GetEnrollmentRequestByID retrieves request by UUID.
+func (s *SQLStore) GetEnrollmentRequestByID(ctx context.Context, id string) (*EnrollmentRequest, error) {
+ query := `SELECT id, peer_id, public_key, token_id, status, biscuit_token, created_at, resolved_at, resolved_by
+ FROM enrollment_requests WHERE id = ?`
+ return s.scanEnrollmentRequest(s.db.QueryRowContext(ctx, s.rebind(query), id))
+}
+
+type scannable interface {
+ Scan(dest ...any) error
+}
+
+func (s *SQLStore) scanEnrollmentRequest(row scannable) (*EnrollmentRequest, error) {
+ var created int64
+ var resAt sql.NullInt64
+ var statusVal int
+ var req EnrollmentRequest
+
+ err := row.Scan(
+ &req.ID,
+ &req.PeerID,
+ &req.PublicKey,
+ &req.TokenID,
+ &statusVal,
+ &req.BiscuitToken,
+ &created,
+ &resAt,
+ &req.ResolvedBy,
+ )
+ if err == sql.ErrNoRows {
+ return nil, ErrNotFound
+ } else if err != nil {
+ return nil, fmt.Errorf("failed to scan enrollment request: %w", err)
+ }
+
+ req.CreatedAt = time.Unix(created, 0)
+ req.Status = api.EnrollmentStatus(statusVal)
+ if resAt.Valid {
+ t := time.Unix(resAt.Int64, 0)
+ req.ResolvedAt = &t
+ }
+ return &req, nil
+}
+
+// ListEnrollmentRequests retrieves all requests.
+func (s *SQLStore) ListEnrollmentRequests(ctx context.Context) ([]EnrollmentRequest, error) {
+ query := `SELECT id, peer_id, public_key, token_id, status, biscuit_token, created_at, resolved_at, resolved_by
+ FROM enrollment_requests ORDER BY created_at DESC`
+ rows, err := s.db.QueryContext(ctx, s.rebind(query))
+ if err != nil {
+ return nil, fmt.Errorf("failed to query enrollment requests: %w", err)
+ }
+ defer func() { _ = rows.Close() }()
+
+ var reqs []EnrollmentRequest
+ for rows.Next() {
+ req, err := s.scanEnrollmentRequest(rows)
+ if err != nil {
+ return nil, err
+ }
+ reqs = append(reqs, *req)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return reqs, nil
+}
+
+// UpdateEnrollmentRequest updates status, timestamp and biscuit token.
+func (s *SQLStore) UpdateEnrollmentRequest(ctx context.Context, id string, status api.EnrollmentStatus, biscuit []byte, resolvedBy string) error {
+ query := `UPDATE enrollment_requests SET status = ?, biscuit_token = ?, resolved_at = ?, resolved_by = ? WHERE id = ?`
+ _, err := s.db.ExecContext(ctx, s.rebind(query),
+ int(status),
+ biscuit,
+ time.Now().Unix(),
+ resolvedBy,
+ id,
+ )
+ if err != nil {
+ return fmt.Errorf("failed to update enrollment request: %w", err)
+ }
+ return nil
+}
+
// Close implements Store.
func (s *SQLStore) Close() error {
return s.db.Close()
diff --git a/internal/storage/sql_store_test.go b/internal/storage/sql_store_test.go
index 8b9cb9c9..28a94274 100644
--- a/internal/storage/sql_store_test.go
+++ b/internal/storage/sql_store_test.go
@@ -343,3 +343,93 @@ func TestTimezoneComparison(t *testing.T) {
t.Fatalf("expected router %s, got %s", peerID, routers[0].PeerID)
}
}
+
+func TestBootstrapTokensAndEnrollmentRequestsOps(t *testing.T) {
+ store := newTestStore(t)
+ defer func() { _ = store.Close() }()
+
+ ctx := context.Background()
+
+ // 1. Test BootstrapToken Operations
+ tok := &BootstrapToken{
+ ID: "token-id-1",
+ TokenHash: "hash-1",
+ Role: "sam:role:router",
+ MaxUsages: 5,
+ UsagesCount: 0,
+ Description: "Router join token",
+ CreatedAt: time.Now().Truncate(time.Second),
+ ExpiresAt: time.Now().Add(24 * time.Hour).Truncate(time.Second),
+ }
+
+ if err := store.SaveBootstrapToken(ctx, tok); err != nil {
+ t.Fatalf("failed to save bootstrap token: %v", err)
+ }
+
+ ret, err := store.GetBootstrapToken(ctx, tok.ID)
+ if err != nil {
+ t.Fatalf("failed to get bootstrap token: %v", err)
+ }
+ if ret.TokenHash != tok.TokenHash || ret.Role != tok.Role || ret.MaxUsages != tok.MaxUsages {
+ t.Errorf("retrieved token mismatch: %+v", ret)
+ }
+
+ if err := store.IncrementBootstrapTokenUsage(ctx, tok.ID); err != nil {
+ t.Fatalf("failed to increment usage: %v", err)
+ }
+ ret2, _ := store.GetBootstrapToken(ctx, tok.ID)
+ if ret2.UsagesCount != 1 {
+ t.Errorf("expected usage count 1, got %d", ret2.UsagesCount)
+ }
+
+ // 2. Test EnrollmentRequest Operations
+ req := &EnrollmentRequest{
+ ID: "req-id-1",
+ PeerID: "peer-id-1",
+ PublicKey: []byte("my-public-key-bytes"),
+ TokenID: tok.ID,
+ Status: api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING,
+ BiscuitToken: nil,
+ CreatedAt: time.Now().Truncate(time.Second),
+ }
+
+ if err := store.CreateEnrollmentRequest(ctx, req); err != nil {
+ t.Fatalf("failed to create enrollment request: %v", err)
+ }
+
+ gotReq, err := store.GetEnrollmentRequest(ctx, req.PeerID)
+ if err != nil {
+ t.Fatalf("failed to get enrollment request by PeerID: %v", err)
+ }
+ if gotReq.ID != req.ID || gotReq.Status != req.Status || !bytes.Equal(gotReq.PublicKey, req.PublicKey) {
+ t.Errorf("retrieved request mismatch: %+v", gotReq)
+ }
+
+ gotReqByID, err := store.GetEnrollmentRequestByID(ctx, req.ID)
+ if err != nil {
+ t.Fatalf("failed to get enrollment request by ID: %v", err)
+ }
+ if gotReqByID.PeerID != req.PeerID {
+ t.Errorf("retrieved request by ID mismatch: %+v", gotReqByID)
+ }
+
+ list, err := store.ListEnrollmentRequests(ctx)
+ if err != nil {
+ t.Fatalf("failed to list enrollment requests: %v", err)
+ }
+ if len(list) != 1 || list[0].ID != req.ID {
+ t.Errorf("unexpected list size or content: %+v", list)
+ }
+
+ // 3. Test UpdateEnrollmentRequest
+ biscuitToken := []byte("signed-biscuit-token-bytes")
+ err = store.UpdateEnrollmentRequest(ctx, req.ID, api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED, biscuitToken, "admin-oidc")
+ if err != nil {
+ t.Fatalf("failed to update enrollment request: %v", err)
+ }
+
+ updatedReq, _ := store.GetEnrollmentRequestByID(ctx, req.ID)
+ if updatedReq.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_APPROVED || !bytes.Equal(updatedReq.BiscuitToken, biscuitToken) || updatedReq.ResolvedBy != "admin-oidc" || updatedReq.ResolvedAt == nil {
+ t.Errorf("updated request details mismatch: %+v", updatedReq)
+ }
+}
diff --git a/internal/storage/storage.go b/internal/storage/storage.go
index 36fd1f50..0383acd7 100644
--- a/internal/storage/storage.go
+++ b/internal/storage/storage.go
@@ -51,6 +51,31 @@ type EnrolledNode struct {
Banned bool
}
+// BootstrapToken represents a pre-shared token for node enrollment.
+type BootstrapToken struct {
+ ID string
+ TokenHash string
+ Role string
+ MaxUsages int
+ UsagesCount int
+ Description string
+ CreatedAt time.Time
+ ExpiresAt time.Time
+}
+
+// EnrollmentRequest represents a pending or resolved node registration request (CSR).
+type EnrollmentRequest struct {
+ ID string
+ PeerID string
+ PublicKey []byte
+ TokenID string
+ Status api.EnrollmentStatus
+ BiscuitToken []byte
+ CreatedAt time.Time
+ ResolvedAt *time.Time
+ ResolvedBy string
+}
+
// Store defines the persistent operations for the SAM control plane.
type Store interface {
// GetCurrentKey retrieves the active key pair for biscuit signing.
@@ -89,6 +114,30 @@ type Store interface {
// GetPolicy loads the mesh configurations.
GetPolicy(ctx context.Context) (*api.PolicyConfig, error)
+ // SaveBootstrapToken persists a new bootstrap token.
+ SaveBootstrapToken(ctx context.Context, token *BootstrapToken) error
+
+ // GetBootstrapToken retrieves a bootstrap token by its ID (sha256 hash).
+ GetBootstrapToken(ctx context.Context, id string) (*BootstrapToken, error)
+
+ // IncrementBootstrapTokenUsage increments the usage count of a token.
+ IncrementBootstrapTokenUsage(ctx context.Context, id string) error
+
+ // CreateEnrollmentRequest saves a new pending enrollment request.
+ CreateEnrollmentRequest(ctx context.Context, req *EnrollmentRequest) error
+
+ // GetEnrollmentRequest retrieves an enrollment request by PeerID.
+ GetEnrollmentRequest(ctx context.Context, peerID string) (*EnrollmentRequest, error)
+
+ // GetEnrollmentRequestByID retrieves an enrollment request by ID.
+ GetEnrollmentRequestByID(ctx context.Context, id string) (*EnrollmentRequest, error)
+
+ // ListEnrollmentRequests retrieves all enrollment requests.
+ ListEnrollmentRequests(ctx context.Context) ([]EnrollmentRequest, error)
+
+ // UpdateEnrollmentRequest updates status, resolved details, and stored Biscuit of a request.
+ UpdateEnrollmentRequest(ctx context.Context, id string, status api.EnrollmentStatus, biscuit []byte, resolvedBy string) error
+
// Close closes the underlying database connection.
Close() error
}
diff --git a/site/content/docs/manifests/sam-control-plane.yaml b/site/content/docs/manifests/sam-control-plane.yaml
index eb7bdc33..8c2c260d 100644
--- a/site/content/docs/manifests/sam-control-plane.yaml
+++ b/site/content/docs/manifests/sam-control-plane.yaml
@@ -92,7 +92,7 @@ data:
policies.yaml: |
version: "v1alpha1"
bindings:
- - members: ["system:authenticated"]
+ - members: ["sam:system:authenticated"]
role: "public-mesh"
roles:
public-mesh:
diff --git a/tests/e2e/fixtures/control-plane-router.yaml b/tests/e2e/fixtures/control-plane-router.yaml
index efb95a3d..13f64a16 100644
--- a/tests/e2e/fixtures/control-plane-router.yaml
+++ b/tests/e2e/fixtures/control-plane-router.yaml
@@ -137,6 +137,9 @@ spec:
- "--policy-file=/etc/sam/policy.yaml"
- "--insecure-skip-tls-verify"
- "--lease-duration=15s"
+ - "--admin-token=super-secret-admin-token"
+ - "--bootstrap-token=super-secret-bootstrap-token"
+ - "--auto-approve-enrollment"
- "--log-level=debug"
volumeMounts:
- name: config-volume
@@ -203,7 +206,7 @@ spec:
- "--external-addr=/dns4/sam-router/udp/4501/quic-v1"
- "--external-addr=/ip4/$(ROUTER_NODE_IP)/tcp/4501"
- "--external-addr=/ip4/$(ROUTER_NODE_IP)/udp/4501/quic-v1"
- - "--jwt-path=/var/run/secrets/tokens/sa-token"
+ - "--bootstrap-token-path=/var/run/secrets/tokens/sa-token"
- "--keys-path=/data/router.key"
- "--allow-loopback"
- "--lease-renew-interval=5s"
diff --git a/tests/e2e/fixtures/default-policy.yaml b/tests/e2e/fixtures/default-policy.yaml
index fc4385ad..38fbcbd3 100644
--- a/tests/e2e/fixtures/default-policy.yaml
+++ b/tests/e2e/fixtures/default-policy.yaml
@@ -1,6 +1,6 @@
version: v1alpha1
bindings:
- - members: ["system:authenticated"]
+ - members: ["sam:system:authenticated"]
role: admin
roles:
admin:
diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bash
index 432d189d..cddf6324 100644
--- a/tests/e2e/lib/container_mesh.bash
+++ b/tests/e2e/lib/container_mesh.bash
@@ -263,17 +263,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
local oidc_node_ip
oidc_node_ip=$(docker inspect -f "{{(index .NetworkSettings.Networks \"${MESH_NETWORK:-kind}\").IPAddress}}" "${oidc_node}")
- local router_token=""
- local i
- for ((i=0; i<15; i++)); do
- router_token=$(curl -s -d "client_id=router-client" http://${oidc_node_ip}:18080/token | jq -r .access_token || true)
- if [[ -n "${router_token}" && "${router_token}" != "null" ]]; then
- break
- fi
- sleep 0.5
- done
- [[ -n "${router_token}" && "${router_token}" != "null" ]]
-
+ local router_token="super-secret-bootstrap-token"
kubectl --context="${KUBECONTEXT}" create secret generic sam-router-token --from-literal=token="${router_token}" --dry-run=client -o yaml | kubectl --context="${KUBECONTEXT}" apply -f -
envsubst '$ISSUERS' < tests/e2e/fixtures/control-plane-router.yaml | kubectl --context="${KUBECONTEXT}" apply -f -
diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.go
index 5ace784a..48753146 100644
--- a/tests/integration/minimal_helpers_test.go
+++ b/tests/integration/minimal_helpers_test.go
@@ -615,11 +615,11 @@ func writePolicyWithRouter(t *testing.T, path string, yamlContent string) {
content = strings.ReplaceAll(content, "bindings: []", "bindings:")
content = strings.ReplaceAll(content, "roles: {}", "roles:")
- routerRole := ` router:
+ routerRole := fmt.Sprintf(` %s:
allowed_services: []
- allowed_targets: []`
- routerBinding := ` - role: router
- members: ["group:routers"]`
+ allowed_targets: []`, api.RoleRouter)
+ routerBinding := fmt.Sprintf(` - role: %s
+ members: ["group:routers"]`, api.RoleRouter)
if strings.Contains(content, "roles:") {
content = strings.Replace(content, "roles:", "roles:\n"+routerRole, 1)