Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
feat(node): implement zero-config join CLI and Tailscale-like UX
Antonio Ojea8ff16b4e2e9f
diff --git a/api/sam.pb.go b/api/sam.pb.goindex d3a34561..10f6d266 100644--- a/api/sam.pb.go+++ b/api/sam.pb.go@@ -717,6 +717,66 @@ func (x *DiscoveredProvider) GetSrvDescription() string {return ""}+type HubInfoResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ OidcIssuer string `protobuf:"bytes,1,opt,name=oidc_issuer,json=oidcIssuer,proto3" json:"oidc_issuer,omitempty"`+ ClientId string `protobuf:"bytes,2,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"`+ Audience string `protobuf:"bytes,3,opt,name=audience,proto3" json:"audience,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *HubInfoResponse) Reset() {+ *x = HubInfoResponse{}+ mi := &file_api_sam_proto_msgTypes[9]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *HubInfoResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*HubInfoResponse) ProtoMessage() {}++func (x *HubInfoResponse) ProtoReflect() protoreflect.Message {+ mi := &file_api_sam_proto_msgTypes[9]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use HubInfoResponse.ProtoReflect.Descriptor instead.+func (*HubInfoResponse) Descriptor() ([]byte, []int) {+ return file_api_sam_proto_rawDescGZIP(), []int{9}+}++func (x *HubInfoResponse) GetOidcIssuer() string {+ if x != nil {+ return x.OidcIssuer+ }+ return ""+}++func (x *HubInfoResponse) GetClientId() string {+ if x != nil {+ return x.ClientId+ }+ return ""+}++func (x *HubInfoResponse) GetAudience() string {+ if x != nil {+ return x.Audience+ }+ return ""+}+var File_api_sam_proto protoreflect.FileDescriptorconst file_api_sam_proto_rawDesc = "" +@@ -772,7 +832,12 @@ const file_api_sam_proto_rawDesc = "" +"\apeer_id\x18\x01 \x01(\tR\x06peerId\x12&\n" +"\x0flocal_proxy_url\x18\x02 \x01(\tR\rlocalProxyUrl\x12\x19\n" +"\bsrv_name\x18\x03 \x01(\tR\asrvName\x12'\n" +- "\x0fsrv_description\x18\x04 \x01(\tR\x0esrvDescription*s\n" ++ "\x0fsrv_description\x18\x04 \x01(\tR\x0esrvDescription\"k\n" ++ "\x0fHubInfoResponse\x12\x1f\n" ++ "\voidc_issuer\x18\x01 \x01(\tR\n" ++ "oidcIssuer\x12\x1b\n" ++ "\tclient_id\x18\x02 \x01(\tR\bclientId\x12\x1a\n" ++ "\baudience\x18\x03 \x01(\tR\baudience*s\n" +"\vServiceType\x12\x1c\n" +"\x18SERVICE_TYPE_UNSPECIFIED\x10\x00\x12\x14\n" +"\x10SERVICE_TYPE_MCP\x10\x01\x12\x1a\n" +@@ -792,7 +857,7 @@ func file_api_sam_proto_rawDescGZIP() []byte {}var file_api_sam_proto_enumTypes = make([]protoimpl.EnumInfo, 2)-var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 10)+var file_api_sam_proto_msgTypes = make([]protoimpl.MessageInfo, 11)var file_api_sam_proto_goTypes = []any{(ServiceType)(0), // 0: sam.v1.ServiceType(MeshEvent_Type)(0), // 1: sam.v1.MeshEvent.Type@@ -805,12 +870,13 @@ var file_api_sam_proto_goTypes = []any{(*CommandBackend)(nil), // 8: sam.v1.CommandBackend(*RegisterServiceRequest)(nil), // 9: sam.v1.RegisterServiceRequest(*DiscoveredProvider)(nil), // 10: sam.v1.DiscoveredProvider- nil, // 11: sam.v1.CommandBackend.EnvEntry+ (*HubInfoResponse)(nil), // 11: sam.v1.HubInfoResponse+ nil, // 12: sam.v1.CommandBackend.EnvEntry}var file_api_sam_proto_depIdxs = []int32{1, // 0: sam.v1.MeshEvent.type:type_name -> sam.v1.MeshEvent.Type0, // 1: sam.v1.ServiceInfo.type:type_name -> sam.v1.ServiceType- 11, // 2: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry+ 12, // 2: sam.v1.CommandBackend.env:type_name -> sam.v1.CommandBackend.EnvEntry7, // 3: sam.v1.RegisterServiceRequest.service:type_name -> sam.v1.ServiceInfo8, // 4: sam.v1.RegisterServiceRequest.command:type_name -> sam.v1.CommandBackend5, // [5:5] is the sub-list for method output_type@@ -835,7 +901,7 @@ func file_api_sam_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_sam_proto_rawDesc), len(file_api_sam_proto_rawDesc)),NumEnums: 2,- NumMessages: 10,+ NumMessages: 11,NumExtensions: 0,NumServices: 0,},diff --git a/api/sam.proto b/api/sam.protoindex e6b0eaae..d08f6115 100644--- a/api/sam.proto+++ b/api/sam.proto@@ -89,3 +89,9 @@ message DiscoveredProvider {string srv_name = 3;string srv_description = 4;}++message HubInfoResponse {+ string oidc_issuer = 1;+ string client_id = 2;+ string audience = 3;+}diff --git a/cmd/sam-hub/main_test.go b/cmd/sam-hub/main_test.goindex 0974440d..3e1e4d89 100644--- a/cmd/sam-hub/main_test.go+++ b/cmd/sam-hub/main_test.go@@ -15,6 +15,9 @@package mainimport (+ "io"+ "net/http"+ "net/http/httptest""path/filepath""testing""time"@@ -24,6 +27,7 @@ import ("github.com/google/sam/api""github.com/libp2p/go-libp2p/core/crypto""github.com/libp2p/go-libp2p/core/peer"+ "google.golang.org/protobuf/proto")func TestMintBiscuitToken(t *testing.T) {@@ -78,3 +82,55 @@ func TestMintBiscuitToken(t *testing.T) {t.Error("Expected non-empty biscuit data")}}++func TestHandleInfoHTTP(t *testing.T) {+ dir := t.TempDir()+ dbPath := filepath.Join(dir, "test.db")++ kr, err := NewKeyRing(dbPath, 24*time.Hour, nil)+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = kr.Close() }()++ oidcIssuer = "http://mock-issuer"++ hub := &Hub{+ KeyRing: kr,+ AllowedAudiences: []string{"test-audience-1", "test-audience-2"},+ }++ handler := handleInfoHTTP(hub)++ req := httptest.NewRequest("GET", "/info", nil)+ w := httptest.NewRecorder()++ handler(w, req)++ resp := w.Result()+ if resp.StatusCode != http.StatusOK {+ t.Errorf("Expected status 200, got %d", resp.StatusCode)+ }++ body, err := io.ReadAll(resp.Body)+ if err != nil {+ t.Fatal(err)+ }++ var info api.HubInfoResponse+ if err := proto.Unmarshal(body, &info); err != nil {+ t.Fatalf("Failed to unmarshal protobuf: %v", err)+ }++ if info.OidcIssuer != "http://mock-issuer" {+ t.Errorf("Expected issuer 'http://mock-issuer', got %q", info.OidcIssuer)+ }++ if info.ClientId != "test-audience-1" {+ t.Errorf("Expected client ID 'test-audience-1', got %q", info.ClientId)+ }++ if info.Audience != "test-audience-1" {+ t.Errorf("Expected audience 'test-audience-1', got %q", info.Audience)+ }+}diff --git a/cmd/sam-hub/server.go b/cmd/sam-hub/server.goindex e6c17272..63f575b8 100644--- a/cmd/sam-hub/server.go+++ b/cmd/sam-hub/server.go@@ -21,6 +21,7 @@ import ("io""net/http""os"+ "sort""strings""sync/atomic"@@ -36,6 +37,7 @@ func startHTTPServer(h *Hub, bindAddr string, adminToken string, tlsCertFile strmux := http.NewServeMux()mux.Handle("/metrics", promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{}))mux.HandleFunc("/register", handleRegisterHTTP(h))+ mux.HandleFunc("/info", handleInfoHTTP(h))mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {if isHubReady.Load() {w.WriteHeader(http.StatusOK)@@ -206,3 +208,56 @@ func handleRegisterHTTP(h *Hub) http.HandlerFunc {samHubEnrollmentTotal.WithLabelValues("success").Inc()}}++func handleInfoHTTP(h *Hub) http.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ // Find the OIDC issuer deterministically by sorting the map keys+ issuer := ""+ if len(h.Providers) > 0 {+ issuers := make([]string, 0, len(h.Providers))+ for iss := range h.Providers {+ issuers = append(issuers, iss)+ }+ sort.Strings(issuers)+ issuer = issuers[0]+ }++ // Fallback if Providers isn't fully populated (e.g. in unit tests)+ if issuer == "" {+ issuer = oidcIssuer+ }+ // If multiple issuers in fallback, pick the first one deterministically+ if strings.Contains(issuer, ",") {+ parts := strings.Split(issuer, ",")+ issuer = strings.TrimSpace(parts[0])+ }++ // Get primary client ID / audience+ aud := api.DefaultAudience+ if len(h.AllowedAudiences) > 0 {+ aud = h.AllowedAudiences[0]+ }++ resp := &api.HubInfoResponse{+ OidcIssuer: issuer,+ ClientId: aud,+ Audience: aud,+ }++ respData, err := proto.Marshal(resp)+ if err != nil {+ logger.Errorf("[Info] Failed to marshal info response: %v", err)+ http.Error(w, "Failed to serialize response", http.StatusInternalServerError)+ return+ }++ w.Header().Set("Content-Type", "application/x-protobuf")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write(respData)+ }+}diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.goindex dbf3ac00..34b6e12c 100644--- a/cmd/sam-node/main.go+++ b/cmd/sam-node/main.go@@ -15,6 +15,7 @@package mainimport (+ "bufio""bytes""context""crypto/ed25519"@@ -249,11 +250,39 @@ func main() {},}- loginCmd := &cobra.Command{- Use: "login",- Short: "Log in to the mesh via interactive OIDC flow",+ joinCmd := &cobra.Command{+ Use: "join [hub_url]",+ Short: "Join the Sovereign Agent Mesh hub",+ Args: cobra.MaximumNArgs(1),Run: func(cmd *cobra.Command, args []string) {ctx := cmd.Context()++ targetHub := ""+ if len(args) > 0 {+ targetHub = args[0]+ }++ if targetHub == "" {+ fmt.Print("No hub URL provided. Do you want to join the default community testing network (https://bananas.sam-mesh.dev)? [y/N]: ")+ reader := bufio.NewReader(os.Stdin)+ response, err := reader.ReadString('\n')+ if err != nil {+ fmt.Println("\nAborting: failed to read input.")+ return+ }+ response = strings.ToLower(strings.TrimSpace(response))+ if response != "y" && response != "yes" {+ fmt.Println("Aborting join operation.")+ return+ }+ targetHub = "https://bananas.sam-mesh.dev"+ }++ if !strings.HasPrefix(targetHub, "http://") && !strings.HasPrefix(targetHub, "https://") {+ targetHub = "https://" + targetHub+ }+ targetHub = strings.TrimSuffix(targetHub, "/")+store, err := NewStore(resolveDataDir())if err != nil {logger.Fatalf("Failed to open store: %v", err)@@ -270,33 +299,30 @@ func main() {}()dummyNode := &SamNode{Store: store}- deviceAuthURL := deviceAuthURLFlag- tokenURL := ""- if oidcIssuerFlag != "" {- logger.Info("Discovering OIDC endpoints...")- var err error- tokenURL, deviceAuthURL, err = dummyNode.DiscoverEndpoints(context.Background(), oidcIssuerFlag)- if err != nil {- logger.Fatalf("Failed to discover OIDC endpoints: %v", err)- }+ fmt.Printf("Discovering hub info from %s...\n", targetHub)+ hubInfo, err := dummyNode.DiscoverHubInfo(ctx, targetHub)+ if err != nil {+ logger.Fatalf("Failed to discover hub info: %v", err)}- if deviceAuthURL == "" {- deviceAuthURL = "https://oauth2.googleapis.com/device/code"- }- if tokenURL == "" {- tokenURL = "https://oauth2.googleapis.com/token"- }- clientID := clientIDFlag- if clientID == "" {- clientID = api.DefaultAudience+ fmt.Printf("OIDC Issuer discovered: %s\n", hubInfo.OidcIssuer)+ fmt.Printf("Client ID discovered: %s\n", hubInfo.ClientId)++ logger.Info("Discovering OIDC endpoints...")+ tokenURL, deviceAuthURL, err := dummyNode.DiscoverEndpoints(ctx, hubInfo.OidcIssuer)+ if err != nil {+ logger.Fatalf("Failed to discover OIDC endpoints: %v", err)}- jwtStr, err := dummyNode.InteractiveLogin(ctx, deviceAuthURL, tokenURL, clientID, audienceFlag)++ jwtStr, err := dummyNode.InteractiveLogin(ctx, deviceAuthURL, tokenURL, hubInfo.ClientId, hubInfo.Audience)if err != nil {logger.Fatalf("Failed to get token: %v", err)}+ // Override global hubAddr with targetHub for enrollment+ hubAddr = targetHub+// Connect to Hub and Enrollvar initHubAddrs []multiaddr.Multiaddrif !strings.HasPrefix(hubAddr, "http://") && !strings.HasPrefix(hubAddr, "https://") {@@ -331,7 +357,7 @@ func main() {logger.Fatalf("Enrollment failed: %v", err)}- fmt.Println("Login successful and identity stored.")+ fmt.Println("Successfully joined the Sovereign Agent Mesh!")},}@@ -360,7 +386,7 @@ func main() {rootCmd.PersistentFlags().StringVar(&dataDirFlag, "data-dir", os.Getenv("SAM_DATA_DIR"), "Override directory for the agent store (defaults to OS user config dir)")rootCmd.AddCommand(runCmd)- rootCmd.AddCommand(loginCmd)+ rootCmd.AddCommand(joinCmd)ctx, cancel := context.WithCancel(context.Background())defer cancel()diff --git a/cmd/sam-node/oidc.go b/cmd/sam-node/oidc.goindex eae93dbc..800e2f1e 100644--- a/cmd/sam-node/oidc.go+++ b/cmd/sam-node/oidc.go@@ -21,11 +21,15 @@ import ("io""net/http""net/url"+ "os/exec"+ "runtime""strings""time""github.com/coreos/go-oidc/v3/oidc"+ "github.com/google/sam/api""golang.org/x/oauth2/clientcredentials"+ "google.golang.org/protobuf/proto")// FetchJWT fetches a JWT token using the Client Credentials flow.@@ -79,16 +83,17 @@ func (n *SamNode) InteractiveLogin(ctx context.Context, deviceAuthURL, tokenURL,}()if resp.StatusCode != http.StatusOK {- body, _ := io.ReadAll(resp.Body)+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024*1024))return "", fmt.Errorf("device auth request failed: %s - %s", resp.Status, string(body))}var authResp struct {- DeviceCode string `json:"device_code"`- UserCode string `json:"user_code"`- VerificationURI string `json:"verification_uri"`- ExpiresIn int `json:"expires_in"`- Interval int `json:"interval"`+ DeviceCode string `json:"device_code"`+ UserCode string `json:"user_code"`+ VerificationURI string `json:"verification_uri"`+ VerificationURIComplete string `json:"verification_uri_complete"`+ ExpiresIn int `json:"expires_in"`+ Interval int `json:"interval"`}if err := json.NewDecoder(resp.Body).Decode(&authResp); err != nil {@@ -99,12 +104,23 @@ func (n *SamNode) InteractiveLogin(ctx context.Context, deviceAuthURL, tokenURL,fmt.Println("Device Authorization Flow")fmt.Println("------------------------------------------------------------")fmt.Printf("To authenticate, please go to the following URL in your browser:\n\n")- fmt.Printf(" %s\n\n", authResp.VerificationURI)- fmt.Printf("And enter the following code:\n\n")- fmt.Printf(" %s\n\n", authResp.UserCode)+ targetURL := authResp.VerificationURIComplete+ if targetURL == "" {+ targetURL = authResp.VerificationURI+ }+ fmt.Printf(" %s\n\n", targetURL)+ if authResp.VerificationURIComplete == "" {+ fmt.Printf("And enter the following code:\n\n")+ fmt.Printf(" %s\n\n", authResp.UserCode)+ } else {+ fmt.Println("The login code has been pre-filled for your convenience.")+ }fmt.Println("Waiting for authorization...")fmt.Println("------------------------------------------------------------")+ // Try to open browser automatically+ openBrowser(targetURL)+interval := authResp.Intervalif interval <= 0 {interval = 5@@ -213,3 +229,69 @@ func (n *SamNode) DiscoverEndpoints(ctx context.Context, issuerURL string) (toke}return claims.TokenURL, claims.DeviceURL, nil}++// DiscoverHubInfo queries the hub's /info endpoint to fetch OIDC configurations.+func (n *SamNode) DiscoverHubInfo(ctx context.Context, hubURL string) (*api.HubInfoResponse, error) {+ if !strings.HasPrefix(hubURL, "http://") && !strings.HasPrefix(hubURL, "https://") {+ hubURL = "https://" + hubURL+ }+ hubURL = strings.TrimSuffix(hubURL, "/")++ urlStr := hubURL + "/info"+ req, err := http.NewRequestWithContext(ctx, "GET", urlStr, nil)+ if err != nil {+ return nil, fmt.Errorf("failed to create HTTP request: %w", err)+ }++ client := &http.Client{+ Timeout: 10 * time.Second,+ }+ resp, err := client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("HTTP request failed: %w", err)+ }+ defer func() {+ if err := resp.Body.Close(); err != nil {+ logger.Errorf("Failed to close response body: %v", err)+ }+ }()++ if resp.StatusCode != http.StatusOK {+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024*1024))+ return nil, fmt.Errorf("hub returned status %s: %s", resp.Status, string(body))+ }++ body, err := io.ReadAll(io.LimitReader(resp.Body, 1024*1024))+ if err != nil {+ return nil, fmt.Errorf("failed to read response body: %w", err)+ }++ var hubInfo api.HubInfoResponse+ if err := proto.Unmarshal(body, &hubInfo); err != nil {+ return nil, fmt.Errorf("failed to unmarshal hub info: %w", err)+ }++ return &hubInfo, nil+}++func openBrowser(targetURL string) {+ parsedURL, err := url.Parse(targetURL)+ if err != nil || (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") {+ logger.Debugf("Failed to open browser: invalid or unsafe URL scheme %q", targetURL)+ return+ }+ var cmdErr error+ switch runtime.GOOS {+ case "linux":+ cmdErr = exec.Command("xdg-open", targetURL).Start()+ case "darwin":+ cmdErr = exec.Command("open", targetURL).Start()+ case "windows":+ cmdErr = exec.Command("rundll32", "url.dll,FileProtocolHandler", targetURL).Start()+ default:+ cmdErr = fmt.Errorf("unsupported platform")+ }+ if cmdErr != nil {+ logger.Debugf("Failed to open browser: %v", cmdErr)+ }+}diff --git a/tests/integration/login_test.go b/tests/integration/login_test.goindex 1e8ea56f..229f7230 100644--- a/tests/integration/login_test.go+++ b/tests/integration/login_test.go@@ -26,9 +26,8 @@ import ("time")-func TestSamNodeLogin(t *testing.T) {+func TestSamNodeJoin(t *testing.T) {nodeBin := buildBinary(t, "./cmd/sam-node")- _, hubAddr := startMockLibp2pHub(t)tmpHome := t.TempDir()env := append(os.Environ(),"HOME="+tmpHome,@@ -50,11 +49,12 @@ func TestSamNodeLogin(t *testing.T) {mux.HandleFunc("/device/code", func(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")if err := json.NewEncoder(w).Encode(map[string]interface{}{- "device_code": "dev_code_123",- "user_code": "ABCD-1234",- "verification_uri": "http://example.com/verify",- "expires_in": 60,- "interval": 1,+ "device_code": "dev_code_123",+ "user_code": "ABCD-1234",+ "verification_uri": "http://example.com/verify",+ "verification_uri_complete": "http://example.com/verify?code=ABCD-1234",+ "expires_in": 60,+ "interval": 1,}); err != nil {t.Errorf("Failed to encode response: %v", err)}@@ -68,8 +68,11 @@ func TestSamNodeLogin(t *testing.T) {t.Errorf("Failed to encode response: %v", err)}})- server := httptest.NewServer(mux)- defer server.Close()+ oidcServer := httptest.NewServer(mux)+ defer oidcServer.Close()++ // Start mock libp2p hub that knows about our mock OIDC server+ _, hubAddr := startMockLibp2pHubWithOIDC(t, oidcServer.URL)stdout, stderr, err := runCommand(t,@@ -78,21 +81,19 @@ func TestSamNodeLogin(t *testing.T) {env,"", // No stdin needednodeBin,- "login",- "--hub", hubAddr,- "--oidc-issuer", server.URL,+ "join",+ hubAddr,)if err != nil {- t.Fatalf("login command failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)+ t.Fatalf("join command failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)}out := stdout + stderr- if !strings.Contains(out, "Login successful and identity stored.") {- t.Fatalf("login did not succeed:\n%s", out)+ if !strings.Contains(out, "Successfully joined the Sovereign Agent Mesh!") {+ t.Fatalf("join did not succeed:\n%s", out)}- // Verify that the identity is actually stored.- // We can try to run the node without flags now!+ // Verify that the identity is stored and node can runstdout, stderr, err = runCommand(t,repoRoot(t),@@ -105,7 +106,6 @@ func TestSamNodeLogin(t *testing.T) {"--bind-addr", "127.0.0.1:0","--api-token", "dummy-token",)- // We expect it to keep running because it uses stored identity.if err != context.DeadlineExceeded {t.Fatalf("expected run command to keep running, got: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)}diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.goindex 73a180b2..449a0ba0 100644--- a/tests/integration/minimal_helpers_test.go+++ b/tests/integration/minimal_helpers_test.go@@ -147,3 +147,80 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {return h.ID(), httpServer.URL}++func startMockLibp2pHubWithOIDC(t *testing.T, oidcIssuerURL string) (peer.ID, string) {+ t.Helper()++ h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))+ if err != nil {+ t.Fatalf("failed to create mock libp2p host: %v", err)+ }++ kdht, err := dht.New(context.Background(), h, dht.Mode(dht.ModeServer), dht.ProtocolPrefix("/sam"))+ if err != nil {+ t.Fatalf("failed to create DHT on mock hub: %v", err)+ }++ // Start HTTP server for enrollment and info+ mux := http.NewServeMux()+ mux.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }+ resp := &api.HubInfoResponse{+ OidcIssuer: oidcIssuerURL,+ ClientId: "sam-mesh-audience",+ Audience: "sam-mesh-audience",+ }+ data, err := proto.Marshal(resp)+ if err != nil {+ http.Error(w, "Failed to marshal response", http.StatusInternalServerError)+ return+ }+ w.Header().Set("Content-Type", "application/x-protobuf")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write(data)+ })+ mux.HandleFunc("/register", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }+ body, err := io.ReadAll(r.Body)+ if err != nil {+ http.Error(w, "Failed to read body", http.StatusBadRequest)+ return+ }+ var req api.EnrollRequest+ if err := proto.Unmarshal(body, &req); err != nil {+ http.Error(w, "Invalid request format", http.StatusBadRequest)+ return+ }++ resp := &api.EnrollResponse{+ BiscuitToken: []byte("mock-biscuit-token"),+ HubPublicKey: []byte("mock-hub-pub-key"),+ HubAddresses: []string{h.Addrs()[0].String() + "/p2p/" + h.ID().String()},+ KnownPeers: []string{},+ }+ data, err := proto.Marshal(resp)+ if err != nil {+ http.Error(w, "Failed to marshal response", http.StatusInternalServerError)+ return+ }+ w.Header().Set("Content-Type", "application/x-protobuf")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write(data)+ })++ httpServer := httptest.NewServer(mux)++ t.Cleanup(func() {+ httpServer.Close()+ _ = kdht.Close()+ _ = h.Close()+ })++ return h.ID(), httpServer.URL+}