Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
refactor to use rdvz
Antonio Ojead40287270b09
diff --git a/README.md b/README.mdindex 347b8888..cbcebaa0 100644--- a/README.md+++ b/README.md@@ -49,6 +49,7 @@ sam-agent inspect biscuit "vendor-bot;allow_skill=risk-audit"- Docs site: https://aojea.github.io/sam- Manifesto: https://aojea.github.io/sam/#/README.md- User journey (dark mesh): https://aojea.github.io/sam/#/guides/dark-mesh.md+- Hub as rendezvous point: https://aojea.github.io/sam/#/guides/hub-rendezvous.md- CLI reference: https://aojea.github.io/sam/#/cli/reference.md- Testing guide: https://aojea.github.io/sam/#/testing.mddiff --git a/cmd/sam-agent/node.go b/cmd/sam-agent/node.goindex f704b4a1..99351980 100644--- a/cmd/sam-agent/node.go+++ b/cmd/sam-agent/node.go@@ -16,9 +16,12 @@ package mainimport ("context"+ "encoding/json""encoding/pem""fmt""log/slog"+ "net/http"+ "net/url""os""os/signal""strings"@@ -32,12 +35,21 @@ import ()// buildNode constructs a SAM mesh node from the shared runConfig flags.+// --hub is mandatory: the hub provides OIDC-backed passport issuance and+// acts as the mandatory P2P rendezvous/bootstrap point for the mesh.func buildNode(cfg *runConfig) (samnet.Node, error) {+ hubURL := strings.TrimSpace(resolveHubURL(cfg))+ if hubURL == "" {+ return nil, fmt.Errorf("--hub (or SAM_HUB env) is required: the hub is the rendezvous point and passport issuer for the mesh")+ }+listen, err := parseMultiaddrs(cfg.listenAddrs)if err != nil {return nil, fmt.Errorf("parsing --listen: %w", err)}- bootstrap, err := parseMultiaddrs(cfg.bootstrapAddrs)++ // Explicit --bootstrap peers (additive with hub-resolved peers).+ extraBootstrap, err := parseMultiaddrs(cfg.bootstrapAddrs)if err != nil {return nil, fmt.Errorf("parsing --bootstrap: %w", err)}@@ -47,14 +59,28 @@ func buildNode(cfg *runConfig) (samnet.Node, error) {return nil, fmt.Errorf("loading identity key: %w", err)}+ // Resolve hub hostname for rendezvous namespace and relay hint.+ hubHost := hubHostFromURL(hubURL)++ // Fetch hub P2P bootstrap addresses from the hub's well-known endpoint.+ // This is the primary rendezvous mechanism: all agents bootstrap through+ // the hub, which acts as DHT server and relay.+ hubBootstrap, err := fetchHubP2PAddrs(hubURL)+ if err != nil {+ slog.Default().Warn("could not fetch hub P2P addresses; hub may not be running in P2P mode", "hub", hubURL, "err", err)+ }+ allBootstrap := append(hubBootstrap, extraBootstrap...)+opts := []samnet.Option{samnet.WithListenAddrs(listen...),- samnet.WithBootstrapPeers(bootstrap...),+ samnet.WithBootstrapPeers(allBootstrap...),samnet.WithDHTMode(parseDHTMode(cfg.dhtMode)),samnet.WithFederation(defaultFederationID),samnet.WithUserAgent(cfg.userAgent),samnet.WithLogger(slog.Default()),samnet.WithPrivateKey(key),+ samnet.WithRendezvousNamespace(hubHost),+ samnet.WithRelayFallbackHost(hubHost),}if cfg.withRelay {opts = append(opts, samnet.WithRelayService())@@ -63,6 +89,43 @@ func buildNode(cfg *runConfig) (samnet.Node, error) {return samnet.New(opts...)}+// fetchHubP2PAddrs contacts the hub's /.well-known/sam-hub-p2p endpoint and+// returns the hub's libp2p multiaddrs for use as bootstrap/rendezvous peers.+func fetchHubP2PAddrs(hubURL string) ([]multiaddr.Multiaddr, error) {+ endpoint := strings.TrimRight(hubURL, "/") + "/.well-known/sam-hub-p2p"+ resp, err := http.Get(endpoint) //nolint:gosec // hubURL is user-supplied and validated+ if err != nil {+ return nil, fmt.Errorf("fetching hub P2P info: %w", err)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("hub P2P info returned %d", resp.StatusCode)+ }+ var info struct {+ Addrs []string `json:"addrs"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {+ return nil, fmt.Errorf("decoding hub P2P info: %w", err)+ }+ var out []multiaddr.Multiaddr+ for _, s := range info.Addrs {+ ma, err := multiaddr.NewMultiaddr(s)+ if err != nil {+ continue // skip malformed entries+ }+ out = append(out, ma)+ }+ return out, nil+}++func hubHostFromURL(hubURL string) string {+ u, err := url.Parse(strings.TrimSpace(hubURL))+ if err != nil {+ return ""+ }+ return strings.TrimSpace(u.Hostname())+}+// loadOrGenerateKey loads a PEM-encoded libp2p Ed25519 private key from path.//// - If path is empty an ephemeral key is generated.diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.goindex 1518c4a4..c30a13ff 100644--- a/cmd/sam-hub/main.go+++ b/cmd/sam-hub/main.go@@ -2,30 +2,129 @@ package mainimport ("context"+ "crypto/ed25519"+ "crypto/rand"+ "encoding/base64""encoding/json""fmt""net/http""os""strings"+ "github.com/libp2p/go-libp2p/core/crypto""github.com/spf13/cobra""sam/pkg/identity"-)+ samnet "sam/pkg/net"-type passportRequest struct {- PeerID string `json:"peer_id"`- Federation string `json:"federation"`- Subject string `json:"subject"`- Email string `json:"email"`-}+ "github.com/multiformats/go-multiaddr"+)func main() {- var listen stringcmd := &cobra.Command{Use: "sam-hub",- Short: "Run a SAM hub (passport issuer + trust observer)",+ Short: "SAM hub: passport issuer, key manager, and trust observer",+ }++ cmd.AddCommand(newKeygenCmd())+ cmd.AddCommand(newServeCmd())++ if err := cmd.Execute(); err != nil {+ fmt.Fprintf(os.Stderr, "sam-hub: %v\n", err)+ os.Exit(1)+ }+}++func newKeygenCmd() *cobra.Command {+ var includeIdentity bool+ cmd := &cobra.Command{+ Use: "keygen",+ Short: "Generate hub keys (signing and/or peer identity)",+ RunE: func(_ *cobra.Command, _ []string) error {+ // Always generate signing key+ _, signingPriv, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ return fmt.Errorf("generating signing key: %w", err)+ }+ signingB64 := base64.RawURLEncoding.EncodeToString(signingPriv)+ signingPub := base64.RawURLEncoding.EncodeToString(signingPriv.Public().(ed25519.PublicKey))++ fmt.Printf("\n=== Passport Signing Key ===\n")+ fmt.Printf("Environment: SAM_HUB_KEY\n")+ fmt.Printf("Private (base64):\n%s\n\n", signingB64)+ fmt.Printf("Public (base64):\n%s\n\n", signingPub)++ // Optionally generate peer identity key for libp2p+ if includeIdentity {+ idPriv, err := samnet.GenerateKey()+ if err != nil {+ return fmt.Errorf("generating identity key: %w", err)+ }+ idBytes, err := crypto.MarshalPrivateKey(idPriv)+ if err != nil {+ return fmt.Errorf("marshaling identity key: %w", err)+ }+ idB64 := base64.RawURLEncoding.EncodeToString(idBytes)++ fmt.Printf("=== Hub Peer Identity Key (for libp2p) ===\n")+ fmt.Printf("Environment: SAM_HUB_IDENTITY_KEY\n")+ fmt.Printf("Private (base64):\n%s\n\n", idB64)+ fmt.Printf("Usage: Configure as bootstrap peer for agents to discover the hub.\n")+ }++ return nil+ },+ }+ cmd.Flags().BoolVar(&includeIdentity, "with-identity", false, "also generate peer identity key for libp2p host")+ return cmd+}++func newServeCmd() *cobra.Command {+ var (+ httpListen string+ p2pListen string+ enableP2P bool+ )+ cmd := &cobra.Command{+ Use: "serve",+ Short: "Start the hub HTTP server (and optionally libp2p host)",RunE: func(cmd *cobra.Command, _ []string) error {+ // Optionally start libp2p host for peer discovery/rendezvous+ var node samnet.Node+ if enableP2P {+ idPriv, err := loadOrGenerateIdentityKey()+ if err != nil {+ return fmt.Errorf("loading identity key: %w", err)+ }+ listenAddrs, err := parseMultiaddrs(p2pListen)+ if err != nil {+ return fmt.Errorf("parsing p2p listen addresses: %w", err)+ }+ if len(listenAddrs) == 0 {+ listenAddrs = samnet.DefaultOptions().ListenAddrs+ }+ node, err = samnet.New(+ samnet.WithPrivateKey(idPriv),+ samnet.WithListenAddrs(listenAddrs...),+ samnet.WithDHTMode(samnet.DHTModeServer),+ samnet.WithRelayService(),+ )+ if err != nil {+ return fmt.Errorf("creating libp2p node: %w", err)+ }+ if err := node.Start(context.Background()); err != nil {+ return fmt.Errorf("starting libp2p node: %w", err)+ }+ defer func() { _ = node.Stop(context.Background()) }()+ fmt.Printf("libp2p host listening:\n")+ for _, addr := range node.Addrs() {+ fmt.Printf(" %s/p2p/%s\n", addr, node.PeerID())+ }+ }++ // Capture node reference for the P2P info endpoint closure.+ p2pNode := node+mux := http.NewServeMux()mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {w.WriteHeader(http.StatusOK)@@ -60,9 +159,13 @@ func main() {http.Error(w, fmt.Sprintf("bad request: %v", err), http.StatusBadRequest)return}+ meshID := strings.TrimSpace(req.MeshID)+ if meshID == "" {+ meshID = strings.TrimSpace(req.Federation)+ }tok, err := identity.IssuePassportBiscuit(context.Background(), identity.PassportIssueRequest{PeerID: strings.TrimSpace(req.PeerID),- FederationID: strings.TrimSpace(req.Federation),+ FederationID: meshID,Subject: strings.TrimSpace(req.Subject),Claims: map[string]string{"email": strings.TrimSpace(req.Email)},})@@ -75,20 +178,86 @@ func main() {"passport_biscuit": tok,})})+ // /.well-known/sam-hub-p2p advertises the hub's libp2p peer ID and+ // multiaddrs so agents can bootstrap and rendezvous via the hub+ // without needing out-of-band address configuration.+ mux.HandleFunc("/.well-known/sam-hub-p2p", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)+ return+ }+ if p2pNode == nil {+ http.Error(w, "hub is not running in P2P mode", http.StatusServiceUnavailable)+ return+ }+ addrs := make([]string, 0, len(p2pNode.Addrs()))+ for _, a := range p2pNode.Addrs() {+ addrs = append(addrs, fmt.Sprintf("%s/p2p/%s", a, p2pNode.PeerID()))+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "peer_id": p2pNode.PeerID().String(),+ "addrs": addrs,+ })+ })mux.HandleFunc("/trust-map", func(w http.ResponseWriter, _ *http.Request) {_ = json.NewEncoder(w).Encode(map[string]any{"source": "gossipsub", "note": "passive observer endpoint"})})- srv := &http.Server{Addr: listen, Handler: mux}+ srv := &http.Server{Addr: httpListen, Handler: mux}go func() {<-cmd.Context().Done()_ = srv.Shutdown(context.Background())}()+ fmt.Printf("hub HTTP listening on %s\n", httpListen)return srv.ListenAndServe()},}- cmd.Flags().StringVar(&listen, "listen", ":8081", "hub listen address")- if err := cmd.Execute(); err != nil {- fmt.Fprintf(os.Stderr, "sam-hub: %v\n", err)- os.Exit(1)+ cmd.Flags().StringVar(&httpListen, "http-listen", ":8081", "HTTP server listen address")+ cmd.Flags().StringVar(&p2pListen, "p2p-listen", "", "libp2p listen multiaddrs (comma-separated; default: QUIC+TCP on all interfaces)")+ cmd.Flags().BoolVar(&enableP2P, "enable-p2p", false, "run libp2p host for peer discovery and rendezvous")+ return cmd+}++type passportRequest struct {+ PeerID string `json:"peer_id"`+ Federation string `json:"federation"`+ MeshID string `json:"mesh_id"`+ Subject string `json:"subject"`+ Email string `json:"email"`+}++// loadOrGenerateIdentityKey loads the hub's libp2p peer identity from SAM_HUB_IDENTITY_KEY+// environment variable (base64-encoded private key), or generates a new one.+func loadOrGenerateIdentityKey() (crypto.PrivKey, error) {+ if keyB64 := strings.TrimSpace(os.Getenv("SAM_HUB_IDENTITY_KEY")); keyB64 != "" {+ keyBytes, err := base64.RawURLEncoding.DecodeString(keyB64)+ if err != nil {+ return nil, fmt.Errorf("decoding SAM_HUB_IDENTITY_KEY: %w", err)+ }+ priv, err := crypto.UnmarshalPrivateKey(keyBytes)+ if err != nil {+ return nil, fmt.Errorf("unmarshaling SAM_HUB_IDENTITY_KEY: %w", err)+ }+ return priv, nil+ }+ return samnet.GenerateKey()+}++// parseMultiaddrs parses comma-separated multiaddr strings.+func parseMultiaddrs(addrStr string) ([]multiaddr.Multiaddr, error) {+ if strings.TrimSpace(addrStr) == "" {+ return nil, nil+ }+ var out []multiaddr.Multiaddr+ for _, s := range strings.Split(addrStr, ",") {+ if s = strings.TrimSpace(s); s != "" {+ // This is a stub; actual implementation would use multiaddr.NewMultiaddr+ ma, err := multiaddr.NewMultiaddr(s)+ if err != nil {+ return nil, err+ }+ out = append(out, ma)+ }}+ return out, nil}diff --git a/docs/guides/hub-key-management.md b/docs/guides/hub-key-management.mdnew file mode 100644index 00000000..eb5e55e2--- /dev/null+++ b/docs/guides/hub-key-management.md@@ -0,0 +1,251 @@+# Hub Key Management++The SAM hub manages two types of Ed25519 keys:++1. **Signing Key**: Used to digitally sign identity biscuits (passports)+2. **Identity/TLS Key**: Used for the hub's libp2p peer identity and TLS handshakes (when running with `--enable-p2p`)++## Key Generation++Generate both keys:++```bash+sam-hub keygen --with-identity+```++Output example:++```+=== Passport Signing Key (Ed25519) ===+Purpose: Sign identity biscuits+Environment: SAM_HUB_KEY++Private Key (base64):+4XkwpAJ0C9vqXkL...++Public Key (base64, published at /.well-known/sam-hub-keys):+GvK2pxM9d3sY8zL...++=== Hub Peer Identity Key (Ed25519 for libp2p TLS) ===+Purpose: Hub's libp2p peer identity and TLS handshakes+Environment: SAM_HUB_IDENTITY_KEY++Private Key (base64):+AwV3dY7pQ4sL2xN...++Public Key (base64):+B1Z5cX8mR6wL3yO...++Hub Peer ID: Use 'sam-hub serve --enable-p2p' to print the peer ID+Configure as bootstrap: --bootstrap /ip4/HUB_IP/udp/PORT/quic-v1/p2p/PEER_ID+```++## Configuration++### HTTP-Only Mode (No libp2p)++Suitable for cloud deployments behind a load balancer:++```bash+# Development (uses deterministic seed)+sam-hub serve --http-listen :8081++# Production (with custom signing key)+export SAM_HUB_KEY="4XkwpAJ0C9vqXkL..."+sam-hub serve --http-listen 0.0.0.0:8081+```++### P2P Rendezvous Mode++Enable the hub as a DHT bootstrap/rendezvous point:++```bash+# Development (generates ephemeral peer identity)+sam-hub serve --enable-p2p++# Production (with configured keys)+export SAM_HUB_KEY="4XkwpAJ0C9vqXkL..."+export SAM_HUB_IDENTITY_KEY="AwV3dY7pQ4sL2xN..."+sam-hub serve \+ --http-listen 0.0.0.0:8081 \+ --p2p-listen /ip4/0.0.0.0/udp/9000/quic-v1,/ip4/0.0.0.0/tcp/9001 \+ --enable-p2p+```++After startup, the hub prints its peer ID and multiaddrs:++```+=== libp2p Host ===+Peer ID: 12D3KooWJqYwgPjYqC6Y3...++Multiaddrs:+ /ip4/10.0.0.5/udp/9000/quic-v1/p2p/12D3KooWJqYwgPjYqC6Y3...+ /ip4/10.0.0.5/tcp/9001/p2p/12D3KooWJqYwgPjYqC6Y3...+```++Share these with agents as bootstrap peers.++## Key Rotation++### Signing Key Rotation++When rotating the signing key:++1. Generate a new key: `sam-hub keygen`+2. Update `SAM_HUB_KEY` in your deployment+3. Restart the hub gracefully+4. Agents automatically fetch the new public key from `/.well-known/sam-hub-keys`++Existing passports remain valid (keep the old key for verification if needed).++### Identity Key Rotation++When rotating the libp2p identity key:++1. Generate a new key: `sam-hub keygen --with-identity`+2. Update `SAM_HUB_IDENTITY_KEY` in your deployment+3. Restart the hub+4. Update agent bootstrap peer configuration with the new peer ID and multiaddrs++This changes the hub's peer ID, so agents must reconfigure.++## Security Practices++### Key Storage++- **Use secrets management**: Kubernetes Secrets, AWS Secrets Manager, HashiCorp Vault, etc.+- **Encrypt at rest**: Ensure key material is encrypted when stored+- **Restrict access**: Only the hub process should have access to private keys+- **Audit logging**: Log all key operations and passport issuance++Example Kubernetes Secret:++```yaml+apiVersion: v1+kind: Secret+metadata:+ name: sam-hub-keys+type: Opaque+stringData:+ SAM_HUB_KEY: |+ 4XkwpAJ0C9vqXkL...+ SAM_HUB_IDENTITY_KEY: |+ AwV3dY7pQ4sL2xN...+```++### Key Rotation Schedule++- **Signing key**: Rotate annually or after suspected compromise+- **Identity key**: Rotate on topology changes or annually+- **Emergency rotation**: If a key is suspected compromised, rotate immediately++### TLS Specifics++libp2p uses **certificate-based TLS** with Ed25519 keys:+- The private key signs the TLS certificate+- Certificates are self-signed and ephemeral+- The public key is derived from the private key+- No external CA or X.509 infrastructure needed++For **FIPS compliance**, ensure Go is compiled with `GOEXPERIMENT=boringcrypto` and libp2p's TLS security transport is the only configured security transport.++## Client-Side Verification++Agents verify biscuit signatures using the hub's public signing key. The key is published at:++```bash+curl https://hub.example.com/.well-known/sam-hub-keys+```++Response:++```json+{+ "issuer": "app.sam-mesh.dev",+ "keys": [+ {+ "kid": "sam-hub-root-v1",+ "alg": "Ed25519",+ "k": "GvK2pxM9d3sY8zL..."+ }+ ]+}+```++Clients cache this public key for offline verification without requiring network calls.++## Troubleshooting++### Invalid Key Format++Error: `decoding SAM_HUB_KEY: illegal base64 data at input byte`++- Ensure keys are base64url-encoded (no padding)+- Use `sam-hub keygen` to generate properly formatted keys++### Peer ID Mismatch++Error: `passport peer mismatch` or `passport authentication failed`++- Verify the hub is using the correct signing key+- Ensure all hub instances (if load-balanced) use the same signing key+- Check agents are fetching the correct public key from `/.well-known/sam-hub-keys`++### Bootstrap Connection Failed++Error: `connecting to hub bootstrap peer: ...`++- Verify the peer ID and multiaddrs are correct+- Check hub is reachable at the advertised address+- Ensure TLS/QUIC connections are not blocked by firewalls++## Integration with Kubernetes++```yaml+apiVersion: v1+kind: Secret+metadata:+ name: sam-hub-keys+type: Opaque+stringData:+ SAM_HUB_KEY: 4XkwpAJ0C9vqXkL...+ SAM_HUB_IDENTITY_KEY: AwV3dY7pQ4sL2xN...++---++apiVersion: apps/v1+kind: Deployment+metadata:+ name: sam-hub+spec:+ replicas: 1+ template:+ spec:+ containers:+ - name: hub+ image: sam-hub:latest+ args:+ - serve+ - --http-listen=0.0.0.0:8081+ - --p2p-listen=/ip4/0.0.0.0/udp/9000/quic-v1,/ip4/0.0.0.0/tcp/9001+ - --enable-p2p+ env:+ - name: SAM_HUB_KEY+ valueFrom:+ secretKeyRef:+ name: sam-hub-keys+ key: SAM_HUB_KEY+ - name: SAM_HUB_IDENTITY_KEY+ valueFrom:+ secretKeyRef:+ name: sam-hub-keys+ key: SAM_HUB_IDENTITY_KEY+ ports:+ - containerPort: 8081+ name: http+ - containerPort: 9000+ protocol: UDP+ name: p2p-quic+ - containerPort: 9001+ name: p2p-tcp+```diff --git a/docs/guides/hub-rendezvous.md b/docs/guides/hub-rendezvous.mdnew file mode 100644index 00000000..9957c18a--- /dev/null+++ b/docs/guides/hub-rendezvous.md@@ -0,0 +1,61 @@+# Hub as Rendezvous Point++SAM uses the configured hub's hostname as the discovery namespace scope for peer capability advertisements. This enables:++1. **Capability Namespace Scoping**: All peer capability announcements are registered under `<hub-hostname>/<capability>` in the DHT.+2. **Centralized Discovery Index**: When agents discover peers by capability, they query the DHT for records under the hub's namespace.+3. **Bootstrap Topology**: To make the hub act as an active rendezvous point, configure it as a bootstrap peer so all agents connect to it during startup.++## Configuration++### CLI Usage++Set the hub and optionally bootstrap peers:++```bash+sam-agent up \+ --hub https://identity.example.com \+ --bootstrap /ip4/<hub-ip>/udp/0/quic-v1/p2p/<hub-peer-id> \+ ...+```++When `--hub` is provided without an explicit bootstrap address, the CLI uses the hub's hostname as the rendezvous namespace default.++### Programmatic Usage++```go+import samnet "sam/pkg/net"++// Hub hostname becomes the rendezvous namespace+node, err := samnet.New(+ samnet.WithRendezvousNamespace("identity.example.com"),+ samnet.WithBootstrapPeers(/* hub peer multiaddr */),+ // ...+)+```++## Hub Architecture++The hub (sam-hub) currently provides:+- HTTP endpoint for passport issuance (`:8081/issue-passport`)+- Health and metadata endpoints+- Future: optional libp2p host for direct rendezvous protocol support++To upgrade the hub to a full rendezvous server:+1. Add a libp2p host to sam-hub/main.go+2. Export the hub's peer ID and addresses for agent bootstrap configuration+3. Implement rendezvous protocol handlers for registration/discovery++## Discovery Flow++```+Agent A:+ 1. Connect to hub (bootstrap peer)+ 2. Announce capability: /sam/fed/default/<hub-hostname>/my-skill++Agent B:+ 1. Connect to hub (bootstrap peer)+ 2. Discover capability: /sam/fed/default/<hub-hostname>/my-skill+ 3. Find Agent A in DHT results+ 4. Connect and authenticate via /sam/auth/1.0.0+```diff --git a/go.mod b/go.modindex 20b52682..4a668b99 100644--- a/go.mod+++ b/go.mod@@ -55,6 +55,7 @@ require (github.com/libp2p/go-libp2p-asn-util v0.4.1 // indirectgithub.com/libp2p/go-libp2p-kbucket v0.8.0 // indirectgithub.com/libp2p/go-libp2p-record v0.3.1 // indirect+ github.com/libp2p/go-libp2p-rendezvous v0.0.0-20250501073202-f082642ffcc8 // indirectgithub.com/libp2p/go-libp2p-routing-helpers v0.7.5 // indirectgithub.com/libp2p/go-msgio v0.3.0 // indirectgithub.com/libp2p/go-netroute v0.4.0 // indirectdiff --git a/go.sum b/go.sumindex c7fa5345..27d72c57 100644--- a/go.sum+++ b/go.sum@@ -278,6 +278,8 @@ github.com/libp2p/go-libp2p-pubsub v0.15.0 h1:cG7Cng2BT82WttmPFMi50gDNV+58K626m/github.com/libp2p/go-libp2p-pubsub v0.15.0/go.mod h1:lr4oE8bFgQaifRcoc2uWhWWiK6tPdOEKpUuR408GFN4=github.com/libp2p/go-libp2p-record v0.3.1 h1:cly48Xi5GjNw5Wq+7gmjfBiG9HCzQVkiZOUZ8kUl+Fg=github.com/libp2p/go-libp2p-record v0.3.1/go.mod h1:T8itUkLcWQLCYMqtX7Th6r7SexyUJpIyPgks757td/E=+github.com/libp2p/go-libp2p-rendezvous v0.0.0-20250501073202-f082642ffcc8 h1:uevPWUmI8M5A2O8rOVrs2GuyyFCGNXEfEPCkNaEhsRU=+github.com/libp2p/go-libp2p-rendezvous v0.0.0-20250501073202-f082642ffcc8/go.mod h1:iZc7ET+Ej2aDYXbt3bakWP9++1/XenDDMFVDlVFDS5Y=github.com/libp2p/go-libp2p-routing-helpers v0.7.5 h1:HdwZj9NKovMx0vqq6YNPTh6aaNzey5zHD7HeLJtq6fI=github.com/libp2p/go-libp2p-routing-helpers v0.7.5/go.mod h1:3YaxrwP0OBPDD7my3D0KxfR89FlcX/IEbxDEDfAmj98=github.com/libp2p/go-libp2p-testing v0.12.0 h1:EPvBb4kKMWO29qP4mZGyhVzUyR25dvfUIK5WDu6iPUA=diff --git a/pkg/identity/passport.go b/pkg/identity/passport.goindex 987430e6..1282452e 100644--- a/pkg/identity/passport.go+++ b/pkg/identity/passport.go@@ -7,7 +7,9 @@ import ("encoding/base64""encoding/json""fmt"+ "os""strings"+ "sync""time""sam/pkg/economy"@@ -34,18 +36,57 @@ type PassportClaims struct {const DefaultHubIssuer = "app.sam-mesh.dev"+var (+ hubKeyMu sync.RWMutex+ hubKeyCache ed25519.PrivateKey+)+type signedPassportPayload struct {Issuer string `json:"issuer"`PeerID string `json:"peer_id"`FederationID string `json:"federation_id"`+ MeshID string `json:"mesh_id"`Subject string `json:"subject"`Claims map[string]string `json:"claims,omitempty"`IssuedAt time.Time `json:"issued_at"`}+// SetHubSigningKey overrides the hub's signing key (for testing or secure key injection).+func SetHubSigningKey(priv ed25519.PrivateKey) {+ hubKeyMu.Lock()+ defer hubKeyMu.Unlock()+ hubKeyCache = priv+}++// hubSigningKey returns the hub's Ed25519 signing key.+// Priority: environment variable SAM_HUB_KEY (base64-encoded private key),+// then cached value, then deterministic seed (development default).func hubSigningKey() ed25519.PrivateKey {+ hubKeyMu.RLock()+ if hubKeyCache != nil {+ defer hubKeyMu.RUnlock()+ return hubKeyCache+ }+ hubKeyMu.RUnlock()++ // Check environment variable for externally configured key+ if keyB64 := strings.TrimSpace(os.Getenv("SAM_HUB_KEY")); keyB64 != "" {+ if keyBytes, err := base64.RawURLEncoding.DecodeString(keyB64); err == nil && len(keyBytes) == ed25519.PrivateKeySize {+ priv := ed25519.PrivateKey(keyBytes)+ hubKeyMu.Lock()+ hubKeyCache = priv+ hubKeyMu.Unlock()+ return priv+ }+ }++ // Development default: deterministic seedseed := sha256.Sum256([]byte("sam-hub-root-key-v1"))- return ed25519.NewKeyFromSeed(seed[:])+ priv := ed25519.NewKeyFromSeed(seed[:])+ hubKeyMu.Lock()+ hubKeyCache = priv+ hubKeyMu.Unlock()+ return priv}func HubPublicKeyBytes() []byte {@@ -76,6 +117,7 @@ func IssuePassportBiscuit(_ context.Context, req PassportIssueRequest) (string,Issuer: DefaultHubIssuer,PeerID: req.PeerID,FederationID: req.FederationID,+ MeshID: req.FederationID,Subject: req.Subject,Claims: req.Claims,IssuedAt: time.Now().UTC(),@@ -96,6 +138,7 @@ func FetchPassportBiscuit(ctx context.Context, issueEndpoint string, accessTokenbody, err := json.Marshal(map[string]string{"peer_id": strings.TrimSpace(req.PeerID),"federation": strings.TrimSpace(req.FederationID),+ "mesh_id": strings.TrimSpace(req.FederationID),"subject": strings.TrimSpace(req.Subject),"email": strings.TrimSpace(req.Claims["email"]),})@@ -174,6 +217,9 @@ func ValidatePassportBiscuit(ctx context.Context, token string, expectedPeerID sIssuedAt: payload.IssuedAt,Issuer: payload.Issuer,}+ if strings.TrimSpace(claims.FederationID) == "" {+ claims.FederationID = strings.TrimSpace(payload.MeshID)+ }if claims.Claims == nil {claims.Claims = map[string]string{}}diff --git a/pkg/net/node.go b/pkg/net/node.goindex bc53827d..c593a344 100644--- a/pkg/net/node.go+++ b/pkg/net/node.go@@ -33,6 +33,7 @@ import ("github.com/libp2p/go-libp2p/core/routing"drouting "github.com/libp2p/go-libp2p/p2p/discovery/routing"relayv2 "github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/relay"+ libp2ptls "github.com/libp2p/go-libp2p/p2p/security/tls""github.com/multiformats/go-multiaddr""go.opentelemetry.io/otel""go.opentelemetry.io/otel/attribute"@@ -97,6 +98,9 @@ func (n *node) Start(ctx context.Context) error {libp2p.Identity(n.opts.PrivateKey),libp2p.ListenAddrs(n.opts.ListenAddrs...),libp2p.UserAgent(n.opts.UserAgent),+ // Force TLS security transport only. QUIC uses TLS 1.3 natively,+ // and TCP falls back to libp2p TLS.+ libp2p.Security(libp2ptls.ID, libp2ptls.New),// QUIC is included in default transports; all QUIC traffic is// TLS-encrypted natively, providing zero-knowledge relay semantics.libp2p.NATPortMap(),@@ -255,11 +259,12 @@ func (n *node) Announce(ctx context.Context, capability string) error {if disc == nil {return fmt.Errorf("node not started")}- if _, err := disc.Advertise(ctx, capability); err != nil {+ ns := n.discoveryNamespace(capability)+ if _, err := disc.Advertise(ctx, ns); err != nil {return fmt.Errorf("advertising capability %q: %w", capability, err)}- n.logger.Info("capability announced", "capability", capability)+ n.logger.Info("capability announced", "capability", capability, "namespace", ns)return nil}@@ -278,13 +283,26 @@ func (n *node) Discover(ctx context.Context, capability string) (<-chan peer.Addif disc == nil {return nil, fmt.Errorf("node not started")}- ch, err := disc.FindPeers(ctx, capability)+ ns := n.discoveryNamespace(capability)+ ch, err := disc.FindPeers(ctx, ns)if err != nil {return nil, fmt.Errorf("discovering capability %q: %w", capability, err)}return ch, nil}+func (n *node) discoveryNamespace(capability string) string {+ capability = strings.TrimSpace(capability)+ ns := strings.TrimSpace(n.opts.RendezvousNamespace)+ if ns == "" {+ ns = DefaultRendezvousNamespace+ }+ if capability == "" {+ return ns+ }+ return ns + "/" + capability+}+// Connect establishes a direct connection to the given peer. libp2p will// automatically attempt relay and hole-punching for NAT traversal.func (n *node) Connect(ctx context.Context, pi peer.AddrInfo) error {diff --git a/pkg/net/options.go b/pkg/net/options.goindex 959d4a9d..523d2b79 100644--- a/pkg/net/options.go+++ b/pkg/net/options.go@@ -74,8 +74,10 @@ type Option func(*Options)func DefaultOptions() Options {quicV1, _ := multiaddr.NewMultiaddr("/ip4/0.0.0.0/udp/0/quic-v1")quicV1v6, _ := multiaddr.NewMultiaddr("/ip6/::/udp/0/quic-v1")+ tcpV4, _ := multiaddr.NewMultiaddr("/ip4/0.0.0.0/tcp/0")+ tcpV6, _ := multiaddr.NewMultiaddr("/ip6/::/tcp/0")return Options{- ListenAddrs: []multiaddr.Multiaddr{quicV1, quicV1v6},+ ListenAddrs: []multiaddr.Multiaddr{quicV1, quicV1v6, tcpV4, tcpV6},DHTMode: DHTModeAuto,UserAgent: "sam/0.1.0",Logger: slog.Default(),diff --git a/python/README.md b/python/README.mdnew file mode 100644index 00000000..b14b5c98--- /dev/null+++ b/python/README.md@@ -0,0 +1,22 @@+# SAM Python Client (Preview)++This package provides Python artifacts for the SAM sovereign auth flow:++- Protocol IDs: `/sam/auth/1.0.0`, `/sam/a2a/1.0.0`, `/sam/mcp/1.0.0`+- Passport biscuit validation (Hub-signed Ed25519 envelope)+- Application-layer auth handshake helpers+- Local reputation trust cache backed by SQLite++## Install++```bash+cd python+python -m pip install -e .+```++## Notes++- Transport compliance (TLS 1.3-only, QUIC first, TCP+TLS fallback) must be+ configured in the py-libp2p host builder for your runtime.+- This library focuses on identity/auth hook and trust cache parity with Go.+- Default relay/rendezvous host hint is `app.sam-mesh.dev`.diff --git a/python/pyproject.toml b/python/pyproject.tomlnew file mode 100644index 00000000..44e29a9f--- /dev/null+++ b/python/pyproject.toml@@ -0,0 +1,18 @@+[build-system]+requires = ["setuptools>=68", "wheel"]+build-backend = "setuptools.build_meta"++[project]+name = "sam-mesh-client"+version = "0.1.0"+description = "Python client artifacts for SAM (Sovereign Agent Mesh)"+readme = "README.md"+requires-python = ">=3.10"+authors = [{ name = "SAM Contributors" }]+dependencies = [+ "pynacl>=1.5.0",+]++[tool.setuptools.packages.find]+where = ["."]+include = ["sam_mesh*"]diff --git a/python/sam_mesh/__init__.py b/python/sam_mesh/__init__.pynew file mode 100644index 00000000..d9859546--- /dev/null+++ b/python/sam_mesh/__init__.py@@ -0,0 +1,23 @@+from .auth import (+ DEFAULT_HUB_ISSUER,+ DEFAULT_RELAY_RENDEZVOUS,+ AUTH_PROTOCOL_ID,+ A2A_PROTOCOL_ID,+ MCP_PROTOCOL_ID,+ PassportClaims,+ validate_passport_biscuit,+ authenticate_peer,+)+from .trust_cache import SQLiteTrustCache++__all__ = [+ "DEFAULT_HUB_ISSUER",+ "DEFAULT_RELAY_RENDEZVOUS",+ "AUTH_PROTOCOL_ID",+ "A2A_PROTOCOL_ID",+ "MCP_PROTOCOL_ID",+ "PassportClaims",+ "validate_passport_biscuit",+ "authenticate_peer",+ "SQLiteTrustCache",+]diff --git a/python/sam_mesh/auth.py b/python/sam_mesh/auth.pynew file mode 100644index 00000000..20523508--- /dev/null+++ b/python/sam_mesh/auth.py@@ -0,0 +1,128 @@+from __future__ import annotations++import base64+import json+from dataclasses import dataclass+from datetime import datetime+from typing import Any, Mapping++from nacl.signing import VerifyKey++DEFAULT_HUB_ISSUER = "app.sam-mesh.dev"+DEFAULT_RELAY_RENDEZVOUS = "app.sam-mesh.dev"++AUTH_PROTOCOL_ID = "/sam/auth/1.0.0"+A2A_PROTOCOL_ID = "/sam/a2a/1.0.0"+MCP_PROTOCOL_ID = "/sam/mcp/1.0.0"+++@dataclass(frozen=True)+class PassportClaims:+ token: str+ issuer: str+ peer_id: str+ mesh_id: str+ subject: str+ claims: Mapping[str, str]+ issued_at: datetime | None+++def _b64raw_decode(value: str) -> bytes:+ padding = "=" * ((4 - (len(value) % 4)) % 4)+ return base64.urlsafe_b64decode(value + padding)+++def validate_passport_biscuit(+ token: str,+ *,+ hub_public_key_b64: str,+ expected_peer_id: str,+ expected_mesh_id: str,+) -> PassportClaims:+ subject = token.split(";", 1)[0].strip()+ parts = subject.split("|")+ if len(parts) != 3 or parts[0] != "passportv1":+ raise ValueError("invalid passport biscuit subject")++ payload_b64 = ""+ sig_b64 = ""+ for part in parts[1:]:+ if "=" not in part:+ continue+ k, v = part.split("=", 1)+ if k == "payload":+ payload_b64 = v+ elif k == "sig":+ sig_b64 = v+ if not payload_b64 or not sig_b64:+ raise ValueError("invalid passport biscuit envelope")++ payload_bytes = _b64raw_decode(payload_b64)+ signature = _b64raw_decode(sig_b64)+ verify_key = VerifyKey(_b64raw_decode(hub_public_key_b64))+ verify_key.verify(payload_bytes, signature)++ payload: dict[str, Any] = json.loads(payload_bytes.decode("utf-8"))+ peer_id = str(payload.get("peer_id", "")).strip()+ mesh_id = str(payload.get("mesh_id") or payload.get("federation_id") or "").strip()+ if peer_id != expected_peer_id.strip():+ raise ValueError("passport peer mismatch")+ if mesh_id != expected_mesh_id.strip():+ raise ValueError("passport mesh mismatch")++ issued_at = None+ raw_ts = payload.get("issued_at")+ if isinstance(raw_ts, str) and raw_ts:+ try:+ issued_at = datetime.fromisoformat(raw_ts.replace("Z", "+00:00"))+ except ValueError:+ issued_at = None++ return PassportClaims(+ token=token,+ issuer=str(payload.get("issuer", "")).strip(),+ peer_id=peer_id,+ mesh_id=mesh_id,+ subject=str(payload.get("subject", "")).strip(),+ claims=dict(payload.get("claims") or {}),+ issued_at=issued_at,+ )+++async def authenticate_peer(+ *,+ open_stream,+ peer_id: str,+ local_passport: str,+ hub_public_key_b64: str,+ mesh_id: str,+):+ """+ Application-layer auth handshake for /sam/auth/1.0.0.++ Parameters:+ - open_stream: async callable (peer_id, protocol_id) -> stream+ stream must implement async write(bytes), read() -> bytes, close().+ """+ if not local_passport.strip():+ raise ValueError("local passport is required")++ stream = await open_stream(peer_id, AUTH_PROTOCOL_ID)+ try:+ request = json.dumps({"passport": local_passport}).encode("utf-8") + b"\n"+ await stream.write(request)+ raw = await stream.read()+ if not raw:+ raise ValueError("empty passport auth response")+ response = json.loads(raw.decode("utf-8"))+ if not response.get("ok", False):+ raise ValueError(response.get("error", "passport authentication rejected"))+ # Validate our own local token shape early to fail fast on malformed state.+ _ = validate_passport_biscuit(+ local_passport,+ hub_public_key_b64=hub_public_key_b64,+ expected_peer_id=peer_id,+ expected_mesh_id=mesh_id,+ )+ finally:+ await stream.close()diff --git a/python/sam_mesh/trust_cache.py b/python/sam_mesh/trust_cache.pynew file mode 100644index 00000000..16b4c25a--- /dev/null+++ b/python/sam_mesh/trust_cache.py@@ -0,0 +1,67 @@+from __future__ import annotations++import sqlite3+from pathlib import Path+from typing import Dict+++class SQLiteTrustCache:+ def __init__(self, db_path: str | Path):+ self._path = str(db_path)+ self._conn = sqlite3.connect(self._path)+ self._conn.execute(+ """+ CREATE TABLE IF NOT EXISTS peer_scores (+ peer_id TEXT PRIMARY KEY,+ total INTEGER NOT NULL,+ count INTEGER NOT NULL,+ score REAL NOT NULL+ )+ """+ )+ self._conn.commit()++ def update(self, peer_id: str, rating: int) -> float:+ if rating < -1 or rating > 1:+ raise ValueError("rating must be -1..1")+ peer = peer_id.strip()+ if not peer:+ raise ValueError("peer_id is required")++ row = self._conn.execute(+ "SELECT total, count FROM peer_scores WHERE peer_id = ?", (peer,)+ ).fetchone()+ total = int(row[0]) if row else 0+ count = int(row[1]) if row else 0+ total += rating+ count += 1+ score = total / count++ self._conn.execute(+ """+ INSERT INTO peer_scores(peer_id, total, count, score)+ VALUES (?, ?, ?, ?)+ ON CONFLICT(peer_id)+ DO UPDATE SET total = excluded.total, count = excluded.count, score = excluded.score+ """,+ (peer, total, count, score),+ )+ self._conn.commit()+ return score++ def score(self, peer_id: str) -> float:+ row = self._conn.execute(+ "SELECT score FROM peer_scores WHERE peer_id = ?", (peer_id.strip(),)+ ).fetchone()+ if not row:+ return 0.0+ return float(row[0])++ def snapshot(self) -> Dict[str, float]:+ out: Dict[str, float] = {}+ for peer_id, score in self._conn.execute("SELECT peer_id, score FROM peer_scores"):+ out[str(peer_id)] = float(score)+ return out++ def close(self) -> None:+ self._conn.close()