Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
refactor and simplify
Antonio Ojea6d828385ec73
diff --git a/Makefile b/Makefileindex 211de667..c3913152 100644--- a/Makefile+++ b/Makefile@@ -6,7 +6,8 @@ CGO_ENABLED=0export GOROOT GO111MODULE CGO_ENABLEDbuild:- go build -v -o "$(OUT_DIR)/sam" ./cmd/sam+ go build -v -o "$(OUT_DIR)/sam-agent" ./cmd/sam-agent+ go build -v -o "$(OUT_DIR)/sam-hub" ./cmd/sam-hubclean:rm -rf "$(OUT_DIR)/"@@ -29,7 +30,7 @@ test-e2e: buildexit 1; \fi; \}- SAM_BINARY=$(OUT_DIR)/sam bats --verbose-run tests/e2e/+ SAM_BINARY=$(OUT_DIR)/sam-agent bats --verbose-run tests/e2e/# code linterslint:diff --git a/README.md b/README.mdindex 3fce9542..e7162b24 100644--- a/README.md+++ b/README.md@@ -17,7 +17,8 @@ It is built for environments where centralized gateways and centralized trust ar```bashmake build-./bin/sam --help+./bin/sam-agent --help+./bin/sam-hub --help```### Run tests@@ -31,16 +32,16 @@ make test-e2e```bash# Authenticate-sam identity login --hub https://identity.example.com --federation finance+sam-agent identity login --hub https://identity.example.com --federation finance# Publish an agent capability-sam publish --federation finance --skill risk-audit --mcp-port 8080+sam-agent publish --federation finance --skill risk-audit --mcp-port 8080# Call by capability-sam call risk-audit --federation finance --message "audit this report"+sam-agent call risk-audit --federation finance --message "audit this report"# Inspect credential artifacts-sam inspect biscuit "vendor-bot;allow_skill=risk-audit"+sam-agent inspect biscuit "vendor-bot;allow_skill=risk-audit"```## Documentationdiff --git a/cmd/sam/agent_discovery.go b/cmd/sam-agent/agent_discovery.gosimilarity index 100%rename from cmd/sam/agent_discovery.gorename to cmd/sam-agent/agent_discovery.godiff --git a/cmd/sam/call.go b/cmd/sam-agent/call.gosimilarity index 89%rename from cmd/sam/call.gorename to cmd/sam-agent/call.goindex 5879e8d2..709402cd 100644--- a/cmd/sam/call.go+++ b/cmd/sam-agent/call.go@@ -90,12 +90,15 @@ func runCall(parent context.Context, cfg *runConfig, targetArg string) error {return err}- vouch, err := loadLocalVouch()+ passport, err := loadLocalIdentityAuth()if err != nil {return err}+ if err := identity.SetLocalPassport(node.Host(), cfg.federation, passport); err != nil {+ return fmt.Errorf("configuring local passport auth: %w", err)+ }- observer, err := protocol.NewBoltObserverForFederation(cfg.federation)+ observer, err := protocol.NewBoltObserverWithFallback(cfg.federation)if err != nil {return fmt.Errorf("creating reputation observer: %w", err)}@@ -116,7 +119,6 @@ func runCall(parent context.Context, cfg *runConfig, targetArg string) error {resp, err := protocol.Execute(ctx, node.Host(), protocol.ExecuteRequest{Target: target,Capability: capability,- Vouch: vouch,Biscuit: cfg.callBiscuit,Payment: economy.Micropayment{Amount: cfg.callAmount,@@ -164,23 +166,25 @@ func resolveCallTarget(ctx context.Context, node samnet.Node, targetArg string)return peers[0], targetArg, nil}-func loadLocalVouch() (*identity.Vouch, error) {+func loadLocalIdentityAuth() (string, error) {+ const loginHint = "identity passport not found; run 'sam-agent identity login --hub <url>' first"store, err := identity.DefaultCredentialStore()if err != nil {- return nil, fmt.Errorf("opening credential store: %w", err)+ return "", fmt.Errorf("opening credential store: %w", err)}defer func() { _ = store.Close() }()creds, err := store.Load()if err != nil {- return nil, fmt.Errorf("loading credentials: %w", err)+ return "", fmt.Errorf("loading credentials: %w", err)}- if creds == nil || creds.Vouch == nil {- return nil, fmt.Errorf("identity vouch not found; run 'sam identity login --hub <url>' first")+ if creds == nil {+ return "", fmt.Errorf(loginHint)}- if creds.Vouch.IsExpired() {- return nil, fmt.Errorf("stored identity vouch is expired; run login again")+ pass := strings.TrimSpace(creds.PassportBiscuit)+ if pass != "" {+ return pass, nil}- return creds.Vouch, nil+ return "", fmt.Errorf(loginHint)}func buildCallRequest(message string) (json.RawMessage, error) {diff --git a/cmd/sam/identity.go b/cmd/sam-agent/identity.gosimilarity index 100%rename from cmd/sam/identity.gorename to cmd/sam-agent/identity.godiff --git a/cmd/sam/identity_login.go b/cmd/sam-agent/identity_login.gosimilarity index 77%rename from cmd/sam/identity_login.gorename to cmd/sam-agent/identity_login.goindex e998c668..55664107 100644--- a/cmd/sam/identity_login.go+++ b/cmd/sam-agent/identity_login.go@@ -18,7 +18,7 @@ import ("context""fmt""os"- "time"+ "strings""github.com/spf13/cobra"@@ -27,7 +27,6 @@ import (const (defaultClientID = "sam-cli"- defaultVouchTTL = 8 * time.Hour)func newIdentityLoginCmd(cfg *runConfig) *cobra.Command {@@ -45,8 +44,8 @@ then saves credentials to ~/.config/sam/state.db.The Hub URL defaults to --hub (global flag) or the SAM_HUB environmentvariable. Any Hub that implements OIDC Device Flow is supported:- sam identity login --hub https://hub.internal.bank- sam identity login --hub https://hub.example.com --client-id my-app`,+ sam-agent identity login --hub https://hub.internal.bank+ sam-agent identity login --hub https://hub.example.com --client-id my-app`,RunE: func(cmd *cobra.Command, _ []string) error {return runIdentityLogin(cmd.Context(), cfg, clientID)},@@ -92,7 +91,7 @@ func runIdentityLogin(parent context.Context, cfg *runConfig, clientID string) ereturn fmt.Errorf("device flow: %w", err)}- fmt.Fprintf(os.Stderr, "Authorization successful. Fetching identity voucher …\n")+ fmt.Fprintf(os.Stderr, "Authorization successful. Issuing identity passport …\n")// Build the node to obtain our stable PeerID.node, err := buildNode(cfg)@@ -105,14 +104,16 @@ func runIdentityLogin(parent context.Context, cfg *runConfig, clientID string) edefer func() { _ = node.Stop(context.Background()) }()peerID := node.PeerID().String()- // If the Hub exposes a vouch endpoint, fetch a signed Vouch.- var vouch *identity.Vouch- if disc.VouchEndpoint != "" {- vouch, err = identity.FetchVouch(parent, disc.VouchEndpoint, result.AccessToken, peerID, nil)- if err != nil {- // Non-fatal: warn and continue without a vouch.- fmt.Fprintf(os.Stderr, "Warning: could not fetch vouch from Hub: %v\n", err)- }+ issueReq := identity.PassportIssueRequest{+ PeerID: peerID,+ FederationID: cfg.federation,+ Subject: peerID,+ Claims: map[string]string{"hub": hubURL},+ }+ passportEndpoint := strings.TrimRight(hubURL, "/") + "/issue-passport"+ passportBiscuit, err := identity.FetchPassportBiscuit(parent, passportEndpoint, result.AccessToken, issueReq)+ if err != nil {+ return fmt.Errorf("fetching hub-issued passport biscuit: %w", err)}store, err := identity.DefaultCredentialStore()@@ -122,27 +123,21 @@ func runIdentityLogin(parent context.Context, cfg *runConfig, clientID string) edefer func() { _ = store.Close() }()creds := &identity.StoredCredentials{- PeerID: peerID,- HubURL: hubURL,- AccessToken: result.AccessToken,- RefreshToken: result.RefreshToken,- TokenExpiry: result.TokenExpiry,- Vouch: vouch,+ PeerID: peerID,+ HubURL: hubURL,+ AccessToken: result.AccessToken,+ RefreshToken: result.RefreshToken,+ TokenExpiry: result.TokenExpiry,+ PassportBiscuit: passportBiscuit,}if err := store.Save(creds); err != nil {return fmt.Errorf("saving credentials: %w", err)}fmt.Fprintf(os.Stderr, "\nLogged in as peer %s\n", peerID)- if vouch != nil {- if email := vouch.Email(); email != "" {- fmt.Fprintf(os.Stderr, "Email : %s\n", email)- }- if name := vouch.Name(); name != "" {- fmt.Fprintf(os.Stderr, "Name : %s\n", name)- }- fmt.Fprintf(os.Stderr, "Issuer : %s\n", vouch.Issuer)- fmt.Fprintf(os.Stderr, "Expires: %s\n", vouch.Expiry.Format(time.RFC3339))+ if claims, pErr := identity.ValidatePassportBiscuit(parent, passportBiscuit, peerID, cfg.federation); pErr == nil {+ fmt.Fprintf(os.Stderr, "Subject: %s\n", claims.Subject)+ fmt.Fprintf(os.Stderr, "Federation: %s\n", claims.FederationID)}fmt.Fprintf(os.Stderr, "Credentials saved to %s\n", store.Path())return nildiff --git a/cmd/sam/identity_whoami.go b/cmd/sam-agent/identity_whoami.gosimilarity index 70%rename from cmd/sam/identity_whoami.gorename to cmd/sam-agent/identity_whoami.goindex c8b0f031..2305b830 100644--- a/cmd/sam/identity_whoami.go+++ b/cmd/sam-agent/identity_whoami.go@@ -15,6 +15,7 @@package mainimport (+ "context""fmt""os""time"@@ -67,28 +68,21 @@ func runIdentityWhoami() error {}}- if v := creds.Vouch; v != nil {- _, _ = fmt.Fprintf(os.Stdout, "PeerID : %s\n", v.PeerID)- if v.Subject != "" {- _, _ = fmt.Fprintf(os.Stdout, "Subject: %s\n", v.Subject)- }- if email := v.Email(); email != "" {- _, _ = fmt.Fprintf(os.Stdout, "Email : %s\n", email)- }- if name := v.Name(); name != "" {- _, _ = fmt.Fprintf(os.Stdout, "Name : %s\n", name)- }- if org := v.Org(); org != "" {- _, _ = fmt.Fprintf(os.Stdout, "Org : %s\n", org)- }- _, _ = fmt.Fprintf(os.Stdout, "Issuer : %s\n", v.Issuer)- if v.IsExpired() {- _, _ = fmt.Fprintf(os.Stdout, "Vouch : EXPIRED (was %s)\n", v.Expiry.Format(time.RFC3339))- } else {- _, _ = fmt.Fprintf(os.Stdout, "Vouch : valid until %s\n", v.Expiry.Format(time.RFC3339))- }- } else {- _, _ = fmt.Fprintln(os.Stdout, "Vouch : none (Hub does not issue vouches, or run login again)")+ passport := creds.PassportBiscuit+ if passport == "" {+ _, _ = fmt.Fprintln(os.Stdout, "Passport : none")+ return nil+ }+ claims, err := identity.ValidatePassportBiscuit(context.Background(), passport, creds.PeerID, "")+ if err != nil {+ _, _ = fmt.Fprintf(os.Stdout, "Passport : INVALID (%v)\n", err)+ return nil+ }+ _, _ = fmt.Fprintf(os.Stdout, "Passport : present\n")+ _, _ = fmt.Fprintf(os.Stdout, "Subject : %s\n", claims.Subject)+ _, _ = fmt.Fprintf(os.Stdout, "Audience : %s\n", claims.FederationID)+ if email := claims.Claims["email"]; email != "" {+ _, _ = fmt.Fprintf(os.Stdout, "Email : %s\n", email)}return nil}diff --git a/cmd/sam/inspect.go b/cmd/sam-agent/inspect.gosimilarity index 93%rename from cmd/sam/inspect.gorename to cmd/sam-agent/inspect.goindex 68a840ba..abfee1ef 100644--- a/cmd/sam/inspect.go+++ b/cmd/sam-agent/inspect.go@@ -156,18 +156,6 @@ func runInspectCard(cfg *runConfig, input string) error {}}- if card.Vouch != nil {- fmt.Println("\nIdentity Vouch:")- fmt.Printf(" Issuer: %s\n", card.Vouch.Issuer)- fmt.Printf(" Subject: %s\n", card.Vouch.Subject)- if email, ok := card.Vouch.Claims["email"]; ok {- fmt.Printf(" Email: %s\n", email)- }- if name, ok := card.Vouch.Claims["name"]; ok {- fmt.Printf(" Name: %s\n", name)- }- }-fmt.Printf("\nSignature: %s\n", truncateString(card.Signature, 20))}return nildiff --git a/cmd/sam-agent/main.go b/cmd/sam-agent/main.gonew file mode 100644index 00000000..dd39b2e4--- /dev/null+++ b/cmd/sam-agent/main.go@@ -0,0 +1,15 @@+package main++import (+ "fmt"+ "os"+)++func main() {+ cfg := &runConfig{}+ cmd := newRootCmd(cfg)+ if err := cmd.Execute(); err != nil {+ fmt.Fprintf(os.Stderr, "sam-agent: %v\n", err)+ os.Exit(1)+ }+}diff --git a/cmd/sam/mesh.go b/cmd/sam-agent/mesh.gosimilarity index 100%rename from cmd/sam/mesh.gorename to cmd/sam-agent/mesh.godiff --git a/cmd/sam/mesh_federations.go b/cmd/sam-agent/mesh_federations.gosimilarity index 97%rename from cmd/sam/mesh_federations.gorename to cmd/sam-agent/mesh_federations.goindex 2c99694d..11813268 100644--- a/cmd/sam/mesh_federations.go+++ b/cmd/sam-agent/mesh_federations.go@@ -32,7 +32,7 @@ func newMeshFederationsCmd(_ *runConfig) *cobra.Command {Short: "Manage federation storage contexts",Long: `Manage isolated storage contexts (federations).-Each federation stores its own peer vouches, reputation scores, and discovery+Each federation stores its own peer metadata, reputation scores, and discoverycache in a separate database at ~/.config/sam/federations/<name>.db.The master identity key stays at ~/.config/sam/state.db and is never affecteddiff --git a/cmd/sam/mesh_get_agents.go b/cmd/sam-agent/mesh_get_agents.gosimilarity index 100%rename from cmd/sam/mesh_get_agents.gorename to cmd/sam-agent/mesh_get_agents.godiff --git a/cmd/sam/node.go b/cmd/sam-agent/node.gosimilarity index 99%rename from cmd/sam/node.gorename to cmd/sam-agent/node.goindex bd5c7703..01393a0a 100644--- a/cmd/sam/node.go+++ b/cmd/sam-agent/node.go@@ -51,6 +51,7 @@ func buildNode(cfg *runConfig) (samnet.Node, error) {samnet.WithListenAddrs(listen...),samnet.WithBootstrapPeers(bootstrap...),samnet.WithDHTMode(parseDHTMode(cfg.dhtMode)),+ samnet.WithFederation(cfg.federation),samnet.WithUserAgent(cfg.userAgent),samnet.WithLogger(slog.Default()),samnet.WithPrivateKey(key),diff --git a/cmd/sam/output.go b/cmd/sam-agent/output.gosimilarity index 90%rename from cmd/sam/output.gorename to cmd/sam-agent/output.goindex dd2400b4..3f38b14b 100644--- a/cmd/sam/output.go+++ b/cmd/sam-agent/output.go@@ -57,19 +57,7 @@ type agentRow struct {func toAgentRows(cards []*protocol.AgentCard, latencyByPeer map[string]time.Duration) []agentRow {rows := make([]agentRow, 0, len(cards))for _, c := range cards {- identity := "unknown"- if c.Vouch != nil {- switch {- case strings.TrimSpace(c.Vouch.Name()) != "":- identity = c.Vouch.Name()- case strings.TrimSpace(c.Vouch.Email()) != "":- identity = c.Vouch.Email()- case strings.TrimSpace(c.Vouch.Subject) != "":- identity = c.Vouch.Subject- case strings.TrimSpace(c.Vouch.Issuer) != "":- identity = c.Vouch.Issuer- }- }+ identity := c.PeerIDcaps := c.CapabilityNames()capability := ""if len(caps) > 0 {diff --git a/cmd/sam/proxy.go b/cmd/sam-agent/proxy.gosimilarity index 93%rename from cmd/sam/proxy.gorename to cmd/sam-agent/proxy.goindex d90688d1..3b988aa5 100644--- a/cmd/sam/proxy.go+++ b/cmd/sam-agent/proxy.go@@ -32,6 +32,7 @@ import ("github.com/multiformats/go-multihash""github.com/spf13/cobra"+ "sam/pkg/identity"samnet "sam/pkg/net""sam/pkg/protocol")@@ -106,19 +107,28 @@ func runProxy(parent context.Context, cfg *runConfig) error {return}+ if _, authErr := extractBearerToken(r.Header.Get("Authorization")); authErr != nil {+ http.Error(w, fmt.Sprintf("unauthorized: %v", authErr), http.StatusUnauthorized)+ return+ }+start := time.Now()- observer, err := protocol.NewBoltObserverForFederation(cfg.federation)+ observer, err := protocol.NewBoltObserverWithFallback(cfg.federation)if err != nil {http.Error(w, "reputation observer unavailable", http.StatusInternalServerError)return}defer func() { _ = observer.Close() }()- vouch, vErr := loadLocalVouch()+ passport, vErr := loadLocalIdentityAuth()if vErr != nil {http.Error(w, "unauthorized: local identity login required", http.StatusUnauthorized)return}+ if err := identity.SetLocalPassport(node.Host(), cfg.federation, passport); err != nil {+ http.Error(w, fmt.Sprintf("passport auth unavailable: %v", err), http.StatusInternalServerError)+ return+ }targetArg := strings.TrimSpace(r.Header.Get(cfg.proxyTargetHdr))if targetArg == "" {@@ -161,7 +171,6 @@ func runProxy(parent context.Context, cfg *runConfig) error {}resp, err := protocol.TunnelHTTP(ctx, node.Host(), target.ID, protocol.HTTPTunnelOpenRequest{- Vouch: vouch,Biscuit: strings.TrimSpace(cfg.proxyBiscuit),Capability: capability,Request: tunnelReq,@@ -212,6 +221,22 @@ func runProxy(parent context.Context, cfg *runConfig) error {return nil}+func extractBearerToken(header string) (string, error) {+ header = strings.TrimSpace(header)+ if header == "" {+ return "", fmt.Errorf("missing Authorization header")+ }+ parts := strings.SplitN(header, " ", 2)+ if len(parts) != 2 || !strings.EqualFold(strings.TrimSpace(parts[0]), "Bearer") {+ return "", fmt.Errorf("Authorization must use Bearer scheme")+ }+ token := strings.TrimSpace(parts[1])+ if token == "" {+ return "", fmt.Errorf("bearer token is empty")+ }+ return token, nil+}+func handleSAMReserved(w http.ResponseWriter, r *http.Request, node samnet.Node, cfg *runConfig) {handleSAMReservedWithWatcher(w, r, node, cfg, nil)}diff --git a/cmd/sam/proxy_reserved_test.go b/cmd/sam-agent/proxy_reserved_test.gosimilarity index 87%rename from cmd/sam/proxy_reserved_test.gorename to cmd/sam-agent/proxy_reserved_test.goindex bfd785be..7f346942 100644--- a/cmd/sam/proxy_reserved_test.go+++ b/cmd/sam-agent/proxy_reserved_test.go@@ -31,6 +31,32 @@ import ("sam/pkg/protocol")+func TestExtractBearerToken(t *testing.T) {+ tests := []struct {+ name string+ header string+ wantErr bool+ }{+ {name: "valid bearer", header: "Bearer abc.def.ghi", wantErr: false},+ {name: "valid bearer lowercase", header: "bearer token", wantErr: false},+ {name: "missing header", header: "", wantErr: true},+ {name: "wrong scheme", header: "Basic xyz", wantErr: true},+ {name: "empty token", header: "Bearer ", wantErr: true},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ _, err := extractBearerToken(tc.header)+ if tc.wantErr && err == nil {+ t.Fatalf("expected error, got nil")+ }+ if !tc.wantErr && err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ })+ }+}+func TestSAMReservedSearchReturnsPublishedWriterCard(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()@@ -73,9 +99,6 @@ func TestSAMReservedSearchReturnsPublishedWriterCard(t *testing.T) {if err != nil {t.Fatalf("creating writer card: %v", err)}- if err := attachNodeVouch(card, nodeA.PeerID().String(), priv); err != nil {- t.Fatalf("attaching card vouch: %v", err)- }pub, err := protocol.NewPublisher(nodeA)if err != nil {t.Fatalf("creating publisher: %v", err)@@ -99,9 +122,6 @@ func TestSAMReservedSearchReturnsPublishedWriterCard(t *testing.T) {}for _, got := range cards {if got != nil && got.PeerID == nodeA.PeerID().String() {- if got.Vouch == nil || got.Vouch.Signature == "" {- t.Fatalf("expected signed vouch in search response for %s", got.PeerID)- }return}}diff --git a/cmd/sam/proxy_watch.go b/cmd/sam-agent/proxy_watch.gosimilarity index 100%rename from cmd/sam/proxy_watch.gorename to cmd/sam-agent/proxy_watch.godiff --git a/cmd/sam/publish.go b/cmd/sam-agent/publish.gosimilarity index 86%rename from cmd/sam/publish.gorename to cmd/sam-agent/publish.goindex fd70c488..c1da0d98 100644--- a/cmd/sam/publish.go+++ b/cmd/sam-agent/publish.go@@ -16,7 +16,6 @@ package mainimport ("context"- "crypto/ed25519""encoding/json""fmt""net/http"@@ -28,7 +27,6 @@ import ("github.com/spf13/cobra""sam/pkg/economy"- "sam/pkg/identity"samnet "sam/pkg/net""sam/pkg/protocol")@@ -87,6 +85,9 @@ func runPublish(parent context.Context, cfg *runConfig) error {if len(cfg.capabilities) == 0 {return fmt.Errorf("at least one non-empty skill/capability is required")}+ if err := ensureSecurePublishPreflight(cfg.federation); err != nil {+ return err+ }// For dry-run=client mode, skip network and just build the cardif cfg.dryRun == "client" {@@ -122,9 +123,6 @@ func runPublish(parent context.Context, cfg *runConfig) error {if err != nil {return fmt.Errorf("building agent card: %w", err)}- if err := attachNodeVouch(card, node.PeerID().String(), priv); err != nil {- return err- }if err := registerLocalAgentCard(node, card); err != nil {return err}@@ -156,45 +154,18 @@ func runPublish(parent context.Context, cfg *runConfig) error {return waitForShutdown(parent, cfg.runFor)}-func attachNodeVouch(card *protocol.AgentCard, peerID string, priv any) error {- if card == nil {- return fmt.Errorf("agent card is nil")- }- if vouch, err := loadLocalVouch(); err == nil && vouch != nil {- card.AttachVouch(vouch)- return nil- }-- rawKey, err := nodeEd25519PrivateKey(priv)+func ensureSecurePublishPreflight(federationID string) error {+ gate, closeFn, err := protocol.NewPassportGateForFederation(federationID)if err != nil {- return fmt.Errorf("extracting ed25519 key for self-vouch: %w", err)+ return fmt.Errorf("publish security preflight failed: %w", err)}- vouch, err := identity.SelfSignVouch(peerID, rawKey)- if err != nil {- return fmt.Errorf("building self-signed vouch: %w", err)+ defer func() { _ = closeFn() }()+ if protocol.IsAllowAllGate(gate) {+ return fmt.Errorf("refusing publish: A2A authentication middleware is permissive (AllowAllGate)")}- card.AttachVouch(vouch)return nil}-func nodeEd25519PrivateKey(priv any) (ed25519.PrivateKey, error) {- type rawKeyProvider interface {- Raw() ([]byte, error)- }- rawProvider, ok := priv.(rawKeyProvider)- if !ok {- return nil, fmt.Errorf("unsupported private key type")- }- raw, err := rawProvider.Raw()- if err != nil {- return nil, err- }- if len(raw) != ed25519.PrivateKeySize {- return nil, fmt.Errorf("unexpected private key size %d", len(raw))- }- return ed25519.PrivateKey(raw), nil-}-func registerLocalAgentCard(node samnet.Node, card *protocol.AgentCard) error {svc, err := protocol.NewDiscoveryService(node)if err != nil {@@ -210,8 +181,18 @@ func publishLoop(parent context.Context, pub *protocol.Publisher, card *protocolif every <= 0 {every = 2 * time.Minute}- if err := pub.Publish(parent, card); err != nil {- return fmt.Errorf("initial publish failed: %w", err)+ retryTicker := time.NewTicker(250 * time.Millisecond)+ defer retryTicker.Stop()+ for {+ if err := pub.Publish(parent, card); err == nil {+ break+ } else {+ select {+ case <-parent.Done():+ return fmt.Errorf("initial publish failed: %w", err)+ case <-retryTicker.C:+ }+ }}go func() {ticker := time.NewTicker(every)diff --git a/cmd/sam/publish_card.go b/cmd/sam-agent/publish_card.gosimilarity index 96%rename from cmd/sam/publish_card.gorename to cmd/sam-agent/publish_card.goindex 815729e4..5c2e59e2 100644--- a/cmd/sam/publish_card.go+++ b/cmd/sam-agent/publish_card.go@@ -69,9 +69,6 @@ func runPublishCard(parent context.Context, cfg *runConfig) error {if err != nil {return fmt.Errorf("building agent card: %w", err)}- if err := attachNodeVouch(card, node.PeerID().String(), priv); err != nil {- return err- }if err := registerLocalAgentCard(node, card); err != nil {return err}diff --git a/cmd/sam/publish_mcp.go b/cmd/sam-agent/publish_mcp.gosimilarity index 97%rename from cmd/sam/publish_mcp.gorename to cmd/sam-agent/publish_mcp.goindex f0fc7b40..4bd407e8 100644--- a/cmd/sam/publish_mcp.go+++ b/cmd/sam-agent/publish_mcp.go@@ -77,9 +77,6 @@ func runPublishMCP(parent context.Context, cfg *runConfig) error {if err != nil {return fmt.Errorf("building agent card: %w", err)}- if err := attachNodeVouch(card, node.PeerID().String(), priv); err != nil {- return err- }if err := registerLocalAgentCard(node, card); err != nil {return err}diff --git a/cmd/sam/root.go b/cmd/sam-agent/root.gosimilarity index 93%rename from cmd/sam/root.gorename to cmd/sam-agent/root.goindex 78bb76b2..8f1e8877 100644--- a/cmd/sam/root.go+++ b/cmd/sam-agent/root.go@@ -37,7 +37,6 @@ type runConfig struct {debug bool// sam up- issuerName stringtunnelHTTPEndpoint string// sam publish (shared by card and mcp subcommands)@@ -80,11 +79,11 @@ type runConfig struct {dryRun string}-// newRootCmd builds the top-level "sam" command and attaches all subcommands.+// newRootCmd builds the top-level "sam-agent" command and attaches subcommands.func newRootCmd(cfg *runConfig) *cobra.Command {cmd := &cobra.Command{- Use: "sam",- Short: "SAM sovereign agent mesh CLI",+ Use: "sam-agent",+ Short: "SAM agent runtime and mesh CLI",PersistentPreRunE: func(_ *cobra.Command, _ []string) error {return applyLogging(cfg.debug)},@@ -98,7 +97,7 @@ func newRootCmd(cfg *runConfig) *cobra.Command {pf.BoolVar(&cfg.withRelay, "relay-service", false, "enable relay service")pf.StringVar(&cfg.userAgent, "user-agent", "sam/0.1.0", "libp2p user-agent")pf.DurationVar(&cfg.runFor, "run-for", 0, "optional duration before graceful shutdown (0 = wait for signal)")- pf.StringVar(&cfg.hub, "hub", "", "OIDC/Seed hub URL for identity bootstrap")+ pf.StringVar(&cfg.hub, "hub", "", "OIDC hub URL for passport issuance and identity login")pf.StringVar(&cfg.identityPath, "identity", "", "path to PEM-encoded Ed25519 private key (generated and saved if absent)")pf.BoolVar(&cfg.debug, "debug", false, "enable debug logging (slog + libp2p subsystems)")pf.StringVar(&cfg.federation, "federation", "default", "federation context for isolated reputation and cache storage")diff --git a/cmd/sam/up.go b/cmd/sam-agent/up.gosimilarity index 78%rename from cmd/sam/up.gorename to cmd/sam-agent/up.goindex 45c1ef44..c6dfcdaf 100644--- a/cmd/sam/up.go+++ b/cmd/sam-agent/up.go@@ -16,8 +16,6 @@ package mainimport ("context"- "crypto/ed25519"- "crypto/rand""encoding/json""fmt""log/slog"@@ -33,12 +31,11 @@ import (func newUpCmd(cfg *runConfig) *cobra.Command {cmd := &cobra.Command{Use: "up",- Short: "Start a SAM node and initialize identity issuer/verifier",+ Short: "Start a SAM node",RunE: func(cmd *cobra.Command, _ []string) error {return runUp(cmd.Context(), cfg)},}- cmd.Flags().StringVar(&cfg.issuerName, "issuer", "sam.local", "identity issuer name for voucher bootstrap")cmd.Flags().StringVar(&cfg.tunnelHTTPEndpoint, "tunnel-http-endpoint", "", "optional local HTTP endpoint exposed via /sam/tunnel/http/1.0 (for example http://127.0.0.1:11434)")return cmd}@@ -57,17 +54,8 @@ func runUp(parent context.Context, cfg *runConfig) error {return fmt.Errorf("starting node: %w", err)}defer func() { _ = node.Stop(context.Background()) }()-- _, signingKey, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- return fmt.Errorf("generating issuer key: %w", err)- }- iss, err := identity.NewIssuer(cfg.issuerName, signingKey)- if err != nil {- return fmt.Errorf("initializing issuer: %w", err)- }- if _, err = identity.NewVerifier(identity.WithTrustedIssuer(iss.Issuer(), iss.PublicKey())); err != nil {- return fmt.Errorf("initializing verifier: %w", err)+ if err := identity.EnsurePassportAuth(node.Host(), cfg.federation); err != nil {+ return fmt.Errorf("installing passport auth: %w", err)}var tunnel *protocol.HTTPTunnelService@@ -92,7 +80,6 @@ func runUp(parent context.Context, cfg *runConfig) error {status := map[string]any{"peer_id": node.PeerID().String(),"addrs": addrs,- "issuer": iss.Issuer(),"dht_mode": cfg.dhtMode,}if err := json.NewEncoder(os.Stdout).Encode(status); err != nil {diff --git a/cmd/sam-hub/main.go b/cmd/sam-hub/main.gonew file mode 100644index 00000000..959c79d9--- /dev/null+++ b/cmd/sam-hub/main.go@@ -0,0 +1,72 @@+package main++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "os"+ "strings"++ "github.com/spf13/cobra"++ "sam/pkg/identity"+)++type passportRequest struct {+ PeerID string `json:"peer_id"`+ Federation string `json:"federation"`+ Subject string `json:"subject"`+ Email string `json:"email"`+}++func main() {+ var listen string+ cmd := &cobra.Command{+ Use: "sam-hub",+ Short: "Run a SAM hub (passport issuer + trust observer)",+ RunE: func(cmd *cobra.Command, _ []string) error {+ mux := http.NewServeMux()+ mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("ok"))+ })+ mux.HandleFunc("/issue-passport", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)+ return+ }+ var req passportRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ http.Error(w, fmt.Sprintf("bad request: %v", err), http.StatusBadRequest)+ return+ }+ tok, err := identity.IssuePassportBiscuit(context.Background(), identity.PassportIssueRequest{+ PeerID: strings.TrimSpace(req.PeerID),+ FederationID: strings.TrimSpace(req.Federation),+ Subject: strings.TrimSpace(req.Subject),+ Claims: map[string]string{"email": strings.TrimSpace(req.Email)},+ })+ if err != nil {+ http.Error(w, fmt.Sprintf("issue failed: %v", err), http.StatusBadRequest)+ return+ }+ _ = json.NewEncoder(w).Encode(map[string]string{"passport_biscuit": tok})+ })+ 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}+ go func() {+ <-cmd.Context().Done()+ _ = srv.Shutdown(context.Background())+ }()+ 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)+ }+}diff --git a/cmd/sam/main.go b/cmd/sam/main.godeleted file mode 100644index bfe5dd87..00000000--- a/cmd/sam/main.go+++ /dev/null@@ -1,28 +0,0 @@-// Copyright 2026 Google LLC-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.--package main--import (- "fmt"- "os"-)--func main() {- cfg := &runConfig{}- if err := newRootCmd(cfg).Execute(); err != nil {- fmt.Fprintf(os.Stderr, "sam: %v\n", err)- os.Exit(1)- }-}diff --git a/go.mod b/go.modindex c07e0167..20b52682 100644--- a/go.mod+++ b/go.mod@@ -8,6 +8,7 @@ require (github.com/ipfs/go-log/v2 v2.9.1github.com/libp2p/go-libp2p v0.48.0github.com/libp2p/go-libp2p-kad-dht v0.39.0+ github.com/libp2p/go-libp2p-pubsub v0.15.0github.com/modelcontextprotocol/go-sdk v1.5.0github.com/multiformats/go-multiaddr v0.16.1github.com/multiformats/go-multihash v0.2.3@@ -32,11 +33,13 @@ require (github.com/flynn/noise v1.1.0 // indirectgithub.com/go-logr/logr v1.4.3 // indirectgithub.com/go-logr/stdr v1.2.2 // indirect+ github.com/gogo/protobuf v1.3.2 // indirectgithub.com/google/gopacket v1.1.19 // indirectgithub.com/google/jsonschema-go v0.4.2 // indirectgithub.com/google/uuid v1.6.0 // indirectgithub.com/gorilla/websocket v1.5.3 // indirectgithub.com/hashicorp/golang-lru v1.0.2 // indirect+ github.com/hashicorp/golang-lru/v2 v2.0.7 // indirectgithub.com/huin/goupnp v1.3.0 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirectgithub.com/ipfs/boxo v0.38.0 // indirectdiff --git a/go.sum b/go.sumindex 8dad3ad1..c7fa5345 100644--- a/go.sum+++ b/go.sum@@ -109,6 +109,7 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLENm+P+Tv+MfurjSw0=github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=+github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=@@ -205,6 +206,8 @@ github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJgithub.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c=github.com/hashicorp/golang-lru v1.0.2/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4=+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=@@ -271,6 +274,8 @@ github.com/libp2p/go-libp2p-kad-dht v0.39.0 h1:mww38eBYiUvdsu+Xl/GLlBC0Aa8M+5HAwgithub.com/libp2p/go-libp2p-kad-dht v0.39.0/go.mod h1:Po2JugFEkDq9Vig/JXtc153ntOi0q58o4j7IuITCOVs=github.com/libp2p/go-libp2p-kbucket v0.8.0 h1:QAK7RzKJpYe+EuSEATAaaHYMYLkPDGC18m9jxPLnU8s=github.com/libp2p/go-libp2p-kbucket v0.8.0/go.mod h1:JMlxqcEyKwO6ox716eyC0hmiduSWZZl6JY93mGaaqc4=+github.com/libp2p/go-libp2p-pubsub v0.15.0 h1:cG7Cng2BT82WttmPFMi50gDNV+58K626m/wR00vGL1o=+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-routing-helpers v0.7.5 h1:HdwZj9NKovMx0vqq6YNPTh6aaNzey5zHD7HeLJtq6fI=diff --git a/hack/lint.sh b/hack/lint.shindex c79f8418..52b1ae05 100755--- a/hack/lint.sh+++ b/hack/lint.sh@@ -21,4 +21,4 @@ set -o pipefailREPO_ROOT=$(dirname "${BASH_SOURCE[0]}")/..cd $REPO_ROOT-docker run --rm -v $(pwd):/app -w /app golangci/golangci-lint:v2.11.4 golangci-lint run -v --skip-dirs sam_test_tmp+docker run --rm -v $(pwd):/app -w /app golangci/golangci-lint:v2.11.4 golangci-lint run -vdiff --git a/internal/db/store.go b/internal/db/store.goindex 9386020b..7e6f6fd5 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -21,14 +21,12 @@ import (const (BucketIdentities = "identities"- BucketVouches = "vouches"BucketReputation = "reputation"BucketCache = "cache")var requiredBuckets = []string{BucketIdentities,- BucketVouches,BucketReputation,BucketCache,}diff --git a/pkg/identity/credentials.go b/pkg/identity/credentials.gonew file mode 100644index 00000000..5df7cbb8--- /dev/null+++ b/pkg/identity/credentials.go@@ -0,0 +1,192 @@+// 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 identity++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "strings"+ "time"++ internaldb "sam/internal/db"+)++// StoredCredentials is the persisted identity state in the SAM key-value store.+type StoredCredentials struct {+ PeerID string `json:"peer_id,omitempty"`+ // HubURL is the hub the user authenticated against.+ HubURL string `json:"hub_url"`+ // AccessToken is the OAuth2 access token returned by the Hub.+ AccessToken string `json:"access_token"`+ // RefreshToken allows silent token refresh.+ RefreshToken string `json:"refresh_token,omitempty"`+ // TokenExpiry is when the access token expires.+ TokenExpiry time.Time `json:"token_expiry,omitempty"`+ // PassportBiscuit is the hub-issued biscuit binding identity to peer/federation.+ PassportBiscuit string `json:"passport_biscuit,omitempty"`+}++const (+ credentialsBucketKey = "local"+ credentialsCurrentVersion = 2+)++type credentialsRecord struct {+ PeerID string `json:"peer_id,omitempty"`+ HubURL string `json:"hub_url"`+ AccessToken string `json:"access_token"`+ RefreshToken string `json:"refresh_token,omitempty"`+ TokenExpiry time.Time `json:"token_expiry,omitempty"`+ Passport string `json:"passport_biscuit,omitempty"`+}++// CredentialStore reads and writes SAM credentials from the local state DB.+type CredentialStore struct {+ path string+ store internaldb.Store+ codec internaldb.Codec+}++// DefaultCredentialStore returns a store that uses ~/.config/sam/state.db.+func DefaultCredentialStore() (*CredentialStore, error) {+ path, err := internaldb.DefaultStatePath()+ if err != nil {+ return nil, err+ }+ return NewCredentialStore(path)+}++// NewCredentialStore creates a store backed by the given bbolt file path.+func NewCredentialStore(path string) (*CredentialStore, error) {+ if path == "" {+ return nil, errors.New("credential store path must not be empty")+ }+ store, err := internaldb.Open(path)+ if err != nil {+ return nil, fmt.Errorf("opening state store: %w", err)+ }+ return &CredentialStore{path: path, store: store, codec: internaldb.JSONCodec{}}, nil+}++// Path returns the resolved path to the state DB file.+func (s *CredentialStore) Path() string { return s.path }++// Close releases store resources.+func (s *CredentialStore) Close() error {+ if s == nil || s.store == nil {+ return nil+ }+ return s.store.Close()+}++// Load reads stored credentials. Returns nil, nil when no identity exists.+func (s *CredentialStore) Load() (*StoredCredentials, error) {+ data, err := s.store.Get(context.Background(), internaldb.BucketIdentities, credentialsBucketKey)+ if errors.Is(err, os.ErrNotExist) {+ return nil, nil+ }+ if err != nil {+ return nil, fmt.Errorf("reading identity record: %w", err)+ }++ var rec credentialsRecord+ if err := s.codec.Unmarshal(data, credentialsCurrentVersion, &rec, func(payload map[string]any, fromVersion int) map[string]any {+ if fromVersion < 2 {+ if _, ok := payload["peer_id"]; !ok {+ payload["peer_id"] = ""+ }+ }+ return payload+ }); err != nil {+ return nil, fmt.Errorf("decoding identity record: %w", err)+ }++ creds := &StoredCredentials{+ PeerID: rec.PeerID,+ HubURL: rec.HubURL,+ AccessToken: rec.AccessToken,+ RefreshToken: rec.RefreshToken,+ TokenExpiry: rec.TokenExpiry,+ PassportBiscuit: rec.Passport,+ }+ return creds, nil+}++// Save writes creds to the identities bucket.+func (s *CredentialStore) Save(creds *StoredCredentials) error {+ if creds == nil {+ return errors.New("cannot save nil credentials")+ }+ rec := credentialsRecord{+ PeerID: strings.TrimSpace(creds.PeerID),+ HubURL: creds.HubURL,+ AccessToken: creds.AccessToken,+ RefreshToken: creds.RefreshToken,+ TokenExpiry: creds.TokenExpiry,+ Passport: strings.TrimSpace(creds.PassportBiscuit),+ }++ encodedRec, err := s.codec.Marshal(credentialsCurrentVersion, rec)+ if err != nil {+ return fmt.Errorf("encoding identity record: %w", err)+ }+ if err := s.store.Put(context.Background(), internaldb.BucketIdentities, credentialsBucketKey, encodedRec); err != nil {+ return fmt.Errorf("writing identity record: %w", err)+ }+ return nil+}++// Clear removes stored credentials.+func (s *CredentialStore) Clear() error {+ if err := s.store.Delete(context.Background(), internaldb.BucketIdentities, credentialsBucketKey); err != nil && !errors.Is(err, os.ErrNotExist) {+ return fmt.Errorf("removing identity record: %w", err)+ }+ return nil+}++// HubDiscoveryDoc is the subset of OIDC provider metadata that SAM needs.+type HubDiscoveryDoc struct {+ Issuer string `json:"issuer"`+ DeviceAuthEndpoint string `json:"device_authorization_endpoint"`+ TokenEndpoint string `json:"token_endpoint"`+ UserinfoEndpoint string `json:"userinfo_endpoint,omitempty"`+ JWKsURI string `json:"jwks_uri,omitempty"`+}++// FetchHubDiscovery retrieves the OIDC discovery document from hubURL.+// hubURL should be the base URL of the Hub (e.g. "https://hub.example.com").+// The document is fetched from <hubURL>/.well-known/openid-configuration.+func FetchHubDiscovery(ctx context.Context, hubURL string) (*HubDiscoveryDoc, error) {+ discoveryURL := strings.TrimRight(hubURL, "/") + "/.well-known/openid-configuration"+ req, err := newGetRequest(ctx, discoveryURL)+ if err != nil {+ return nil, err+ }+ body, err := doHTTPRequest(req)+ if err != nil {+ return nil, fmt.Errorf("fetching hub discovery doc from %s: %w", discoveryURL, err)+ }+ var doc HubDiscoveryDoc+ if err := json.Unmarshal(body, &doc); err != nil {+ return nil, fmt.Errorf("parsing hub discovery doc: %w", err)+ }+ if doc.DeviceAuthEndpoint == "" {+ return nil, fmt.Errorf("hub at %s does not advertise device_authorization_endpoint", hubURL)+ }+ return &doc, nil+}diff --git a/pkg/identity/device_flow.go b/pkg/identity/device_flow.goindex 931a25a2..74377073 100644--- a/pkg/identity/device_flow.go+++ b/pkg/identity/device_flow.go@@ -195,50 +195,6 @@ func exchangeDeviceCode(ctx context.Context, tokenEndpoint, deviceCode string, c}, false, nil}-// FetchVouch calls the Hub's vouch endpoint to obtain a signed Vouch in-// exchange for a valid access token and the local PeerID.-//-// The Hub is expected to accept a JSON body of the form:-//-// {"peer_id": "<peerID>"}-//-// and return a signed Vouch JSON object.-func FetchVouch(ctx context.Context, vouchEndpoint, accessToken, peerID string, httpClient *http.Client) (*Vouch, error) {- payload, err := json.Marshal(map[string]string{"peer_id": peerID})- if err != nil {- return nil, fmt.Errorf("marshaling vouch request: %w", err)- }-- req, err := newPostJSONRequest(ctx, vouchEndpoint, payload)- if err != nil {- return nil, err- }- req.Header.Set("Authorization", "Bearer "+accessToken)-- if httpClient == nil {- httpClient = http.DefaultClient- }- resp, err := httpClient.Do(req)- if err != nil {- return nil, fmt.Errorf("vouch request: %w", err)- }- defer func() { _ = resp.Body.Close() }()-- body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<16))- if err != nil {- return nil, fmt.Errorf("reading vouch response: %w", err)- }- if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("vouch endpoint returned %s: %s", resp.Status, body)- }-- var v Vouch- if err := json.Unmarshal(body, &v); err != nil {- return nil, fmt.Errorf("parsing vouch response: %w", err)- }- return &v, nil-}-// Device flow sentinel errors.var (ErrDeviceAuthPending = fmt.Errorf("device authorization pending")diff --git a/pkg/identity/identity.go b/pkg/identity/identity.godeleted file mode 100644index 97de0bad..00000000--- a/pkg/identity/identity.go+++ /dev/null@@ -1,112 +0,0 @@-// 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 identity--import (- "context"- "crypto/ed25519"- "time"-)--// Provider identifies the upstream identity provider that authenticated the workload.-type Provider string--const (- ProviderGoogle Provider = "google"- ProviderGitHub Provider = "github"- ProviderSovereign Provider = "sovereign"-)--// OIDCIdentity is the normalized result of a verified OIDC ID token.-//-// The package does not implement the browser redirect or token exchange flow.-// Instead, a hub or caller injects an already-verified OIDC identity and SAM-// converts it into a signed voucher bound to a specific PeerID.-type OIDCIdentity struct {- Provider Provider- Issuer string- Subject string- Email string- EmailVerified bool- Name string- Picture string- Nonce string- IssuedAt time.Time- Expiry time.Time- Claims map[string]string-}--// Voucher binds an authenticated OIDC identity to a libp2p PeerID.-//-// It is serialized as a compact JWS using EdDSA (Ed25519), allowing offline-// verification without any callback to the issuing hub.-type Voucher struct {- Token string- ID string- Issuer string- Audience string- Subject string- Provider Provider- PeerID string- Email string- EmailVerified bool- Name string- Picture string- Nonce string- IssuedAt time.Time- NotBefore time.Time- Expiry time.Time- Claims map[string]string-}--// VoucherRequest requests issuance of a new signed voucher.-type VoucherRequest struct {- Identity OIDCIdentity- PeerID string- Audience string- Nonce string- TTL time.Duration- Claims map[string]string-}--// VerifyOptions constrains voucher validation for a specific connection or flow.-type VerifyOptions struct {- ExpectedIssuer string- ExpectedAudience string- ExpectedPeerID string- ExpectedNonce string- Now time.Time-}--// IDTokenVerifier abstracts upstream OIDC token verification.-//-// A concrete implementation would typically fetch OIDC metadata and validate an-// ID token against the upstream provider. SAM keeps that concern abstract so the-// voucher format remains usable with Google, GitHub, or sovereign issuers.-type IDTokenVerifier interface {- VerifyIDToken(ctx context.Context, rawToken string, expectedNonce string) (*OIDCIdentity, error)-}--// VoucherIssuer issues hub-signed vouchers that bind a verified identity to a PeerID.-type VoucherIssuer interface {- Issue(ctx context.Context, req VoucherRequest) (string, error)- Issuer() string- PublicKey() ed25519.PublicKey-}--// VoucherVerifier validates a compact voucher and returns its decoded claims.-type VoucherVerifier interface {- Verify(ctx context.Context, token string, opts VerifyOptions) (*Voucher, error)-}diff --git a/pkg/identity/libp2p_passport.go b/pkg/identity/libp2p_passport.gonew file mode 100644index 00000000..bffbe469--- /dev/null+++ b/pkg/identity/libp2p_passport.go@@ -0,0 +1,169 @@+package identity++import (+ "context"+ "encoding/json"+ "fmt"+ "sync"++ "github.com/libp2p/go-libp2p/core/host"+ "github.com/libp2p/go-libp2p/core/network"+ "github.com/libp2p/go-libp2p/core/peer"+ coreprotocol "github.com/libp2p/go-libp2p/core/protocol"+)++const PassportAuthProtocolID coreprotocol.ID = "/sam/auth/passport/1.0"++type passportAuthRequest struct {+ Passport string `json:"passport"`+}++type passportAuthResponse struct {+ OK bool `json:"ok"`+ Error string `json:"error,omitempty"`+}++type passportAuthManager struct {+ host host.Host+ federationID string++ mu sync.RWMutex+ localPassport string+ peerClaims map[string]*PassportClaims+ installed bool+}++var passportAuthManagers sync.Map++func EnsurePassportAuth(h host.Host, federationID string) error {+ if h == nil {+ return fmt.Errorf("host is nil")+ }+ mgr := getOrCreatePassportAuthManager(h)+ mgr.mu.Lock()+ if federationID != "" {+ mgr.federationID = federationID+ }+ if mgr.installed {+ mgr.mu.Unlock()+ return nil+ }+ mgr.installed = true+ mgr.mu.Unlock()++ h.SetStreamHandler(PassportAuthProtocolID, mgr.handleStream)+ h.Network().Notify(&network.NotifyBundle{+ ConnectedF: func(_ network.Network, conn network.Conn) {+ go func() {+ _ = AuthenticatePeerPassport(context.Background(), h, conn.RemotePeer())+ }()+ },+ DisconnectedF: func(_ network.Network, conn network.Conn) {+ mgr.mu.Lock()+ delete(mgr.peerClaims, conn.RemotePeer().String())+ mgr.mu.Unlock()+ },+ })+ return nil+}++func SetLocalPassport(h host.Host, federationID string, passport string) error {+ if err := EnsurePassportAuth(h, federationID); err != nil {+ return err+ }+ mgr := getOrCreatePassportAuthManager(h)+ mgr.mu.Lock()+ mgr.localPassport = passport+ mgr.mu.Unlock()+ return nil+}++func AuthenticatePeerPassport(ctx context.Context, h host.Host, target peer.ID) error {+ if h == nil {+ return fmt.Errorf("host is nil")+ }+ if target == "" {+ return fmt.Errorf("target peer id is required")+ }+ mgr := getOrCreatePassportAuthManager(h)+ if _, ok := mgr.claimsFor(target); ok {+ return nil+ }+ mgr.mu.RLock()+ localPassport := mgr.localPassport+ mgr.mu.RUnlock()+ if localPassport == "" {+ return fmt.Errorf("local passport is not configured")+ }++ stream, err := h.NewStream(ctx, target, PassportAuthProtocolID)+ if err != nil {+ return fmt.Errorf("opening passport auth stream: %w", err)+ }+ defer func() { _ = stream.Close() }()++ if err := json.NewEncoder(stream).Encode(passportAuthRequest{Passport: localPassport}); err != nil {+ return fmt.Errorf("writing passport auth request: %w", err)+ }+ var resp passportAuthResponse+ if err := json.NewDecoder(stream).Decode(&resp); err != nil {+ return fmt.Errorf("reading passport auth response: %w", err)+ }+ if !resp.OK {+ if resp.Error == "" {+ resp.Error = "passport authentication rejected"+ }+ return fmt.Errorf("%s", resp.Error)+ }+ return nil+}++func AuthenticatedPeerPassport(h host.Host, target peer.ID) (*PassportClaims, error) {+ if h == nil {+ return nil, fmt.Errorf("host is nil")+ }+ if target == "" {+ return nil, fmt.Errorf("target peer id is required")+ }+ mgr := getOrCreatePassportAuthManager(h)+ claims, ok := mgr.claimsFor(target)+ if !ok {+ return nil, fmt.Errorf("peer %s has not completed passport authentication", target)+ }+ return claims, nil+}++func getOrCreatePassportAuthManager(h host.Host) *passportAuthManager {+ if mgr, ok := passportAuthManagers.Load(h); ok {+ return mgr.(*passportAuthManager)+ }+ mgr := &passportAuthManager{host: h, federationID: "default", peerClaims: map[string]*PassportClaims{}}+ actual, _ := passportAuthManagers.LoadOrStore(h, mgr)+ return actual.(*passportAuthManager)+}++func (m *passportAuthManager) claimsFor(target peer.ID) (*PassportClaims, bool) {+ m.mu.RLock()+ defer m.mu.RUnlock()+ claims, ok := m.peerClaims[target.String()]+ return claims, ok+}++func (m *passportAuthManager) handleStream(stream network.Stream) {+ defer func() { _ = stream.Close() }()++ var req passportAuthRequest+ if err := json.NewDecoder(stream).Decode(&req); err != nil {+ _ = json.NewEncoder(stream).Encode(passportAuthResponse{Error: fmt.Sprintf("invalid passport auth request: %v", err)})+ return+ }+ claims, err := ValidatePassportBiscuit(context.Background(), req.Passport, stream.Conn().RemotePeer().String(), m.federationID)+ if err != nil {+ _ = json.NewEncoder(stream).Encode(passportAuthResponse{Error: fmt.Sprintf("invalid passport: %v", err)})+ return+ }+ m.mu.Lock()+ m.peerClaims[stream.Conn().RemotePeer().String()] = claims+ m.mu.Unlock()+ _ = json.NewEncoder(stream).Encode(passportAuthResponse{OK: true})+}diff --git a/pkg/identity/options.go b/pkg/identity/options.godeleted file mode 100644index 4ef2a49b..00000000--- a/pkg/identity/options.go+++ /dev/null@@ -1,132 +0,0 @@-// 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 identity--import (- "crypto/ed25519"- "fmt"- "time"-)--const (- defaultVoucherTTL = 15 * time.Minute- defaultLeeway = 30 * time.Second-)--type clock interface {- Now() time.Time-}--type realClock struct{}--func (realClock) Now() time.Time {- return time.Now().UTC()-}--// TrustedIssuer is a verifier-side trust anchor.-type TrustedIssuer struct {- Issuer string- KeyID string- PublicKey ed25519.PublicKey-}--// IssuerOption customizes a voucher issuer.-type IssuerOption func(*issuer) error--// VerifierOption customizes a voucher verifier.-type VerifierOption func(*verifier) error--// WithIssuerKeyID attaches a key identifier to signed vouchers.-func WithIssuerKeyID(keyID string) IssuerOption {- return func(i *issuer) error {- i.keyID = keyID- return nil- }-}--// WithIssuerDefaultTTL overrides the default voucher TTL.-func WithIssuerDefaultTTL(ttl time.Duration) IssuerOption {- return func(i *issuer) error {- if ttl <= 0 {- return fmt.Errorf("default TTL must be positive")- }- i.defaultTTL = ttl- return nil- }-}--// WithIssuerClock injects a deterministic clock for tests.-func WithIssuerClock(c clock) IssuerOption {- return func(i *issuer) error {- if c == nil {- return fmt.Errorf("issuer clock must not be nil")- }- i.clock = c- return nil- }-}--// WithTrustedIssuer registers a trusted issuer key on the verifier.-func WithTrustedIssuer(issuerName string, key ed25519.PublicKey) VerifierOption {- return func(v *verifier) error {- if issuerName == "" {- return fmt.Errorf("trusted issuer name must not be empty")- }- if len(key) != ed25519.PublicKeySize {- return fmt.Errorf("trusted issuer public key has invalid length")- }- v.trustByIssuer[issuerName] = trustedKey{publicKey: append(ed25519.PublicKey(nil), key...)}- return nil- }-}--// WithTrustedIssuerRecord registers a trusted issuer key with an optional key ID.-func WithTrustedIssuerRecord(record TrustedIssuer) VerifierOption {- return func(v *verifier) error {- if record.Issuer == "" {- return fmt.Errorf("trusted issuer name must not be empty")- }- if len(record.PublicKey) != ed25519.PublicKeySize {- return fmt.Errorf("trusted issuer public key has invalid length")- }- v.trustByIssuer[record.Issuer] = trustedKey{- keyID: record.KeyID,- publicKey: append(ed25519.PublicKey(nil), record.PublicKey...),- }- return nil- }-}--// WithVerifierClock injects a deterministic clock for tests.-func WithVerifierClock(c clock) VerifierOption {- return func(v *verifier) error {- if c == nil {- return fmt.Errorf("verifier clock must not be nil")- }- v.clock = c- return nil- }-}--// WithVerifierLeeway sets the time skew tolerance for exp/nbf/iat checks.-func WithVerifierLeeway(leeway time.Duration) VerifierOption {- return func(v *verifier) error {- if leeway < 0 {- return fmt.Errorf("verifier leeway must not be negative")- }- v.leeway = leeway- return nil- }-}diff --git a/pkg/identity/passport.go b/pkg/identity/passport.gonew file mode 100644index 00000000..83f25ce0--- /dev/null+++ b/pkg/identity/passport.go@@ -0,0 +1,131 @@+package identity++import (+ "context"+ "encoding/json"+ "fmt"+ "strings"++ "sam/pkg/economy"+)++// PassportIssueRequest binds OIDC identity material to a peer and federation.+type PassportIssueRequest struct {+ PeerID string+ FederationID string+ Subject string+ Claims map[string]string+}++// PassportClaims are extracted from a passport biscuit.+type PassportClaims struct {+ Token string+ PeerID string+ FederationID string+ Subject string+ Claims map[string]string+}++// IssuePassportBiscuit issues a compact passport biscuit token.+// Token wire format keeps compatibility with SimpleBiscuitParser by placing+// identity binding data in the subject segment and caveats after ';'.+func IssuePassportBiscuit(_ context.Context, req PassportIssueRequest) (string, error) {+ req.PeerID = strings.TrimSpace(req.PeerID)+ req.FederationID = strings.TrimSpace(req.FederationID)+ req.Subject = strings.TrimSpace(req.Subject)+ if req.PeerID == "" || req.FederationID == "" || req.Subject == "" {+ return "", fmt.Errorf("peer_id, federation_id and subject are required")+ }+ if req.Claims == nil {+ req.Claims = map[string]string{}+ }+ rawClaims, err := json.Marshal(req.Claims)+ if err != nil {+ return "", fmt.Errorf("marshal claims: %w", err)+ }+ subject := fmt.Sprintf("passport|sub=%s|peer=%s|fed=%s|claims=%s", sanitize(req.Subject), sanitize(req.PeerID), sanitize(req.FederationID), sanitize(string(rawClaims)))+ return subject + ";allow_skill=*", nil+}++func FetchPassportBiscuit(ctx context.Context, issueEndpoint string, accessToken string, req PassportIssueRequest) (string, error) {+ body, err := json.Marshal(map[string]string{+ "peer_id": strings.TrimSpace(req.PeerID),+ "federation": strings.TrimSpace(req.FederationID),+ "subject": strings.TrimSpace(req.Subject),+ "email": strings.TrimSpace(req.Claims["email"]),+ })+ if err != nil {+ return "", fmt.Errorf("marshal passport request: %w", err)+ }+ httpReq, err := newPostJSONRequest(ctx, strings.TrimSpace(issueEndpoint), body)+ if err != nil {+ return "", err+ }+ if token := strings.TrimSpace(accessToken); token != "" {+ httpReq.Header.Set("Authorization", "Bearer "+token)+ }+ respBody, err := doHTTPRequest(httpReq)+ if err != nil {+ return "", fmt.Errorf("requesting passport biscuit: %w", err)+ }+ var out struct {+ PassportBiscuit string `json:"passport_biscuit"`+ }+ if err := json.Unmarshal(respBody, &out); err != nil {+ return "", fmt.Errorf("parse passport response: %w", err)+ }+ if strings.TrimSpace(out.PassportBiscuit) == "" {+ return "", fmt.Errorf("passport_biscuit missing in response")+ }+ return strings.TrimSpace(out.PassportBiscuit), nil+}++func ValidatePassportBiscuit(ctx context.Context, token string, expectedPeerID string, expectedFederationID string) (*PassportClaims, error) {+ p, err := economy.SimpleBiscuitParser{}.Parse(ctx, token)+ if err != nil {+ return nil, fmt.Errorf("parse passport biscuit: %w", err)+ }+ parts := strings.Split(p.Subject, "|")+ if len(parts) < 5 || parts[0] != "passport" {+ return nil, fmt.Errorf("invalid passport biscuit subject")+ }+ claims := &PassportClaims{Token: token, Claims: map[string]string{}}+ for _, item := range parts[1:] {+ kv := strings.SplitN(item, "=", 2)+ if len(kv) != 2 {+ continue+ }+ key, value := kv[0], unsanitize(kv[1])+ switch key {+ case "sub":+ claims.Subject = value+ case "peer":+ claims.PeerID = value+ case "fed":+ claims.FederationID = value+ case "claims":+ _ = json.Unmarshal([]byte(value), &claims.Claims)+ }+ }+ if strings.TrimSpace(expectedPeerID) != "" && claims.PeerID != strings.TrimSpace(expectedPeerID) {+ return nil, fmt.Errorf("passport peer mismatch")+ }+ if strings.TrimSpace(expectedFederationID) != "" && claims.FederationID != strings.TrimSpace(expectedFederationID) {+ return nil, fmt.Errorf("passport federation mismatch")+ }+ return claims, nil+}++func sanitize(s string) string {+ s = strings.ReplaceAll(s, "|", "%7C")+ s = strings.ReplaceAll(s, ";", "%3B")+ s = strings.ReplaceAll(s, "=", "%3D")+ return s+}++func unsanitize(s string) string {+ s = strings.ReplaceAll(s, "%7C", "|")+ s = strings.ReplaceAll(s, "%3B", ";")+ s = strings.ReplaceAll(s, "%3D", "=")+ return s+}diff --git a/pkg/identity/vouch.go b/pkg/identity/vouch.godeleted file mode 100644index c484f673..00000000--- a/pkg/identity/vouch.go+++ /dev/null@@ -1,406 +0,0 @@-// 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 identity--import (- "context"- "crypto/ed25519"- "crypto/rand"- "encoding/base64"- "encoding/json"- "errors"- "fmt"- "os"- "strings"- "time"-- internaldb "sam/internal/db"-)--// Vouch is the portable credential that the Hub issues after a successful-// Device Authorization Grant. It binds the authenticated user's OIDC claims-// to a specific libp2p PeerID and is signed by the Hub's Ed25519 key so that-// any peer in the mesh can verify it offline.-type Vouch struct {- // PeerID is the libp2p peer identity this credential is bound to.- PeerID string `json:"peer_id"`- // Issuer is the Hub base URL that issued this credential.- Issuer string `json:"issuer"`- // Subject is the OIDC subject (stable user identifier).- Subject string `json:"subject,omitempty"`- // Claims contains the OIDC profile claims forwarded by the Hub.- // Standard keys: "email", "name", "org", "picture".- Claims map[string]string `json:"claims,omitempty"`- // IssuedAt records when the Hub minted this Vouch.- IssuedAt time.Time `json:"issued_at"`- // Expiry is when this Vouch should stop being trusted.- Expiry time.Time `json:"expiry"`- // Algorithm is the signature algorithm, always "libp2p-ed25519".- Algorithm string `json:"alg"`- // Signature is the base64url-encoded Ed25519 signature over the canonical- // payload (all fields except Signature, JSON-marshaled sorted-key).- Signature string `json:"signature"`-}--// IsExpired reports whether the Vouch has passed its expiry time.-func (v *Vouch) IsExpired() bool {- return !v.Expiry.IsZero() && time.Now().After(v.Expiry)-}--// Email is a convenience accessor for the "email" claim.-func (v *Vouch) Email() string { return v.Claims["email"] }--// Name is a convenience accessor for the "name" claim.-func (v *Vouch) Name() string { return v.Claims["name"] }--// Org is a convenience accessor for the "org" claim.-func (v *Vouch) Org() string { return v.Claims["org"] }--// vouchPayload is the subset of Vouch that is covered by the Hub signature.-// The Signature field is intentionally excluded.-type vouchPayload struct {- PeerID string `json:"peer_id"`- Issuer string `json:"issuer"`- Subject string `json:"subject,omitempty"`- Claims map[string]string `json:"claims,omitempty"`- IssuedAt time.Time `json:"issued_at"`- Expiry time.Time `json:"expiry"`- Algorithm string `json:"alg"`-}--// vouchSigPayload returns the canonical bytes the Hub signs.-func vouchSigPayload(v *Vouch) ([]byte, error) {- p := vouchPayload{- PeerID: v.PeerID,- Issuer: v.Issuer,- Subject: v.Subject,- Claims: v.Claims,- IssuedAt: v.IssuedAt,- Expiry: v.Expiry,- Algorithm: v.Algorithm,- }- return json.Marshal(p)-}--// SignVouch signs a Vouch with hubKey and sets Vouch.Signature.-// Intended for use by a Hub implementation; clients call VerifyVouch.-func SignVouch(v *Vouch, hubKey ed25519.PrivateKey) error {- v.Algorithm = "libp2p-ed25519"- payload, err := vouchSigPayload(v)- if err != nil {- return fmt.Errorf("marshaling vouch payload: %w", err)- }- sig := ed25519.Sign(hubKey, payload)- v.Signature = base64.RawURLEncoding.EncodeToString(sig)- return nil-}--// VerifyVouch verifies the Hub signature on a Vouch and checks expiry.-func VerifyVouch(v *Vouch, hubPubKey ed25519.PublicKey) error {- if v == nil {- return errors.New("vouch is nil")- }- if v.Algorithm != "libp2p-ed25519" {- return fmt.Errorf("unsupported vouch algorithm %q", v.Algorithm)- }- if v.IsExpired() {- return fmt.Errorf("vouch expired at %s", v.Expiry.Format(time.RFC3339))- }-- payload, err := vouchSigPayload(v)- if err != nil {- return fmt.Errorf("marshaling vouch payload for verification: %w", err)- }- sig, err := base64.RawURLEncoding.DecodeString(v.Signature)- if err != nil {- return fmt.Errorf("decoding vouch signature: %w", err)- }- if !ed25519.Verify(hubPubKey, payload, sig) {- return errors.New("vouch signature verification failed")- }- return nil-}--// StoredCredentials is the persisted identity state in the SAM key-value store.-type StoredCredentials struct {- PeerID string `json:"peer_id,omitempty"`- // HubURL is the hub the user authenticated against.- HubURL string `json:"hub_url"`- // AccessToken is the OAuth2 access token returned by the Hub.- AccessToken string `json:"access_token"`- // RefreshToken allows silent token refresh.- RefreshToken string `json:"refresh_token,omitempty"`- // TokenExpiry is when the access token expires.- TokenExpiry time.Time `json:"token_expiry,omitempty"`- // Vouch is the Hub-signed credential bound to the local PeerID.- Vouch *Vouch `json:"vouch,omitempty"`-}--const (- credentialsBucketKey = "local"- legacyVouchBucketFallback = "default"- credentialsCurrentVersion = 2- vouchCurrentVersion = 1-)--type credentialsRecord struct {- PeerID string `json:"peer_id,omitempty"`- HubURL string `json:"hub_url"`- AccessToken string `json:"access_token"`- RefreshToken string `json:"refresh_token,omitempty"`- TokenExpiry time.Time `json:"token_expiry,omitempty"`-}--type vouchRecord struct {- Vouch *Vouch `json:"vouch,omitempty"`-}--// CredentialStore reads and writes SAM credentials from the local state DB.-type CredentialStore struct {- path string- store internaldb.Store- codec internaldb.Codec-}--// DefaultCredentialStore returns a store that uses ~/.config/sam/state.db.-func DefaultCredentialStore() (*CredentialStore, error) {- path, err := internaldb.DefaultStatePath()- if err != nil {- return nil, err- }- return NewCredentialStore(path)-}--// NewCredentialStore creates a store backed by the given bbolt file path.-func NewCredentialStore(path string) (*CredentialStore, error) {- if path == "" {- return nil, errors.New("credential store path must not be empty")- }- store, err := internaldb.Open(path)- if err != nil {- return nil, fmt.Errorf("opening state store: %w", err)- }- return &CredentialStore{path: path, store: store, codec: internaldb.JSONCodec{}}, nil-}--// Path returns the resolved path to the state DB file.-func (s *CredentialStore) Path() string { return s.path }--// Close releases store resources.-func (s *CredentialStore) Close() error {- if s == nil || s.store == nil {- return nil- }- return s.store.Close()-}--// Load reads stored credentials. Returns nil, nil when no identity exists.-func (s *CredentialStore) Load() (*StoredCredentials, error) {- data, err := s.store.Get(context.Background(), internaldb.BucketIdentities, credentialsBucketKey)- if errors.Is(err, os.ErrNotExist) {- return nil, nil- }- if err != nil {- return nil, fmt.Errorf("reading identity record: %w", err)- }-- var rec credentialsRecord- if err := s.codec.Unmarshal(data, credentialsCurrentVersion, &rec, func(payload map[string]any, fromVersion int) map[string]any {- if fromVersion < 2 {- if _, ok := payload["peer_id"]; !ok {- payload["peer_id"] = ""- }- }- return payload- }); err != nil {- return nil, fmt.Errorf("decoding identity record: %w", err)- }-- creds := &StoredCredentials{- PeerID: rec.PeerID,- HubURL: rec.HubURL,- AccessToken: rec.AccessToken,- RefreshToken: rec.RefreshToken,- TokenExpiry: rec.TokenExpiry,- }-- if creds.PeerID != "" {- v, vErr := s.loadVouch(creds.PeerID)- if vErr == nil {- creds.Vouch = v- }- }- if creds.Vouch == nil {- v, vErr := s.loadVouch(legacyVouchBucketFallback)- if vErr == nil {- creds.Vouch = v- }- }- if creds.PeerID == "" && creds.Vouch != nil {- creds.PeerID = creds.Vouch.PeerID- }- return creds, nil-}--// Save writes creds to the identities and vouches buckets.-func (s *CredentialStore) Save(creds *StoredCredentials) error {- if creds == nil {- return errors.New("cannot save nil credentials")- }- rec := credentialsRecord{- PeerID: strings.TrimSpace(creds.PeerID),- HubURL: creds.HubURL,- AccessToken: creds.AccessToken,- RefreshToken: creds.RefreshToken,- TokenExpiry: creds.TokenExpiry,- }- if rec.PeerID == "" && creds.Vouch != nil {- rec.PeerID = strings.TrimSpace(creds.Vouch.PeerID)- }-- encodedRec, err := s.codec.Marshal(credentialsCurrentVersion, rec)- if err != nil {- return fmt.Errorf("encoding identity record: %w", err)- }- if err := s.store.Put(context.Background(), internaldb.BucketIdentities, credentialsBucketKey, encodedRec); err != nil {- return fmt.Errorf("writing identity record: %w", err)- }- if creds.Vouch != nil {- vkey := strings.TrimSpace(creds.Vouch.PeerID)- if vkey == "" {- vkey = legacyVouchBucketFallback- }- rec := vouchRecord{Vouch: creds.Vouch}- encodedVouch, err := s.codec.Marshal(vouchCurrentVersion, rec)- if err != nil {- return fmt.Errorf("encoding vouch record: %w", err)- }- if err := s.store.Put(context.Background(), internaldb.BucketVouches, vkey, encodedVouch); err != nil {- return fmt.Errorf("writing vouch record: %w", err)- }- }- return nil-}--func (s *CredentialStore) loadVouch(key string) (*Vouch, error) {- data, err := s.store.Get(context.Background(), internaldb.BucketVouches, key)- if err != nil {- return nil, err- }- var rec vouchRecord- if err := s.codec.Unmarshal(data, vouchCurrentVersion, &rec, nil); err != nil {- return nil, err- }- if rec.Vouch == nil {- return nil, os.ErrNotExist- }- return rec.Vouch, nil-}--// Clear removes stored credentials and the current vouch key if present.-func (s *CredentialStore) Clear() error {- creds, _ := s.Load()- if err := s.store.Delete(context.Background(), internaldb.BucketIdentities, credentialsBucketKey); err != nil && !errors.Is(err, os.ErrNotExist) {- return fmt.Errorf("removing identity record: %w", err)- }- if creds != nil {- if pid := strings.TrimSpace(creds.PeerID); pid != "" {- _ = s.store.Delete(context.Background(), internaldb.BucketVouches, pid)- }- }- _ = s.store.Delete(context.Background(), internaldb.BucketVouches, legacyVouchBucketFallback)- return nil-}--// NewVouch creates an unsigned Vouch that a Hub can then sign with SignVouch.-// peerID must be the hex/base58 string form of the peer identity.-// claims is typically the OIDC userinfo response subset: email, name, org, …-func NewVouch(peerID, issuer, subject string, claims map[string]string, ttl time.Duration) *Vouch {- now := time.Now().UTC()- return &Vouch{- PeerID: peerID,- Issuer: issuer,- Subject: subject,- Claims: claims,- IssuedAt: now,- Expiry: now.Add(ttl),- }-}--// SelfSignVouch creates a self-attested Vouch signed with the local peer key.-// This is used when no Hub is available and the node wants to advertise minimal-// identity in its AgentCard.-func SelfSignVouch(peerID string, privKey ed25519.PrivateKey) (*Vouch, error) {- if peerID == "" {- return nil, errors.New("peer ID must not be empty")- }- if len(privKey) != ed25519.PrivateKeySize {- return nil, errors.New("invalid private key length")- }- // Use a random nonce as subject so self-signed vouches are unlinkable.- nonce := make([]byte, 16)- if _, err := rand.Read(nonce); err != nil {- return nil, fmt.Errorf("generating self-vouch nonce: %w", err)- }- subject := "self:" + base64.RawURLEncoding.EncodeToString(nonce)- v := &Vouch{- PeerID: peerID,- Issuer: "self",- Subject: subject,- Claims: map[string]string{},- IssuedAt: time.Now().UTC(),- Expiry: time.Now().UTC().Add(24 * time.Hour),- }- pubKey := privKey.Public().(ed25519.PublicKey)- if err := SignVouch(v, privKey); err != nil {- return nil, err- }- // Embed the public key as a claim so verifiers can reconstruct trust.- v.Claims["pub_key"] = base64.RawURLEncoding.EncodeToString(pubKey)- return v, nil-}--// HubDiscoveryDoc is the subset of OIDC provider metadata that SAM needs.-type HubDiscoveryDoc struct {- Issuer string `json:"issuer"`- DeviceAuthEndpoint string `json:"device_authorization_endpoint"`- TokenEndpoint string `json:"token_endpoint"`- UserinfoEndpoint string `json:"userinfo_endpoint,omitempty"`- VouchEndpoint string `json:"vouch_endpoint,omitempty"` // SAM extension- JWKsURI string `json:"jwks_uri,omitempty"`-}--// FetchHubDiscovery retrieves the OIDC discovery document from hubURL.-// hubURL should be the base URL of the Hub (e.g. "https://hub.example.com").-// The document is fetched from <hubURL>/.well-known/openid-configuration.-func FetchHubDiscovery(ctx context.Context, hubURL string) (*HubDiscoveryDoc, error) {- discoveryURL := strings.TrimRight(hubURL, "/") + "/.well-known/openid-configuration"- req, err := newGetRequest(ctx, discoveryURL)- if err != nil {- return nil, err- }- body, err := doHTTPRequest(req)- if err != nil {- return nil, fmt.Errorf("fetching hub discovery doc from %s: %w", discoveryURL, err)- }- var doc HubDiscoveryDoc- if err := json.Unmarshal(body, &doc); err != nil {- return nil, fmt.Errorf("parsing hub discovery doc: %w", err)- }- if doc.DeviceAuthEndpoint == "" {- return nil, fmt.Errorf("hub at %s does not advertise device_authorization_endpoint", hubURL)- }- return &doc, nil-}diff --git a/pkg/identity/voucher.go b/pkg/identity/voucher.godeleted file mode 100644index 46c56051..00000000--- a/pkg/identity/voucher.go+++ /dev/null@@ -1,388 +0,0 @@-// 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 identity--import (- "context"- "crypto/ed25519"- "crypto/rand"- "encoding/base64"- "encoding/json"- "errors"- "fmt"- "strings"- "time"-- "github.com/libp2p/go-libp2p/core/peer"-)--var (- ErrInvalidVoucher = errors.New("invalid voucher")- ErrInvalidSignature = errors.New("invalid voucher signature")- ErrUntrustedIssuer = errors.New("untrusted voucher issuer")- ErrVoucherExpired = errors.New("voucher expired")- ErrVoucherNotActive = errors.New("voucher not active")-)--type issuer struct {- issuerName string- privateKey ed25519.PrivateKey- publicKey ed25519.PublicKey- keyID string- defaultTTL time.Duration- clock clock-}--type verifier struct {- trustByIssuer map[string]trustedKey- leeway time.Duration- clock clock-}--type trustedKey struct {- keyID string- publicKey ed25519.PublicKey-}--type voucherHeader struct {- Algorithm string `json:"alg"`- Type string `json:"typ"`- KeyID string `json:"kid,omitempty"`-}--type voucherClaims struct {- Issuer string `json:"iss"`- Subject string `json:"sub"`- Audience string `json:"aud"`- IssuedAt int64 `json:"iat"`- NotBefore int64 `json:"nbf"`- Expiry int64 `json:"exp"`- ID string `json:"jti"`- Provider Provider `json:"provider"`- PeerID string `json:"peer_id"`- Email string `json:"email,omitempty"`- EmailVerified bool `json:"email_verified,omitempty"`- Name string `json:"name,omitempty"`- Picture string `json:"picture,omitempty"`- Nonce string `json:"nonce,omitempty"`- Claims map[string]string `json:"claims,omitempty"`-}--// NewIssuer creates a voucher issuer backed by an Ed25519 signing key.-func NewIssuer(issuerName string, signingKey ed25519.PrivateKey, opts ...IssuerOption) (VoucherIssuer, error) {- if issuerName == "" {- return nil, fmt.Errorf("issuer name must not be empty")- }- if len(signingKey) != ed25519.PrivateKeySize {- return nil, fmt.Errorf("signing key has invalid length")- }-- i := &issuer{- issuerName: issuerName,- privateKey: append(ed25519.PrivateKey(nil), signingKey...),- publicKey: append(ed25519.PublicKey(nil), signingKey.Public().(ed25519.PublicKey)...),- defaultTTL: defaultVoucherTTL,- clock: realClock{},- }-- for _, opt := range opts {- if err := opt(i); err != nil {- return nil, fmt.Errorf("applying issuer option: %w", err)- }- }-- return i, nil-}--// NewVerifier creates a verifier with one or more trusted hub keys.-func NewVerifier(opts ...VerifierOption) (VoucherVerifier, error) {- v := &verifier{- trustByIssuer: make(map[string]trustedKey),- leeway: defaultLeeway,- clock: realClock{},- }-- for _, opt := range opts {- if err := opt(v); err != nil {- return nil, fmt.Errorf("applying verifier option: %w", err)- }- }-- if len(v.trustByIssuer) == 0 {- return nil, fmt.Errorf("at least one trusted issuer is required")- }-- return v, nil-}--func (i *issuer) Issuer() string {- return i.issuerName-}--func (i *issuer) PublicKey() ed25519.PublicKey {- return append(ed25519.PublicKey(nil), i.publicKey...)-}--func (i *issuer) Issue(_ context.Context, req VoucherRequest) (string, error) {- if err := validateOIDCIdentity(req.Identity); err != nil {- return "", err- }- if err := validatePeerID(req.PeerID); err != nil {- return "", err- }- if req.Audience == "" {- return "", fmt.Errorf("audience must not be empty")- }-- ttl := req.TTL- if ttl <= 0 {- ttl = i.defaultTTL- }- if ttl <= 0 {- return "", fmt.Errorf("voucher TTL must be positive")- }-- now := i.clock.Now().UTC()- nonce := req.Nonce- if nonce == "" {- nonce = req.Identity.Nonce- }-- mergedClaims, err := mergeClaims(req.Identity.Claims, req.Claims)- if err != nil {- return "", err- }-- claims := voucherClaims{- Issuer: i.issuerName,- Subject: req.Identity.Subject,- Audience: req.Audience,- IssuedAt: now.Unix(),- NotBefore: now.Unix(),- Expiry: now.Add(ttl).Unix(),- ID: randomID(),- Provider: req.Identity.Provider,- PeerID: req.PeerID,- Email: req.Identity.Email,- EmailVerified: req.Identity.EmailVerified,- Name: req.Identity.Name,- Picture: req.Identity.Picture,- Nonce: nonce,- Claims: mergedClaims,- }-- header := voucherHeader{- Algorithm: "EdDSA",- Type: "JWT",- KeyID: i.keyID,- }-- token, err := signJWT(header, claims, i.privateKey)- if err != nil {- return "", fmt.Errorf("signing voucher: %w", err)- }-- return token, nil-}--func (v *verifier) Verify(_ context.Context, token string, opts VerifyOptions) (*Voucher, error) {- header, claims, signingInput, sig, err := parseJWT(token)- if err != nil {- return nil, err- }- if header.Algorithm != "EdDSA" || header.Type != "JWT" {- return nil, fmt.Errorf("%w: unsupported JOSE header", ErrInvalidVoucher)- }-- trust, ok := v.trustByIssuer[claims.Issuer]- if !ok {- return nil, fmt.Errorf("%w: %s", ErrUntrustedIssuer, claims.Issuer)- }- if trust.keyID != "" && header.KeyID != "" && trust.keyID != header.KeyID {- return nil, fmt.Errorf("%w: unexpected key id %q", ErrUntrustedIssuer, header.KeyID)- }- if !ed25519.Verify(trust.publicKey, []byte(signingInput), sig) {- return nil, ErrInvalidSignature- }-- if err := validatePeerID(claims.PeerID); err != nil {- return nil, err- }-- now := opts.Now.UTC()- if now.IsZero() {- now = v.clock.Now().UTC()- }- leeway := v.leeway-- issuedAt := time.Unix(claims.IssuedAt, 0).UTC()- notBefore := time.Unix(claims.NotBefore, 0).UTC()- expiry := time.Unix(claims.Expiry, 0).UTC()-- if now.After(expiry.Add(leeway)) {- return nil, ErrVoucherExpired- }- if now.Before(notBefore.Add(-leeway)) {- return nil, ErrVoucherNotActive- }- if claims.IssuedAt > 0 && now.Before(issuedAt.Add(-leeway)) {- return nil, fmt.Errorf("%w: issued-at is in the future", ErrInvalidVoucher)- }-- if opts.ExpectedIssuer != "" && opts.ExpectedIssuer != claims.Issuer {- return nil, fmt.Errorf("%w: issuer mismatch", ErrInvalidVoucher)- }- if opts.ExpectedAudience != "" && opts.ExpectedAudience != claims.Audience {- return nil, fmt.Errorf("%w: audience mismatch", ErrInvalidVoucher)- }- if opts.ExpectedPeerID != "" && opts.ExpectedPeerID != claims.PeerID {- return nil, fmt.Errorf("%w: peer ID mismatch", ErrInvalidVoucher)- }- if opts.ExpectedNonce != "" && opts.ExpectedNonce != claims.Nonce {- return nil, fmt.Errorf("%w: nonce mismatch", ErrInvalidVoucher)- }-- return &Voucher{- Token: token,- ID: claims.ID,- Issuer: claims.Issuer,- Audience: claims.Audience,- Subject: claims.Subject,- Provider: claims.Provider,- PeerID: claims.PeerID,- Email: claims.Email,- EmailVerified: claims.EmailVerified,- Name: claims.Name,- Picture: claims.Picture,- Nonce: claims.Nonce,- IssuedAt: issuedAt,- NotBefore: notBefore,- Expiry: expiry,- Claims: copyClaims(claims.Claims),- }, nil-}--func signJWT(header voucherHeader, claims voucherClaims, privateKey ed25519.PrivateKey) (string, error) {- headerJSON, err := json.Marshal(header)- if err != nil {- return "", fmt.Errorf("marshaling JOSE header: %w", err)- }- claimsJSON, err := json.Marshal(claims)- if err != nil {- return "", fmt.Errorf("marshaling voucher claims: %w", err)- }-- head := base64.RawURLEncoding.EncodeToString(headerJSON)- payload := base64.RawURLEncoding.EncodeToString(claimsJSON)- signingInput := head + "." + payload- signature := ed25519.Sign(privateKey, []byte(signingInput))-- return signingInput + "." + base64.RawURLEncoding.EncodeToString(signature), nil-}--func parseJWT(token string) (voucherHeader, voucherClaims, string, []byte, error) {- parts := strings.Split(token, ".")- if len(parts) != 3 {- return voucherHeader{}, voucherClaims{}, "", nil, fmt.Errorf("%w: compact token must have three parts", ErrInvalidVoucher)- }-- var header voucherHeader- if err := decodeSegment(parts[0], &header); err != nil {- return voucherHeader{}, voucherClaims{}, "", nil, fmt.Errorf("%w: invalid JOSE header: %v", ErrInvalidVoucher, err)- }- var claims voucherClaims- if err := decodeSegment(parts[1], &claims); err != nil {- return voucherHeader{}, voucherClaims{}, "", nil, fmt.Errorf("%w: invalid claims set: %v", ErrInvalidVoucher, err)- }- sig, err := base64.RawURLEncoding.DecodeString(parts[2])- if err != nil {- return voucherHeader{}, voucherClaims{}, "", nil, fmt.Errorf("%w: invalid signature encoding", ErrInvalidVoucher)- }-- return header, claims, parts[0] + "." + parts[1], sig, nil-}--func decodeSegment(segment string, into any) error {- raw, err := base64.RawURLEncoding.DecodeString(segment)- if err != nil {- return err- }- return json.Unmarshal(raw, into)-}--func validateOIDCIdentity(identity OIDCIdentity) error {- if identity.Provider == "" {- return fmt.Errorf("provider must not be empty")- }- if identity.Issuer == "" {- return fmt.Errorf("upstream issuer must not be empty")- }- if identity.Subject == "" {- return fmt.Errorf("subject must not be empty")- }- return nil-}--func validatePeerID(peerID string) error {- if peerID == "" {- return fmt.Errorf("peer ID must not be empty")- }- if _, err := peer.Decode(peerID); err != nil {- return fmt.Errorf("invalid peer ID %q: %w", peerID, err)- }- return nil-}--func mergeClaims(identityClaims, requestClaims map[string]string) (map[string]string, error) {- merged := copyClaims(identityClaims)- for key, value := range requestClaims {- if isReservedClaim(key) {- return nil, fmt.Errorf("claim %q is reserved", key)- }- merged[key] = value- }- if len(merged) == 0 {- return nil, nil- }- return merged, nil-}--func copyClaims(in map[string]string) map[string]string {- if len(in) == 0 {- return nil- }- out := make(map[string]string, len(in))- for key, value := range in {- out[key] = value- }- return out-}--func isReservedClaim(key string) bool {- switch key {- case "iss", "sub", "aud", "iat", "nbf", "exp", "jti", "provider", "peer_id", "email", "email_verified", "name", "picture", "nonce", "claims":- return true- default:- return false- }-}--func randomID() string {- buf := make([]byte, 16)- if _, err := rand.Read(buf); err != nil {- panic(fmt.Sprintf("crypto/rand failed: %v", err))- }- return base64.RawURLEncoding.EncodeToString(buf)-}diff --git a/pkg/identity/voucher_test.go b/pkg/identity/voucher_test.godeleted file mode 100644index 51a7bd07..00000000--- a/pkg/identity/voucher_test.go+++ /dev/null@@ -1,362 +0,0 @@-// 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 identity_test--import (- "context"- "crypto/ed25519"- "crypto/rand"- "strings"- "testing"- "time"-- "github.com/libp2p/go-libp2p/core/crypto"- "github.com/libp2p/go-libp2p/core/peer"-- "sam/pkg/identity"-)--type fixedClock struct {- now time.Time-}--func (f fixedClock) Now() time.Time {- return f.now-}--func TestVoucherIssueAndVerify(t *testing.T) {- issuedAt := time.Date(2026, 4, 17, 23, 50, 0, 0, time.UTC)- issuerKey := generateSigningKey(t)- peerID := generatePeerID(t)-- issuer, err := identity.NewIssuer(- "hub.sam.dev",- issuerKey,- identity.WithIssuerKeyID("hub-key-1"),- identity.WithIssuerDefaultTTL(10*time.Minute),- identity.WithIssuerClock(fixedClock{now: issuedAt}),- )- if err != nil {- t.Fatalf("NewIssuer() error = %v", err)- }-- verifier, err := identity.NewVerifier(- identity.WithTrustedIssuerRecord(identity.TrustedIssuer{- Issuer: issuer.Issuer(),- KeyID: "hub-key-1",- PublicKey: issuer.PublicKey(),- }),- identity.WithVerifierClock(fixedClock{now: issuedAt.Add(2 * time.Minute)}),- )- if err != nil {- t.Fatalf("NewVerifier() error = %v", err)- }-- token, err := issuer.Issue(context.Background(), identity.VoucherRequest{- PeerID: peerID,- Audience: "sam://mesh/bootstrap",- Nonce: "nonce-123",- Identity: identity.OIDCIdentity{- Provider: identity.ProviderGoogle,- Issuer: "https://accounts.google.com",- Subject: "user-123",- Email: "[email protected]",- EmailVerified: true,- Name: "Agent Smith",- Picture: "https://example.com/avatar.png",- Claims: map[string]string{- "tenant": "example",- },- },- Claims: map[string]string{- "role": "executor",- },- })- if err != nil {- t.Fatalf("Issue() error = %v", err)- }-- voucher, err := verifier.Verify(context.Background(), token, identity.VerifyOptions{- ExpectedIssuer: "hub.sam.dev",- ExpectedAudience: "sam://mesh/bootstrap",- ExpectedPeerID: peerID,- ExpectedNonce: "nonce-123",- })- if err != nil {- t.Fatalf("Verify() error = %v", err)- }-- if voucher.Issuer != "hub.sam.dev" {- t.Fatalf("voucher issuer = %q, want %q", voucher.Issuer, "hub.sam.dev")- }- if voucher.Subject != "user-123" {- t.Fatalf("voucher subject = %q, want %q", voucher.Subject, "user-123")- }- if voucher.PeerID != peerID {- t.Fatalf("voucher peer ID = %q, want %q", voucher.PeerID, peerID)- }- if voucher.Provider != identity.ProviderGoogle {- t.Fatalf("voucher provider = %q, want %q", voucher.Provider, identity.ProviderGoogle)- }- if voucher.Claims["tenant"] != "example" || voucher.Claims["role"] != "executor" {- t.Fatalf("voucher claims = %#v, want merged tenant and role", voucher.Claims)- }- if voucher.Expiry.Sub(voucher.IssuedAt) != 10*time.Minute {- t.Fatalf("voucher TTL = %s, want %s", voucher.Expiry.Sub(voucher.IssuedAt), 10*time.Minute)- }-}--func TestIssueRejectsInvalidInput(t *testing.T) {- issuerKey := generateSigningKey(t)- issuer, err := identity.NewIssuer("hub.sam.dev", issuerKey)- if err != nil {- t.Fatalf("NewIssuer() error = %v", err)- }-- tests := []struct {- name string- req identity.VoucherRequest- wantErr string- }{- {- name: "missing provider",- req: identity.VoucherRequest{- PeerID: generatePeerID(t),- Audience: "sam://mesh",- Identity: identity.OIDCIdentity{Issuer: "https://accounts.google.com", Subject: "sub"},- },- wantErr: "provider must not be empty",- },- {- name: "invalid peer id",- req: identity.VoucherRequest{- PeerID: "not-a-peer-id",- Audience: "sam://mesh",- Identity: identity.OIDCIdentity{Provider: identity.ProviderGoogle, Issuer: "https://accounts.google.com", Subject: "sub"},- },- wantErr: "invalid peer ID",- },- {- name: "missing audience",- req: identity.VoucherRequest{- PeerID: generatePeerID(t),- Identity: identity.OIDCIdentity{Provider: identity.ProviderGoogle, Issuer: "https://accounts.google.com", Subject: "sub"},- },- wantErr: "audience must not be empty",- },- {- name: "reserved claim rejected",- req: identity.VoucherRequest{- PeerID: generatePeerID(t),- Audience: "sam://mesh",- Identity: identity.OIDCIdentity{Provider: identity.ProviderGoogle, Issuer: "https://accounts.google.com", Subject: "sub"},- Claims: map[string]string{"iss": "forbidden"},- },- wantErr: "reserved",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- _, err := issuer.Issue(context.Background(), tt.req)- if err == nil || !strings.Contains(err.Error(), tt.wantErr) {- t.Fatalf("Issue() error = %v, want substring %q", err, tt.wantErr)- }- })- }-}--func TestVerifyFailures(t *testing.T) {- baseTime := time.Date(2026, 4, 17, 23, 55, 0, 0, time.UTC)- issuerKey := generateSigningKey(t)- issuer, err := identity.NewIssuer(- "hub.sam.dev",- issuerKey,- identity.WithIssuerClock(fixedClock{now: baseTime}),- )- if err != nil {- t.Fatalf("NewIssuer() error = %v", err)- }- peerID := generatePeerID(t)- token, err := issuer.Issue(context.Background(), identity.VoucherRequest{- PeerID: peerID,- Audience: "sam://mesh/bootstrap",- Nonce: "nonce-abc",- TTL: 5 * time.Minute,- Identity: identity.OIDCIdentity{- Provider: identity.ProviderGoogle,- Issuer: "https://accounts.google.com",- Subject: "user-123",- },- })- if err != nil {- t.Fatalf("Issue() error = %v", err)- }-- tests := []struct {- name string- token string- options identity.VerifyOptions- verifier identity.VoucherVerifier- wantErr error- }{- {- name: "untrusted issuer",- token: token,- verifier: mustVerifier(t,- identity.WithTrustedIssuer("other.sam.dev", generateSigningKey(t).Public().(ed25519.PublicKey)),- identity.WithVerifierClock(fixedClock{now: baseTime.Add(time.Minute)}),- ),- wantErr: identity.ErrUntrustedIssuer,- },- {- name: "tampered signature",- token: func() string {- parts := strings.Split(token, ".")- if len(parts) != 3 || len(parts[2]) == 0 {- return token + "tampered"- }- if parts[2][0] == 'A' {- parts[2] = "B" + parts[2][1:]- } else {- parts[2] = "A" + parts[2][1:]- }- return strings.Join(parts, ".")- }(),- verifier: mustVerifier(t,- identity.WithTrustedIssuer("hub.sam.dev", issuer.PublicKey()),- identity.WithVerifierClock(fixedClock{now: baseTime.Add(time.Minute)}),- ),- wantErr: identity.ErrInvalidSignature,- },- {- name: "expired voucher",- token: token,- verifier: mustVerifier(t,- identity.WithTrustedIssuer("hub.sam.dev", issuer.PublicKey()),- identity.WithVerifierClock(fixedClock{now: baseTime.Add(6 * time.Minute)}),- identity.WithVerifierLeeway(0),- ),- wantErr: identity.ErrVoucherExpired,- },- {- name: "peer mismatch",- token: token,- verifier: mustVerifier(t,- identity.WithTrustedIssuer("hub.sam.dev", issuer.PublicKey()),- identity.WithVerifierClock(fixedClock{now: baseTime.Add(time.Minute)}),- ),- options: identity.VerifyOptions{ExpectedPeerID: generatePeerID(t)},- wantErr: identity.ErrInvalidVoucher,- },- {- name: "audience mismatch",- token: token,- verifier: mustVerifier(t,- identity.WithTrustedIssuer("hub.sam.dev", issuer.PublicKey()),- identity.WithVerifierClock(fixedClock{now: baseTime.Add(time.Minute)}),- ),- options: identity.VerifyOptions{ExpectedAudience: "sam://mesh/other"},- wantErr: identity.ErrInvalidVoucher,- },- {- name: "nonce mismatch",- token: token,- verifier: mustVerifier(t,- identity.WithTrustedIssuer("hub.sam.dev", issuer.PublicKey()),- identity.WithVerifierClock(fixedClock{now: baseTime.Add(time.Minute)}),- ),- options: identity.VerifyOptions{ExpectedNonce: "wrong"},- wantErr: identity.ErrInvalidVoucher,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- _, err := tt.verifier.Verify(context.Background(), tt.token, tt.options)- if err == nil || !strings.Contains(err.Error(), tt.wantErr.Error()) {- t.Fatalf("Verify() error = %v, want %v", err, tt.wantErr)- }- })- }-}--func TestVerifyLeeway(t *testing.T) {- baseTime := time.Date(2026, 4, 18, 0, 0, 0, 0, time.UTC)- issuerKey := generateSigningKey(t)- issuer, err := identity.NewIssuer(- "hub.sam.dev",- issuerKey,- identity.WithIssuerClock(fixedClock{now: baseTime}),- )- if err != nil {- t.Fatalf("NewIssuer() error = %v", err)- }-- token, err := issuer.Issue(context.Background(), identity.VoucherRequest{- PeerID: generatePeerID(t),- Audience: "sam://mesh/bootstrap",- TTL: 1 * time.Minute,- Identity: identity.OIDCIdentity{- Provider: identity.ProviderGoogle,- Issuer: "https://accounts.google.com",- Subject: "user-123",- },- })- if err != nil {- t.Fatalf("Issue() error = %v", err)- }-- verifier := mustVerifier(t,- identity.WithTrustedIssuer("hub.sam.dev", issuer.PublicKey()),- identity.WithVerifierClock(fixedClock{now: baseTime.Add(65 * time.Second)}),- identity.WithVerifierLeeway(10*time.Second),- )-- if _, err := verifier.Verify(context.Background(), token, identity.VerifyOptions{}); err != nil {- t.Fatalf("Verify() error = %v, want nil", err)- }-}--func mustVerifier(t *testing.T, opts ...identity.VerifierOption) identity.VoucherVerifier {- t.Helper()- v, err := identity.NewVerifier(opts...)- if err != nil {- t.Fatalf("NewVerifier() error = %v", err)- }- return v-}--func generateSigningKey(t *testing.T) ed25519.PrivateKey {- t.Helper()- _, key, err := ed25519.GenerateKey(rand.Reader)- if err != nil {- t.Fatalf("GenerateKey() error = %v", err)- }- return key-}--func generatePeerID(t *testing.T) string {- t.Helper()- priv, _, err := crypto.GenerateEd25519Key(rand.Reader)- if err != nil {- t.Fatalf("GenerateEd25519Key() error = %v", err)- }- id, err := peer.IDFromPrivateKey(priv)- if err != nil {- t.Fatalf("IDFromPrivateKey() error = %v", err)- }- return id.String()-}diff --git a/pkg/net/node.go b/pkg/net/node.goindex 1f546d25..43abd506 100644--- a/pkg/net/node.go+++ b/pkg/net/node.go@@ -26,6 +26,7 @@ import ("github.com/libp2p/go-libp2p"dht "github.com/libp2p/go-libp2p-kad-dht"+ pubsub "github.com/libp2p/go-libp2p-pubsub""github.com/libp2p/go-libp2p/core/host""github.com/libp2p/go-libp2p/core/peer"coreprotocol "github.com/libp2p/go-libp2p/core/protocol"@@ -36,6 +37,8 @@ import ("go.opentelemetry.io/otel""go.opentelemetry.io/otel/attribute""go.opentelemetry.io/otel/trace"++ "sam/pkg/reputation")var tracer = otel.Tracer("sam/net")@@ -52,6 +55,8 @@ type node struct {kdht *dht.IpfsDHTrelay *relayv2.Relaydisc *drouting.RoutingDiscovery+ gsub *pubsub.PubSub+ trust *reputation.TrustStorestarted boollogger *slog.Logger}@@ -139,6 +144,24 @@ func (n *node) Start(ctx context.Context) error {// Initialize routing-based discovery backed by the DHT.n.disc = drouting.NewRoutingDiscovery(n.kdht)+ gs, err := pubsub.NewGossipSub(ctx, h)+ if err != nil {+ _ = h.Close()+ return fmt.Errorf("initializing gossipsub: %w", err)+ }+ n.gsub = gs+ trust, err := reputation.NewTrustStore(h, gs)+ if err != nil {+ _ = h.Close()+ return fmt.Errorf("initializing reputation trust store: %w", err)+ }+ if err := trust.Start(ctx); err != nil {+ _ = h.Close()+ return fmt.Errorf("starting reputation trust store: %w", err)+ }+ n.trust = trust+ reputation.SetDefaultEvaluator(trust)+ reputation.SetDefaultAttestor(trust)n.started = truen.logger.Info("node started",@@ -174,6 +197,8 @@ func (n *node) Stop(ctx context.Context) error {}n.started = false+ reputation.SetDefaultEvaluator(nil)+ reputation.SetDefaultAttestor(nil)n.logger.Info("node stopped")return errors.Join(errs...)}diff --git a/pkg/protocol/a2a.go b/pkg/protocol/a2a.goindex 569bcdef..81213a8d 100644--- a/pkg/protocol/a2a.go+++ b/pkg/protocol/a2a.go@@ -33,6 +33,7 @@ import ("sam/pkg/economy""sam/pkg/identity"+ "sam/pkg/reputation")const A2AProtocolID coreprotocol.ID = "/sam/a2a/1.0"@@ -83,14 +84,12 @@ func (e *LivenessError) Unwrap() error {type ExecuteRequest struct {Target peer.AddrInfoCapability string- Vouch *identity.VouchBiscuit stringPayment economy.MicropaymentMCPRequest json.RawMessage}type a2aHeader struct {- Vouch *identity.Vouch `json:"vouch,omitempty"`Biscuit string `json:"biscuit"`Capability string `json:"capability,omitempty"`Payment economy.Micropayment `json:"payment"`@@ -106,7 +105,19 @@ type FederationGate interface {// AllowAllGate is a FederationGate that accepts every peer (default, open mesh).type AllowAllGate struct{}-func (AllowAllGate) Allow(_ context.Context, _ string, _ string) error { return nil }+func (AllowAllGate) Allow(_ context.Context, _ string, _ string) error {+ return nil+}++// IsAllowAllGate reports whether g is the permissive default gate implementation.+func IsAllowAllGate(g FederationGate) bool {+ switch g.(type) {+ case AllowAllGate, *AllowAllGate:+ return true+ default:+ return false+ }+}// A2AService serves /sam/a2a/1.0 and forwards JSON-RPC over a local MCP connector.type A2AService struct {@@ -143,6 +154,9 @@ func NewA2AService(h host.Host, connector MCPConnector, observer Observer, optsif observer == nil {observer = NopObserver{}}+ if err := identity.EnsurePassportAuth(h, ""); err != nil {+ return nil, fmt.Errorf("installing passport auth: %w", err)+ }s := &A2AService{host: h, observer: observer, mcp: connector, gate: AllowAllGate{}}for _, o := range opts {o(s)@@ -202,11 +216,23 @@ func Execute(ctx context.Context, h host.Host, req ExecuteRequest, observer Obse}peerID := req.Target.ID.String()started := time.Now()+ if err := h.Connect(ctx, req.Target); err != nil {+ observer.OnFailure(peerID, FailureTypeLiveness)+ return nil, &LivenessError{PeerID: peerID, Err: err}+ }+ if err := identity.AuthenticatePeerPassport(ctx, h, req.Target.ID); err != nil {+ observer.OnFailure(peerID, FailureTypeProtocol)+ return nil, fmt.Errorf("passport authentication failed for %s: %w", peerID, err)+ }if err := Preflight(ctx, h, req.Target); err != nil {observer.OnFailure(peerID, FailureTypeLiveness)return nil, err}+ if eval := reputation.DefaultEvaluator(); eval != nil && eval.IsNegative(peerID) {+ observer.OnFailure(peerID, FailureTypeProtocol)+ return nil, fmt.Errorf("refusing A2A call to negatively-rated peer %s", peerID)+ }stream, err := h.NewStream(ctx, req.Target.ID, A2AProtocolID)if err != nil {@@ -231,7 +257,6 @@ func Execute(ctx context.Context, h host.Host, req ExecuteRequest, observer Obse}()header := a2aHeader{- Vouch: req.Vouch,Biscuit: strings.TrimSpace(req.Biscuit),Capability: strings.TrimSpace(req.Capability),Payment: req.Payment,@@ -275,6 +300,9 @@ func Execute(ctx context.Context, h host.Host, req ExecuteRequest, observer Obse}observer.OnSuccess(peerID, time.Since(started))+ if att := reputation.DefaultAttestor(); att != nil {+ _ = att.Publish(context.Background(), peerID, 1)+ }return json.RawMessage(resp), nil}@@ -310,10 +338,16 @@ func (s *A2AService) handleStream(stream network.Stream) {fail(FailureTypeProtocol, fmt.Errorf("missing biscuit token"))return}+ claims, err := identity.AuthenticatedPeerPassport(s.host, stream.Conn().RemotePeer())+ if err != nil {+ fail(FailureTypeProtocol, fmt.Errorf("passport authentication required: %w", err))+ return+ }// Identity gate: verify the requester's PeerID is allowed in this federation// before forwarding any payload to the local MCP backend.- if err := s.gate.Allow(context.Background(), peerID, strings.TrimSpace(header.Capability)); err != nil {+ authCtx := withAuthenticatedPassportClaims(context.Background(), claims)+ if err := s.gate.Allow(authCtx, peerID, strings.TrimSpace(header.Capability)); err != nil {fail(FailureTypeProtocol, fmt.Errorf("federation gate denied peer %s: %w", peerID, err))return}@@ -378,12 +412,30 @@ func (s *A2AService) handleStream(stream network.Stream) {}s.observer.OnSuccess(peerID, time.Since(started))+ if att := reputation.DefaultAttestor(); att != nil {+ _ = att.Publish(context.Background(), peerID, 1)+ }}func writeA2AError(w io.Writer, err error) error {+ if err == nil {+ err = fmt.Errorf("a2a request failed")+ }return json.NewEncoder(w).Encode(struct {- Error string `json:"error"`- }{Error: err.Error()})+ JSONRPC string `json:"jsonrpc"`+ Error struct {+ Code int `json:"code"`+ Message string `json:"message"`+ } `json:"error"`+ ID any `json:"id"`+ }{+ JSONRPC: "2.0",+ Error: struct {+ Code int `json:"code"`+ Message string `json:"message"`+ }{Code: -32001, Message: err.Error()},+ ID: nil,+ })}func wrapRuntimeLiveness(pid peer.ID, err error) error {@@ -426,6 +478,17 @@ func classifyFailure(err error) string {}func decodeA2AError(payload []byte) string {+ var rpcOut struct {+ Error struct {+ Message string `json:"message"`+ } `json:"error"`+ }+ if err := json.Unmarshal(payload, &rpcOut); err == nil {+ if msg := strings.TrimSpace(rpcOut.Error.Message); msg != "" {+ return msg+ }+ }+var out struct {Error string `json:"error"`}diff --git a/pkg/protocol/a2a_test.go b/pkg/protocol/a2a_test.goindex aef089b5..1ded2fca 100644--- a/pkg/protocol/a2a_test.go+++ b/pkg/protocol/a2a_test.go@@ -125,15 +125,19 @@ func TestExecuteSuccessRecordsObserver(t *testing.T) {defer svc.Close()clientObserver := &testObserver{}+ passport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{+ PeerID: clientHost.ID().String(),+ FederationID: "default",+ Subject: "sub",+ })+ if err != nil {+ t.Fatalf("IssuePassportBiscuit() error = %v", err)+ }+ if err := identity.SetLocalPassport(clientHost, "default", passport); err != nil {+ t.Fatalf("SetLocalPassport() error = %v", err)+ }resp, err := Execute(ctx, clientHost, ExecuteRequest{- Target: peer.AddrInfo{ID: serverHost.ID(), Addrs: serverHost.Addrs()},- Vouch: identity.NewVouch(- clientHost.ID().String(),- "self",- "sub",- map[string]string{"name": "tester"},- time.Hour,- ),+ Target: peer.AddrInfo{ID: serverHost.ID(), Addrs: serverHost.Addrs()},Biscuit: "test-biscuit",Payment: economy.Micropayment{Amount: 1, Asset: "sam-credit", Nonce: "n-1"},MCPRequest: []byte(`{"jsonrpc":"2.0","id":"sam-call","method":"message","params":{"message":"ping"}}`),@@ -173,6 +177,17 @@ func TestExecuteReturnsLivenessErrorWhenPeerDown(t *testing.T) {}clientObserver := &testObserver{}+ passport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{+ PeerID: clientHost.ID().String(),+ FederationID: "default",+ Subject: "sub",+ })+ if err != nil {+ t.Fatalf("IssuePassportBiscuit() error = %v", err)+ }+ if err := identity.SetLocalPassport(clientHost, "default", passport); err != nil {+ t.Fatalf("SetLocalPassport() error = %v", err)+ }_, err = Execute(ctx, clientHost, ExecuteRequest{Target: target,Biscuit: "test-biscuit",diff --git a/pkg/protocol/agent_card.go b/pkg/protocol/agent_card.goindex 2c0d2bdc..5e48c4fc 100644--- a/pkg/protocol/agent_card.go+++ b/pkg/protocol/agent_card.go@@ -26,8 +26,6 @@ import ("github.com/a2aproject/a2a-go/v2/a2a""github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/peer"-- "sam/pkg/identity")const (@@ -46,9 +44,7 @@ type MCPResource struct {// AgentCard is the signed capability document advertised in the SAM mesh.//-// The signature covers all fields except Signature and Vouch.-// Vouch is attached after signing and allows peers to verify the operator's-// identity as asserted by a trusted Hub.+// The signature covers all fields except Signature.type AgentCard struct {a2a.AgentCardPeerID string `json:"peer_id"`@@ -56,10 +52,6 @@ type AgentCard struct {IssuedAt time.Time `json:"issued_at"`Algorithm string `json:"alg"`Signature string `json:"signature"`- // Vouch is the optional Hub-signed identity credential bound to this PeerID.- // It is not covered by the AgentCard signature; its own Hub signature provides- // the authenticity guarantee.- Vouch *identity.Vouch `json:"vouch,omitempty"`}type agentCardPayload struct {@@ -193,13 +185,6 @@ func (c *AgentCard) Verify() error {return VerifyAgentCard(c)}-// AttachVouch sets the Vouch on an AgentCard. The Vouch is not covered by the-// AgentCard signature; its own Hub signature guarantees authenticity.-// Passing nil clears any previously attached Vouch.-func (c *AgentCard) AttachVouch(v *identity.Vouch) {- c.Vouch = v-}-func (c *AgentCard) validateBase() error {if strings.TrimSpace(c.Version) == "" {return fmt.Errorf("card version is required")diff --git a/pkg/protocol/federation_gate.go b/pkg/protocol/federation_gate.goindex 7504c435..10e267e6 100644--- a/pkg/protocol/federation_gate.go+++ b/pkg/protocol/federation_gate.go@@ -17,52 +17,65 @@ package protocolimport ("context""fmt"- "os"+ "strings"- internaldb "sam/internal/db"+ "sam/pkg/identity")-// VouchGate is a FederationGate that allows a peer only when a valid vouch-// record exists in the local bbolt store for the given federation.-// Entries in the vouch bucket are keyed by requester PeerID.-// If the key is absent the peer is denied.-type VouchGate struct {- store internaldb.Store-}+type passportClaimsContextKey struct{}-// NewVouchGate creates a gate backed by the given store (federation-scoped).-func NewVouchGate(store internaldb.Store) *VouchGate {- return &VouchGate{store: store}+func withAuthenticatedPassportClaims(ctx context.Context, claims *identity.PassportClaims) context.Context {+ return context.WithValue(ctx, passportClaimsContextKey{}, claims)}-// NewVouchGateForFederation opens (or lazily creates) the federation-scoped-// bbolt store and returns a VouchGate. The caller is responsible for calling-// the returned close function when done.-func NewVouchGateForFederation(federationID string) (*VouchGate, func() error, error) {- mgr, err := internaldb.NewManager()- if err != nil {- return nil, nil, fmt.Errorf("creating federation manager: %w", err)+func authenticatedPassportClaimsFromContext(ctx context.Context) (*identity.PassportClaims, bool) {+ claims, ok := ctx.Value(passportClaimsContextKey{}).(*identity.PassportClaims)+ if !ok || claims == nil {+ return nil, false}- store, err := mgr.Store(federationID)- if err != nil {- _ = mgr.Close()- return nil, nil, fmt.Errorf("opening federation %q store: %w", federationID, err)+ return claims, true+}++// PassportGate is a FederationGate that allows a peer only when it presents a+// valid passport biscuit bound to the peer and federation.+type PassportGate struct {+ federationID string+}++// NewPassportGate creates a gate scoped to the default federation.+func NewPassportGate() *PassportGate {+ return NewPassportGateWithFederation("default")+}++// NewPassportGateWithFederation creates a gate with an explicit local federation audience.+func NewPassportGateWithFederation(federationID string) *PassportGate {+ federationID = strings.TrimSpace(federationID)+ if federationID == "" {+ federationID = "default"}- return NewVouchGate(store), mgr.Close, nil+ return &PassportGate{federationID: federationID}+}++// NewPassportGateForFederation returns a passport gate and a no-op close function+// for compatibility with existing setup code.+func NewPassportGateForFederation(federationID string) (*PassportGate, func() error, error) {+ return NewPassportGateWithFederation(federationID), func() error { return nil }, nil}-// Allow returns nil when the requester's PeerID has a vouch record in the-// federation store, or a descriptive error when it is absent.-func (g *VouchGate) Allow(ctx context.Context, peerID string, _ string) error {+// Allow returns nil when the requester has authenticated passport claims.+func (g *PassportGate) Allow(ctx context.Context, peerID string, _ string) error {if peerID == "" {return fmt.Errorf("empty peer ID")}- _, err := g.store.Get(ctx, internaldb.BucketVouches, peerID)- if err != nil {- if os.IsNotExist(err) {- return fmt.Errorf("peer %s has no vouch in this federation", peerID)- }- return fmt.Errorf("checking vouch for peer %s: %w", peerID, err)+ claims, ok := authenticatedPassportClaimsFromContext(ctx)+ if !ok {+ return fmt.Errorf("authentication error: missing authenticated passport claims")+ }+ if strings.TrimSpace(claims.PeerID) != strings.TrimSpace(peerID) {+ return fmt.Errorf("authentication error: authenticated peer mismatch")+ }+ if strings.TrimSpace(g.federationID) != "" && strings.TrimSpace(claims.FederationID) != strings.TrimSpace(g.federationID) {+ return fmt.Errorf("authentication error: passport federation mismatch")}return nil}diff --git a/pkg/protocol/federation_gate_test.go b/pkg/protocol/federation_gate_test.gonew file mode 100644index 00000000..e962ecd9--- /dev/null+++ b/pkg/protocol/federation_gate_test.go@@ -0,0 +1,46 @@+// 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 protocol++import (+ "context"+ "strings"+ "testing"++ "sam/pkg/identity"+)++func TestPassportGateRejectsAudienceMismatch(t *testing.T) {+ passport, err := identity.IssuePassportBiscuit(context.Background(), identity.PassportIssueRequest{+ PeerID: "12D3KooWTestPeer",+ FederationID: "Federation-A",+ Subject: "sub-1",+ })+ if err != nil {+ t.Fatalf("issuing passport: %v", err)+ }+ claims, err := identity.ValidatePassportBiscuit(context.Background(), passport, "12D3KooWTestPeer", "")+ if err != nil {+ t.Fatalf("validating passport: %v", err)+ }+ gate := NewPassportGateWithFederation("Federation-B")+ err = gate.Allow(withAuthenticatedPassportClaims(context.Background(), claims), "12D3KooWTestPeer", "writer")+ if err == nil {+ t.Fatalf("expected audience mismatch error, got nil")+ }+ if !strings.Contains(err.Error(), "passport federation mismatch") {+ t.Fatalf("unexpected error: %v", err)+ }+}diff --git a/pkg/protocol/http_tunnel.go b/pkg/protocol/http_tunnel.goindex e1850543..cded5ec9 100644--- a/pkg/protocol/http_tunnel.go+++ b/pkg/protocol/http_tunnel.go@@ -37,7 +37,6 @@ import (const HTTPTunnelProtocolID coreprotocol.ID = "/sam/tunnel/http/1.0"type HTTPTunnelOpenRequest struct {- Vouch *identity.Vouch `json:"vouch,omitempty"`Biscuit string `json:"biscuit"`Capability string `json:"capability,omitempty"`Request HTTPTunnelRequest `json:"request"`@@ -95,6 +94,9 @@ func NewHTTPTunnelService(h host.Host, endpoint string, opts ...HTTPTunnelServicfor _, opt := range opts {opt(s)}+ if err := identity.EnsurePassportAuth(h, ""); err != nil {+ return nil, fmt.Errorf("installing passport auth: %w", err)+ }h.SetStreamHandler(HTTPTunnelProtocolID, s.handleStream)return s, nil@@ -117,8 +119,8 @@ func TunnelHTTP(ctx context.Context, h host.Host, target peer.ID, req HTTPTunnelif strings.TrimSpace(req.Biscuit) == "" {return nil, fmt.Errorf("biscuit is required")}- if req.Vouch == nil {- return nil, fmt.Errorf("vouch is required")+ if err := identity.AuthenticatePeerPassport(ctx, h, target); err != nil {+ return nil, fmt.Errorf("passport authentication failed: %w", err)}if strings.TrimSpace(req.Request.Method) == "" {return nil, fmt.Errorf("request method is required")@@ -158,8 +160,7 @@ func (s *HTTPTunnelService) handleStream(stream network.Stream) {return}- remotePeer := stream.Conn().RemotePeer().String()- if err := s.verifyMetadata(context.Background(), remotePeer, &openReq); err != nil {+ if err := s.verifyMetadata(context.Background(), stream.Conn().RemotePeer(), &openReq); err != nil {_ = json.NewEncoder(stream).Encode(HTTPTunnelResponse{StatusCode: http.StatusForbidden, Error: err.Error()})return}@@ -168,19 +169,20 @@ func (s *HTTPTunnelService) handleStream(stream network.Stream) {_ = json.NewEncoder(stream).Encode(resp)}-func (s *HTTPTunnelService) verifyMetadata(ctx context.Context, remotePeer string, req *HTTPTunnelOpenRequest) error {- if req.Vouch == nil {- return fmt.Errorf("missing vouch metadata")- }- if req.Vouch.IsExpired() {- return fmt.Errorf("vouch is expired")- }- if strings.TrimSpace(req.Vouch.PeerID) != remotePeer {- return fmt.Errorf("vouch peer mismatch")+func (s *HTTPTunnelService) verifyMetadata(ctx context.Context, remotePeer peer.ID, req *HTTPTunnelOpenRequest) error {+ if _, err := identity.AuthenticatedPeerPassport(s.host, remotePeer); err != nil {+ return fmt.Errorf("passport authentication required: %w", err)}if strings.TrimSpace(req.Biscuit) == "" {return fmt.Errorf("missing biscuit metadata")}+ authValues := req.Request.Headers["Authorization"]+ if len(authValues) == 0 {+ authValues = req.Request.Headers["authorization"]+ }+ if _, err := extractBearerFromValues(authValues); err != nil {+ return err+ }if strings.TrimSpace(req.Capability) != "" {if err := s.skillGate.CheckSkill(ctx, req.Biscuit, strings.TrimSpace(req.Capability)); err != nil {return fmt.Errorf("biscuit denied capability: %w", err)@@ -189,6 +191,24 @@ func (s *HTTPTunnelService) verifyMetadata(ctx context.Context, remotePeer strinreturn nil}+func extractBearerFromValues(values []string) (string, error) {+ for _, value := range values {+ parts := strings.SplitN(strings.TrimSpace(value), " ", 2)+ if len(parts) != 2 || !strings.EqualFold(strings.TrimSpace(parts[0]), "Bearer") {+ continue+ }+ token := strings.TrimSpace(parts[1])+ if token == "" {+ return "", fmt.Errorf("bearer token is empty")+ }+ return token, nil+ }+ if len(values) == 0 {+ return "", fmt.Errorf("missing Authorization header")+ }+ return "", fmt.Errorf("Authorization must use Bearer scheme")+}+func (s *HTTPTunnelService) forwardLocal(ctx context.Context, treq HTTPTunnelRequest) HTTPTunnelResponse {method := strings.TrimSpace(treq.Method)if method == "" {diff --git a/pkg/protocol/http_tunnel_test.go b/pkg/protocol/http_tunnel_test.gonew file mode 100644index 00000000..c0609750--- /dev/null+++ b/pkg/protocol/http_tunnel_test.go@@ -0,0 +1,43 @@+// 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 protocol++import "testing"++func TestExtractBearerFromValues(t *testing.T) {+ tests := []struct {+ name string+ values []string+ wantErr bool+ }{+ {name: "valid bearer", values: []string{"Bearer token-1"}, wantErr: false},+ {name: "valid among many", values: []string{"Basic abc", "Bearer token-2"}, wantErr: false},+ {name: "missing header", values: nil, wantErr: true},+ {name: "wrong scheme", values: []string{"Basic abc"}, wantErr: true},+ {name: "empty token", values: []string{"Bearer "}, wantErr: true},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ _, err := extractBearerFromValues(tc.values)+ if tc.wantErr && err == nil {+ t.Fatalf("expected error, got nil")+ }+ if !tc.wantErr && err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ })+ }+}diff --git a/pkg/protocol/mcp_bridge.go b/pkg/protocol/mcp_bridge.goindex 2173b10e..c3d77278 100644--- a/pkg/protocol/mcp_bridge.go+++ b/pkg/protocol/mcp_bridge.go@@ -28,6 +28,7 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp""sam/pkg/economy"+ "sam/pkg/reputation")const MCPProtocolID = "/sam/mcp/1.0"@@ -76,6 +77,9 @@ func NewMCPBridge(h host.Host, verifier economy.Verifier, connector MCPConnector// Open opens an outbound MCP stream and sends the bridge preface.func (b *MCPBridge) Open(ctx context.Context, peerID peer.ID, req BridgeOpenRequest) (network.Stream, error) {+ if eval := reputation.DefaultEvaluator(); eval != nil && eval.IsNegative(peerID.String()) {+ return nil, fmt.Errorf("refusing MCP stream to negatively-rated peer %s", peerID)+ }stream, err := b.host.NewStream(ctx, peerID, MCPProtocolID)if err != nil {return nil, fmt.Errorf("opening MCP stream: %w", err)@@ -140,6 +144,9 @@ func (b *MCPBridge) handleInbound(stream network.Stream) {_ = writeBridgeError(stream, fmt.Errorf("%w: %v", economy.ErrVerifierDeniedRequest, err))return}+ if att := reputation.DefaultAttestor(); att != nil {+ _ = att.Publish(context.Background(), stream.Conn().RemotePeer().String(), 1)+ }local, err := b.connector.Open(ctx)if err != nil {diff --git a/pkg/protocol/observer_db.go b/pkg/protocol/observer_db.goindex 1a4d27e9..14522ba4 100644--- a/pkg/protocol/observer_db.go+++ b/pkg/protocol/observer_db.go@@ -17,6 +17,7 @@ package protocolimport ("context""fmt"+ "strings""sync""time"@@ -61,6 +62,10 @@ func NewBoltObserver(path string) (*BoltObserver, error) {// federation name. The database is stored at// ~/.config/sam/federations/<name>.db.func NewBoltObserverForFederation(fedID string) (*BoltObserver, error) {+ fedID = strings.TrimSpace(fedID)+ if fedID == "" {+ fedID = "default"+ }mgr, err := internaldb.NewManager()if err != nil {return nil, fmt.Errorf("creating federation manager: %w", err)@@ -73,6 +78,20 @@ func NewBoltObserverForFederation(fedID string) (*BoltObserver, error) {return &BoltObserver{store: store, codec: internaldb.JSONCodec{}}, nil}+// NewBoltObserverWithFallback prefers federation-scoped storage and falls back+// to default state storage when federation manager setup is unavailable.+func NewBoltObserverWithFallback(fedID string) (*BoltObserver, error) {+ observer, err := NewBoltObserverForFederation(fedID)+ if err == nil {+ return observer, nil+ }+ fallback, fallbackErr := DefaultBoltObserver()+ if fallbackErr != nil {+ return nil, fmt.Errorf("creating federation observer: %v; fallback failed: %w", err, fallbackErr)+ }+ return fallback, nil+}+func (o *BoltObserver) OnSuccess(peerID string, latency time.Duration) {o.writeRecord(peerID, reputationRecord{PeerID: peerID, OK: true, LatencyMS: latency.Milliseconds()})}diff --git a/pkg/reputation/reputation.go b/pkg/reputation/reputation.gonew file mode 100644index 00000000..cff69ea9--- /dev/null+++ b/pkg/reputation/reputation.go@@ -0,0 +1,200 @@+package reputation++import (+ "context"+ "crypto/ed25519"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "strings"+ "sync"+ "time"++ pubsub "github.com/libp2p/go-libp2p-pubsub"+ "github.com/libp2p/go-libp2p/core/host"+)++const TopicV1 = "sam/reputation/v1"++type Attestation struct {+ ReporterID string `json:"reporter_id"`+ TargetID string `json:"target_id"`+ Rating int `json:"rating"`+ IssuedAt time.Time `json:"issued_at"`+ Signature string `json:"signature"`+}++type Evaluator interface {+ Score(peerID string) float64+ IsNegative(peerID string) bool+}++type Attestor interface {+ Publish(ctx context.Context, targetID string, rating int) error+}++type TrustStore struct {+ host host.Host+ ps *pubsub.PubSub++ mu sync.RWMutex+ scores map[string]float64+ sums map[string]int+ counts map[string]int+}++func NewTrustStore(h host.Host, ps *pubsub.PubSub) (*TrustStore, error) {+ if h == nil {+ return nil, fmt.Errorf("host is nil")+ }+ if ps == nil {+ return nil, fmt.Errorf("gossipsub is nil")+ }+ return &TrustStore{+ host: h,+ ps: ps,+ scores: map[string]float64{},+ sums: map[string]int{},+ counts: map[string]int{},+ }, nil+}++func (s *TrustStore) Start(ctx context.Context) error {+ topic, err := s.ps.Join(TopicV1)+ if err != nil {+ return fmt.Errorf("join reputation topic: %w", err)+ }+ sub, err := topic.Subscribe()+ if err != nil {+ return fmt.Errorf("subscribe reputation topic: %w", err)+ }+ go func() {+ defer sub.Cancel()+ for {+ msg, nextErr := sub.Next(ctx)+ if nextErr != nil {+ return+ }+ if msg == nil || msg.ReceivedFrom == s.host.ID() {+ continue+ }+ var att Attestation+ if err := json.Unmarshal(msg.Data, &att); err != nil {+ continue+ }+ if !s.verify(att) {+ continue+ }+ s.mu.Lock()+ s.sums[att.TargetID] += att.Rating+ s.counts[att.TargetID]+++ s.scores[att.TargetID] = float64(s.sums[att.TargetID]) / float64(s.counts[att.TargetID])+ s.mu.Unlock()+ }+ }()+ return nil+}++func (s *TrustStore) Publish(ctx context.Context, targetID string, rating int) error {+ targetID = strings.TrimSpace(targetID)+ if targetID == "" {+ return fmt.Errorf("target peer id is required")+ }+ if rating < -1 || rating > 1 {+ return fmt.Errorf("rating must be -1..1")+ }+ topic, err := s.ps.Join(TopicV1)+ if err != nil {+ return fmt.Errorf("join reputation topic: %w", err)+ }+ att := Attestation{+ ReporterID: s.host.ID().String(),+ TargetID: targetID,+ Rating: rating,+ IssuedAt: time.Now().UTC(),+ }+ sig, err := s.sign(att)+ if err != nil {+ return err+ }+ att.Signature = sig+ payload, err := json.Marshal(att)+ if err != nil {+ return fmt.Errorf("marshal attestation: %w", err)+ }+ if err := topic.Publish(ctx, payload); err != nil {+ return fmt.Errorf("publish attestation: %w", err)+ }+ // apply locally too+ s.mu.Lock()+ s.sums[targetID] += rating+ s.counts[targetID]+++ s.scores[targetID] = float64(s.sums[targetID]) / float64(s.counts[targetID])+ s.mu.Unlock()+ return nil+}++func (s *TrustStore) Score(peerID string) float64 {+ s.mu.RLock()+ defer s.mu.RUnlock()+ return s.scores[strings.TrimSpace(peerID)]+}++func (s *TrustStore) IsNegative(peerID string) bool {+ return s.Score(peerID) < 0+}++func (s *TrustStore) sign(att Attestation) (string, error) {+ priv := s.host.Peerstore().PrivKey(s.host.ID())+ if priv == nil {+ return "", fmt.Errorf("host private key unavailable")+ }+ raw, err := priv.Raw()+ if err != nil {+ return "", fmt.Errorf("extract private key bytes: %w", err)+ }+ if len(raw) != ed25519.PrivateKeySize {+ return "", fmt.Errorf("unsupported key size")+ }+ payload := []byte(att.ReporterID + "|" + att.TargetID + "|" + fmt.Sprintf("%d", att.Rating) + "|" + att.IssuedAt.UTC().Format(time.RFC3339Nano))+ sig := ed25519.Sign(ed25519.PrivateKey(raw), payload)+ return base64.RawURLEncoding.EncodeToString(sig), nil+}++func (s *TrustStore) verify(att Attestation) bool {+ if strings.TrimSpace(att.ReporterID) == "" || strings.TrimSpace(att.TargetID) == "" || strings.TrimSpace(att.Signature) == "" {+ return false+ }+ _, err := base64.RawURLEncoding.DecodeString(att.Signature)+ return err == nil+}++var (+ defaultMu sync.RWMutex+ defaultEvaluator Evaluator+ defaultAttestor Attestor+)++func SetDefaultEvaluator(e Evaluator) {+ defaultMu.Lock()+ defer defaultMu.Unlock()+ defaultEvaluator = e+}++func SetDefaultAttestor(a Attestor) {+ defaultMu.Lock()+ defer defaultMu.Unlock()+ defaultAttestor = a+}++func DefaultEvaluator() Evaluator {+ defaultMu.RLock()+ defer defaultMu.RUnlock()+ return defaultEvaluator+}++func DefaultAttestor() Attestor {+ defaultMu.RLock()+ defer defaultMu.RUnlock()+ return defaultAttestor+}diff --git a/tests/e2e/sam.bats b/tests/e2e/sam.batsindex 04417376..60404db7 100644--- a/tests/e2e/sam.bats+++ b/tests/e2e/sam.bats@@ -1,7 +1,7 @@#!/usr/bin/env batssetup() {- export SAM_BINARY="${SAM_BINARY:-./bin/sam}"+ export SAM_BINARY="${SAM_BINARY:-./bin/sam-agent}"if [[ ! -x "$SAM_BINARY" ]]; thenskip "sam binary not found at $SAM_BINARY"fi@@ -125,7 +125,7 @@ teardown() {[[ "$output" == *"unauthorized"* ]]}-@test "sam proxy /.sam/search discovers writer skill with vouch" {+@test "sam proxy /.sam/search discovers writer skill" {node_a_log="$TEST_TMPDIR/node-a.log"node_b_log="$TEST_TMPDIR/node-b.log"proxy_port=18081@@ -175,6 +175,5 @@ teardown() {[[ "$search_status" == "200" ]]run cat "$TEST_TMPDIR/search_body.json"[[ "$output" == *"$node_a_peer"* ]]- [[ "$output" == *'"vouch"'* ]][[ "$output" == *'"signature"'* ]]}diff --git a/tests/e2e/watch.bats b/tests/e2e/watch.batsindex fe694863..99744e5d 100644--- a/tests/e2e/watch.bats+++ b/tests/e2e/watch.bats@@ -1,7 +1,7 @@#!/usr/bin/env batssetup() {- export SAM_BINARY="${SAM_BINARY:-./bin/sam}"+ export SAM_BINARY="${SAM_BINARY:-./bin/sam-agent}"if [[ ! -x "$SAM_BINARY" ]]; thenskip "sam binary not found at $SAM_BINARY"fidiff --git a/tests/integration/call_test.go b/tests/integration/call_test.goindex bfe8dd04..1a9ad76c 100644--- a/tests/integration/call_test.go+++ b/tests/integration/call_test.go@@ -307,11 +307,20 @@ func runCallConsumerRole() error {}defer func() { _ = observer.Close() }()- vouch := identity.NewVouch(node.PeerID().String(), "self", "test-subject", map[string]string{"name": "consumer"}, time.Hour)+ passport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{+ PeerID: node.PeerID().String(),+ FederationID: "default",+ Subject: "test-subject",+ })+ if err != nil {+ return fmt.Errorf("issuing passport biscuit: %w", err)+ }+ if err := identity.SetLocalPassport(node.Host(), "default", passport); err != nil {+ return fmt.Errorf("setting local passport auth: %w", err)+ }req := protocol.ExecuteRequest{Target: target,Capability: callCapability,- Vouch: vouch,Biscuit: "integration-biscuit",Payment: economy.Micropayment{Amount: 1,diff --git a/tests/integration/proxy_test.go b/tests/integration/proxy_test.goindex b795616a..1798db73 100644--- a/tests/integration/proxy_test.go+++ b/tests/integration/proxy_test.go@@ -117,8 +117,19 @@ func runProxyTunnelLegacyFlowIntegration(t *testing.T) {t.Fatalf("connecting consumer->provider: %v", err)}- vouch := identity.NewVouch(consumerNode.PeerID().String(), "test-issuer", "test-subject", map[string]string{"email": "[email protected]"}, 5*time.Minute)- proxySrv := httptest.NewServer(proxyTunnelHandler(consumerNode, observer, "X-SAM-Target", "alice;allow_skill=risk-audit", vouch))+ passport, err := identity.IssuePassportBiscuit(ctx, identity.PassportIssueRequest{+ PeerID: consumerNode.PeerID().String(),+ FederationID: "default",+ Subject: "test-subject",+ Claims: map[string]string{"email": "[email protected]"},+ })+ if err != nil {+ t.Fatalf("issuing passport biscuit: %v", err)+ }+ if err := identity.SetLocalPassport(consumerNode.Host(), "default", passport); err != nil {+ t.Fatalf("setting local passport auth: %v", err)+ }+ proxySrv := httptest.NewServer(proxyTunnelHandler(consumerNode, observer, "X-SAM-Target", "alice;allow_skill=risk-audit", passport))defer proxySrv.Close()payload := []byte(`{"request":"through-proxy"}`)@@ -236,7 +247,7 @@ func runProxyTunnelUnauthorizedBeforeDial(t *testing.T) {}defer func() { _ = consumerNode.Stop(context.Background()) }()- proxySrv := httptest.NewServer(proxyTunnelHandler(consumerNode, protocol.NopObserver{}, "X-SAM-Target", "", nil))+ proxySrv := httptest.NewServer(proxyTunnelHandler(consumerNode, protocol.NopObserver{}, "X-SAM-Target", "", ""))defer proxySrv.Close()req, err := http.NewRequestWithContext(ctx, http.MethodGet, proxySrv.URL+"/blocked", nil)@@ -260,9 +271,9 @@ func runProxyTunnelUnauthorizedBeforeDial(t *testing.T) {}}-func proxyTunnelHandler(node samnet.Node, observer protocol.Observer, targetHeader, biscuit string, vouch *identity.Vouch) http.Handler {+func proxyTunnelHandler(node samnet.Node, observer protocol.Observer, targetHeader, biscuit string, passport string) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if vouch == nil {+ if strings.TrimSpace(passport) == "" {http.Error(w, "unauthorized: local identity login required", http.StatusUnauthorized)return}@@ -289,7 +300,6 @@ func proxyTunnelHandler(node samnet.Node, observer protocol.Observer, targetHeadstart := time.Now()resp, err := protocol.TunnelHTTP(r.Context(), node.Host(), targetID, protocol.HTTPTunnelOpenRequest{- Vouch: vouch,Biscuit: biscuit,Capability: "risk-audit",Request: protocol.HTTPTunnelRequest{