Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
security: translate OIDC claims to Biscuit facts dynamically, reorganize token logic, and add specifications references
Antonio Ojea34e48f89ea64
diff --git a/api/constants.go b/api/constants.goindex c2603682..9c1f5442 100644--- a/api/constants.go+++ b/api/constants.go@@ -32,6 +32,28 @@ const (FactGroup = "group"FactRole = "role"FactUser = "user"+ FactEmail = "email"FactMCPServer = "allow_mcp_server"FactNetworkTarget = "allow_network_target")++// OIDCClaimToFact maps standard OIDC claims to their corresponding Biscuit facts.+//+// Specification References:+// - OIDC Claims: Standard JWT payload claims are defined in OpenID Connect Core 1.0 section 5.1:+// https://openid.net/specs/openid-connect-core-1_0.html#Claims+// - Biscuit Symbols / Facts: The Biscuit symbol table and fact specification is defined at:+// https://doc.biscuitsec.org/reference/specifications.html#symbol-table+//+// How to add a new translation:+// 1. Define a constant for the Biscuit fact name in the "Biscuit fact names" block above+// (e.g., FactMyNewClaim = "my_new_fact").+// 2. Add an entry to the OIDCClaimToFact map below (e.g., "my_oidc_claim": FactMyNewClaim).+// 3. Update TranslateClaimsToFacts in api/translation.go to handle parsing/type conversion+// for the new fact if it uses a custom format (e.g. integer, date, list).+// 4. Implement unit tests in api/translation_test.go covering the new mapping.+var OIDCClaimToFact = map[string]string{+ "sub": FactUser,+ "email": FactEmail,+ "groups": FactGroup,+}diff --git a/cmd/sam-hub/biscuit.go b/cmd/sam-hub/biscuit.gonew file mode 100644index 00000000..49463bfc--- /dev/null+++ b/cmd/sam-hub/biscuit.go@@ -0,0 +1,260 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package main++import (+ "fmt"+ "strings"+ "time"++ "github.com/biscuit-auth/biscuit-go/v2"+ "github.com/biscuit-auth/biscuit-go/v2/datalog"+ "github.com/biscuit-auth/biscuit-go/v2/parser"+ "github.com/coreos/go-oidc/v3/oidc"+ "github.com/golang-jwt/jwt/v5"+ "github.com/google/sam/api"+ "github.com/libp2p/go-libp2p/core/peer"+)++func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remotePeer peer.ID) ([]byte, error) {+ var oidcRoles []string+ if rolesAny, ok := claims["roles"].([]any); ok {+ for _, r := range rolesAny {+ if str, ok := r.(string); ok && str != "" {+ oidcRoles = append(oidcRoles, str)+ }+ }+ }++ var oidcGroups []string+ if groupsAny, ok := claims["groups"].([]any); ok {+ for _, g := range groupsAny {+ if str, ok := g.(string); ok && str != "" {+ oidcGroups = append(oidcGroups, str)+ }+ }+ }++ oidcSub, _ := claims["sub"].(string)++ // Resolve roles based on configured bindings and explicit OIDC roles+ resolvedRoles := make(map[string]bool)+ if h.Policy != nil {+ // 1. Map OIDC groups and users to roles via configured bindings (RBAC mapping)+ for _, b := range h.Policy.Bindings {+ if b.Group != "" {+ for _, cg := range oidcGroups {+ if b.Group == cg {+ resolvedRoles[b.Role] = true+ }+ }+ }+ if b.User != "" && oidcSub != "" {+ if b.User == oidcSub {+ resolvedRoles[b.Role] = true+ }+ }+ }++ // 2. Validate and accept pre-resolved OIDC roles directly if defined in policy (Zero-Trust check)+ for _, r := range oidcRoles {+ if _, exists := h.Policy.Roles[r]; exists {+ resolvedRoles[r] = true+ }+ }+ }++ builder := biscuit.NewBuilder(h.KeyRing.GetCurrentKey())++ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactExpiration,+ IDs: []biscuit.Term{biscuit.Date(token.Expiry)},+ }}); err != nil {+ return nil, fmt.Errorf("failed to add expiration fact: %w", err)+ }++ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactNode,+ IDs: []biscuit.Term{biscuit.String(remotePeer.String())},+ }}); err != nil {+ return nil, fmt.Errorf("failed to add node fact: %w", err)+ }++ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactClientPeerID,+ IDs: []biscuit.Term{biscuit.String(remotePeer.String())},+ }}); err != nil {+ return nil, fmt.Errorf("failed to add client_peer_id fact: %w", err)+ }++ // Dynamic claims to facts mapping using api.OIDCClaimToFact+ if err := translateClaimsToFacts(builder, claims); err != nil {+ return nil, err+ }++ // Assert resolved authorized roles in the token+ for role := range resolvedRoles {+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactRole,+ IDs: []biscuit.Term{biscuit.String(role)},+ }}); err != nil {+ return nil, fmt.Errorf("failed to add role fact: %w", err)+ }++ if h.Policy != nil {+ if rolePolicy, ok := h.Policy.Roles[role]; ok {+ for _, tool := range rolePolicy.MCP.AllowedServers {+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactMCPServer,+ IDs: []biscuit.Term{biscuit.String(tool)},+ }}); err != nil {+ logger.Errorw("Failed to add MCP tool fact to biscuit", "peer_id", remotePeer, "tool", tool, "error", err)+ }+ }+ for _, target := range rolePolicy.Network.AllowedTargets {+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: api.FactNetworkTarget,+ IDs: []biscuit.Term{biscuit.String(target)},+ }}); err != nil {+ logger.Errorw("Failed to add network target fact to biscuit", "peer_id", remotePeer, "target", target, "error", err)+ }+ }+ for _, customFact := range rolePolicy.CustomDatalog {+ trimmed := strings.TrimRight(strings.TrimSpace(customFact), ";")+ if trimmed == "" {+ continue+ }+ func() {+ defer func() {+ if r := recover(); r != nil {+ logger.Errorw("Panic parsing custom fact", "peer_id", remotePeer, "fact", trimmed, "recover", r)+ }+ }()+ fact, err := parser.FromStringFact(trimmed)+ if err != nil {+ logger.Errorw("Failed to parse custom fact", "peer_id", remotePeer, "fact", trimmed, "error", err)+ return+ }+ if err := builder.AddAuthorityFact(fact); err != nil {+ logger.Errorw("Failed to add custom fact to biscuit", "peer_id", remotePeer, "fact", trimmed, "error", err)+ }+ }()+ }+ }+ }+ }++ t, err := builder.Build()+ if err != nil {+ return nil, fmt.Errorf("failed to build biscuit: %w", err)+ }++ biscuitData, err := t.Serialize()+ if err != nil {+ return nil, fmt.Errorf("failed to serialize biscuit: %w", err)+ }++ return biscuitData, nil+}++func (h *Hub) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscuit.Biscuit, error) {+ b, err := biscuit.Unmarshal(biscuitData)+ if err != nil {+ return nil, fmt.Errorf("malformed biscuit: %w", err)+ }++ var authOpts []biscuit.AuthorizerOption+ if h.BiscuitTimeout > 0 {+ authOpts = append(authOpts, biscuit.WithWorldOptions(datalog.WithMaxDuration(h.BiscuitTimeout)))+ }++ keys := h.KeyRing.GetAllValidPublicKeys()+ var lastErr error+ for _, pubKey := range keys {+ authorizer, err := b.Authorizer(pubKey, authOpts...)+ if err != nil {+ lastErr = err+ continue+ }++ authorizer.AddFact(biscuit.Fact{+ Predicate: biscuit.Predicate{+ Name: "time",+ IDs: []biscuit.Term{biscuit.Date(time.Now())},+ },+ })++ timeCheck, err := parser.FromStringCheck(`check if time($time), expiration($exp), $time <= $exp`)+ if err != nil {+ lastErr = err+ continue+ }+ authorizer.AddCheck(timeCheck)++ rule, err := parser.FromStringPolicy("allow if true")+ if err != nil {+ lastErr = err+ continue+ }+ authorizer.AddPolicy(rule)++ if err := authorizer.Authorize(); err == nil {+ return b, nil+ } else {+ lastErr = err+ }+ }++ return nil, fmt.Errorf("no valid key found for verification: %v", lastErr)+}++func translateClaimsToFacts(builder biscuit.Builder, claims map[string]any) error {+ for claimKey, factName := range api.OIDCClaimToFact {+ val, ok := claims[claimKey]+ if !ok || val == nil {+ continue+ }+ switch factName {+ case api.FactUser, api.FactEmail:+ if strVal, ok := val.(string); ok && strVal != "" {+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: factName,+ IDs: []biscuit.Term{biscuit.String(strVal)},+ }}); err != nil {+ return fmt.Errorf("failed to add %s fact: %w", factName, err)+ }+ }+ case api.FactGroup:+ if sliceVal, ok := val.([]any); ok {+ seen := make(map[string]bool)+ for _, item := range sliceVal {+ if strItem, ok := item.(string); ok && strItem != "" {+ if seen[strItem] {+ continue+ }+ seen[strItem] = true+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{+ Name: factName,+ IDs: []biscuit.Term{biscuit.String(strItem)},+ }}); err != nil {+ return fmt.Errorf("failed to add %s fact: %w", factName, err)+ }+ }+ }+ }+ }+ }+ return nil+}diff --git a/cmd/sam-hub/biscuit_test.go b/cmd/sam-hub/biscuit_test.gonew file mode 100644index 00000000..10a4eb99--- /dev/null+++ b/cmd/sam-hub/biscuit_test.go@@ -0,0 +1,394 @@+// Copyright 2026 Google LLC+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package main++import (+ "path/filepath"+ "testing"+ "time"++ "github.com/biscuit-auth/biscuit-go/v2"+ "github.com/coreos/go-oidc/v3/oidc"+ "github.com/golang-jwt/jwt/v5"+ "github.com/google/sam/api"+ "github.com/libp2p/go-libp2p/core/crypto"+ "github.com/libp2p/go-libp2p/core/peer"+)++func TestMintBiscuitToken(t *testing.T) {+ dir := t.TempDir()+ dbPath := filepath.Join(dir, "test.db")++ kr, err := NewKeyRing(dbPath, 24*time.Hour, nil)+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = kr.Close() }()++ hub := &Hub{+ KeyRing: kr,+ Policy: &api.PolicyConfig{+ Bindings: []api.Binding{+ {+ Group: "system:serviceaccounts:sam-canary",+ Role: "canary-role",+ },+ {+ User: "system:serviceaccount:sam-canary:sam-node-sa",+ Role: "canary-role",+ },+ },+ Roles: map[string]api.RolePolicy{+ "admin": {+ MCP: api.MCPPolicy{+ AllowedServers: []string{"read", "write"},+ },+ Network: api.NetworkPolicy{+ AllowedTargets: []string{"target1"},+ },+ },+ "canary-role": {+ MCP: api.MCPPolicy{+ AllowedServers: []string{"/sam/mcp/1.0.0"},+ },+ },+ },+ },+ }++ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)+ if err != nil {+ t.Fatal(err)+ }+ dummyPeer, err := peer.IDFromPrivateKey(priv)+ if err != nil {+ t.Fatal(err)+ }++ token := &oidc.IDToken{+ Expiry: time.Now().Add(1 * time.Hour),+ }++ // Case 1: Direct OIDC role (valid)+ claims1 := jwt.MapClaims{+ "roles": []any{"admin"},+ }+ biscuitData1, err := hub.mintBiscuitToken(claims1, token, dummyPeer)+ if err != nil {+ t.Fatal(err)+ }+ if len(biscuitData1) == 0 {+ t.Error("Expected non-empty biscuit data for direct role")+ }++ b1, err := biscuit.Unmarshal(biscuitData1)+ if err != nil {+ t.Fatal(err)+ }+ authorizer1, err := b1.Authorizer(kr.GetCurrentPublicKey())+ if err != nil {+ t.Fatal(err)+ }+ rule1 := biscuit.Policy{Queries: []biscuit.Rule{+ {+ Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},+ Body: []biscuit.Predicate{+ {Name: "role", IDs: []biscuit.Term{biscuit.String("admin")}},+ },+ },+ }, Kind: biscuit.PolicyKindAllow}+ authorizer1.AddPolicy(rule1)+ if err := authorizer1.Authorize(); err != nil {+ t.Errorf("Expected direct role 'admin' to be authorized: %v", err)+ }++ // Case 2: OIDC group claim mapped to role via bindings+ claims2 := jwt.MapClaims{+ "groups": []any{"system:serviceaccounts:sam-canary"},+ }+ biscuitData2, err := hub.mintBiscuitToken(claims2, token, dummyPeer)+ if err != nil {+ t.Fatal(err)+ }+ if len(biscuitData2) == 0 {+ t.Error("Expected non-empty biscuit data for mapped group")+ }++ b2, err := biscuit.Unmarshal(biscuitData2)+ if err != nil {+ t.Fatal(err)+ }+ authorizer2, err := b2.Authorizer(kr.GetCurrentPublicKey())+ if err != nil {+ t.Fatal(err)+ }+ rule2 := biscuit.Policy{Queries: []biscuit.Rule{+ {+ Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},+ Body: []biscuit.Predicate{+ {Name: "role", IDs: []biscuit.Term{biscuit.String("canary-role")}},+ },+ },+ }, Kind: biscuit.PolicyKindAllow}+ authorizer2.AddPolicy(rule2)+ if err := authorizer2.Authorize(); err != nil {+ t.Errorf("Expected mapped role 'canary-role' to be authorized: %v", err)+ }++ // Case 3: Unmapped OIDC group and undefined direct role+ claims3 := jwt.MapClaims{+ "groups": []any{"unknown-group"},+ "roles": []any{"undefined-role"},+ }+ biscuitData3, err := hub.mintBiscuitToken(claims3, token, dummyPeer)+ if err != nil {+ t.Fatal(err)+ }+ b3, err := biscuit.Unmarshal(biscuitData3)+ if err != nil {+ t.Fatal(err)+ }+ authorizer3, err := b3.Authorizer(kr.GetCurrentPublicKey())+ if err != nil {+ t.Fatal(err)+ }+ // Verify no role matches+ rule3 := biscuit.Policy{Queries: []biscuit.Rule{+ {+ Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},+ Body: []biscuit.Predicate{+ {Name: "role", IDs: []biscuit.Term{biscuit.Variable("any_role")}},+ },+ },+ }, 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")+ }++ // Case 4: GKE Workload Identity projected token (no groups claim, sub-based mapping)+ claims4 := jwt.MapClaims{+ "sub": "system:serviceaccount:sam-canary:sam-node-sa",+ }+ biscuitData4, err := hub.mintBiscuitToken(claims4, token, dummyPeer)+ if err != nil {+ t.Fatal(err)+ }+ b4, err := biscuit.Unmarshal(biscuitData4)+ if err != nil {+ t.Fatal(err)+ }+ authorizer4, err := b4.Authorizer(kr.GetCurrentPublicKey())+ if err != nil {+ t.Fatal(err)+ }+ // Verify that it mapped the derived group "system:serviceaccounts:sam-canary" to "canary-role"+ rule4 := biscuit.Policy{Queries: []biscuit.Rule{+ {+ Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},+ Body: []biscuit.Predicate{+ {Name: "role", IDs: []biscuit.Term{biscuit.String("canary-role")}},+ },+ },+ }, Kind: biscuit.PolicyKindAllow}+ authorizer4.AddPolicy(rule4)+ if err := authorizer4.Authorize(); err != nil {+ t.Errorf("Expected sub-derived role 'canary-role' to be authorized: %v", err)+ }+}++func TestVerifyBiscuit_Expiration(t *testing.T) {+ dir := t.TempDir()+ dbPath := filepath.Join(dir, "test.db")++ kr, err := NewKeyRing(dbPath, 24*time.Hour, nil)+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = kr.Close() }()++ hub := &Hub{+ KeyRing: kr,+ Policy: &api.PolicyConfig{},+ BiscuitTimeout: 500 * time.Millisecond,+ }++ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)+ if err != nil {+ t.Fatal(err)+ }+ dummyPeer, err := peer.IDFromPrivateKey(priv)+ if err != nil {+ t.Fatal(err)+ }++ tests := []struct {+ name string+ expiry time.Time+ expectError bool+ }{+ {+ name: "Valid unexpired token",+ expiry: time.Now().Add(1 * time.Hour),+ expectError: false,+ },+ {+ name: "Expired token",+ expiry: time.Now().Add(-1 * time.Hour),+ expectError: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ token := &oidc.IDToken{+ Expiry: tt.expiry,+ }+ claims := jwt.MapClaims{+ "roles": []any{"admin"},+ }++ biscuitData, err := hub.mintBiscuitToken(claims, token, dummyPeer)+ if err != nil {+ t.Fatalf("mintBiscuitToken failed: %v", err)+ }++ _, err = hub.verifyBiscuit(biscuitData, dummyPeer)+ if tt.expectError && err == nil {+ t.Errorf("Expected error due to expiration, got nil")+ }+ if !tt.expectError && err != nil {+ t.Errorf("Expected no error, got: %v", err)+ }+ })+ }+}++func TestMintBiscuitToken_ClaimsTranslation(t *testing.T) {+ dir := t.TempDir()+ dbPath := filepath.Join(dir, "test.db")++ kr, err := NewKeyRing(dbPath, 24*time.Hour, nil)+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = kr.Close() }()++ hub := &Hub{+ KeyRing: kr,+ Policy: &api.PolicyConfig{+ Bindings: []api.Binding{+ {+ Group: "engineering",+ Role: "developer-role",+ },+ },+ Roles: map[string]api.RolePolicy{+ "developer-role": {+ MCP: api.MCPPolicy{+ AllowedServers: []string{"git-helper"},+ },+ },+ },+ },+ }++ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)+ if err != nil {+ t.Fatal(err)+ }+ dummyPeer, err := peer.IDFromPrivateKey(priv)+ if err != nil {+ t.Fatal(err)+ }++ token := &oidc.IDToken{+ Expiry: time.Now().Add(1 * time.Hour),+ }++ claims := jwt.MapClaims{+ "sub": "user-12345",+ "email": "[email protected]",+ "groups": []any{"beta-testers", "engineering"},+ }++ biscuitData, err := hub.mintBiscuitToken(claims, token, dummyPeer)+ if err != nil {+ t.Fatalf("Failed to mint biscuit: %v", err)+ }++ b, err := biscuit.Unmarshal(biscuitData)+ if err != nil {+ t.Fatalf("Failed to unmarshal biscuit: %v", err)+ }++ authorizer, err := b.Authorizer(kr.GetCurrentPublicKey())+ if err != nil {+ t.Fatalf("Failed to get authorizer: %v", err)+ }++ // Verify user("user-12345") fact is present+ checkUser := biscuit.Check{Queries: []biscuit.Rule{+ {+ Body: []biscuit.Predicate{+ {Name: "user", IDs: []biscuit.Term{biscuit.String("user-12345")}},+ },+ },+ }}+ authorizer.AddCheck(checkUser)++ // Verify email("[email protected]") fact is present+ checkEmail := biscuit.Check{Queries: []biscuit.Rule{+ {+ Body: []biscuit.Predicate{+ {Name: "email", IDs: []biscuit.Term{biscuit.String("[email protected]")}},+ },+ },+ }}+ authorizer.AddCheck(checkEmail)++ // Verify group("beta-testers") fact is present+ checkGroupBeta := biscuit.Check{Queries: []biscuit.Rule{+ {+ Body: []biscuit.Predicate{+ {Name: "group", IDs: []biscuit.Term{biscuit.String("beta-testers")}},+ },+ },+ }}+ authorizer.AddCheck(checkGroupBeta)++ // Verify group("engineering") fact is present+ checkGroupEng := biscuit.Check{Queries: []biscuit.Rule{+ {+ Body: []biscuit.Predicate{+ {Name: "group", IDs: []biscuit.Term{biscuit.String("engineering")}},+ },+ },+ }}+ authorizer.AddCheck(checkGroupEng)++ // To authorize, we also need to allow since checks run in authorizer.+ // We will add an allow policy that matches anything+ 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("Authorization/Checks failed: %v\nWorld:\n%s", err, authorizer.PrintWorld())+ }+}diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.goindex e3e84263..15c93507 100644--- a/cmd/sam-hub/main.go+++ b/cmd/sam-hub/main.go@@ -39,8 +39,6 @@ import ("time""github.com/biscuit-auth/biscuit-go/v2"- "github.com/biscuit-auth/biscuit-go/v2/datalog"- "github.com/biscuit-auth/biscuit-go/v2/parser""github.com/coreos/go-oidc/v3/oidc""github.com/golang-jwt/jwt/v5""github.com/google/sam/api"@@ -376,166 +374,6 @@ func (h *Hub) parseAndVerifyJWT(ctx context.Context, jwtStr string, allowedAudiereturn claims, token, nil}-func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remotePeer peer.ID) ([]byte, error) {- var oidcRoles []string- if rolesAny, ok := claims["roles"].([]any); ok {- for _, r := range rolesAny {- if str, ok := r.(string); ok && str != "" {- oidcRoles = append(oidcRoles, str)- }- }- }-- var oidcGroups []string- if groupsAny, ok := claims["groups"].([]any); ok {- for _, g := range groupsAny {- if str, ok := g.(string); ok && str != "" {- oidcGroups = append(oidcGroups, str)- }- }- }-- oidcSub, _ := claims["sub"].(string)-- // Resolve roles based on configured bindings and explicit OIDC roles- resolvedRoles := make(map[string]bool)- if h.Policy != nil {- // 1. Map OIDC groups and users to roles via configured bindings (RBAC mapping)- for _, b := range h.Policy.Bindings {- if b.Group != "" {- for _, cg := range oidcGroups {- if b.Group == cg {- resolvedRoles[b.Role] = true- }- }- }- if b.User != "" && oidcSub != "" {- if b.User == oidcSub {- resolvedRoles[b.Role] = true- }- }- }-- // 2. Validate and accept pre-resolved OIDC roles directly if defined in policy (Zero-Trust check)- for _, r := range oidcRoles {- if _, exists := h.Policy.Roles[r]; exists {- resolvedRoles[r] = true- }- }- }-- builder := biscuit.NewBuilder(h.KeyRing.GetCurrentKey())-- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactExpiration,- IDs: []biscuit.Term{biscuit.Date(token.Expiry)},- }}); err != nil {- return nil, fmt.Errorf("failed to add expiration fact: %w", err)- }-- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactNode,- IDs: []biscuit.Term{biscuit.String(remotePeer.String())},- }}); err != nil {- return nil, fmt.Errorf("failed to add node fact: %w", err)- }-- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactClientPeerID,- IDs: []biscuit.Term{biscuit.String(remotePeer.String())},- }}); err != nil {- return nil, fmt.Errorf("failed to add client_peer_id fact: %w", err)- }-- if oidcSub != "" {- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactUser,- IDs: []biscuit.Term{biscuit.String(oidcSub)},- }}); err != nil {- return nil, fmt.Errorf("failed to add user fact: %w", err)- }- }-- // Assert original OIDC groups in the token (semantic audit trail)- seenGroups := make(map[string]bool)- for _, cg := range oidcGroups {- if seenGroups[cg] {- continue- }- seenGroups[cg] = true- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactGroup,- IDs: []biscuit.Term{biscuit.String(cg)},- }}); err != nil {- return nil, fmt.Errorf("failed to add group fact: %w", err)- }- }-- // Assert resolved authorized roles in the token- for role := range resolvedRoles {- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactRole,- IDs: []biscuit.Term{biscuit.String(role)},- }}); err != nil {- return nil, fmt.Errorf("failed to add role fact: %w", err)- }-- if h.Policy != nil {- if rolePolicy, ok := h.Policy.Roles[role]; ok {- for _, tool := range rolePolicy.MCP.AllowedServers {- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactMCPServer,- IDs: []biscuit.Term{biscuit.String(tool)},- }}); err != nil {- logger.Errorw("Failed to add MCP tool fact to biscuit", "peer_id", remotePeer, "tool", tool, "error", err)- }- }- for _, target := range rolePolicy.Network.AllowedTargets {- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{- Name: api.FactNetworkTarget,- IDs: []biscuit.Term{biscuit.String(target)},- }}); err != nil {- logger.Errorw("Failed to add network target fact to biscuit", "peer_id", remotePeer, "target", target, "error", err)- }- }- for _, customFact := range rolePolicy.CustomDatalog {- trimmed := strings.TrimRight(strings.TrimSpace(customFact), ";")- if trimmed == "" {- continue- }- func() {- defer func() {- if r := recover(); r != nil {- logger.Errorw("Panic parsing custom fact", "peer_id", remotePeer, "fact", trimmed, "recover", r)- }- }()- fact, err := parser.FromStringFact(trimmed)- if err != nil {- logger.Errorw("Failed to parse custom fact", "peer_id", remotePeer, "fact", trimmed, "error", err)- return- }- if err := builder.AddAuthorityFact(fact); err != nil {- logger.Errorw("Failed to add custom fact to biscuit", "peer_id", remotePeer, "fact", trimmed, "error", err)- }- }()- }- }- }- }-- t, err := builder.Build()- if err != nil {- return nil, fmt.Errorf("failed to build biscuit: %w", err)- }-- biscuitData, err := t.Serialize()- if err != nil {- return nil, fmt.Errorf("failed to serialize biscuit: %w", err)- }-- return biscuitData, nil-}-// startWatchdog periodically checks for peers that have connected but not completed OIDC// authentication within the grace period, and evicts them from the network.@@ -852,57 +690,6 @@ func isLoopbackOrLinkLocal(addr multiaddr.Multiaddr) bool {return false}-func (h *Hub) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscuit.Biscuit, error) {- b, err := biscuit.Unmarshal(biscuitData)- if err != nil {- return nil, fmt.Errorf("malformed biscuit: %w", err)- }-- var authOpts []biscuit.AuthorizerOption- if h.BiscuitTimeout > 0 {- authOpts = append(authOpts, biscuit.WithWorldOptions(datalog.WithMaxDuration(h.BiscuitTimeout)))- }-- keys := h.KeyRing.GetAllValidPublicKeys()- var lastErr error- for _, pubKey := range keys {- authorizer, err := b.Authorizer(pubKey, authOpts...)- if err != nil {- lastErr = err- continue- }-- authorizer.AddFact(biscuit.Fact{- Predicate: biscuit.Predicate{- Name: "time",- IDs: []biscuit.Term{biscuit.Date(time.Now())},- },- })-- timeCheck, err := parser.FromStringCheck(`check if time($time), expiration($exp), $time <= $exp`)- if err != nil {- lastErr = err- continue- }- authorizer.AddCheck(timeCheck)-- rule, err := parser.FromStringPolicy("allow if true")- if err != nil {- lastErr = err- continue- }- authorizer.AddPolicy(rule)-- if err := authorizer.Authorize(); err == nil {- return b, nil- } else {- lastErr = err- }- }-- return nil, fmt.Errorf("no valid key found for verification: %v", lastErr)-}-func (h *Hub) HandleAuthHandshake(s network.Stream) {defer func() {if err := s.Close(); err != nil {diff --git a/cmd/sam-hub/main_test.go b/cmd/sam-hub/main_test.goindex 85652f05..dcf48a7e 100644--- a/cmd/sam-hub/main_test.go+++ b/cmd/sam-hub/main_test.go@@ -22,194 +22,12 @@ import ("testing""time"- "github.com/biscuit-auth/biscuit-go/v2"- "github.com/coreos/go-oidc/v3/oidc"- "github.com/golang-jwt/jwt/v5""github.com/google/sam/api""github.com/libp2p/go-libp2p""github.com/libp2p/go-libp2p/core/crypto"- "github.com/libp2p/go-libp2p/core/peer""google.golang.org/protobuf/proto")-func TestMintBiscuitToken(t *testing.T) {- dir := t.TempDir()- dbPath := filepath.Join(dir, "test.db")-- kr, err := NewKeyRing(dbPath, 24*time.Hour, nil)- if err != nil {- t.Fatal(err)- }- defer func() { _ = kr.Close() }()-- hub := &Hub{- KeyRing: kr,- Policy: &api.PolicyConfig{- Bindings: []api.Binding{- {- Group: "system:serviceaccounts:sam-canary",- Role: "canary-role",- },- {- User: "system:serviceaccount:sam-canary:sam-node-sa",- Role: "canary-role",- },- },- Roles: map[string]api.RolePolicy{- "admin": {- MCP: api.MCPPolicy{- AllowedServers: []string{"read", "write"},- },- Network: api.NetworkPolicy{- AllowedTargets: []string{"target1"},- },- },- "canary-role": {- MCP: api.MCPPolicy{- AllowedServers: []string{"/sam/mcp/1.0.0"},- },- },- },- },- }-- priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)- if err != nil {- t.Fatal(err)- }- dummyPeer, err := peer.IDFromPrivateKey(priv)- if err != nil {- t.Fatal(err)- }-- token := &oidc.IDToken{- Expiry: time.Now().Add(1 * time.Hour),- }-- // Case 1: Direct OIDC role (valid)- claims1 := jwt.MapClaims{- "roles": []any{"admin"},- }- biscuitData1, err := hub.mintBiscuitToken(claims1, token, dummyPeer)- if err != nil {- t.Fatal(err)- }- if len(biscuitData1) == 0 {- t.Error("Expected non-empty biscuit data for direct role")- }-- b1, err := biscuit.Unmarshal(biscuitData1)- if err != nil {- t.Fatal(err)- }- authorizer1, err := b1.Authorizer(kr.GetCurrentPublicKey())- if err != nil {- t.Fatal(err)- }- rule1 := biscuit.Policy{Queries: []biscuit.Rule{- {- Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},- Body: []biscuit.Predicate{- {Name: "role", IDs: []biscuit.Term{biscuit.String("admin")}},- },- },- }, Kind: biscuit.PolicyKindAllow}- authorizer1.AddPolicy(rule1)- if err := authorizer1.Authorize(); err != nil {- t.Errorf("Expected direct role 'admin' to be authorized: %v", err)- }-- // Case 2: OIDC group claim mapped to role via bindings- claims2 := jwt.MapClaims{- "groups": []any{"system:serviceaccounts:sam-canary"},- }- biscuitData2, err := hub.mintBiscuitToken(claims2, token, dummyPeer)- if err != nil {- t.Fatal(err)- }- if len(biscuitData2) == 0 {- t.Error("Expected non-empty biscuit data for mapped group")- }-- b2, err := biscuit.Unmarshal(biscuitData2)- if err != nil {- t.Fatal(err)- }- authorizer2, err := b2.Authorizer(kr.GetCurrentPublicKey())- if err != nil {- t.Fatal(err)- }- rule2 := biscuit.Policy{Queries: []biscuit.Rule{- {- Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},- Body: []biscuit.Predicate{- {Name: "role", IDs: []biscuit.Term{biscuit.String("canary-role")}},- },- },- }, Kind: biscuit.PolicyKindAllow}- authorizer2.AddPolicy(rule2)- if err := authorizer2.Authorize(); err != nil {- t.Errorf("Expected mapped role 'canary-role' to be authorized: %v", err)- }-- // Case 3: Unmapped OIDC group and undefined direct role- claims3 := jwt.MapClaims{- "groups": []any{"unknown-group"},- "roles": []any{"undefined-role"},- }- biscuitData3, err := hub.mintBiscuitToken(claims3, token, dummyPeer)- if err != nil {- t.Fatal(err)- }- b3, err := biscuit.Unmarshal(biscuitData3)- if err != nil {- t.Fatal(err)- }- authorizer3, err := b3.Authorizer(kr.GetCurrentPublicKey())- if err != nil {- t.Fatal(err)- }- // Verify no role matches- rule3 := biscuit.Policy{Queries: []biscuit.Rule{- {- Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},- Body: []biscuit.Predicate{- {Name: "role", IDs: []biscuit.Term{biscuit.Variable("any_role")}},- },- },- }, Kind: biscuit.PolicyKindAllow}- authorizer3.AddPolicy(rule3)- // Case 4: GKE Workload Identity projected token (no groups claim, sub-based mapping)- claims4 := jwt.MapClaims{- "sub": "system:serviceaccount:sam-canary:sam-node-sa",- }- biscuitData4, err := hub.mintBiscuitToken(claims4, token, dummyPeer)- if err != nil {- t.Fatal(err)- }- b4, err := biscuit.Unmarshal(biscuitData4)- if err != nil {- t.Fatal(err)- }- authorizer4, err := b4.Authorizer(kr.GetCurrentPublicKey())- if err != nil {- t.Fatal(err)- }- // Verify that it mapped the derived group "system:serviceaccounts:sam-canary" to "canary-role"- rule4 := biscuit.Policy{Queries: []biscuit.Rule{- {- Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},- Body: []biscuit.Predicate{- {Name: "role", IDs: []biscuit.Term{biscuit.String("canary-role")}},- },- },- }, Kind: biscuit.PolicyKindAllow}- authorizer4.AddPolicy(rule4)- if err := authorizer4.Authorize(); err != nil {- t.Errorf("Expected sub-derived role 'canary-role' to be authorized: %v", err)- }-}-func TestHandleInfoHTTP(t *testing.T) {dir := t.TempDir()dbPath := filepath.Join(dir, "test.db")@@ -270,70 +88,3 @@ func TestHandleInfoHTTP(t *testing.T) {t.Errorf("Expected audience 'test-audience-1', got %q", info.Audience)}}--func TestVerifyBiscuit_Expiration(t *testing.T) {- dir := t.TempDir()- dbPath := filepath.Join(dir, "test.db")-- kr, err := NewKeyRing(dbPath, 24*time.Hour, nil)- if err != nil {- t.Fatal(err)- }- defer func() { _ = kr.Close() }()-- hub := &Hub{- KeyRing: kr,- Policy: &api.PolicyConfig{},- BiscuitTimeout: 500 * time.Millisecond,- }-- priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)- if err != nil {- t.Fatal(err)- }- dummyPeer, err := peer.IDFromPrivateKey(priv)- if err != nil {- t.Fatal(err)- }-- tests := []struct {- name string- expiry time.Time- expectError bool- }{- {- name: "Valid unexpired token",- expiry: time.Now().Add(1 * time.Hour),- expectError: false,- },- {- name: "Expired token",- expiry: time.Now().Add(-1 * time.Hour),- expectError: true,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- token := &oidc.IDToken{- Expiry: tt.expiry,- }- claims := jwt.MapClaims{- "roles": []any{"admin"},- }-- biscuitData, err := hub.mintBiscuitToken(claims, token, dummyPeer)- if err != nil {- t.Fatalf("mintBiscuitToken failed: %v", err)- }-- _, err = hub.verifyBiscuit(biscuitData, dummyPeer)- if tt.expectError && err == nil {- t.Errorf("Expected error due to expiration, got nil")- }- if !tt.expectError && err != nil {- t.Errorf("Expected no error, got: %v", err)- }- })- }-}diff --git a/site/content/docs/development/policy.md b/site/content/docs/development/policy.mdindex d83c3e8d..bbb5ce2f 100644--- a/site/content/docs/development/policy.md+++ b/site/content/docs/development/policy.md@@ -12,10 +12,57 @@ The Hub automatically translates OIDC claims into undeniable cryptographic facts| :--- | :--- | :--- || `sub` | `user("<sub-id>")` | The unique subject ID from the identity provider. || `email` | `email("<email>")` | The user's email address (if present). |-| `groups` / `roles` | `role("<role-name>")` | One fact is injected for *each* role/group the user possesses. |-| Generated FQDN | `name("<fqdn>")` | The collision-proof mesh name granted by the Hub. |-| Peer ID | `node("<peer-id>")` | Binds the token to the specific agent's libp2p cryptographic identity. |-| Expiration | `time(<date>)` | The token expiration date based on the OIDC session. |+| `groups` | `group("<group-name>")` | One fact is injected for *each* group the user possesses. |+| `roles` / Resolved Roles | `role("<role-name>")` | One fact is injected for *each* role mapped or direct role. |+| Peer ID | `node("<peer-id>")`, `client_peer_id("<peer-id>")` | Binds the token to the specific agent's libp2p cryptographic identity. |+| Expiration | `expiration(<date>)` | The token expiration date based on the OIDC session. |++### 1.1 Translating Identity to Capability: OIDC to Biscuit+The core innovation of the SAM Network's security model is translating standard web identity (OIDC JSON Web Tokens defined in [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html#Claims)) into decentralized capability tokens (Biscuits). This translation happens securely at the `sam-hub` during the authentication phase.++The Datalog authority facts generated by the Hub are constructed using the Biscuit [Symbol Table specification](https://doc.biscuitsec.org/reference/specifications.html#symbol-table), ensuring compact serialization and cryptographically undeniable credentials.++Here is exactly how an OIDC JWT is transformed into a policy-ready Biscuit:++#### 1. Claim Extraction+When an agent or user submits a valid OIDC JWT, the sam-hub verifies the token's signature against the Identity Provider. Once validated, the Hub extracts the payload claims—typically attributes like sub (subject), email, and custom arrays like groups or roles.++#### 2. Datalog Fact Generation+Biscuit policies are written in Datalog, a declarative logic language. The sam-hub acts as a translator, mapping the JSON claims from the OIDC token into immutable Datalog facts.++For example, an incoming OIDC payload like this:++```json+{+ "sub": "user-12345",+ "email": "[email protected]",+ "groups": ["beta-testers", "engineering"]+}+```++Is translated by the Hub into the following Datalog facts:++```datalog+user("user-12345");+email("[email protected]");+group("beta-testers");+group("engineering");+```++#### 3. Minting the Authority Block+The sam-hub takes these generated Datalog facts and embeds them into the Authority Block of a brand new Biscuit token. The Hub signs this block with its private cryptographic key.++Because the facts are sealed in the Authority Block by the Hub, any sam-node in the mesh can implicitly trust that the user holding the Biscuit possesses those specific emails and groups.++#### 4. Policy Evaluation at the Node+When the agent presents the Biscuit to a sam-node to execute a tool, the node evaluates its local policies against the facts embedded in the token.++Because the OIDC claims were translated into Datalog, a node administrator can write elegant, logic-based rules in policy.go or their YAML configs:++```datalog+// The node will only execute the tool if the Hub certified the agent is in the engineering group+allow if group("engineering");+```## 2. Hub Policy Schema (`policies.yaml`)Admins define central permissions by mapping OIDC roles to specific capabilities.