Skip to content

Agent Mesh

expose datalog as an api

Antonio Ojea46b3954378d7
diff --git a/api/datalog.go b/api/datalog.go
new file mode 100644
index 00000000..aebf4fb6
--- /dev/null
+++ b/api/datalog.go
@@ -0,0 +1,286 @@
+// 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 api
+
+import (
+ "fmt"
+ "maps"
+
+ "github.com/biscuit-auth/biscuit-go/v2"
+ "github.com/biscuit-auth/biscuit-go/v2/parser"
+)
+
+// ============================================================================
+// SAM Datalog Authorization Concepts & Predicates
+// ============================================================================
+//
+// SAM enforces security policies using Biscuit tokens containing Datalog facts,
+// rules, and checks. Here are the core concepts used in our Datalog engine:
+//
+// 1. Replay Defense Facts:
+// - client_peer_id: The libp2p PeerID of the node that authenticated with the
+// Hub to request this token. Embedded in the token authority block.
+// - connection_peer_id: The libp2p PeerID of the caller initiating the connection
+// to the receiving node. Injected dynamically at runtime by the receiver.
+// - Replay Check: Verified using the check:
+// `check if client_peer_id($id), connection_peer_id($id)`
+// This guarantees that a token can only be used by its rightful owner.
+//
+// 2. Target Constraints & Resolution:
+// - target_fact(type, value): Standardized format representing an identity claim
+// (e.g., user, group, node ID) asserted by the caller. Derived dynamically at
+// runtime from OIDC claims or node authentication.
+// - allow_network_target: Derived fact generated on the receiver node by matching
+// target_fact against the token's allowed targets (e.g., granted_target_exact).
+// - target_unrestricted: Fact injected in the token by the Hub indicating that
+// the client has unrestricted network access and bypasses target constraints.
+// - Target Check: Verified using the check:
+// `check if allow_network_target($fact, $val) or target_unrestricted()`
+// If target_unrestricted is present, target checking succeeds immediately.
+// Otherwise, it requires a matching allow_network_target rule to succeed.
+//
+// For a high-level overview of policy translation and schemas, see the
+// documentation in site/content/docs/development/policy.md.
+//
+// ============================================================================
+
+// Biscuit fact names represent the Datalog predicates used in auth tokens and policy evaluation.
+const (
+ // FactExpiration defines the token expiration time.
+ // Contains: biscuit.Date(expirationTime)
+ // Example Datalog: check if time($time), expiration($exp), $time <= $exp
+ FactExpiration = "expiration"
+
+ // FactNode defines the PeerID of the node that this token belongs to.
+ // Contains: biscuit.String(nodePeerID)
+ // Example Datalog: allow if node("12D3KooWP2G8nJCLASp1Kb4TmQS4wCpMH2vpSUz8ug8DYEJiuf1i")
+ FactNode = "node"
+
+ // FactClientPeerID defines the client PeerID performing the request, used for replay defense.
+ // Contains: biscuit.String(clientPeerID)
+ // Example Datalog: check if client_peer_id($id), connection_peer_id($id)
+ FactClientPeerID = "client_peer_id"
+
+ // FactGroup defines the group claim extracted from the OIDC token.
+ // Contains: biscuit.String(groupName)
+ // Example Datalog: allow if group("data-science")
+ FactGroup = "group"
+
+ // FactRole defines a custom SAM role assigned to the user or node.
+ // Contains: biscuit.String(roleName)
+ // Example Datalog: allow if role("mesh-member")
+ FactRole = "role"
+
+ // FactUser defines the subject (username/userID) claim extracted from the OIDC token.
+ // Contains: biscuit.String(username)
+ // Example Datalog: allow if user("alice")
+ FactUser = "user"
+
+ // FactEmail defines the email claim extracted from the OIDC token.
+ // Contains: biscuit.String(emailAddress)
+ // Example Datalog: allow if email("[email protected]")
+ FactEmail = "email"
+
+ // FactGrantedServiceAllTypes allows access to all service types (e.g., mcp, inference) and all targets.
+ // Contains: (no terms)
+ // Example Datalog: allow if granted_service_all_types()
+ FactGrantedServiceAllTypes = "granted_service_all_types"
+
+ // FactGrantedServiceAll allows access to all targets under a specific service type.
+ // Contains: biscuit.String(serviceType) (e.g., "mcp")
+ // Example Datalog: allow if service("mcp", $target), granted_service_all("mcp")
+ FactGrantedServiceAll = "granted_service_all"
+
+ // FactGrantedServiceSuffix allows access to services matching a suffix pattern (e.g. *.service.local).
+ // Contains: biscuit.String(serviceType), biscuit.String(suffixPattern)
+ FactGrantedServiceSuffix = "granted_service_suffix"
+
+ // FactGrantedServicePrefix allows access to services matching a prefix pattern (e.g. calculator.*).
+ // Contains: biscuit.String(serviceType), biscuit.String(prefixPattern)
+ FactGrantedServicePrefix = "granted_service_prefix"
+
+ // FactGrantedServiceExact allows access to a specific service type and target.
+ // Contains: biscuit.String(serviceType), biscuit.String(targetName)
+ // Example Datalog: allow if service("mcp", "calculator"), granted_service_exact("mcp", "calculator")
+ FactGrantedServiceExact = "granted_service_exact"
+
+ // FactGrantedTargetAllTypes allows target access to all network targets (unrestricted).
+ // Contains: (no terms)
+ FactGrantedTargetAllTypes = "granted_target_all_types"
+
+ // FactGrantedTargetAll allows target access to all values of a specific fact.
+ // Contains: biscuit.String(factName) (e.g., "group")
+ FactGrantedTargetAll = "granted_target_all"
+
+ // FactGrantedTargetSuffix allows target access to values matching a suffix pattern.
+ // Contains: biscuit.String(factName), biscuit.String(suffixPattern)
+ FactGrantedTargetSuffix = "granted_target_suffix"
+
+ // FactGrantedTargetPrefix allows target access to values matching a prefix pattern.
+ // Contains: biscuit.String(factName), biscuit.String(prefixPattern)
+ FactGrantedTargetPrefix = "granted_target_prefix"
+
+ // FactGrantedTargetExact allows target access to a specific fact name and value combination.
+ // Contains: biscuit.String(factName), biscuit.String(factValue)
+ // Example Datalog: allow_network_target("group", "backend") <- target_fact("group", "backend"), granted_target_exact("group", "backend")
+ FactGrantedTargetExact = "granted_target_exact"
+
+ // FactGrantedTargetAllFacts allows target access to any fact name and value combination.
+ // Contains: (no terms)
+ FactGrantedTargetAllFacts = "granted_target_all_facts"
+
+ // FactConnectionPeerID defines the actual PeerID of the remote peer making the connection.
+ // Contains: biscuit.String(connectionPeerID)
+ // Example Datalog: check if client_peer_id($id), connection_peer_id($id)
+ FactConnectionPeerID = "connection_peer_id"
+
+ // FactTargetFact normalizes identity assertions (claims, node, user) to a standardized target.
+ // Contains: biscuit.String(factName), biscuit.String(factValue)
+ // Example Datalog: target_fact("group", $val) <- group($val)
+ FactTargetFact = "target_fact"
+
+ // FactAllowNetworkTarget evaluates whether a target assertion meets the token access grants.
+ // Contains: biscuit.String(factName), biscuit.String(factValue)
+ // Example Datalog: allow_network_target("group", "backend")
+ FactAllowNetworkTarget = "allow_network_target"
+
+ // FactTargetUnrestricted indicates that target authorization checks are bypassed.
+ // Contains: (no terms)
+ // Example Datalog: check if allow_network_target($fact, $val) or target_unrestricted()
+ FactTargetUnrestricted = "target_unrestricted"
+
+ // FactTargetRestricted indicates that target authorization checks must be enforced.
+ // Contains: (no terms)
+ FactTargetRestricted = "target_restricted"
+
+ // FactService represents the service target that a node is requesting access to.
+ // Contains: biscuit.String(serviceType), biscuit.String(serviceName)
+ // Example Datalog: service("mcp", "calculator")
+ FactService = "service"
+
+ // FactTime defines the current system time injected during evaluation.
+ // Contains: biscuit.Date(currentTime)
+ // Example Datalog: check if time($time)
+ FactTime = "time"
+)
+
+var oidcClaimToFact = map[string]string{
+ "sub": FactUser,
+ "email": FactEmail,
+ "groups": FactGroup,
+}
+
+// OIDCClaimToFact returns a copy of the OIDC claims to Biscuit facts map.
+// This ensures that the global map is immutable and thread-safe for concurrent readers.
+func OIDCClaimToFact() map[string]string {
+ return maps.Clone(oidcClaimToFact)
+}
+
+var (
+ // BaselinePolicies are the pre-compiled authorization policies for the node middleware.
+ BaselinePolicies []biscuit.Policy
+
+ // BaselineRules are the pre-compiled target evaluation rules for the node middleware.
+ BaselineRules []biscuit.Rule
+
+ // BaselineReplayCheck verifies that the client peer ID matches the connection peer ID.
+ BaselineReplayCheck biscuit.Check
+
+ // BaselineTargetCheck verifies that the target matches one of the allowed network targets.
+ BaselineTargetCheck biscuit.Check
+
+ // TargetFactRules maps node and OIDC claims to target_fact datalog facts.
+ TargetFactRules []biscuit.Rule
+
+ // HubStaticTimeCheck is the standard check for verifying OIDC token expiration.
+ HubStaticTimeCheck biscuit.Check
+
+ // AllowIfTruePolicy is the static policy "allow if true" used during token verification.
+ AllowIfTruePolicy biscuit.Policy
+)
+
+func init() {
+ // 1. Service Allow Policies
+ policyStrs := []string{
+ fmt.Sprintf(`allow if %s($type, $name), %s($type, $name)`, FactService, FactGrantedServiceExact),
+ fmt.Sprintf(`allow if %s($type, $name), %s($type, $prefix), $name.starts_with($prefix)`, FactService, FactGrantedServicePrefix),
+ fmt.Sprintf(`allow if %s($type, $name), %s($type, $suffix), $name.ends_with($suffix)`, FactService, FactGrantedServiceSuffix),
+ fmt.Sprintf(`allow if %s($type, $name), %s($type)`, FactService, FactGrantedServiceAll),
+ fmt.Sprintf(`allow if %s($type, $name), %s()`, FactService, FactGrantedServiceAllTypes),
+ fmt.Sprintf(`allow if %s(%q, "%s")`, FactService, SystemNamespace, CatalogTarget),
+ }
+
+ for i, pStr := range policyStrs {
+ p, err := parser.FromStringPolicy(pStr)
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse baseline policy %d: %v", i, err))
+ }
+ BaselinePolicies = append(BaselinePolicies, p)
+ }
+
+ // 2. Target Evaluation Rules
+ // These rules satisfy the check if allow_network_target($fact, $val) injected by the Hub.
+ ruleStrs := []string{
+ fmt.Sprintf(`%s($fact, $val) <- %s($fact, $val), %s($fact, $val)`, FactAllowNetworkTarget, FactTargetFact, FactGrantedTargetExact),
+ fmt.Sprintf(`%s($fact, $val) <- %s($fact, $val), %s($fact, $prefix), $val.starts_with($prefix)`, FactAllowNetworkTarget, FactTargetFact, FactGrantedTargetPrefix),
+ fmt.Sprintf(`%s($fact, $val) <- %s($fact, $val), %s($fact, $suffix), $val.ends_with($suffix)`, FactAllowNetworkTarget, FactTargetFact, FactGrantedTargetSuffix),
+ fmt.Sprintf(`%s($fact, $val) <- %s($fact, $val), %s($fact)`, FactAllowNetworkTarget, FactTargetFact, FactGrantedTargetAll),
+ fmt.Sprintf(`%s($fact, $val) <- %s($fact, $val), %s()`, FactAllowNetworkTarget, FactTargetFact, FactGrantedTargetAllFacts),
+ }
+
+ for i, rStr := range ruleStrs {
+ r, err := parser.FromStringRule(rStr)
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse baseline rule %d: %v", i, err))
+ }
+ BaselineRules = append(BaselineRules, r)
+ }
+
+ var err error
+ BaselineReplayCheck, err = parser.FromStringCheck(fmt.Sprintf(`check if %s($id), %s($id)`, FactClientPeerID, FactConnectionPeerID))
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse replay check: %v", err))
+ }
+
+ BaselineTargetCheck, err = parser.FromStringCheck(fmt.Sprintf(`check if %s($fact, $val) or %s()`, FactAllowNetworkTarget, FactTargetUnrestricted))
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse target check: %v", err))
+ }
+
+ for _, val := range OIDCClaimToFact() {
+ ruleStr := fmt.Sprintf(`%s(%q, $val) <- %s($val)`, FactTargetFact, val, val)
+ r, err := parser.FromStringRule(ruleStr)
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse target fact rule: %v", err))
+ }
+ TargetFactRules = append(TargetFactRules, r)
+ }
+
+ r, err := parser.FromStringRule(fmt.Sprintf(`%s(%q, $val) <- %s($val)`, FactTargetFact, FactNode, FactNode))
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse node fact rule: %v", err))
+ }
+ TargetFactRules = append(TargetFactRules, r)
+
+ HubStaticTimeCheck, err = parser.FromStringCheck(fmt.Sprintf(`check if %s($time), %s($exp), $time <= $exp`, FactTime, FactExpiration))
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse static time check: %v", err))
+ }
+
+ AllowIfTruePolicy, err = parser.FromStringPolicy("allow if true")
+ if err != nil {
+ panic(fmt.Sprintf("failed to parse static allow policy: %v", err))
+ }
+}
diff --git a/api/datalog_test.go b/api/datalog_test.go
new file mode 100644
index 00000000..4171bd1f
--- /dev/null
+++ b/api/datalog_test.go
@@ -0,0 +1,373 @@
+// 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 api
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ reflect "reflect"
+ "testing"
+ "time"
+
+ "github.com/biscuit-auth/biscuit-go/v2"
+)
+
+// helper to generate keypair for tests
+func makeKeyPair(t *testing.T) (ed25519.PublicKey, ed25519.PrivateKey) {
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("failed to generate key pair: %v", err)
+ }
+ return pub, priv
+}
+
+func TestBaselinePolicies(t *testing.T) {
+ pub, priv := makeKeyPair(t)
+
+ tests := []struct {
+ name string
+ tokenFacts []biscuit.Fact
+ requestTarget string // e.g. "mcp://calculator/add"
+ expectAllow bool
+ }{
+ {
+ name: "Exact match allowed",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactGrantedServiceExact, IDs: []biscuit.Term{biscuit.String("mcp"), biscuit.String("calculator")}}},
+ },
+ requestTarget: "mcp://calculator",
+ expectAllow: true,
+ },
+ {
+ name: "Exact match denied (mismatched service)",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactGrantedServiceExact, IDs: []biscuit.Term{biscuit.String("mcp"), biscuit.String("database")}}},
+ },
+ requestTarget: "mcp://calculator",
+ expectAllow: false,
+ },
+ {
+ name: "Prefix wildcard allowed (subdomain prefix match)",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactGrantedServicePrefix, IDs: []biscuit.Term{biscuit.String("mcp"), biscuit.String("calc.")}}},
+ },
+ requestTarget: "mcp://calc.service.internal",
+ expectAllow: true,
+ },
+ {
+ name: "Prefix wildcard denied (mismatched prefix)",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactGrantedServicePrefix, IDs: []biscuit.Term{biscuit.String("mcp"), biscuit.String("calc.")}}},
+ },
+ requestTarget: "mcp://db.service.internal",
+ expectAllow: false,
+ },
+ {
+ name: "Suffix wildcard allowed (domain suffix match)",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactGrantedServiceSuffix, IDs: []biscuit.Term{biscuit.String("mcp"), biscuit.String(".internal")}}},
+ },
+ requestTarget: "mcp://calc.service.internal",
+ expectAllow: true,
+ },
+ {
+ name: "Suffix wildcard denied (mismatched suffix)",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactGrantedServiceSuffix, IDs: []biscuit.Term{biscuit.String("mcp"), biscuit.String(".internal")}}},
+ },
+ requestTarget: "mcp://calc.service.external",
+ expectAllow: false,
+ },
+ {
+ name: "All services matching scheme allowed",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactGrantedServiceAll, IDs: []biscuit.Term{biscuit.String("mcp")}}},
+ },
+ requestTarget: "mcp://any-random-service",
+ expectAllow: true,
+ },
+ {
+ name: "All services matching scheme denied (mismatched scheme)",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactGrantedServiceAll, IDs: []biscuit.Term{biscuit.String("mcp")}}},
+ },
+ requestTarget: "inference://any-random-service",
+ expectAllow: false,
+ },
+ {
+ name: "Global wildcard allows everything",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactGrantedServiceAllTypes, IDs: []biscuit.Term{}}},
+ },
+ requestTarget: "mcp://calculator",
+ expectAllow: true,
+ },
+ {
+ name: "System catalog is always allowed",
+ tokenFacts: []biscuit.Fact{},
+ requestTarget: "system://sam.catalog",
+ expectAllow: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ builder := biscuit.NewBuilder(priv)
+ for _, fact := range tt.tokenFacts {
+ if err := builder.AddAuthorityFact(fact); err != nil {
+ t.Fatalf("failed to add authority fact: %v", err)
+ }
+ }
+
+ tok, err := builder.Build()
+ if err != nil {
+ t.Fatalf("failed to build token: %v", err)
+ }
+
+ authorizer, err := tok.Authorizer(pub)
+ if err != nil {
+ t.Fatalf("failed to create authorizer: %v", err)
+ }
+
+ // Parse target like middleware
+ opType, opName := ParseServiceTarget(tt.requestTarget)
+ authorizer.AddFact(biscuit.Fact{
+ Predicate: biscuit.Predicate{
+ Name: FactService,
+ IDs: []biscuit.Term{biscuit.String(opType), biscuit.String(opName)},
+ },
+ })
+
+ // Add baseline policies
+ for _, p := range BaselinePolicies {
+ authorizer.AddPolicy(p)
+ }
+
+ err = authorizer.Authorize()
+ if tt.expectAllow && err != nil {
+ t.Errorf("expected authorized, got error: %v", err)
+ } else if !tt.expectAllow && err == nil {
+ t.Error("expected denied, but authorization succeeded")
+ }
+ })
+ }
+}
+
+func TestBaselineReplayCheck(t *testing.T) {
+ pub, priv := makeKeyPair(t)
+
+ tests := []struct {
+ name string
+ clientPeerID string
+ connectionPeerID string
+ expectAllow bool
+ }{
+ {
+ name: "Peer IDs match",
+ clientPeerID: "12D3KooWP2G8nJCLASp1Kb4TmQS4wCpMH2vpSUz8ug8DYEJiuf1i",
+ connectionPeerID: "12D3KooWP2G8nJCLASp1Kb4TmQS4wCpMH2vpSUz8ug8DYEJiuf1i",
+ expectAllow: true,
+ },
+ {
+ name: "Peer IDs mismatch",
+ clientPeerID: "12D3KooWP2G8nJCLASp1Kb4TmQS4wCpMH2vpSUz8ug8DYEJiuf1i",
+ connectionPeerID: "12D3KooWLgPBrLFKA533cKkXaecYUKfSZ48BkhwwYQ7ThDn1XwHb",
+ expectAllow: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ builder := biscuit.NewBuilder(priv)
+ // client_peer_id is embedded in the token authority block
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: FactClientPeerID,
+ IDs: []biscuit.Term{biscuit.String(tt.clientPeerID)},
+ }})
+
+ tok, _ := builder.Build()
+ authorizer, _ := tok.Authorizer(pub)
+
+ // connection_peer_id is injected as a runtime connection fact
+ authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: FactConnectionPeerID,
+ IDs: []biscuit.Term{biscuit.String(tt.connectionPeerID)},
+ }})
+
+ // Add replay check and generic allow
+ authorizer.AddCheck(BaselineReplayCheck)
+ authorizer.AddPolicy(AllowIfTruePolicy)
+
+ err := authorizer.Authorize()
+ if tt.expectAllow && err != nil {
+ t.Errorf("expected authorized, got error: %v", err)
+ } else if !tt.expectAllow && err == nil {
+ t.Error("expected denied, but authorization succeeded")
+ }
+ })
+ }
+}
+
+func TestBaselineTargetCheck(t *testing.T) {
+ pub, priv := makeKeyPair(t)
+
+ tests := []struct {
+ name string
+ tokenFacts []biscuit.Fact
+ targetFact string // e.g. "node" or "group"
+ targetVal string // e.g. "12D3Koo..." or "backend"
+ expectAllow bool
+ }{
+ {
+ name: "Exact target matching allows",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactTargetRestricted}},
+ {Predicate: biscuit.Predicate{Name: FactGrantedTargetExact, IDs: []biscuit.Term{biscuit.String("group"), biscuit.String("backend")}}},
+ },
+ targetFact: "group",
+ targetVal: "backend",
+ expectAllow: true,
+ },
+ {
+ name: "Mismatched target denied when restricted",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactTargetRestricted}},
+ {Predicate: biscuit.Predicate{Name: FactGrantedTargetExact, IDs: []biscuit.Term{biscuit.String("group"), biscuit.String("backend")}}},
+ },
+ targetFact: "group",
+ targetVal: "frontend",
+ expectAllow: false,
+ },
+ {
+ name: "Any target allowed when target_unrestricted",
+ tokenFacts: []biscuit.Fact{
+ {Predicate: biscuit.Predicate{Name: FactTargetUnrestricted}},
+ },
+ targetFact: "group",
+ targetVal: "any-group",
+ expectAllow: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ builder := biscuit.NewBuilder(priv)
+ for _, fact := range tt.tokenFacts {
+ _ = builder.AddAuthorityFact(fact)
+ }
+
+ tok, _ := builder.Build()
+ authorizer, _ := tok.Authorizer(pub)
+
+ // target_fact is evaluated at runtime (e.g. node(...) or group(...))
+ authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: tt.targetFact,
+ IDs: []biscuit.Term{biscuit.String(tt.targetVal)},
+ }})
+
+ // Add target check, baseline rules, and generic allow
+ authorizer.AddCheck(BaselineTargetCheck)
+ for _, r := range BaselineRules {
+ authorizer.AddRule(r)
+ }
+ // targetFactRules parses facts like node(...) -> target_fact("node", ...)
+ for _, r := range TargetFactRules {
+ authorizer.AddRule(r)
+ }
+ authorizer.AddPolicy(AllowIfTruePolicy)
+
+ err := authorizer.Authorize()
+ if tt.expectAllow && err != nil {
+ t.Errorf("expected authorized, got error: %v", err)
+ } else if !tt.expectAllow && err == nil {
+ t.Error("expected denied, but authorization succeeded")
+ }
+ })
+ }
+}
+
+func TestHubStaticTimeCheck(t *testing.T) {
+ pub, priv := makeKeyPair(t)
+
+ tests := []struct {
+ name string
+ expiry time.Time
+ timeNow time.Time
+ expectAllow bool
+ }{
+ {
+ name: "Token not expired",
+ expiry: time.Now().Add(1 * time.Hour),
+ timeNow: time.Now(),
+ expectAllow: true,
+ },
+ {
+ name: "Token expired",
+ expiry: time.Now().Add(-1 * time.Hour),
+ timeNow: time.Now(),
+ expectAllow: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ builder := biscuit.NewBuilder(priv)
+ _ = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: FactExpiration,
+ IDs: []biscuit.Term{biscuit.Date(tt.expiry)},
+ }})
+
+ tok, _ := builder.Build()
+ authorizer, _ := tok.Authorizer(pub)
+
+ authorizer.AddFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: FactTime,
+ IDs: []biscuit.Term{biscuit.Date(tt.timeNow)},
+ }})
+
+ authorizer.AddCheck(HubStaticTimeCheck)
+ authorizer.AddPolicy(AllowIfTruePolicy)
+
+ err := authorizer.Authorize()
+ if tt.expectAllow && err != nil {
+ t.Errorf("expected authorized, got error: %v", err)
+ } else if !tt.expectAllow && err == nil {
+ t.Error("expected denied, but authorization succeeded")
+ }
+ })
+ }
+}
+
+func TestOIDCClaimToFact(t *testing.T) {
+ facts := OIDCClaimToFact()
+
+ want := map[string]string{
+ "sub": FactUser,
+ "email": FactEmail,
+ "groups": FactGroup,
+ }
+
+ if !reflect.DeepEqual(facts, want) {
+ t.Errorf("OIDCClaimToFact() = %v, want %v", facts, want)
+ }
+
+ // Verify that modifying the returned map does not mutate the internal map.
+ facts["new_claim"] = "new_fact"
+ facts2 := OIDCClaimToFact()
+
+ if _, ok := facts2["new_claim"]; ok {
+ t.Errorf("OIDCClaimToFact() returned map is not a clone, modifications affect internal state")
+ }
+}
diff --git a/api/types.go b/api/network.go
similarity index 66%
rename from api/types.go
rename to api/network.go
index 44109a1f..c227ce91 100644
--- a/api/types.go
+++ b/api/network.go
@@ -16,7 +16,6 @@ package api
import (
"fmt"
- "maps"
"net/url"
"strings"
@@ -68,60 +67,6 @@ const (
InferenceServicePrefix = "inference://"
)
-// ============================================================================
-// Biscuit Authorization Facts
-// ============================================================================
-
-// Biscuit fact names represent the Datalog predicates used in auth tokens and policy evaluation.
-const (
- FactExpiration = "expiration"
- FactNode = "node"
- FactClientPeerID = "client_peer_id"
- FactGroup = "group"
- FactRole = "role"
- FactUser = "user"
- FactEmail = "email"
- FactGrantedServiceAllTypes = "granted_service_all_types"
- FactGrantedServiceAll = "granted_service_all"
- FactGrantedServiceSuffix = "granted_service_suffix"
- FactGrantedServicePrefix = "granted_service_prefix"
- FactGrantedServiceExact = "granted_service_exact"
-
- FactGrantedTargetAllTypes = "granted_target_all_types"
- FactGrantedTargetAll = "granted_target_all"
- FactGrantedTargetSuffix = "granted_target_suffix"
- FactGrantedTargetPrefix = "granted_target_prefix"
- FactGrantedTargetExact = "granted_target_exact"
- FactGrantedTargetAllFacts = "granted_target_all_facts"
-)
-
-// 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 constants 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 cmd/sam-hub/biscuit.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 cmd/sam-hub/biscuit_test.go covering the new mapping.
-var oidcClaimToFact = map[string]string{
- "sub": FactUser,
- "email": FactEmail,
- "groups": FactGroup,
-}
-
-// OIDCClaimToFact returns a copy of the OIDC claims to Biscuit facts map.
-// This ensures that the global map is immutable and thread-safe for concurrent readers.
-func OIDCClaimToFact() map[string]string {
- return maps.Clone(oidcClaimToFact)
-}
-
// ============================================================================
// Protocol Types & String Mappings
// ============================================================================
diff --git a/api/types_test.go b/api/network_test.go
similarity index 75%
rename from api/types_test.go
rename to api/network_test.go
index 76666f26..09d45a81 100644
--- a/api/types_test.go
+++ b/api/network_test.go
@@ -15,7 +15,6 @@
package api
import (
- "reflect"
"testing"
)
@@ -76,25 +75,3 @@ func TestParseServiceTarget(t *testing.T) {
})
}
}
-
-func TestOIDCClaimToFact(t *testing.T) {
- facts := OIDCClaimToFact()
-
- want := map[string]string{
- "sub": FactUser,
- "email": FactEmail,
- "groups": FactGroup,
- }
-
- if !reflect.DeepEqual(facts, want) {
- t.Errorf("OIDCClaimToFact() = %v, want %v", facts, want)
- }
-
- // Verify that modifying the returned map does not mutate the internal map.
- facts["new_claim"] = "new_fact"
- facts2 := OIDCClaimToFact()
-
- if _, ok := facts2["new_claim"]; ok {
- t.Errorf("OIDCClaimToFact() returned map is not a clone, modifications affect internal state")
- }
-}
diff --git a/cmd/sam-hub/biscuit.go b/cmd/sam-hub/biscuit.go
index b9b33bd4..1b98713a 100644
--- a/cmd/sam-hub/biscuit.go
+++ b/cmd/sam-hub/biscuit.go
@@ -247,11 +247,11 @@ func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remote
}
}
if hasTargets {
- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_restricted"}}); err != nil {
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: api.FactTargetRestricted}}); err != nil {
errs = append(errs, err)
}
} else {
- if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: "target_unrestricted"}}); err != nil {
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{Name: api.FactTargetUnrestricted}}); err != nil {
errs = append(errs, err)
}
}
@@ -273,23 +273,6 @@ func (h *Hub) mintBiscuitToken(claims jwt.MapClaims, token *oidc.IDToken, remote
return biscuitData, nil
}
-var (
- staticTimeCheck biscuit.Check
- staticAllowPolicy biscuit.Policy
-)
-
-func init() {
- var err error
- staticTimeCheck, err = parser.FromStringCheck(`check if time($time), expiration($exp), $time <= $exp`)
- if err != nil {
- panic(fmt.Sprintf("failed to parse static time check: %v", err))
- }
- staticAllowPolicy, err = parser.FromStringPolicy("allow if true")
- if err != nil {
- panic(fmt.Sprintf("failed to parse static allow policy: %v", err))
- }
-}
-
func (h *Hub) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscuit.Biscuit, error) {
b, err := biscuit.Unmarshal(biscuitData)
if err != nil {
@@ -312,13 +295,13 @@ func (h *Hub) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscuit.Bi
authorizer.AddFact(biscuit.Fact{
Predicate: biscuit.Predicate{
- Name: "time",
+ Name: api.FactTime,
IDs: []biscuit.Term{biscuit.Date(time.Now())},
},
})
- authorizer.AddCheck(staticTimeCheck)
- authorizer.AddPolicy(staticAllowPolicy)
+ authorizer.AddCheck(api.HubStaticTimeCheck)
+ authorizer.AddPolicy(api.AllowIfTruePolicy)
if err := authorizer.Authorize(); err == nil {
return b, nil
diff --git a/cmd/sam-node/middleware.go b/cmd/sam-node/middleware.go
index 05e87c4b..59adeab1 100644
--- a/cmd/sam-node/middleware.go
+++ b/cmd/sam-node/middleware.go
@@ -20,7 +20,6 @@ import (
"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/google/sam/api"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
@@ -28,80 +27,6 @@ import (
"google.golang.org/protobuf/proto"
)
-var (
- baselinePolicies []biscuit.Policy
- baselineRules []biscuit.Rule
- baselineReplayCheck biscuit.Check
- baselineTargetCheck biscuit.Check
- targetFactRules []biscuit.Rule
-)
-
-// init compiles the baseline Datalog rules, policies, and checks for the node.
-// These are loaded at initialization to avoid runtime parsing overhead.
-func init() {
- // 1. Service Allow Policies
- policyStrs := []string{
- fmt.Sprintf(`allow if service($type, $name), %s($type, $name)`, api.FactGrantedServiceExact),
- fmt.Sprintf(`allow if service($type, $name), %s($type, $prefix), $name.starts_with($prefix)`, api.FactGrantedServicePrefix),
- fmt.Sprintf(`allow if service($type, $name), %s($type, $suffix), $name.ends_with($suffix)`, api.FactGrantedServiceSuffix),
- fmt.Sprintf(`allow if service($type, $name), %s($type)`, api.FactGrantedServiceAll),
- fmt.Sprintf(`allow if service($type, $name), %s()`, api.FactGrantedServiceAllTypes),
- fmt.Sprintf(`allow if service("system", "%s")`, api.CatalogTarget),
- }
-
- for i, pStr := range policyStrs {
- p, err := parser.FromStringPolicy(pStr)
- if err != nil {
- panic(fmt.Sprintf("failed to parse baseline policy %d: %v", i, err))
- }
- baselinePolicies = append(baselinePolicies, p)
- }
-
- // 2. Target Evaluation Rules
- // These rules satisfy the check if allow_network_target($fact, $val) injected by the Hub.
- ruleStrs := []string{
- fmt.Sprintf(`allow_network_target($fact, $val) <- target_fact($fact, $val), %s($fact, $val)`, api.FactGrantedTargetExact),
- fmt.Sprintf(`allow_network_target($fact, $val) <- target_fact($fact, $val), %s($fact, $prefix), $val.starts_with($prefix)`, api.FactGrantedTargetPrefix),
- fmt.Sprintf(`allow_network_target($fact, $val) <- target_fact($fact, $val), %s($fact, $suffix), $val.ends_with($suffix)`, api.FactGrantedTargetSuffix),
- fmt.Sprintf(`allow_network_target($fact, $val) <- target_fact($fact, $val), %s($fact)`, api.FactGrantedTargetAll),
- fmt.Sprintf(`allow_network_target($fact, $val) <- target_fact($fact, $val), %s()`, api.FactGrantedTargetAllFacts),
- }
-
- for i, rStr := range ruleStrs {
- r, err := parser.FromStringRule(rStr)
- if err != nil {
- panic(fmt.Sprintf("failed to parse baseline rule %d: %v", i, err))
- }
- baselineRules = append(baselineRules, r)
- }
-
- var err error
- baselineReplayCheck, err = parser.FromStringCheck(`check if client_peer_id($id), connection_peer_id($id)`)
- if err != nil {
- panic(fmt.Sprintf("failed to parse replay check: %v", err))
- }
-
- baselineTargetCheck, err = parser.FromStringCheck(`check if allow_network_target($fact, $val) or target_unrestricted()`)
- if err != nil {
- panic(fmt.Sprintf("failed to parse target check: %v", err))
- }
-
- for _, val := range api.OIDCClaimToFact() {
- ruleStr := fmt.Sprintf(`target_fact(%q, $val) <- %s($val)`, val, val)
- r, err := parser.FromStringRule(ruleStr)
- if err != nil {
- panic(fmt.Sprintf("failed to parse target fact rule: %v", err))
- }
- targetFactRules = append(targetFactRules, r)
- }
-
- r, err := parser.FromStringRule(`target_fact("node", $val) <- node($val)`)
- if err != nil {
- panic(fmt.Sprintf("failed to parse node fact rule: %v", err))
- }
- targetFactRules = append(targetFactRules, r)
-}
-
// RequestContext carries the security metadata for a specific stream request
type RequestContext struct {
PeerID peer.ID
@@ -248,7 +173,7 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.
}
authorizer.AddFact(biscuit.Fact{
Predicate: biscuit.Predicate{
- Name: "service",
+ Name: api.FactService,
IDs: []biscuit.Term{biscuit.String(opType), biscuit.String(opName)},
},
})
@@ -256,13 +181,13 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.
// Inject connection_peer_id fact for replay defense
authorizer.AddFact(biscuit.Fact{
Predicate: biscuit.Predicate{
- Name: "connection_peer_id",
+ Name: api.FactConnectionPeerID,
IDs: []biscuit.Term{biscuit.String(req.PeerID.String())},
},
})
// Enforce client_peer_id matches connection_peer_id
- authorizer.AddCheck(baselineReplayCheck)
+ authorizer.AddCheck(api.BaselineReplayCheck)
// Inject facts from our own identity token to support target matching
n.injectIdentityFacts(authorizer, pubKey)
@@ -280,11 +205,11 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext, pubKey ed25519.
}
// Apply Baseline Policies and Rules
- authorizer.AddCheck(baselineTargetCheck)
- for _, p := range baselinePolicies {
+ authorizer.AddCheck(api.BaselineTargetCheck)
+ for _, p := range api.BaselinePolicies {
authorizer.AddPolicy(p)
}
- for _, r := range baselineRules {
+ for _, r := range api.BaselineRules {
authorizer.AddRule(r)
}
@@ -334,7 +259,7 @@ func (n *SamNode) injectIdentityFacts(authorizer biscuit.Authorizer, pubKey ed25
// we continue anyway, as we just want the facts, but ideally it shouldn't fail
}
- for _, rule := range targetFactRules {
+ for _, rule := range api.TargetFactRules {
if factSet, err := auth.Query(rule); err == nil {
for _, fact := range factSet {
authorizer.AddFact(fact)
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index 757326a8..dd8e67c3 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -36,7 +36,6 @@ import (
"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/google/sam/api"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/ipfs/go-cid"
@@ -1203,12 +1202,7 @@ func (n *SamNode) verifyBiscuit(biscuitData []byte, remotePeer peer.ID) (*biscui
continue
}
- rule, err := parser.FromStringPolicy("allow if true")
- if err != nil {
- lastErr = fmt.Errorf("policy error: %w", err)
- continue
- }
- authorizer.AddPolicy(rule)
+ authorizer.AddPolicy(api.AllowIfTruePolicy)
if err := authorizer.Authorize(); err == nil {
return b, nil