Skip to content

Agent Mesh

http enrollement

Antonio Ojea9ae073c412b7
diff --git a/Makefile b/Makefile
index a56d3c17..eaf13d44 100644
--- a/Makefile
+++ b/Makefile
@@ -67,7 +67,7 @@ docker-build-hub:
docker build -t sam-hub:local -f Dockerfile.sam-hub .
docker-build-node:
- docker build -t sam-node:local -f Dockerfile.sam-node .
+ docker build --no-cache -t sam-node:local -f Dockerfile.sam-node .
docker-build-mock-oidc:
docker build -t sam-mock-oidc:local -f tests/e2e/docker/Dockerfile.mock-oidc .
diff --git a/cmd/sam-hub/server.go b/cmd/sam-hub/server.go
index 2a6be2b7..e6c17272 100644
--- a/cmd/sam-hub/server.go
+++ b/cmd/sam-hub/server.go
@@ -15,20 +15,27 @@
package main
import (
+ "context"
"crypto/tls"
"crypto/x509"
+ "io"
"net/http"
"os"
+ "strings"
"sync/atomic"
+ "github.com/google/sam/api"
+ "github.com/libp2p/go-libp2p/core/peer"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
+ "google.golang.org/protobuf/proto"
)
// startHTTPServer starts the HTTP/HTTPS server for metrics, healthz, and admin commands.
func startHTTPServer(h *Hub, bindAddr string, adminToken string, tlsCertFile string, tlsKeyFile string, tlsCAFile string, isHubReady *atomic.Bool) {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{}))
+ mux.HandleFunc("/register", handleRegisterHTTP(h))
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
if isHubReady.Load() {
w.WriteHeader(http.StatusOK)
@@ -86,3 +93,116 @@ func startHTTPServer(h *Hub, bindAddr string, adminToken string, tlsCertFile str
}()
}
}
+
+func handleRegisterHTTP(h *Hub) http.HandlerFunc {
+ return 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
+ }
+ defer func() {
+ if err := r.Body.Close(); err != nil {
+ logger.Errorf("failed to close request body: %v", err)
+ }
+ }()
+
+ var req api.EnrollRequest
+ if err := proto.Unmarshal(body, &req); err != nil {
+ http.Error(w, "Invalid request format", http.StatusBadRequest)
+ return
+ }
+
+ if !h.limiter.Allow() {
+ http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
+ return
+ }
+
+ logger.Infow("New HTTP enrollment request", "peer_id", req.PeerId)
+
+ ctx, cancel := context.WithTimeout(context.Background(), JWTVerificationTimeout)
+ defer cancel()
+
+ claims, token, err := h.parseAndVerifyJWT(ctx, req.Jwt, h.AllowedAudiences)
+ if err != nil {
+ logger.Errorw("JWT verification failed", "peer_id", req.PeerId, "error", err)
+ http.Error(w, "JWT validation failed: "+err.Error(), http.StatusUnauthorized)
+ return
+ }
+
+ pID, err := peer.Decode(req.PeerId)
+ if err != nil {
+ logger.Errorw("Invalid Peer ID", "peer_id", req.PeerId, "error", err)
+ http.Error(w, "Invalid Peer ID", http.StatusBadRequest)
+ return
+ }
+
+ biscuitData, err := h.mintBiscuitToken(claims, token, pID)
+ if err != nil {
+ logger.Errorw("Biscuit minting failed", "peer_id", req.PeerId, "error", err)
+ http.Error(w, "Failed to mint biscuit", http.StatusInternalServerError)
+ return
+ }
+
+ h.gater.mu.Lock()
+ if !h.gater.authenticated[pID] {
+ samHubActiveNodes.Inc()
+ }
+ h.gater.authenticated[pID] = true
+ h.gater.mu.Unlock()
+
+ var authPeers []peer.ID
+ h.gater.mu.Lock()
+ for p := range h.gater.authenticated {
+ authPeers = append(authPeers, p)
+ }
+ h.gater.mu.Unlock()
+
+ var knownPeers []string
+ for _, p := range authPeers {
+ knownPeers = append(knownPeers, p.String())
+ }
+
+ var hubAddrs []string
+ if len(h.ExternalAddrs) > 0 {
+ for _, addr := range h.ExternalAddrs {
+ fullAddr := addr
+ if !strings.Contains(addr, "/p2p/") {
+ fullAddr = addr + "/p2p/" + h.Host.ID().String()
+ }
+ hubAddrs = append(hubAddrs, fullAddr)
+ }
+ } else {
+ for _, addr := range h.Host.Addrs() {
+ hubAddrs = append(hubAddrs, addr.String()+"/p2p/"+h.Host.ID().String())
+ }
+ }
+
+ resp := &api.EnrollResponse{
+ BiscuitToken: biscuitData,
+ HubPublicKey: h.KeyRing.GetCurrentPublicKey(),
+ HubAddresses: hubAddrs,
+ Expiration: token.Expiry.Unix(),
+ KnownPeers: knownPeers,
+ }
+
+ respData, err := proto.Marshal(resp)
+ if err != nil {
+ logger.Errorf("[Enroll] Failed to marshal 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)
+
+ logger.Infow("Successfully enrolled peer via HTTP", "peer_id", req.PeerId)
+ samHubEnrollmentTotal.WithLabelValues("success").Inc()
+ }
+}
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index e40166dc..2a505384 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -15,11 +15,14 @@
package main
import (
+ "bytes"
"context"
"crypto/ed25519"
"encoding/hex"
"fmt"
+ "io"
"net"
+ "net/http"
"os"
"os/signal"
"strings"
@@ -29,7 +32,7 @@ import (
"github.com/google/sam/api"
golog "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/core/crypto"
- "github.com/libp2p/go-msgio"
+ "github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
"github.com/spf13/cobra"
"google.golang.org/protobuf/proto"
@@ -180,26 +183,28 @@ func main() {
} else {
// We have a new JWT (from flag or interactive login), need to enroll
var initHubAddrs []multiaddr.Multiaddr
- ma, err := multiaddr.NewMultiaddr(hubAddr)
- if err == nil {
- initHubAddrs = []multiaddr.Multiaddr{ma}
- } else {
- // Try parsing as host:port
- host, port, err := net.SplitHostPort(hubAddr)
+ if !strings.HasPrefix(hubAddr, "http://") && !strings.HasPrefix(hubAddr, "https://") {
+ ma, err := multiaddr.NewMultiaddr(hubAddr)
if err == nil {
- ip := net.ParseIP(host)
- var maddr multiaddr.Multiaddr
- if ip != nil {
- maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%s", host, port))
- } else {
- maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/dns4/%s/tcp/%s", host, port))
- }
- initHubAddrs = []multiaddr.Multiaddr{maddr}
+ initHubAddrs = []multiaddr.Multiaddr{ma}
} else {
- if len(hubAddrs) > 0 {
- initHubAddrs = hubAddrs
+ // Try parsing as host:port
+ host, port, err := net.SplitHostPort(hubAddr)
+ if err == nil {
+ ip := net.ParseIP(host)
+ var maddr multiaddr.Multiaddr
+ if ip != nil {
+ maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%s", host, port))
+ } else {
+ maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/dns4/%s/tcp/%s", host, port))
+ }
+ initHubAddrs = []multiaddr.Multiaddr{maddr}
} else {
- logger.Fatalf("Invalid hub address and no stored config: %v. You can use community maintained meshes like hub.sam-mesh.dev (Production) or bananas.sam-mesh.dev (Testnet)", err)
+ if len(hubAddrs) > 0 {
+ initHubAddrs = hubAddrs
+ } else {
+ logger.Fatalf("Invalid hub address and no stored config: %v. You can use community maintained meshes like hub.sam-mesh.dev (Production) or bananas.sam-mesh.dev (Testnet)", err)
+ }
}
}
}
@@ -293,22 +298,24 @@ func main() {
// Connect to Hub and Enroll
var initHubAddrs []multiaddr.Multiaddr
- ma, err := multiaddr.NewMultiaddr(hubAddr)
- if err == nil {
- initHubAddrs = []multiaddr.Multiaddr{ma}
- } else {
- host, port, err := net.SplitHostPort(hubAddr)
+ if !strings.HasPrefix(hubAddr, "http://") && !strings.HasPrefix(hubAddr, "https://") {
+ ma, err := multiaddr.NewMultiaddr(hubAddr)
if err == nil {
- ip := net.ParseIP(host)
- var maddr multiaddr.Multiaddr
- if ip != nil {
- maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%s", host, port))
+ initHubAddrs = []multiaddr.Multiaddr{ma}
+ } else {
+ host, port, err := net.SplitHostPort(hubAddr)
+ if err == nil {
+ ip := net.ParseIP(host)
+ var maddr multiaddr.Multiaddr
+ if ip != nil {
+ maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%s", host, port))
+ } else {
+ maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/dns4/%s/tcp/%s", host, port))
+ }
+ initHubAddrs = []multiaddr.Multiaddr{maddr}
} else {
- maddr, _ = multiaddr.NewMultiaddr(fmt.Sprintf("/dns4/%s/tcp/%s", host, port))
+ logger.Fatalf("Invalid hub address: %v", err)
}
- initHubAddrs = []multiaddr.Multiaddr{maddr}
- } else {
- logger.Fatalf("Invalid hub address: %v", err)
}
}
@@ -391,16 +398,6 @@ func getOrGenerateKey(s *Store) crypto.PrivKey {
return priv
}
func (n *SamNode) Enroll(ctx context.Context, jwt string) error {
- if n.HubPeerID == "" {
- return fmt.Errorf("not connected to any hub")
- }
-
- s, err := n.Host.NewStream(ctx, n.HubPeerID, api.EnrollProtocolID)
- if err != nil {
- return fmt.Errorf("failed to open enroll stream: %v", err)
- }
- defer func() { _ = s.Close() }()
-
req := &api.EnrollRequest{
Jwt: jwt,
PeerId: n.Host.ID().String(),
@@ -410,55 +407,97 @@ func (n *SamNode) Enroll(ctx context.Context, jwt string) error {
return fmt.Errorf("failed to marshal enroll request: %v", err)
}
- writer := msgio.NewVarintWriter(s)
- if err := writer.WriteMsg(data); err != nil {
- return fmt.Errorf("failed to write enroll request: %v", err)
+ if !strings.HasPrefix(hubAddr, "http://") && !strings.HasPrefix(hubAddr, "https://") {
+ return fmt.Errorf("hub address must be an HTTP or HTTPS URL for enrollment: %s", hubAddr)
}
+ url := hubAddr + "/register"
+ logger.Infof("Enrolling via HTTP at %s", url)
- reader := msgio.NewVarintReaderSize(s, 1024*64)
- respMsg, err := reader.ReadMsg()
+ httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))
if err != nil {
- return fmt.Errorf("failed to read enroll response: %v", err)
+ return fmt.Errorf("failed to create HTTP request: %v", err)
}
- defer reader.ReleaseMsg(respMsg)
+ httpReq.Header.Set("Content-Type", "application/x-protobuf")
- var resp api.EnrollResponse
- if err := proto.Unmarshal(respMsg, &resp); err != nil {
- return fmt.Errorf("failed to unmarshal enroll response: %v", err)
+ client := &http.Client{}
+ resp, err := client.Do(httpReq)
+ if err != nil {
+ return fmt.Errorf("HTTP request failed: %v", err)
}
+ defer func() {
+ if err := resp.Body.Close(); err != nil {
+ logger.Errorf("failed to close response body: %v", err)
+ }
+ }()
- if resp.ErrorMessage != "" {
- return fmt.Errorf("enrollment failed: %s", resp.ErrorMessage)
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("enrollment failed with status %s: %s", resp.Status, string(body))
}
- if len(resp.BiscuitToken) == 0 {
+ respData, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return fmt.Errorf("failed to read response body: %v", err)
+ }
+
+ var enrollResp api.EnrollResponse
+ if err := proto.Unmarshal(respData, &enrollResp); err != nil {
+ return fmt.Errorf("failed to unmarshal response: %v", err)
+ }
+
+ if enrollResp.ErrorMessage != "" {
+ return fmt.Errorf("enrollment failed: %s", enrollResp.ErrorMessage)
+ }
+
+ if len(enrollResp.BiscuitToken) == 0 {
return fmt.Errorf("received empty biscuit token")
}
- if err := n.Store.SaveIdentity(resp.BiscuitToken); err != nil {
+ if err := n.Store.SaveIdentity(enrollResp.BiscuitToken); err != nil {
return fmt.Errorf("failed to save identity: %v", err)
}
- if err := n.Store.SaveIdentityExpiration(resp.Expiration); err != nil {
+ if err := n.Store.SaveIdentityExpiration(enrollResp.Expiration); err != nil {
return fmt.Errorf("failed to save identity expiration: %v", err)
}
- if err := n.Store.SaveHubConfig(resp.HubPublicKey, resp.HubAddresses); err != nil {
+ if err := n.Store.SaveHubConfig(enrollResp.HubPublicKey, enrollResp.HubAddresses); err != nil {
return fmt.Errorf("failed to save hub config: %v", err)
}
n.keysMu.Lock()
- n.trustedKeys = append(n.trustedKeys, TrustedKey{Key: ed25519.PublicKey(resp.HubPublicKey), ReceivedAt: time.Now()})
+ n.trustedKeys = append(n.trustedKeys, TrustedKey{Key: ed25519.PublicKey(enrollResp.HubPublicKey), ReceivedAt: time.Now()})
n.keysMu.Unlock()
// Add known peers from response
n.mu.Lock()
- for _, p := range resp.KnownPeers {
+ for _, p := range enrollResp.KnownPeers {
n.knownPeers[p] = true
fmt.Printf("[Enroll] Added known peer from hub: %s\n", p)
}
n.mu.Unlock()
- fmt.Println("Successfully enrolled and stored identity and hub config.")
+ // Connect to hub after enrollment to join the mesh
+ for _, addrStr := range enrollResp.HubAddresses {
+ addr, err := multiaddr.NewMultiaddr(addrStr)
+ if err != nil {
+ logger.Warnf("Failed to parse hub address from response: %v", err)
+ continue
+ }
+ addrInfo, err := peer.AddrInfoFromP2pAddr(addr)
+ if err != nil {
+ logger.Warnf("Failed to get AddrInfo from hub address: %v", err)
+ continue
+ }
+ if err := n.Host.Connect(ctx, *addrInfo); err != nil {
+ logger.Warnf("Failed to connect to hub after enrollment: %v", err)
+ } else {
+ logger.Infof("Successfully connected to hub via libp2p after enrollment")
+ n.HubPeerID = addrInfo.ID
+ break
+ }
+ }
+
+ fmt.Println("Successfully enrolled via HTTP and stored identity and hub config.")
return nil
}
diff --git a/cmd/sam-node/node.go b/cmd/sam-node/node.go
index 69750994..8738f71e 100644
--- a/cmd/sam-node/node.go
+++ b/cmd/sam-node/node.go
@@ -301,7 +301,7 @@ func NewSamNode(ctx context.Context, privKey crypto.PrivKey, hubPubKey ed25519.P
return node, nil
}
-func (n *SamNode) StartRenewalLoop(ctx context.Context, tokenURL, clientID, clientSecret, jwtPath string) {
+func (n *SamNode) StartRenewalLoop(ctx context.Context, issuerURL, clientID, clientSecret, jwtPath string) {
go func() {
for {
var renewAfter = DefaultRenewalFallback // Default fallback
@@ -329,8 +329,12 @@ func (n *SamNode) StartRenewalLoop(ctx context.Context, tokenURL, clientID, clie
case <-timer.C:
fmt.Println("Renewing enrollment...")
var newJWT string
- if tokenURL != "" {
- var err error
+ if issuerURL != "" {
+ tokenURL, err := n.DiscoverTokenURL(ctx, issuerURL)
+ if err != nil {
+ fmt.Printf("Failed to discover OIDC endpoints for renewal: %v\n", err)
+ continue
+ }
newJWT, err = n.FetchJWT(ctx, tokenURL, clientID, clientSecret)
if err != nil {
fmt.Printf("Failed to fetch JWT for renewal: %v\n", err)
diff --git a/tests/e2e/auth_flows.bats b/tests/e2e/auth_flows.bats
index 3f679a93..cfd1087b 100644
--- a/tests/e2e/auth_flows.bats
+++ b/tests/e2e/auth_flows.bats
@@ -60,7 +60,7 @@ teardown() {
-v "${data_vol}:/root/.config/sam-mesh" \
-i \
"sam-node:local" \
- login --hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}" --oidc-issuer "http://mock-oidc:18080"
+ login --hub "http://sam-hub:9090" --oidc-issuer "http://mock-oidc:18080"
# Now run the node with the stored identity
docker run -d \
diff --git a/tests/e2e/lib/container_mesh.bash b/tests/e2e/lib/container_mesh.bash
index 3c6fb877..01c395e8 100644
--- a/tests/e2e/lib/container_mesh.bash
+++ b/tests/e2e/lib/container_mesh.bash
@@ -47,9 +47,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
mesh_setup_env() {
mesh_cleanup_stale_resources
- if ! docker image inspect "${MESH_RUNTIME_IMAGE}" >/dev/null 2>&1; then
- mesh_build_runtime_image
- fi
+ mesh_build_runtime_image
MESH_PREFIX="mesh-${BATS_TEST_NUMBER}-$$-$(date +%s)"
MESH_NETWORK="${MESH_PREFIX}-net"
@@ -240,7 +238,7 @@ if [[ -z "${MESH_HELPERS_LOADED:-}" ]]; then
"${MESH_RUNTIME_IMAGE}" \
/usr/local/bin/sam-node run \
${flags} \
- --hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}" \
+ --hub "http://sam-hub:9090" \
--client-id "sam-mesh-audience" \
--client-secret "sam-e2e-secret" \
--oidc-issuer "http://mock-oidc:18080" \
diff --git a/tests/e2e/policy.bats b/tests/e2e/policy.bats
index 1cc91699..8e4a255f 100644
--- a/tests/e2e/policy.bats
+++ b/tests/e2e/policy.bats
@@ -210,7 +210,7 @@ EOF"
-v "${POLICY_VOL}:/etc/sam" \
"sam-node:local" \
run \
- --hub "/dns4/sam-hub/tcp/4002/p2p/${hub_peer_id}" \
+ --hub "http://sam-hub:9090" \
--client-id "sam-e2e" \
--client-secret "sam-e2e-secret" \
--oidc-issuer "http://mock-oidc:18080" \
diff --git a/tests/integration/fallback_test.go b/tests/integration/fallback_test.go
index 74bb1049..ce6d4d5a 100644
--- a/tests/integration/fallback_test.go
+++ b/tests/integration/fallback_test.go
@@ -27,13 +27,15 @@ import (
"testing"
"time"
+ "io"
+ "net/http"
+ "net/http/httptest"
"github.com/biscuit-auth/biscuit-go/v2"
"github.com/biscuit-auth/biscuit-go/v2/parser"
"github.com/google/sam/api"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p/core/crypto"
- "github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-msgio"
"github.com/multiformats/go-multiaddr"
@@ -261,10 +263,24 @@ func startMockHubDynamic(t *testing.T, pubA, pubB ed25519.PublicKey) (peer.ID, s
}
var callCount int
- h.SetStreamHandler(api.EnrollProtocolID, func(s network.Stream) {
- defer func() { _ = s.Close() }()
- callCount++
+ mux := http.NewServeMux()
+ 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
+ }
+ callCount++
var pub []byte
if callCount == 1 {
pub = pubA
@@ -276,18 +292,27 @@ func startMockHubDynamic(t *testing.T, pubA, pubB ed25519.PublicKey) (peer.ID, s
BiscuitToken: []byte("mock-biscuit-token"),
HubPublicKey: pub,
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
}
- data, _ := proto.Marshal(resp)
- writer := msgio.NewVarintWriter(s)
- _ = writer.WriteMsg(data)
+ 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(), h.Addrs()[0].String() + "/p2p/" + h.ID().String()
+ return h.ID(), httpServer.URL
}
type safeBuffer struct {
diff --git a/tests/integration/minimal_helpers_test.go b/tests/integration/minimal_helpers_test.go
index 6ae1514c..73a180b2 100644
--- a/tests/integration/minimal_helpers_test.go
+++ b/tests/integration/minimal_helpers_test.go
@@ -18,19 +18,19 @@ import (
"bytes"
"context"
"errors"
- "fmt"
"os/exec"
"path/filepath"
"runtime"
"testing"
"time"
+ "io"
+ "net/http"
+ "net/http/httptest"
"github.com/google/sam/api"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
- "github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
- "github.com/libp2p/go-msgio"
"google.golang.org/protobuf/proto"
)
@@ -103,32 +103,47 @@ func startMockLibp2pHub(t *testing.T) (peer.ID, string) {
t.Fatalf("failed to create DHT on mock hub: %v", err)
}
- h.SetStreamHandler(api.EnrollProtocolID, func(s network.Stream) {
- defer func() { _ = s.Close() }()
+ // Start HTTP server for enrollment
+ mux := http.NewServeMux()
+ 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
+ }
- // The following constants are mock values used for testing.
- // 'mock-biscuit-token' is a dummy token string.
- // 'mock-hub-pub-key' is a dummy public key string.
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 {
- fmt.Printf("Failed to marshal mock response: %v\n", err)
+ http.Error(w, "Failed to marshal response", http.StatusInternalServerError)
return
}
- writer := msgio.NewVarintWriter(s)
- if err := writer.WriteMsg(data); err != nil {
- fmt.Printf("Failed to write mock response: %v\n", err)
- }
+ 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(), h.Addrs()[0].String() + "/p2p/" + h.ID().String()
+ return h.ID(), httpServer.URL
}