Skip to content

Agent Mesh

add policies

Antonio Ojeafe8db76880e2
diff --git a/README.md b/README.md
index f83b857c..92fe16b7 100644
--- a/README.md
+++ b/README.md
@@ -1,11 +1,15 @@
# SAM: Sovereign Agent Mesh
-SAM is a minimal libp2p-based mesh with two binaries:
+SAM is a smart network built for autonomous agents:
-- `sam-hub`: OIDC bridge + Biscuit issuer + connection gater
-- `sam-node`: node identity/login flow + mesh node runtime + local MCP server
+* **Zero Config:** Nodes discover each other and build the network automatically.
+* **Zero Trust:** Every connection, node, and packet is strictly authenticated.
+* **Agentic Network:** Built for agents to use. The nodes provide the self-healing, peer-to-peer infrastructure, allowing autonomous agents to seamlessly plug in, communicate, and operate across the mesh.
+* **Portability:** Environment-agnostic and IP-independent. Network identity is cryptographic and travels with the node, enabling mobility across cloud, edge, and local setups.
-The current repository intentionally focuses on basic functionality and testability.
+
+- `sam-hub`: The control plane for identity and policy distribution.
+- `sam-node`: The lightweight agents that form the actual peer-to-peer mesh.
## Build
@@ -44,7 +48,7 @@ This prints a login URL. After authenticating in browser, paste the returned bis
Or pass a token directly:
```bash
-./bin/sam-node run --token <identity-biscuit>
+./bin/sam-node run --token <identity-token>
```
## Local MCP Server
diff --git a/api/policy.go b/api/policy.go
new file mode 100644
index 00000000..4979acfa
--- /dev/null
+++ b/api/policy.go
@@ -0,0 +1,41 @@
+package api
+
+const (
+ // FactMCPTool is the Datalog fact name injected by the Hub to authorize specific MCP tools.
+ FactMCPTool = "allow_mcp_tool"
+
+ // FactNetworkTarget is the Datalog fact name injected by the Hub to authorize connections to specific agents.
+ FactNetworkTarget = "allow_network_target"
+)
+
+// PolicyConfig is the root authorization configuration for the SAM Hub.
+type PolicyConfig struct {
+ Version string `yaml:"version"`
+ Roles map[string]RolePolicy `yaml:"roles"`
+}
+
+type RolePolicy struct {
+ Network NetworkPolicy `yaml:"network"`
+ MCP MCPPolicy `yaml:"mcp"`
+ CustomDatalog []string `yaml:"custom_datalog"`
+}
+
+type NetworkPolicy struct {
+ AllowedTargets []string `yaml:"allowed_targets"`
+}
+
+type MCPPolicy struct {
+ AllowedTools []string `yaml:"allowed_tools"`
+}
+
+// LocalPolicy defines the optional attenuation rules for a specific SAM Node.
+type LocalPolicy struct {
+ Version string `yaml:"version"`
+ Attenuation Attenuation `yaml:"attenuation"`
+}
+
+type Attenuation struct {
+ Policies []string `yaml:"policies"`
+ Checks []string `yaml:"checks"`
+ Rules []string `yaml:"rules"`
+}
diff --git a/api/sam.pb.go b/api/sam.pb.go
index d9f0572b..00ad0e59 100644
--- a/api/sam.pb.go
+++ b/api/sam.pb.go
@@ -729,16 +729,15 @@ func (x *EnrollRequest) GetPeerId() string {
}
type EnrollResponse struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- BiscuitToken []byte `protobuf:"bytes,1,opt,name=biscuit_token,json=biscuitToken,proto3" json:"biscuit_token,omitempty"`
- ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`
- HubPublicKey []byte `protobuf:"bytes,3,opt,name=hub_public_key,json=hubPublicKey,proto3" json:"hub_public_key,omitempty"`
- HubAddresses []string `protobuf:"bytes,4,rep,name=hub_addresses,json=hubAddresses,proto3" json:"hub_addresses,omitempty"`
- Expiration int64 `protobuf:"varint,5,opt,name=expiration,proto3" json:"expiration,omitempty"`
- KnownPeers []string `protobuf:"bytes,6,rep,name=known_peers,json=knownPeers,proto3" json:"known_peers,omitempty"`
- DatalogPolicies []string `protobuf:"bytes,7,rep,name=datalog_policies,json=datalogPolicies,proto3" json:"datalog_policies,omitempty"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ state protoimpl.MessageState `protogen:"open.v1"`
+ BiscuitToken []byte `protobuf:"bytes,1,opt,name=biscuit_token,json=biscuitToken,proto3" json:"biscuit_token,omitempty"`
+ ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`
+ HubPublicKey []byte `protobuf:"bytes,3,opt,name=hub_public_key,json=hubPublicKey,proto3" json:"hub_public_key,omitempty"`
+ HubAddresses []string `protobuf:"bytes,4,rep,name=hub_addresses,json=hubAddresses,proto3" json:"hub_addresses,omitempty"`
+ Expiration int64 `protobuf:"varint,5,opt,name=expiration,proto3" json:"expiration,omitempty"`
+ KnownPeers []string `protobuf:"bytes,6,rep,name=known_peers,json=knownPeers,proto3" json:"known_peers,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *EnrollResponse) Reset() {
@@ -813,13 +812,6 @@ func (x *EnrollResponse) GetKnownPeers() []string {
return nil
}
-func (x *EnrollResponse) GetDatalogPolicies() []string {
- if x != nil {
- return x.DatalogPolicies
- }
- return nil
-}
-
var File_api_sam_proto protoreflect.FileDescriptor
const file_api_sam_proto_rawDesc = "" +
@@ -878,7 +870,7 @@ const file_api_sam_proto_rawDesc = "" +
"\x06BANNED\x10\x02\":\n" +
"\rEnrollRequest\x12\x10\n" +
"\x03jwt\x18\x01 \x01(\tR\x03jwt\x12\x17\n" +
- "\apeer_id\x18\x02 \x01(\tR\x06peerId\"\x91\x02\n" +
+ "\apeer_id\x18\x02 \x01(\tR\x06peerId\"\xe6\x01\n" +
"\x0eEnrollResponse\x12#\n" +
"\rbiscuit_token\x18\x01 \x01(\fR\fbiscuitToken\x12#\n" +
"\rerror_message\x18\x02 \x01(\tR\ferrorMessage\x12$\n" +
@@ -888,8 +880,7 @@ const file_api_sam_proto_rawDesc = "" +
"expiration\x18\x05 \x01(\x03R\n" +
"expiration\x12\x1f\n" +
"\vknown_peers\x18\x06 \x03(\tR\n" +
- "knownPeers\x12)\n" +
- "\x10datalog_policies\x18\a \x03(\tR\x0fdatalogPoliciesB\x1bZ\x19github.com/google/sam/apib\x06proto3"
+ "knownPeersB\x1bZ\x19github.com/google/sam/apib\x06proto3"
var (
file_api_sam_proto_rawDescOnce sync.Once
diff --git a/api/sam.proto b/api/sam.proto
index f4eeddf2..1125234f 100644
--- a/api/sam.proto
+++ b/api/sam.proto
@@ -92,5 +92,4 @@ message EnrollResponse {
repeated string hub_addresses = 4;
int64 expiration = 5;
repeated string known_peers = 6;
- repeated string datalog_policies = 7;
}
diff --git a/cmd/mcp-client/main.go b/cmd/mcp-client/main.go
index 1777b707..7db5e081 100644
--- a/cmd/mcp-client/main.go
+++ b/cmd/mcp-client/main.go
@@ -16,6 +16,7 @@ package main
import (
"context"
+ "encoding/json"
"flag"
"fmt"
"log"
@@ -27,6 +28,8 @@ import (
func main() {
socketPath := flag.String("socket", "", "Path to Unix domain socket")
+ toolName := flag.String("tool", "get_mesh_info", "Tool to call")
+ toolArgs := flag.String("args", "{}", "JSON arguments for the tool")
flag.Parse()
if *socketPath == "" {
@@ -59,14 +62,20 @@ func main() {
}
}()
- // Call tool get_mesh_info
+ var args map[string]any
+ if *toolArgs != "" {
+ if err := json.Unmarshal([]byte(*toolArgs), &args); err != nil {
+ log.Fatalf("Failed to parse args: %v", err)
+ }
+ }
+
+ // Call tool
result, err := session.CallTool(ctx, &mcp.CallToolParams{
- Name: "get_mesh_info",
- Arguments: map[string]any{},
+ Name: *toolName,
+ Arguments: args,
})
if err != nil {
- log.Printf("CallTool failed: %v", err)
- return
+ log.Fatalf("CallTool failed: %v", err)
}
for _, content := range result.Content {
diff --git a/cmd/sam-hub/config.go b/cmd/sam-hub/config.go
new file mode 100644
index 00000000..ff657607
--- /dev/null
+++ b/cmd/sam-hub/config.go
@@ -0,0 +1,44 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/biscuit-auth/biscuit-go/v2/parser"
+ "github.com/google/sam/api"
+ "gopkg.in/yaml.v2"
+)
+
+// LoadPolicyConfig loads the policy configuration from the specified path.
+// If the file is missing, it returns an empty initialized config.
+func LoadPolicyConfig(path string) (*api.PolicyConfig, error) {
+ if _, err := os.Stat(path); os.IsNotExist(err) {
+ return &api.PolicyConfig{
+ Version: "v1alpha1",
+ Roles: make(map[string]api.RolePolicy),
+ }, nil
+ }
+
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+
+ var config api.PolicyConfig
+ if err := yaml.Unmarshal(data, &config); err != nil {
+ return nil, err
+ }
+
+ for role, rolePolicy := range config.Roles {
+ for _, customFact := range rolePolicy.CustomDatalog {
+ trimmed := strings.TrimRight(strings.TrimSpace(customFact), ";")
+ _, err := parser.FromStringFact(trimmed)
+ if err != nil {
+ return nil, fmt.Errorf("invalid custom datalog fact for role %q: %w", role, err)
+ }
+ }
+ }
+
+ return &config, nil
+}
diff --git a/cmd/sam-hub/config_test.go b/cmd/sam-hub/config_test.go
new file mode 100644
index 00000000..f37994e3
--- /dev/null
+++ b/cmd/sam-hub/config_test.go
@@ -0,0 +1,97 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestLoadPolicyConfig(t *testing.T) {
+ // 1. Test valid YAML
+ validYAML := `
+version: "v1alpha1"
+roles:
+ data-scientist:
+ network:
+ allowed_targets: ["db-agent.data-mesh"]
+ mcp:
+ allowed_tools: ["query_database"]
+ custom_datalog:
+ - 'department("analytics");'
+`
+ dir := t.TempDir()
+ validFile := filepath.Join(dir, "valid.yaml")
+ if err := os.WriteFile(validFile, []byte(validYAML), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ config, err := LoadPolicyConfig(validFile)
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if config.Version != "v1alpha1" {
+ t.Errorf("expected version v1alpha1, got %s", config.Version)
+ }
+ role, ok := config.Roles["data-scientist"]
+ if !ok {
+ t.Fatal("expected role data-scientist to exist")
+ }
+ if len(role.Network.AllowedTargets) != 1 || role.Network.AllowedTargets[0] != "db-agent.data-mesh" {
+ t.Errorf("unexpected allowed targets: %v", role.Network.AllowedTargets)
+ }
+ if len(role.MCP.AllowedTools) != 1 || role.MCP.AllowedTools[0] != "query_database" {
+ t.Errorf("unexpected allowed tools: %v", role.MCP.AllowedTools)
+ }
+ if len(role.CustomDatalog) != 1 || role.CustomDatalog[0] != `department("analytics");` {
+ t.Errorf("unexpected custom datalog: %v", role.CustomDatalog)
+ }
+
+ // 2. Test invalid YAML
+ invalidYAML := `
+version: "v1alpha1"
+roles:
+ data-scientist:
+ network:
+ allowed_targets: [missing closing bracket
+`
+ invalidFile := filepath.Join(dir, "invalid.yaml")
+ if err := os.WriteFile(invalidFile, []byte(invalidYAML), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ _, err = LoadPolicyConfig(invalidFile)
+ if err == nil {
+ t.Error("expected error for invalid YAML, got nil")
+ }
+
+ // 3. Test missing file
+ missingFile := filepath.Join(dir, "nonexistent.yaml")
+ config, err = LoadPolicyConfig(missingFile)
+ if err != nil {
+ t.Fatalf("expected no error for missing file, got %v", err)
+ }
+ if config == nil {
+ t.Fatal("expected non-nil config for missing file")
+ }
+ if len(config.Roles) != 0 {
+ t.Errorf("expected empty roles, got %d", len(config.Roles))
+ }
+
+ // 4. Test invalid custom datalog
+ invalidDatalogYAML := `
+version: "v1alpha1"
+roles:
+ data-scientist:
+ custom_datalog:
+ - 'invalid fact syntax'
+`
+ invalidDatalogFile := filepath.Join(dir, "invalid_datalog.yaml")
+ if err := os.WriteFile(invalidDatalogFile, []byte(invalidDatalogYAML), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ _, err = LoadPolicyConfig(invalidDatalogFile)
+ if err == nil {
+ t.Error("expected error for invalid custom datalog, got nil")
+ }
+}
diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.go
index 160b1020..c313bfc0 100644
--- a/cmd/sam-hub/main.go
+++ b/cmd/sam-hub/main.go
@@ -26,10 +26,11 @@ import (
"time"
"github.com/biscuit-auth/biscuit-go/v2"
+ "github.com/biscuit-auth/biscuit-go/v2/parser"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/golang-jwt/jwt/v5"
- golog "github.com/ipfs/go-log/v2"
"github.com/google/sam/api"
+ golog "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
pubsub "github.com/libp2p/go-libp2p-pubsub"
@@ -57,6 +58,7 @@ var (
meshName string
insecureSkipTLSVerify bool
logLevel string
+ policyFile string
)
var logger = golog.Logger("sam-hub")
@@ -71,10 +73,11 @@ type Hub struct {
PubSub *pubsub.PubSub
EventTopic *pubsub.Topic
gater *hubConnGate
+ Policy *api.PolicyConfig
}
// NewHub starts a host supporting both QUIC and TCP (with TLS 1.3)
-func NewHub(ctx context.Context) (*Hub, error) {
+func NewHub(ctx context.Context, policy *api.PolicyConfig) (*Hub, error) {
gater := newHubConnGate()
// Multi-transport setup for firewall traversal
h, err := libp2p.New(
@@ -141,6 +144,7 @@ func NewHub(ctx context.Context) (*Hub, error) {
Providers: providers,
BiscuitKey: bKey,
MeshID: meshName,
+ Policy: policy,
}
h.Network().Notify(&notifier{hub: hub})
@@ -185,8 +189,8 @@ func (h *Hub) handleEnroll(s network.Stream) {
}
// Parse JWT unverified to get issuer and audience
- parser := jwt.Parser{}
- jwtToken, _, err := parser.ParseUnverified(req.Jwt, jwt.MapClaims{})
+ jwtParser := jwt.Parser{}
+ jwtToken, _, err := jwtParser.ParseUnverified(req.Jwt, jwt.MapClaims{})
if err != nil {
logger.Errorf("[Enroll] Failed to parse JWT: %v", err)
h.sendEnrollResponse(s, nil, "Failed to parse JWT", 0, nil, nil)
@@ -285,6 +289,48 @@ func (h *Hub) handleEnroll(s network.Stream) {
h.sendEnrollResponse(s, nil, "Failed to mint biscuit", 0, nil, nil)
return
}
+
+ if h.Policy != nil {
+ if rolePolicy, ok := h.Policy.Roles[role]; ok {
+ for _, tool := range rolePolicy.MCP.AllowedTools {
+ if err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: api.FactMCPTool,
+ IDs: []biscuit.Term{biscuit.String(tool)},
+ }}); err != nil {
+ logger.Errorf("[Enroll] Failed to add fact %s: %v", api.FactMCPTool, 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.Errorf("[Enroll] Failed to add fact %s: %v", api.FactNetworkTarget, err)
+ }
+ }
+ for _, customFact := range rolePolicy.CustomDatalog {
+ trimmed := strings.TrimRight(strings.TrimSpace(customFact), ";")
+ if trimmed == "" {
+ continue
+ }
+ func() {
+ defer func() {
+ if r := recover(); r != nil {
+ logger.Errorf("[Enroll] Panic parsing custom fact %q: %v", trimmed, r)
+ }
+ }()
+ fact, err := parser.FromStringFact(trimmed)
+ if err != nil {
+ logger.Errorf("[Enroll] Failed to parse custom fact %q: %v", trimmed, err)
+ return
+ }
+ if err := builder.AddAuthorityFact(fact); err != nil {
+ logger.Errorf("[Enroll] Failed to add custom fact %s: %v", trimmed, err)
+ }
+ }()
+ }
+ }
+ }
}
t, err := builder.Build()
@@ -346,13 +392,12 @@ func (h *Hub) sendEnrollResponse(s network.Stream, biscuitToken []byte, errMsg s
pubKey := h.BiscuitKey.Public().(ed25519.PublicKey)
resp := &api.EnrollResponse{
- BiscuitToken: biscuitToken,
- ErrorMessage: errMsg,
- HubPublicKey: pubKey,
- HubAddresses: hubAddrs,
- Expiration: expiration,
- KnownPeers: knownPeers,
- DatalogPolicies: policies,
+ BiscuitToken: biscuitToken,
+ ErrorMessage: errMsg,
+ HubPublicKey: pubKey,
+ HubAddresses: hubAddrs,
+ Expiration: expiration,
+ KnownPeers: knownPeers,
}
data, err := proto.Marshal(resp)
if err != nil {
@@ -393,7 +438,7 @@ func main() {
Short: "Sovereign Agent Mesh - Multi-Transport Hub",
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
-
+
// Initialize logging
golog.SetAllLoggers(golog.LevelInfo)
if logLevel != "" {
@@ -402,8 +447,13 @@ func main() {
golog.SetAllLoggers(lvl)
}
}
-
- h, err := NewHub(ctx)
+
+ policyConfig, err := LoadPolicyConfig(policyFile)
+ if err != nil {
+ logger.Fatal(err)
+ }
+
+ h, err := NewHub(ctx, policyConfig)
if err != nil {
logger.Fatal(err)
}
@@ -432,6 +482,7 @@ func main() {
rootCmd.Flags().StringVar(&meshName, "mesh", "public-mesh", "Mesh federation name")
rootCmd.Flags().BoolVar(&insecureSkipTLSVerify, "insecure-skip-tls-verify", false, "Skip TLS verification for OIDC issuers")
rootCmd.Flags().StringVar(&logLevel, "log-level", "info", "Log level (debug, info, warn, error)")
+ rootCmd.Flags().StringVar(&policyFile, "policy-file", "policies.yaml", "Path to policies.yaml")
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
diff --git a/cmd/sam-node/config.go b/cmd/sam-node/config.go
new file mode 100644
index 00000000..12a64251
--- /dev/null
+++ b/cmd/sam-node/config.go
@@ -0,0 +1,67 @@
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/biscuit-auth/biscuit-go/v2"
+ "github.com/biscuit-auth/biscuit-go/v2/parser"
+ "github.com/google/sam/api"
+ "gopkg.in/yaml.v2"
+)
+
+type CompiledLocalPolicy struct {
+ Policies []biscuit.Policy
+ Checks []biscuit.Check
+ Rules []biscuit.Rule
+}
+
+// LoadLocalPolicy loads the local policy configuration from the specified path.
+// If the file is missing, it returns an empty initialized config.
+func LoadLocalPolicy(path string) (*CompiledLocalPolicy, error) {
+ if _, err := os.Stat(path); os.IsNotExist(err) {
+ return &CompiledLocalPolicy{}, nil
+ }
+
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+
+ var config api.LocalPolicy
+ if err := yaml.Unmarshal(data, &config); err != nil {
+ return nil, err
+ }
+
+ compiled := &CompiledLocalPolicy{}
+
+ for _, pStr := range config.Attenuation.Policies {
+ trimmed := strings.TrimRight(strings.TrimSpace(pStr), ";")
+ p, err := parser.FromStringPolicy(trimmed)
+ if err != nil {
+ return nil, fmt.Errorf("invalid local policy syntax %q: %w", pStr, err)
+ }
+ compiled.Policies = append(compiled.Policies, p)
+ }
+
+ for _, cStr := range config.Attenuation.Checks {
+ trimmed := strings.TrimRight(strings.TrimSpace(cStr), ";")
+ c, err := parser.FromStringCheck(trimmed)
+ if err != nil {
+ return nil, fmt.Errorf("invalid local check syntax %q: %w", cStr, err)
+ }
+ compiled.Checks = append(compiled.Checks, c)
+ }
+
+ for _, rStr := range config.Attenuation.Rules {
+ trimmed := strings.TrimRight(strings.TrimSpace(rStr), ";")
+ r, err := parser.FromStringRule(trimmed)
+ if err != nil {
+ return nil, fmt.Errorf("invalid local rule syntax %q: %w", rStr, err)
+ }
+ compiled.Rules = append(compiled.Rules, r)
+ }
+
+ return compiled, nil
+}
diff --git a/cmd/sam-node/config_test.go b/cmd/sam-node/config_test.go
new file mode 100644
index 00000000..fe25dcfa
--- /dev/null
+++ b/cmd/sam-node/config_test.go
@@ -0,0 +1,48 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestLoadLocalPolicy(t *testing.T) {
+ // 1. Test valid YAML
+ validYAML := `
+version: "v1alpha1"
+attenuation:
+ policies:
+ - 'deny if user("untrusted_sub_id");'
+ checks:
+ - 'check if time($time), $time < 2026-12-31T00:00:00Z;'
+`
+ dir := t.TempDir()
+ validFile := filepath.Join(dir, "local_policy.yaml")
+ if err := os.WriteFile(validFile, []byte(validYAML), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ config, err := LoadLocalPolicy(validFile)
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if len(config.Policies) != 1 {
+ t.Errorf("expected 1 policy, got %d", len(config.Policies))
+ }
+ if len(config.Checks) != 1 {
+ t.Errorf("expected 1 check, got %d", len(config.Checks))
+ }
+
+ // 2. Test missing file
+ missingFile := filepath.Join(dir, "nonexistent.yaml")
+ config, err = LoadLocalPolicy(missingFile)
+ if err != nil {
+ t.Fatalf("expected no error for missing file, got %v", err)
+ }
+ if config == nil {
+ t.Fatal("expected non-nil config for missing file")
+ }
+ if len(config.Policies) != 0 {
+ t.Errorf("expected empty policies, got %d", len(config.Policies))
+ }
+}
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index ae6859da..a94ef5a3 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -17,7 +17,6 @@ package main
import (
"context"
"crypto/ed25519"
- "encoding/base64"
"encoding/hex"
"fmt"
"net"
@@ -53,6 +52,7 @@ var (
discoveryIntervalFlag string
enableRelayFlag bool
logLevelFlag string
+ localPolicyFile string
)
var logger = golog.Logger("sam-node")
@@ -87,6 +87,11 @@ func main() {
if err != nil {
logger.Fatalf("Failed to open store: %v", err)
}
+
+ localPolicy, err := LoadLocalPolicy(localPolicyFile)
+ if err != nil {
+ logger.Fatalf("Failed to load local policy: %v", err)
+ }
defer func() {
if err := store.Close(); err != nil {
logger.Error("closing store: %v", err)
@@ -137,7 +142,7 @@ func main() {
if jwtStr == "" {
token, _ := store.LoadIdentity()
- if token == "" {
+ if len(token) == 0 {
logger.Fatal("No JWT or stored identity found. Cannot authenticate.")
}
fmt.Println("Using stored identity.")
@@ -146,7 +151,7 @@ func main() {
logger.Fatal("Hub public key not found in store and not provided. Cannot verify peers.")
}
priv := getOrGenerateKey(store)
- node, err = NewSamNode(context.Background(), priv, hubPubKey, hubAddrs, store, meshFlag, discoveryIntervalFlag, listenAddrs, enableRelayFlag)
+ node, err = NewSamNode(context.Background(), priv, hubPubKey, hubAddrs, store, meshFlag, discoveryIntervalFlag, listenAddrs, enableRelayFlag, localPolicy)
if err != nil {
logger.Fatalf("Failed to start mesh node: %v", err)
}
@@ -177,7 +182,7 @@ func main() {
}
priv := getOrGenerateKey(store)
- node, err = NewSamNode(context.Background(), priv, nil, initHubAddrs, store, meshFlag, discoveryIntervalFlag, listenAddrs, enableRelayFlag)
+ node, err = NewSamNode(context.Background(), priv, nil, initHubAddrs, store, meshFlag, discoveryIntervalFlag, listenAddrs, enableRelayFlag, localPolicy)
if err != nil {
logger.Fatalf("Failed to initialize node for enrollment: %v", err)
}
@@ -301,6 +306,11 @@ func main() {
if err != nil {
logger.Fatalf("Failed to open store: %v", err)
}
+
+ localPolicy, err := LoadLocalPolicy(localPolicyFile)
+ if err != nil {
+ logger.Fatalf("Failed to load local policy: %v", err)
+ }
defer func() {
if err := store.Close(); err != nil {
logger.Errorf("closing store: %v", err)
@@ -339,7 +349,7 @@ func main() {
}
priv := getOrGenerateKey(store)
- node, err := NewSamNode(context.Background(), priv, nil, initHubAddrs, store, meshFlag, discoveryIntervalFlag, listenAddrs, enableRelayFlag)
+ node, err := NewSamNode(context.Background(), priv, nil, initHubAddrs, store, meshFlag, discoveryIntervalFlag, listenAddrs, enableRelayFlag, localPolicy)
if err != nil {
logger.Fatalf("Failed to initialize node for enrollment: %v", err)
}
@@ -366,6 +376,7 @@ func main() {
runCmd.Flags().BoolVar(&enableRelayFlag, "enable-relay", false, "Allow this node to serve as a relay for others")
runCmd.Flags().StringVar(&logLevelFlag, "log-level", "info", "Log level (debug, info, warn, error)")
rootCmd.PersistentFlags().StringVar(&hubAddr, "hub", "http://localhost:8080", "Hub URL")
+ rootCmd.PersistentFlags().StringVar(&localPolicyFile, "local-policy", "local_policy.yaml", "Path to local_policy.yaml")
rootCmd.PersistentFlags().StringVar(&tokenURLFlag, "token-url", "", "OIDC Token URL")
rootCmd.AddCommand(runCmd)
@@ -454,8 +465,7 @@ func (n *SamNode) Enroll(ctx context.Context, jwt string) error {
return fmt.Errorf("received empty biscuit token")
}
- tokenStr := base64.StdEncoding.EncodeToString(resp.BiscuitToken)
- if err := n.Store.SaveIdentity(tokenStr); err != nil {
+ if err := n.Store.SaveIdentity(resp.BiscuitToken); err != nil {
return fmt.Errorf("failed to save identity: %v", err)
}
@@ -467,11 +477,7 @@ func (n *SamNode) Enroll(ctx context.Context, jwt string) error {
return fmt.Errorf("failed to save hub config: %v", err)
}
- if len(resp.DatalogPolicies) > 0 {
- if err := n.Store.SavePolicies(resp.DatalogPolicies); err != nil {
- return fmt.Errorf("failed to save policies: %v", err)
- }
- }
+
// Add known peers from response
n.mu.Lock()
diff --git a/cmd/sam-node/mcp.go b/cmd/sam-node/mcp.go
index 93a90118..f20f08dc 100644
--- a/cmd/sam-node/mcp.go
+++ b/cmd/sam-node/mcp.go
@@ -156,6 +156,34 @@ func NewMCPHandler(node *SamNode) http.Handler {
}, nil, nil
})
+ // Add the call_remote_tool tool.
+ mcp.AddTool(server, &mcp.Tool{
+ Name: "call_remote_tool",
+ Description: "Call an MCP tool on a remote agent",
+ }, func(ctx context.Context, req *mcp.CallToolRequest, params struct {
+ PeerID string `json:"peer_id" jsonschema:"The Peer ID of the target agent"`
+ ToolName string `json:"tool_name" jsonschema:"The name of the tool to call"`
+ Arguments string `json:"arguments" jsonschema:"JSON encoded arguments for the tool"`
+ }) (*mcp.CallToolResult, any, error) {
+ logger.Infof("[MCP] call_remote_tool called for peer %s, tool %s", params.PeerID, params.ToolName)
+ targetPeer, err := peer.Decode(params.PeerID)
+ if err != nil {
+ return nil, nil, err
+ }
+ var args map[string]any
+ if params.Arguments != "" {
+ if err := json.Unmarshal([]byte(params.Arguments), &args); err != nil {
+ return nil, nil, err
+ }
+ }
+
+ res, err := node.CallMCPTool(ctx, targetPeer, params.ToolName, args)
+ if err != nil {
+ return nil, nil, err
+ }
+ return res, nil, nil
+ })
+
// Add the connect_peer tool.
mcp.AddTool(server, &mcp.Tool{
Name: "connect_peer",
@@ -221,14 +249,14 @@ func (n *SamNode) callMCPToolOnce(ctx context.Context, targetPeer peer.ID, toolN
}()
// Load this node's biscuit
- biscuitStr, err := n.Store.LoadIdentity()
+ biscuitBytes, err := n.Store.LoadIdentity()
if err != nil {
return nil, fmt.Errorf("failed to load identity biscuit: %w", err)
}
// Marshal AuthFrame
authFrame := api.AuthFrame{
- Biscuit: []byte(biscuitStr),
+ Biscuit: biscuitBytes,
}
authBytes, _ := proto.Marshal(&authFrame)
diff --git a/cmd/sam-node/middleware.go b/cmd/sam-node/middleware.go
index db30f552..48f6351b 100644
--- a/cmd/sam-node/middleware.go
+++ b/cmd/sam-node/middleware.go
@@ -16,7 +16,6 @@ package main
import (
"fmt"
- "strings"
"github.com/biscuit-auth/biscuit-go/v2"
"github.com/biscuit-auth/biscuit-go/v2/parser"
@@ -118,19 +117,33 @@ func (n *SamNode) Authorize(rawToken []byte, req RequestContext) error {
},
})
- // Load dynamic policies from store and add them as facts
- policies, err := n.Store.LoadPolicies()
+ // Apply Pre-compiled Local Attenuation
+ if n.LocalPolicy != nil {
+ for _, p := range n.LocalPolicy.Policies {
+ authorizer.AddPolicy(p)
+ }
+ for _, c := range n.LocalPolicy.Checks {
+ authorizer.AddCheck(c)
+ }
+ for _, r := range n.LocalPolicy.Rules {
+ authorizer.AddRule(r)
+ }
+ }
+
+ // Baseline Rules
+ rule1Str := fmt.Sprintf(`allow if operation($op), %s($op)`, api.FactMCPTool)
+ rule1, err := parser.FromStringPolicy(rule1Str)
if err != nil {
- return fmt.Errorf("failed to load policies: %w", err)
+ return fmt.Errorf("failed to parse baseline rule 1: %w", err)
}
- for _, policyStr := range policies {
- cleanPolicy := strings.TrimRight(strings.TrimSpace(policyStr), ";")
- p, err := parser.FromStringPolicy(cleanPolicy)
- if err != nil {
- return fmt.Errorf("failed to parse policy '%s': %w", policyStr, err)
- }
- authorizer.AddPolicy(p)
+ authorizer.AddPolicy(rule1)
+
+ rule2Str := fmt.Sprintf(`allow if operation($op), %s("*")`, api.FactMCPTool)
+ rule2, err := parser.FromStringPolicy(rule2Str)
+ if err != nil {
+ return fmt.Errorf("failed to parse baseline rule 2: %w", err)
}
+ authorizer.AddPolicy(rule2)
return authorizer.Authorize()
}
diff --git a/cmd/sam-node/middleware_test.go b/cmd/sam-node/middleware_test.go
index 4bf72a70..ad76fc45 100644
--- a/cmd/sam-node/middleware_test.go
+++ b/cmd/sam-node/middleware_test.go
@@ -17,10 +17,14 @@ package main
import (
"crypto/ed25519"
"os"
+ "path/filepath"
"testing"
"github.com/biscuit-auth/biscuit-go/v2"
+ "github.com/biscuit-auth/biscuit-go/v2/parser"
+ "github.com/google/sam/api"
"github.com/libp2p/go-libp2p/core/peer"
+ "github.com/libp2p/go-libp2p/core/protocol"
)
func TestAuthorize(t *testing.T) {
@@ -40,11 +44,7 @@ func TestAuthorize(t *testing.T) {
_ = store.Close()
}()
- // Save a dummy policy
- policies := []string{"allow if operation($op)"}
- if err := store.SavePolicies(policies); err != nil {
- t.Fatal(err)
- }
+
// Create a biscuit token
pub, priv, err := ed25519.GenerateKey(nil)
@@ -64,23 +64,15 @@ func TestAuthorize(t *testing.T) {
t.Fatal(err)
}
- // Add fact and rule to make it succeed
+ // Add fact to match baseline rule
err = builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
- Name: "right",
- IDs: []biscuit.Term{biscuit.String("test")},
+ Name: api.FactMCPTool,
+ IDs: []biscuit.Term{biscuit.String("/test/proto")},
}})
if err != nil {
t.Fatal(err)
}
- err = builder.AddAuthorityRule(biscuit.Rule{
- Head: biscuit.Predicate{Name: "allow", IDs: []biscuit.Term{}},
- Body: []biscuit.Predicate{{Name: "right", IDs: []biscuit.Term{biscuit.String("test")}}},
- })
- if err != nil {
- t.Fatal(err)
- }
-
b, err := builder.Build()
if err != nil {
t.Fatal(err)
@@ -105,3 +97,151 @@ func TestAuthorize(t *testing.T) {
t.Fatalf("Authorize failed: %v", err)
}
}
+
+func TestEnterprisePolicyEngine(t *testing.T) {
+ pub, priv, err := ed25519.GenerateKey(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ dummyPeer := peer.ID("dummy-peer")
+
+ tests := []struct {
+ name string
+ mintToken func(t *testing.T, builder biscuit.Builder)
+ operation string
+ localPolicyYAML string
+ expectSuccess bool
+ }{
+ {
+ name: "Case 1 (Happy Path)",
+ mintToken: func(t *testing.T, builder biscuit.Builder) {
+ fact, err := parser.FromStringFact(`allow_mcp_tool("query_db")`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := builder.AddAuthorityFact(fact); err != nil {
+ t.Fatal(err)
+ }
+ },
+ operation: "query_db",
+ expectSuccess: true,
+ },
+ {
+ name: "Case 2 (Unauthorized Tool)",
+ mintToken: func(t *testing.T, builder biscuit.Builder) {
+ fact, err := parser.FromStringFact(`allow_mcp_tool("query_db")`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := builder.AddAuthorityFact(fact); err != nil {
+ t.Fatal(err)
+ }
+ },
+ operation: "reboot_server",
+ expectSuccess: false,
+ },
+ {
+ name: "Case 3 (Wildcard Access)",
+ mintToken: func(t *testing.T, builder biscuit.Builder) {
+ fact, err := parser.FromStringFact(`allow_mcp_tool("*")`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := builder.AddAuthorityFact(fact); err != nil {
+ t.Fatal(err)
+ }
+ },
+ operation: "anything",
+ expectSuccess: true,
+ },
+ {
+ name: "Case 4 (Local Attenuation Override)",
+ mintToken: func(t *testing.T, builder biscuit.Builder) {
+ fact1, err := parser.FromStringFact(`allow_mcp_tool("*")`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := builder.AddAuthorityFact(fact1); err != nil {
+ t.Fatal(err)
+ }
+ fact2, err := parser.FromStringFact(`user("alice")`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := builder.AddAuthorityFact(fact2); err != nil {
+ t.Fatal(err)
+ }
+ },
+ operation: "query_db",
+ localPolicyYAML: `
+version: "v1alpha1"
+attenuation:
+ policies:
+ - 'deny if user("alice");'
+`,
+ expectSuccess: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ builder := biscuit.NewBuilder(priv)
+
+ err := builder.AddAuthorityFact(biscuit.Fact{Predicate: biscuit.Predicate{
+ Name: "node",
+ IDs: []biscuit.Term{biscuit.String(dummyPeer.String())},
+ }})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ tt.mintToken(t, builder)
+
+ b, err := builder.Build()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ tokenBytes, err := b.Serialize()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ var localPolicy *CompiledLocalPolicy
+ if tt.localPolicyYAML != "" {
+ dir := t.TempDir()
+ policyFile := filepath.Join(dir, "local_policy.yaml")
+ if err := os.WriteFile(policyFile, []byte(tt.localPolicyYAML), 0644); err != nil {
+ t.Fatal(err)
+ }
+ var err error
+ localPolicy, err = LoadLocalPolicy(policyFile)
+ if err != nil {
+ t.Fatalf("failed to load local policy: %v", err)
+ }
+ }
+
+ node := &SamNode{
+ HubPublicKey: pub,
+ LocalPolicy: localPolicy,
+ }
+
+ req := RequestContext{
+ PeerID: dummyPeer,
+ Protocol: protocol.ID(tt.operation),
+ }
+
+ err = node.Authorize(tokenBytes, req)
+ if tt.expectSuccess {
+ if err != nil {
+ t.Errorf("expected success, got error: %v", err)
+ }
+ } else {
+ if err == nil {
+ t.Error("expected failure, got success")
+ }
+ }
+ })
+ }
+}
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index 6987b3cd..6d30d74e 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -54,16 +54,18 @@ type SamNode struct {
receivedMsgs map[string][]string
topics map[string]*pubsub.Topic
mu sync.Mutex
+ LocalPolicy *CompiledLocalPolicy
}
// NewSamNode creates a new Agent instance secured with the 4-layer pipeline.
-func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.PublicKey, hubAddrs []multiaddr.Multiaddr, store *Store, meshID string, discoveryInterval string, listenAddrs []string, enableRelay bool) (*SamNode, error) {
+func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.PublicKey, hubAddrs []multiaddr.Multiaddr, store *Store, meshID string, discoveryInterval string, listenAddrs []string, enableRelay bool, localPolicy *CompiledLocalPolicy) (*SamNode, error) {
node := &SamNode{
Store: store,
HubPublicKey: hubPubKey,
knownPeers: make(map[string]bool),
receivedMsgs: make(map[string][]string),
topics: make(map[string]*pubsub.Topic),
+ LocalPolicy: localPolicy,
}
// Layer 2: Attach the Bouncer (Gater)
diff --git a/cmd/sam-node/store.go b/cmd/sam-node/store.go
index f0bcd79a..79f62e93 100644
--- a/cmd/sam-node/store.go
+++ b/cmd/sam-node/store.go
@@ -29,7 +29,6 @@ const (
keyBiscuit = "identity_biscuit"
keyPrivKey = "node_private_key"
keyIdentityExp = "identity_expiration"
- keyPolicies = "datalog_policies"
)
type Store struct {
@@ -71,14 +70,14 @@ func NewStore(dir string) (*Store, error) {
return &Store{db: db}, err
}
-func (s *Store) SaveIdentity(biscuit string) error {
+func (s *Store) SaveIdentity(biscuit []byte) error {
return s.db.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte(bucketIdentity))
- return b.Put([]byte(keyBiscuit), []byte(biscuit))
+ return b.Put([]byte(keyBiscuit), biscuit)
})
}
-func (s *Store) LoadIdentity() (string, error) {
+func (s *Store) LoadIdentity() ([]byte, error) {
var val []byte
_ = s.db.View(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte(bucketIdentity))
@@ -86,9 +85,9 @@ func (s *Store) LoadIdentity() (string, error) {
return nil
})
if len(val) == 0 {
- return "", fmt.Errorf("no identity found")
+ return nil, fmt.Errorf("no identity found")
}
- return string(val), nil
+ return val, nil
}
func (s *Store) SaveIdentityExpiration(exp int64) error {
@@ -224,25 +223,4 @@ func (s *Store) GetVerifiedIdentity(p peer.ID) (*VerifiedIdentity, error) {
return &identity, err
}
-func (s *Store) SavePolicies(policies []string) error {
- return s.db.Update(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- data, _ := json.Marshal(policies)
- return b.Put([]byte(keyPolicies), data)
- })
-}
-func (s *Store) LoadPolicies() ([]string, error) {
- var val []byte
- _ = s.db.View(func(tx *bbolt.Tx) error {
- b := tx.Bucket([]byte(bucketIdentity))
- val = b.Get([]byte(keyPolicies))
- return nil
- })
- if len(val) == 0 {
- return nil, nil // Return empty if none found
- }
- var policies []string
- err := json.Unmarshal(val, &policies)
- return policies, err
-}
diff --git a/cmd/sam-node/store_test.go b/cmd/sam-node/store_test.go
index bdc3ddb4..cccccecc 100644
--- a/cmd/sam-node/store_test.go
+++ b/cmd/sam-node/store_test.go
@@ -14,46 +14,6 @@
package main
-import (
- "os"
- "testing"
-)
-func TestStorePolicies(t *testing.T) {
- dir, err := os.MkdirTemp("", "store-test")
- if err != nil {
- t.Fatal(err)
- }
- defer func() {
- _ = os.RemoveAll(dir)
- }()
- store, err := NewStore(dir)
- if err != nil {
- t.Fatal(err)
- }
- defer func() {
- _ = store.Close()
- }()
- policies := []string{"allow if operation($op)", "deny if user(bad)"}
-
- if err := store.SavePolicies(policies); err != nil {
- t.Fatalf("failed to save policies: %v", err)
- }
-
- loaded, err := store.LoadPolicies()
- if err != nil {
- t.Fatalf("failed to load policies: %v", err)
- }
-
- if len(loaded) != len(policies) {
- t.Fatalf("expected %d policies, got %d", len(policies), len(loaded))
- }
-
- for i, p := range policies {
- if loaded[i] != p {
- t.Errorf("expected policy %s, got %s", p, loaded[i])
- }
- }
-}
diff --git a/docs/policy.md b/docs/policy.md
new file mode 100644
index 00000000..856ef590
--- /dev/null
+++ b/docs/policy.md
@@ -0,0 +1,43 @@
+# SAM Policy & Authorization Reference
+
+SAM uses a decentralized authorization model powered by [Biscuit](https://www.biscuitsec.org/).
+The `sam-hub` authenticates users via OIDC and injects **Facts** into their token based on `policies.yaml`. The `sam-node` operates offline, evaluating the token against baseline rules and optional local attenuation policies.
+
+## 1. OIDC to Biscuit Translation
+The Hub automatically translates OIDC claims into undeniable cryptographic facts:
+
+| OIDC Claim / Data | Biscuit Fact | Description |
+| :--- | :--- | :--- |
+| `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. |
+
+## 2. Hub Policy Schema (`policies.yaml`)
+Admins define central permissions by mapping OIDC roles to specific capabilities.
+
+```yaml
+version: "v1alpha1"
+roles:
+ data-scientist:
+ network:
+ allowed_targets: ["db-agent.data-mesh"] # Who they can connect to
+ mcp:
+ allowed_tools: ["query_database"] # What tools they can run
+ custom_datalog:
+ - 'department("analytics");' # Raw injected facts
+```
+
+## 3. Node Local Attenuation Schema (`local_policy.yaml`)
+Local developers can further restrict access to their specific node. Local policies can only attenuate (restrict) access, never expand it beyond what the Hub allowed.
+
+```yaml
+version: "v1alpha1"
+attenuation:
+ rules:
+ - 'deny if user("untrusted_sub_id");'
+ checks:
+ - 'check if time($time), $time < 2026-12-31T00:00:00Z;'
+```
diff --git a/go.mod b/go.mod
index 50aeba4a..594472ab 100644
--- a/go.mod
+++ b/go.mod
@@ -17,6 +17,7 @@ require (
go.etcd.io/bbolt v1.4.3
golang.org/x/oauth2 v0.36.0
google.golang.org/protobuf v1.36.11
+ gopkg.in/yaml.v2 v2.4.0
)
require (
diff --git a/tests/e2e/policy.bats b/tests/e2e/policy.bats
new file mode 100644
index 00000000..b706c5cb
--- /dev/null
+++ b/tests/e2e/policy.bats
@@ -0,0 +1,291 @@
+#!/usr/bin/env bats
+
+load "lib/container_mesh.bash"
+
+# Custom mock OIDC server that returns 'data-scientist' role
+mesh_start_mock_oidc_custom() {
+ local name="${MESH_PREFIX}-oidc"
+ local cmd
+ read -r -d '' cmd <<'EOF' || true
+python3 - <<'PY'
+import json
+import time
+import jwt
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+PRIVATE_KEY = """-----BEGIN PRIVATE KEY-----
+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDGtPD85uaT342Y
+yqGAiWQ6OV2BxvpXQRMzsb7VpdLa146xf5/1b9lIR4dFvhvGUqnyzFLV0EdIzTqo
+xyKGHbQY68DIUjH3iwt6rzU0Vkw/3g/R/TBEmGwdqNDLCBItsLOnF4HfsxAWtjaU
+R96S4oXaCUcXOD/3yHs0ha4tu8YgwGwMHa/CQRgcTX5FshR6uHow5G7NiOVYUcAP
+c1HXmwmf0FeSY9r0QudmIjkJSeIH1I/BufpEqbcjrSyjYd4eldbhjlCvuIR93Sva
+8jZBzdCW+xxyU+8dz2tEgRjm9G7CpoCpAwhcEQQW7XRUb8DP9+bid9VfT+3C1Te6
+u8eowndXAgMBAAECggEAGF6ZjZKt5aXNolb7jp2K/r8JUkC6dBgFiFn8uwwOu4sj
+M26hCgNRJRWsp+eEVYLO1/mqERHtpCaTUp61g7hB3aqQJqE6Ao95dW7megg5ar3L
+t+ey0z7UR6DsFnJjdFoO9meiJHK7/uUS9YWI7P++BbsMjnL2GWfrgEoCzhYQ2vQ2
+8t9lGmJfaEeicTcPs4/Jtz9nX+KQ1CqKb5uHP6IyVQjV/nIjWh1WZJV5wsmLM1ZF
+YT7NPEhXkgH5JjwzEI3QR9ZMs4FUgbduImmS280YCMNMUNVsSBbbV/1hh7Sxlp6B
+bRaK12sPPRwW0sHw3odZKjGzKIFlu9I5TieNJ5w2AQKBgQDy3cxDXxj+bcSYuWDp
+p4EVNTwg+IY9eT0x1x+tWXaOjGTscD4GrdUYhspWuoUn5NxZ0ub0apiTMQfoM9a0
+Qr3CKngkL5JTi6OwdnEaTPNvQiSJdgXXzYdCXeucK5soeHCZTPAb3bV27LtpxyMI
+QSx9rnKcSyoRSavLWP0hr8QNVwKBgQDRc84q3I5tZX/whoUmeTj6aNJoIa1KAACM
+0Fnr9ecjLS50kXIiTSCiNE8pcBcsSxYgo+PG5W9oQaZcdd7r2nJOqaizpjnHbF+9
+S/Ts9vj+dJlCUcjjROghzYrI5mdb8Dq2Ngd93IcBt5H+W6bm8wWUgLy0IJmJDKHE
+Z7SS22imAQKBgAETHi5GI3QsxCvw1g7yoM2ZOLTkpKNs/+pSi19XAAFNebzaGkwp
+RMIhBpAvrxsoFhmHp2H5fsdX9jL+17pgeTp8uZ9fXoRkH8tOGt4E7SbW4haBoTD9
+RdXzWHGOd9dMASOMhZt59a2bCpFDQlJtB2de+D7czkjZTJtPv38AqhttAoGAE8X2
+Aa/etk8tu9xHN7GcAm/g5TnArUrAwops4szNLFH4n8KXXsufOBDuJEBTv7e6+Avg
+1gcU9Ge2N+ZczDFMN0bnCUa5D62YgDtqfPB34zXIvi0QZPw9WeuYnYy610AfmtIQ
+9P3btPrKipPGdukcbr+UkQC+3eRWZT9RGcgi4gECgYApA3J0jlD+JFtYKFOuJWxS
+aFEhYPe2dVW78bJoMMhxPtD9hWw/zWVUdyhdXMHoP8/igwNiUqXaYacPbxTFu5ft
+w/+UummqB6KpqPFnpbqP826Udr4SEHH0iwvs4MDqSlXcOC5CXbIoMLB/zMjE+u/J
+IqNKTt9jbR4zISCpyOCsQw==
+-----END PRIVATE KEY-----"""
+
+JWKS = {
+ "keys": [
+ {
+ "kty": "RSA",
+ "alg": "RS256",
+ "use": "sig",
+ "kid": "test-key-id",
+ "n": "xrTw_Obmk9-NmMqhgIlkOjldgcb6V0ETM7G-1aXS2teOsX-f9W_ZSEeHRb4bxlKp8sxS1dBHSM06qMcihh20GOvAyFIx94sLeq81NFZMP94P0f0wRJhsHajQywgSLbCzpxeB37MQFrY2lEfekuKF2glHFzg_98h7NIWuLbvGIMBsDB2vwkEYHE1-RbIUerh6MORuzYjlWFHAD3NR15sJn9BXkmPa9ELnZiI5CUniB9SPwbn6RKm3I60so2HeHpXW4Y5Qr7iEfd0r2vI2Qc3QlvscclPvHc9rRIEY5vRuwqaAqQMIXBEEFu10VG_Az_fm4nfVX0_twtU3urvHqMJ3Vw",
+ "e": "AQAB"
+ }
+ ]
+}
+
+class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ if self.path == '/.well-known/openid-configuration':
+ body = {
+ 'issuer': 'http://mock-oidc:18080',
+ 'authorization_endpoint': 'http://mock-oidc:18080/auth',
+ 'token_endpoint': 'http://mock-oidc:18080/token',
+ 'jwks_uri': 'http://mock-oidc:18080/keys'
+ }
+ data = json.dumps(body).encode('utf-8')
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ if self.path == '/keys':
+ data = json.dumps(JWKS).encode('utf-8')
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ self.send_response(200)
+ self.end_headers()
+ self.wfile.write(b'ok')
+
+ def do_POST(self):
+ if self.path == '/token':
+ payload = {
+ 'iss': 'http://mock-oidc:18080',
+ 'aud': 'sam-e2e',
+ 'sub': 'test-user',
+ 'exp': int(time.time()) + 3600,
+ 'roles': ['data-scientist'] # Custom role
+ }
+ token = jwt.encode(payload, PRIVATE_KEY, algorithm='RS256', headers={'kid': 'test-key-id'})
+ body = {
+ 'access_token': token,
+ 'token_type': 'Bearer',
+ 'expires_in': 3600
+ }
+ data = json.dumps(body).encode('utf-8')
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ self.send_response(404)
+ self.end_headers()
+
+print("Mock OIDC server ready", flush=True)
+HTTPServer(('0.0.0.0', 18080), Handler).serve_forever()
+PY
+EOF
+
+ docker run -d \
+ --name "${name}" \
+ --network "${MESH_NETWORK}" \
+ --network-alias mock-oidc \
+ python:3.12 \
+ sh -lc "pip install pyjwt cryptography && ${cmd}" >/dev/null
+
+ MESH_CONTAINERS+=("${name}")
+ mesh_wait_for_log "${name}" "Mock OIDC server ready" 30
+}
+
+mesh_call_remote_tool() {
+ local caller_idx="$1"
+ local target_peer_id="$2"
+ local tool_name="$3"
+
+ local args="{\"peer_id\":\"${target_peer_id}\",\"tool_name\":\"${tool_name}\",\"arguments\":\"{}\"}"
+
+ docker run --rm -v "${MESH_SOCKET_DIR}:/sockets" -v "$(pwd)/bin/mcp-client:/mcp-client" python:3.12 /mcp-client -socket "/sockets/node-${caller_idx}.sock" -tool "call_remote_tool" -args "${args}"
+}
+
+setup() {
+ if ! mesh_require_docker; then
+ skip "docker not available or daemon not running"
+ fi
+
+ if [[ ! -x "./bin/sam-node" || ! -x "./bin/sam-hub" ]]; then
+ skip "missing binaries; run: make build"
+ fi
+
+ mesh_setup_env
+ mkdir -p tests/e2e/logs
+
+ # Create volume for policies
+ export POLICY_VOL="${MESH_PREFIX}-policy"
+ docker volume create "${POLICY_VOL}"
+
+ # Write policies to volume
+ local hub_policy="version: \"v1alpha1\"
+roles:
+ data-scientist:
+ mcp:
+ allowed_tools:
+ - \"query_database\"
+ - \"delete_tables\""
+
+ local node_policy="version: \"v1alpha1\"
+attenuation:
+ policies:
+ - 'deny if operation(\"delete_tables\");'"
+
+ docker run --rm -v "${POLICY_VOL}:/policies" busybox sh -c "cat <<'EOF' > /policies/policies.yaml
+${hub_policy}
+EOF
+cat <<'EOF' > /policies/local_policy.yaml
+${node_policy}
+EOF"
+
+ # Start services
+ run mesh_start_mock_oidc_custom
+ [[ "$status" -eq 0 ]]
+
+ # Start Hub with policy file
+ local hub_name="${MESH_PREFIX}-hub"
+ local key
+ key="$(mesh_gen_hex32)"
+
+ docker run -d \
+ --name "${hub_name}" \
+ --network "${MESH_NETWORK}" \
+ --network-alias sam-hub \
+ -v "${POLICY_VOL}:/etc/sam" \
+ "sam-hub:local" \
+ --issuer "http://mock-oidc:18080" \
+ --client-id "sam-e2e" \
+ --key "${key}" \
+ --listen "/ip4/0.0.0.0/udp/4001/quic-v1" \
+ --listen "/ip4/0.0.0.0/tcp/4002" \
+ --mesh "e2e-mesh" \
+ --policy-file "/etc/sam/policies.yaml" >/dev/null
+
+ MESH_CONTAINERS+=("${hub_name}")
+ mesh_wait_for_log "${hub_name}" "PeerID:" 20
+
+ local hub_peer_id
+ hub_peer_id=$(docker logs "${hub_name}" 2>&1 | grep -oE '12D3Koo[a-zA-Z0-9]+' | head -n 1)
+ echo "${hub_peer_id}" > "/tmp/${MESH_PREFIX}-hub-peer-id"
+
+ # Start Node 1 (Target) with local policy
+ docker run -d \
+ --name "${MESH_PREFIX}-node-1" \
+ --network "${MESH_NETWORK}" \
+ --network-alias "sam-node-1" \
+ -v "${MESH_SOCKET_DIR}:/sockets" \
+ -v "${POLICY_VOL}:/etc/sam" \
+ "sam-node:local" \
+ run \
+ --hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}" \
+ --client-id "sam-e2e" \
+ --client-secret "sam-e2e-secret" \
+ --token-url "http://mock-oidc:18080/token" \
+ --listen "/ip4/0.0.0.0/udp/5001/quic-v1" \
+ --listen "/ip4/0.0.0.0/tcp/5002" \
+ --mcp-socket "/sockets/node-1.sock" \
+ --mesh "e2e-mesh" \
+ --local-policy "/etc/sam/local_policy.yaml" >/dev/null
+
+ MESH_CONTAINERS+=("${MESH_PREFIX}-node-1")
+ mesh_wait_for_log "${MESH_PREFIX}-node-1" "Successfully enrolled" 20
+
+ # Start Node 2 (Caller) without specific local policy
+ mesh_start_node 2
+ mesh_wait_for_mcp_ready 2
+
+ mesh_wait_for_log "${MESH_PREFIX}-node-2" "SAM Node Online" 20
+ local node2_id
+ node2_id=$(docker logs "${MESH_PREFIX}-node-2" 2>&1 | grep -A 1 "SAM Node Online" | grep -oE '12D3Koo[a-zA-Z0-9]+' | head -n 1)
+
+ # Wait for discovery (Node 2 should see Node 1)
+ local i
+ local hub_id
+ hub_id="$(cat "/tmp/${MESH_PREFIX}-hub-peer-id")"
+ export TARGET_PEER_ID=""
+
+ for ((i=0; i<30; i++)); do
+ local output
+ output="$(docker run --rm -v "${MESH_SOCKET_DIR}:/sockets" -v "$(pwd)/bin/mcp-client:/mcp-client" python:3.12 /mcp-client -socket "/sockets/node-2.sock" 2>/dev/null)"
+ TARGET_PEER_ID=$(echo "${output}" | grep -oE '12D3Koo[a-zA-Z0-9]+' | grep -v "${hub_id}" | grep -v "${node2_id}" | head -n 1)
+ if [[ -n "${TARGET_PEER_ID}" ]]; then
+ break
+ fi
+ sleep 1
+ done
+
+ if [[ -z "${TARGET_PEER_ID}" ]]; then
+ echo "Timeout waiting for discovery of Node 1"
+ return 1
+ fi
+
+ # Explicitly connect Node 2 to Node 1 to avoid "no addresses" error
+ local node1_addr="/dns4/sam-node-1/tcp/5002/p2p/${TARGET_PEER_ID}"
+ docker run --rm -v "${MESH_SOCKET_DIR}:/sockets" -v "$(pwd)/bin/mcp-client:/mcp-client" python:3.12 /mcp-client -socket "/sockets/node-2.sock" -tool "connect_peer" -args "{\"peer_addr\":\"${node1_addr}\"}" >/dev/null
+}
+
+teardown() {
+ if [[ "${BATS_TEST_COMPLETED:-0}" -ne 1 ]]; then
+ mkdir -p tests/e2e/logs
+ local ids
+ ids="$(docker ps -aq --filter "name=mesh-")"
+ for id in ${ids}; do
+ local name
+ name="$(docker inspect -f '{{.Name}}' "${id}" | tr -d '/')"
+ docker logs "${id}" > "tests/e2e/logs/${name}.log" 2>&1 || true
+ done
+ fi
+ mesh_cleanup_env
+ docker volume rm "${POLICY_VOL}" >/dev/null 2>&1 || true
+}
+
+@test "Policy E2E: Positive Path (Allowed by Hub, Not blocked by Node)" {
+ run mesh_call_remote_tool 2 "${TARGET_PEER_ID}" "query_database"
+ echo "Output: $output"
+ [ "$status" -eq 0 ]
+}
+
+@test "Policy E2E: Negative Path (Denied by Hub)" {
+ run mesh_call_remote_tool 2 "${TARGET_PEER_ID}" "reboot_server"
+ echo "Output: $output"
+ [[ "$output" == *"denied"* ]]
+}
+
+@test "Policy E2E: Attenuation Path (Allowed by Hub, Blocked by Node)" {
+ run mesh_call_remote_tool 2 "${TARGET_PEER_ID}" "delete_tables"
+ echo "Output: $output"
+ [[ "$output" == *"denied"* ]]
+}