diff --git a/.github/k8s/agentmesh-router-template.yaml b/.github/k8s/agentmesh-router-template.yaml index 793e8926a..ee6421aca 100644 --- a/.github/k8s/agentmesh-router-template.yaml +++ b/.github/k8s/agentmesh-router-template.yaml @@ -89,6 +89,8 @@ spec: - "--insecure-control-plane" - "--listen=/ip4/0.0.0.0/tcp/4501" - "--listen=/ip4/0.0.0.0/udp/4501/quic-v1" + # Browsers reach the router here; it shares the QUIC socket. + - "--listen=/ip4/0.0.0.0/udp/4501/quic-v1/webtransport" - "--external-addr=/dnsaddr/bootstrap.${ENV_NAME}.sam-mesh.dev" - "--jwt-path=/var/run/secrets/tokens/agentmesh-token" - "--keys-path=/data/router.key" diff --git a/.github/workflows/deploy.yaml b/.github/workflows/deploy.yaml index 3589e1aef..eab027623 100644 --- a/.github/workflows/deploy.yaml +++ b/.github/workflows/deploy.yaml @@ -581,6 +581,7 @@ jobs: --bootstrap-token-path=/run/secrets/bootstrap-token \ --listen=/ip4/0.0.0.0/tcp/4501 \ --listen=/ip4/0.0.0.0/udp/4501/quic-v1 \ + --listen=/ip4/0.0.0.0/udp/4501/quic-v1/webtransport \ --external-addr=/ip4/${EXTERNAL_IP}/tcp/4501 \ --external-addr=/ip4/${EXTERNAL_IP}/udp/4501/quic-v1 \ --metrics-addr=127.0.0.1:9090' diff --git a/charts/agentmesh/README.md b/charts/agentmesh/README.md index 1fa9a3441..d4109b6cc 100644 --- a/charts/agentmesh/README.md +++ b/charts/agentmesh/README.md @@ -174,3 +174,9 @@ alongside libp2p's own relay and connection metrics. With more than one replica the chart leaves out `--external-addr`, so each router announces the addresses it listens on: its own pod IP, for TCP and QUIC. A router is identified by its peer id, and the shared `-router` Service would send a dial to whichever pod it likes (the handshake then fails with "peer id mismatch"). The router puts its address in its lease, which it sends on its first sync with the control plane after it starts and renews from then on. With one replica, or with `router.externalAddrs` / `router.hostPort` set, nothing changes. Change `replicaCount` through Helm (`helm upgrade --set router.replicaCount=N`). `kubectl scale` does not render the template again, so the routers keep the address the chart rendered before. + +## Browsers + +A browser page reaches a router over WebSocket or WebTransport only. The chart's routers listen on TCP and QUIC, so a page cannot join through them, and the chart has no value for another listen address. + +To let a page in over WebTransport, add one argument to the router container, for example with a Helm post-renderer: `--listen=/ip4/0.0.0.0/udp/4501/quic-v1/webtransport`. It shares the UDP port of the QUIC listener, so it needs no new port. With `router.hostPort` set, or with a QUIC address in `router.externalAddrs`, the router then announces a `/webtransport` address for each QUIC address it announces. The page checks the router's self-signed certificate against the `certhash` in that address, so it needs no hostname and no CA certificate. diff --git a/internal/router/address.go b/internal/router/address.go new file mode 100644 index 000000000..1f56fa0eb --- /dev/null +++ b/internal/router/address.go @@ -0,0 +1,211 @@ +// 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 router + +import ( + "context" + "errors" + "net" + "slices" + "time" + + "github.com/libp2p/go-libp2p/core/peer" + "github.com/multiformats/go-multiaddr" + madns "github.com/multiformats/go-multiaddr-dns" +) + +// advertisedAddrs are the addresses the router leases to the control plane: the +// --external-addr ones plus their WebTransport addresses, else all host +// addresses. No operator can set a WebTransport address: its certhash changes. +func (r *Router) advertisedAddrs() []multiaddr.Multiaddr { + if len(r.config.ExternalAddrs) == 0 { + return r.Host.Addrs() + } + addrs := r.externalAddrs() + external := addrs + if resolved := r.resolvedExternalAddrs.Load(); resolved != nil { + external = append(slices.Clone(addrs), *resolved...) + } + return append(addrs, webTransportAddrs(external, r.Host.Network().ListenAddresses())...) +} + +// externalAddrs are the --external-addr values. Validate refused a malformed +// one at start. +func (r *Router) externalAddrs() []multiaddr.Multiaddr { + addrs := make([]multiaddr.Multiaddr, 0, len(r.config.ExternalAddrs)) + for _, s := range r.config.ExternalAddrs { + if ma, err := multiaddr.NewMultiaddr(s); err == nil { + addrs = append(addrs, ma) + } + } + return addrs +} + +// circuitAddrs are advertisedAddrs with /p2p//p2p-circuit appended: +// where a peer that reserved with this router is reached. +func (r *Router) circuitAddrs() []multiaddr.Multiaddr { + via := multiaddr.StringCast("/p2p/" + r.Host.ID().String() + "/p2p-circuit") + advertised := r.advertisedAddrs() + addrs := make([]multiaddr.Multiaddr, 0, len(advertised)) + for _, a := range advertised { + addrs = append(addrs, a.Encapsulate(via)) + } + return addrs +} + +// webTransportAddrs are the external QUIC addresses with the router's +// "/webtransport/certhash/..." suffix. An external QUIC address is taken to +// reach the port of the WebTransport listener: nothing here can check that. +func webTransportAddrs(external, listen []multiaddr.Multiaddr) []multiaddr.Multiaddr { + var addrs []multiaddr.Multiaddr + for _, addr := range external { + // No library returns an empty address: the check keeps a bug there from stopping the router. + if len(addr) == 0 { + continue + } + transport := addr[len(addr)-1].Code() + if transport != multiaddr.P_QUIC_V1 { + continue + } + // ip4, ip6, dns4, dns6 or dns. + hostProtocol := addr[0].Code() + suffix := webTransportSuffix(listen, hostProtocol) + if suffix == nil { + continue + } + if webTransport := addr.Encapsulate(suffix); !multiaddr.Contains(addrs, webTransport) { + addrs = append(addrs, webTransport) + } + } + return addrs +} + +// webTransportSuffix is the "/webtransport/certhash/..." end of a WebTransport +// listen address on the IP version that an address starting with the host +// protocol reaches, nil without one. All listeners carry the same +// certhashes, since a host has one certificate. +func webTransportSuffix(listen []multiaddr.Multiaddr, hostProtocol int) multiaddr.Multiaddr { + for _, addr := range listen { + if len(addr) == 0 { + continue + } + // Cut at /webtransport: the QUIC address before it, and the rest with the certhashes. + _, suffix := multiaddr.SplitFunc(addr, func(c multiaddr.Component) bool { return c.Code() == multiaddr.P_WEBTRANSPORT }) + ipVersion := addr[0].Code() + if len(suffix) > 0 && reachesIPVersion(hostProtocol, ipVersion) { + return suffix + } + } + return nil +} + +// reachesIPVersion reports whether an address starting with the host protocol +// reaches a listener on the IP version. A /dns name reaches both. +func reachesIPVersion(hostProtocol, ipVersion int) bool { + switch hostProtocol { + case multiaddr.P_IP4, multiaddr.P_DNS4: + return ipVersion == multiaddr.P_IP4 + case multiaddr.P_IP6, multiaddr.P_DNS6: + return ipVersion == multiaddr.P_IP6 + } + return hostProtocol == multiaddr.P_DNS +} + +// externalAddrLookupTimeout bounds one /dnsaddr lookup, so a slow DNS server +// cannot hold back the lease. +const externalAddrLookupTimeout = 5 * time.Second + +// resolveExternalAddrs finds the router's own addresses in its /dnsaddr +// --external-addr entries, for advertisedAddrs. A failed lookup keeps the +// last result, so a DNS outage does not withdraw a leased address; a record +// that is gone does. A /dnsaddr record that names another /dnsaddr is not +// followed. +func (r *Router) resolveExternalAddrs(ctx context.Context) { + // P_DNS matches a WebTransport listener on either IP version. + if len(r.config.ExternalAddrs) == 0 || webTransportSuffix(r.Host.Network().ListenAddresses(), multiaddr.P_DNS) == nil { + return + } + var own []multiaddr.Multiaddr + lookedUp := false + for _, ma := range r.externalAddrs() { + if len(ma) == 0 { + continue + } + if hostProtocol := ma[0].Code(); hostProtocol != multiaddr.P_DNSADDR { + continue + } + lookedUp = true + lookupCtx, cancel := context.WithTimeout(ctx, externalAddrLookupTimeout) + resolved, err := madns.DefaultResolver.Resolve(lookupCtx, ma) + cancel() + // No record is an answer, not an outage: the entry has no addresses. + var dnsErr *net.DNSError + if errors.As(err, &dnsErr) && dnsErr.IsNotFound { + continue + } + if ctx.Err() != nil { + // The router is stopping: not a DNS failure. + return + } + if err != nil { + // An outage lasts many leases: one warning, then the count at debug. + if failures := r.externalAddrLookupFailures.Add(1); failures == 1 { + logger.Warnf("Cannot resolve --external-addr %s, its WebTransport addresses stay as they are: %v", ma, err) + } else { + logger.Debugf("Cannot resolve --external-addr %s, %d lookups failed in a row: %v", ma, failures, err) + } + return + } + for _, addr := range resolved { + if pi, err := peer.AddrInfoFromP2pAddr(addr); err == nil && pi.ID == r.Host.ID() { + own = append(own, pi.Addrs...) + } + } + } + if !lookedUp { + return + } + if failures := r.externalAddrLookupFailures.Swap(0); failures > 0 { + logger.Infof("--external-addr resolves again after %d failed lookup(s)", failures) + } + // A DNS server may rotate its answer: the order is no change. + slices.SortFunc(own, multiaddr.Multiaddr.Compare) + last := r.resolvedExternalAddrs.Swap(&own) + if last == nil || !slices.EqualFunc(*last, own, multiaddr.Multiaddr.Equal) { + logger.Infof("--external-addr resolves to %d address(es) of this router: %v", len(own), own) + r.warnAddrsWithoutWebTransport(own) + } +} + +// warnAddrsWithoutWebTransport names the external QUIC addresses that get no +// WebTransport address although the router listens on WebTransport: it does +// not on their IP version. +func (r *Router) warnAddrsWithoutWebTransport(external []multiaddr.Multiaddr) { + listen := r.Host.Network().ListenAddresses() + // P_DNS matches a WebTransport listener on either IP version. + if webTransportSuffix(listen, multiaddr.P_DNS) == nil { + return + } + for _, addr := range external { + if len(addr) == 0 { + continue + } + transport := addr[len(addr)-1].Code() + hostProtocol := addr[0].Code() + if transport == multiaddr.P_QUIC_V1 && webTransportSuffix(listen, hostProtocol) == nil { + logger.Warnf("No WebTransport address for the external address %s: the router does not listen on WebTransport on its IP version", addr) + } + } +} diff --git a/internal/router/address_test.go b/internal/router/address_test.go new file mode 100644 index 000000000..33f0bf4e3 --- /dev/null +++ b/internal/router/address_test.go @@ -0,0 +1,476 @@ +// 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 router + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "testing/synctest" + "time" + + "github.com/google/agentmesh/api" + "github.com/libp2p/go-libp2p" + "github.com/libp2p/go-libp2p/core/host" + "github.com/libp2p/go-libp2p/core/peer" + "github.com/multiformats/go-multiaddr" + madns "github.com/multiformats/go-multiaddr-dns" + "google.golang.org/protobuf/proto" +) + +// newWebTransportHost listens on QUIC and on WebTransport on the same socket, +// as a router does. It returns the host and its "/webtransport/certhash/..." +// suffix. +func newWebTransportHost(t *testing.T) (host.Host, string) { + t.Helper() + h := newLoopbackHost(t, libp2p.DisableRelay(), libp2p.ListenAddrStrings("/ip4/127.0.0.1/udp/0/quic-v1")) + for _, addr := range h.Network().ListenAddresses() { + if transport := addr[len(addr)-1].Code(); transport != multiaddr.P_QUIC_V1 { + continue + } + if err := h.Network().Listen(multiaddr.StringCast(addr.String() + "/webtransport")); err != nil { + t.Fatalf("listen on WebTransport: %v", err) + } + } + for _, addr := range h.Network().ListenAddresses() { + if _, suffix, found := strings.Cut(addr.String(), "/webtransport"); found { + return h, "/webtransport" + suffix + } + } + t.Fatalf("no WebTransport listen address in %v", h.Network().ListenAddresses()) + return nil, "" +} + +// dnsaddrRecords is the DNS a router sees: the TXT records of the mock, "no +// such host" for a name without one as a real resolver answers, an error for +// every lookup while err is set, no answer at all while silent is set, and a +// count of the lookups. +type dnsaddrRecords struct { + *madns.MockResolver + err error + silent bool + lookups int +} + +func (d *dnsaddrRecords) LookupTXT(ctx context.Context, name string) ([]string, error) { + d.lookups++ + if d.silent { + <-ctx.Done() + return nil, ctx.Err() + } + if d.err != nil { + return nil, d.err + } + if len(d.TXT[name]) == 0 { + return nil, &net.DNSError{Err: "no such host", Name: name, IsNotFound: true} + } + return d.MockResolver.LookupTXT(ctx, name) +} + +func (d *dnsaddrRecords) LookupIPAddr(ctx context.Context, name string) ([]net.IPAddr, error) { + d.lookups++ + return d.MockResolver.LookupIPAddr(ctx, name) +} + +// useDNSAddrRecords makes the records the DNS of this test. +func useDNSAddrRecords(t *testing.T, txt map[string][]string) *dnsaddrRecords { + t.Helper() + records := &dnsaddrRecords{MockResolver: &madns.MockResolver{TXT: txt}} + resolver, err := madns.NewResolver(madns.WithDefaultResolver(records)) + if err != nil { + t.Fatal(err) + } + defaultResolver := madns.DefaultResolver + madns.DefaultResolver = resolver + t.Cleanup(func() { madns.DefaultResolver = defaultResolver }) + return records +} + +// advertisedAfter are the addresses the router leases after its external +// addresses, as strings. +func advertisedAfter(r *Router) []string { + var addrs []string + for _, addr := range r.advertisedAddrs()[len(r.config.ExternalAddrs):] { + addrs = append(addrs, addr.String()) + } + return addrs +} + +// With --external-addr, the router leases a WebTransport address for each of +// its external QUIC addresses, given or found in a /dnsaddr under its peer ID. +// It needs no peer to report its address, and leases none it cannot derive. +func TestRouterLeasesWebTransportForItsExternalQUICAddrs(t *testing.T) { + h, webTransport := newWebTransportHost(t) + other := newLoopbackHost(t, libp2p.DisableRelay()) + useDNSAddrRecords(t, map[string][]string{ + "_dnsaddr.bootstrap.example": { + "dnsaddr=/ip4/203.0.113.9/tcp/4501/p2p/" + h.ID().String(), + "dnsaddr=/ip4/203.0.113.9/udp/4501/quic-v1/p2p/" + h.ID().String(), + "dnsaddr=/ip6/2001:db8::9/udp/4501/quic-v1/p2p/" + h.ID().String(), + "dnsaddr=/ip4/203.0.113.10/udp/4501/quic-v1/p2p/" + other.ID().String(), + }, + "_dnsaddr.nested.example": {"dnsaddr=/dnsaddr/bootstrap.example/p2p/" + h.ID().String()}, + }) + + for _, tc := range []struct { + name string + host host.Host + external []string + want []string + }{ + {name: "QUIC by IP", host: h, external: []string{"/ip4/203.0.113.9/udp/4501/quic-v1"}, want: []string{"/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport}}, + {name: "QUIC by private IP", host: h, external: []string{"/ip4/10.89.0.3/udp/4501/quic-v1"}, want: []string{"/ip4/10.89.0.3/udp/4501/quic-v1" + webTransport}}, + {name: "QUIC by name", host: h, external: []string{"/dns4/router.example/udp/4501/quic-v1"}, want: []string{"/dns4/router.example/udp/4501/quic-v1" + webTransport}}, + {name: "own entry in a dnsaddr", host: h, external: []string{"/dnsaddr/bootstrap.example"}, want: []string{"/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport}}, + {name: "same address given and in a dnsaddr", host: h, external: []string{"/dnsaddr/bootstrap.example", "/ip4/203.0.113.9/udp/4501/quic-v1"}, want: []string{"/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport}}, + {name: "dnsaddr without a record", host: h, external: []string{"/dnsaddr/unpublished.example"}}, + {name: "dnsaddr record that names another dnsaddr", host: h, external: []string{"/dnsaddr/nested.example"}}, + {name: "TCP only", host: h, external: []string{"/ip4/203.0.113.9/tcp/4501"}}, + {name: "IPv6 address, IPv4 listener", host: h, external: []string{"/ip6/2001:db8::9/udp/4501/quic-v1"}}, + {name: "no WebTransport listener", host: other, external: []string{"/dnsaddr/bootstrap.example", "/ip4/203.0.113.9/udp/4501/quic-v1"}}, + } { + t.Run(tc.name, func(t *testing.T) { + r := &Router{Host: tc.host, config: Options{ExternalAddrs: tc.external}} + r.resolveExternalAddrs(context.Background()) + if got := advertisedAfter(r); !slices.Equal(got, tc.want) { + t.Errorf("WebTransport addresses for %v: got %v, want %v", tc.external, got, tc.want) + } + }) + } +} + +// A DNS outage does not withdraw the WebTransport address from the lease: the +// router keeps the addresses of its last successful lookup. +func TestRouterKeepsItsWebTransportAddrWhenTheLookupFails(t *testing.T) { + h, webTransport := newWebTransportHost(t) + records := useDNSAddrRecords(t, map[string][]string{ + "_dnsaddr.bootstrap.example": {"dnsaddr=/ip4/203.0.113.9/udp/4501/quic-v1/p2p/" + h.ID().String()}, + }) + r := &Router{Host: h, config: Options{ExternalAddrs: []string{"/dnsaddr/bootstrap.example"}}} + want := []string{"/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport} + + r.resolveExternalAddrs(context.Background()) + if got := advertisedAfter(r); !slices.Equal(got, want) { + t.Fatalf("WebTransport addresses after the first lookup: got %v, want %v", got, want) + } + + records.err = errors.New("no DNS server answered") + for failures := int32(1); failures <= 2; failures++ { + r.resolveExternalAddrs(context.Background()) + if got := r.externalAddrLookupFailures.Load(); got != failures { + t.Fatalf("failed lookups in a row: got %d, want %d", got, failures) + } + if got := advertisedAfter(r); !slices.Equal(got, want) { + t.Fatalf("WebTransport addresses after %d failed lookup(s): got %v, want %v", failures, got, want) + } + } + + // A router that stops in the middle of a lookup has no DNS failure. + stopping, stop := context.WithCancel(context.Background()) + stop() + r.resolveExternalAddrs(stopping) + if got := r.externalAddrLookupFailures.Load(); got != 2 { + t.Fatalf("failed lookups after a canceled one: got %d, want 2", got) + } + + records.err = nil + records.TXT["_dnsaddr.bootstrap.example"] = []string{"dnsaddr=/ip4/203.0.113.77/udp/4501/quic-v1/p2p/" + h.ID().String()} + r.resolveExternalAddrs(context.Background()) + if got := r.externalAddrLookupFailures.Load(); got != 0 { + t.Errorf("failed lookups after DNS answered: got %d, want 0", got) + } + want = []string{"/ip4/203.0.113.77/udp/4501/quic-v1" + webTransport} + if got := advertisedAfter(r); !slices.Equal(got, want) { + t.Errorf("WebTransport addresses after DNS answered: got %v, want %v", got, want) + } +} + +// A DNS server that does not answer holds a lease back for the lookup limit +// and no longer, and the router keeps the addresses of its last lookup. +func TestRouterGivesUpALookupAfterItsLimit(t *testing.T) { + h, webTransport := newWebTransportHost(t) + records := useDNSAddrRecords(t, map[string][]string{ + "_dnsaddr.bootstrap.example": {"dnsaddr=/ip4/203.0.113.9/udp/4501/quic-v1/p2p/" + h.ID().String()}, + }) + r := &Router{Host: h, config: Options{ExternalAddrs: []string{"/dnsaddr/bootstrap.example"}}} + want := []string{"/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport} + r.resolveExternalAddrs(context.Background()) + if got := advertisedAfter(r); !slices.Equal(got, want) { + t.Fatalf("WebTransport addresses after the first lookup: got %v, want %v", got, want) + } + + records.silent = true + synctest.Test(t, func(t *testing.T) { + start := time.Now() + r.resolveExternalAddrs(context.Background()) + if got := time.Since(start); got != externalAddrLookupTimeout { + t.Errorf("a lookup with no answer took %s, want %s", got, externalAddrLookupTimeout) + } + }) + if got := advertisedAfter(r); !slices.Equal(got, want) { + t.Errorf("WebTransport addresses after a lookup with no answer: got %v, want %v", got, want) + } +} + +// The lease follows the router's /dnsaddr record: a new address replaces the +// old one at the next lookup, and a removed record withdraws it. +func TestRouterWebTransportAddrFollowsItsDNSAddrRecord(t *testing.T) { + h, webTransport := newWebTransportHost(t) + records := useDNSAddrRecords(t, map[string][]string{ + "_dnsaddr.bootstrap.example": {"dnsaddr=/ip4/203.0.113.9/udp/4501/quic-v1/p2p/" + h.ID().String()}, + }) + r := &Router{Host: h, config: Options{ExternalAddrs: []string{"/dnsaddr/bootstrap.example"}}} + + for _, step := range []struct { + name string + record []string + want []string + }{ + {name: "first record", record: records.TXT["_dnsaddr.bootstrap.example"], want: []string{"/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport}}, + {name: "the router moved", record: []string{"dnsaddr=/ip4/203.0.113.77/udp/4501/quic-v1/p2p/" + h.ID().String()}, want: []string{"/ip4/203.0.113.77/udp/4501/quic-v1" + webTransport}}, + {name: "record removed", record: nil}, + } { + records.TXT["_dnsaddr.bootstrap.example"] = step.record + r.resolveExternalAddrs(context.Background()) + if got := advertisedAfter(r); !slices.Equal(got, step.want) { + t.Fatalf("%s: WebTransport addresses: got %v, want %v", step.name, got, step.want) + } + } +} + +// The router looks its /dnsaddr up only for a WebTransport address: one that +// does not listen on WebTransport, or has no /dnsaddr, makes no DNS lookup. +func TestRouterLooksUpOnlyADNSAddrItNeeds(t *testing.T) { + h, _ := newWebTransportHost(t) + other := newLoopbackHost(t, libp2p.DisableRelay()) + records := useDNSAddrRecords(t, nil) + + for _, tc := range []struct { + name string + host host.Host + external []string + want int + }{ + {name: "no WebTransport listener", host: other, external: []string{"/dnsaddr/bootstrap.example"}, want: 0}, + {name: "no external address", host: h, want: 0}, + {name: "external addresses by IP and by name", host: h, external: []string{"/ip4/203.0.113.9/udp/4501/quic-v1", "/dns4/router.example/udp/4501/quic-v1"}, want: 0}, + {name: "a dnsaddr and a WebTransport listener", host: h, external: []string{"/dnsaddr/bootstrap.example"}, want: 1}, + } { + t.Run(tc.name, func(t *testing.T) { + records.lookups = 0 + r := &Router{Host: tc.host, config: Options{ExternalAddrs: tc.external}} + r.resolveExternalAddrs(context.Background()) + if records.lookups != tc.want { + t.Errorf("DNS lookups for %v: got %d, want %d", tc.external, records.lookups, tc.want) + } + }) + } +} + +// Without --external-addr the router leases its host addresses, and those +// include its WebTransport listen address. +func TestRouterWithoutExternalAddrsLeasesItsListenAddrs(t *testing.T) { + h, webTransport := newWebTransportHost(t) + r := &Router{Host: h} + var got, want []string + for _, addr := range r.advertisedAddrs() { + got = append(got, addr.String()) + } + for _, addr := range h.Addrs() { + want = append(want, addr.String()) + } + if !slices.Equal(got, want) { + t.Fatalf("advertisedAddrs: got %v, want the host addresses %v", got, want) + } + if !slices.ContainsFunc(got, func(addr string) bool { return strings.HasSuffix(addr, webTransport) }) { + t.Errorf("advertisedAddrs: got %v, want one that ends in %s", got, webTransport) + } +} + +// An empty address is skipped, among the external addresses and among the +// listen addresses, instead of stopping the router. +func TestWebTransportAddrsSkipAnEmptyAddr(t *testing.T) { + h, webTransport := newWebTransportHost(t) + external := []multiaddr.Multiaddr{nil, multiaddr.StringCast("/ip4/203.0.113.9/udp/4501/quic-v1")} + listen := append([]multiaddr.Multiaddr{nil}, h.Network().ListenAddresses()...) + var got []string + for _, ma := range webTransportAddrs(external, listen) { + got = append(got, ma.String()) + } + if want := []string{"/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport}; !slices.Equal(got, want) { + t.Errorf("webTransportAddrs with an empty address: got %v, want %v", got, want) + } + r := &Router{Host: h} + // No result to compare: the call must not panic. + r.warnAddrsWithoutWebTransport(external) +} + +// A WebTransport address is an external QUIC address plus the certhashes of +// the router's WebTransport listener, for the IP versions it listens on. +func TestWebTransportAddrsFollowTheListeners(t *testing.T) { + const webTransport = "/webtransport/certhash/uEiDDq4_xNyDorZBH3TlGazyJdOWSwvo4PUo5YHFMrvDE8g/certhash/uEiAAq4_xNyDorZBH3TlGazyJdOWSwvo4PUo5YHFMrvDE8g" + listen := []string{"/ip4/0.0.0.0/tcp/4501", "/ip4/0.0.0.0/udp/4501/quic-v1", "/ip4/0.0.0.0/udp/4501/quic-v1" + webTransport} + byVersion := []string{"/ip4/203.0.113.9/udp/4501/quic-v1", "/ip6/2001:db8::9/udp/4501/quic-v1", "/dns4/router.example/udp/4501/quic-v1", "/dns6/router.example/udp/4501/quic-v1", "/dns/router.example/udp/4501/quic-v1"} + for _, tc := range []struct { + name string + listen []string + external []string + want []string + }{ + { + name: "QUIC by IP, not TCP", + listen: listen, + external: []string{"/ip4/203.0.113.9/tcp/4501", "/ip4/203.0.113.9/udp/4501/quic-v1"}, + want: []string{"/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport}, + }, + { + name: "IPv4 listener: IPv4 addresses and names", + listen: listen, + external: byVersion, + want: []string{"/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport, "/dns4/router.example/udp/4501/quic-v1" + webTransport, "/dns/router.example/udp/4501/quic-v1" + webTransport}, + }, + { + name: "IPv6 listener: IPv6 addresses and names", + listen: []string{"/ip4/0.0.0.0/udp/4501/quic-v1", "/ip6/::/udp/4501/quic-v1", "/ip6/::/udp/4501/quic-v1" + webTransport}, + external: byVersion, + want: []string{"/ip6/2001:db8::9/udp/4501/quic-v1" + webTransport, "/dns6/router.example/udp/4501/quic-v1" + webTransport, "/dns/router.example/udp/4501/quic-v1" + webTransport}, + }, + { + name: "listeners on both IP versions: every address", + listen: append(slices.Clone(listen), "/ip6/::/udp/4501/quic-v1", "/ip6/::/udp/4501/quic-v1"+webTransport), + external: byVersion, + want: []string{ + "/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport, + "/ip6/2001:db8::9/udp/4501/quic-v1" + webTransport, + "/dns4/router.example/udp/4501/quic-v1" + webTransport, + "/dns6/router.example/udp/4501/quic-v1" + webTransport, + "/dns/router.example/udp/4501/quic-v1" + webTransport, + }, + }, + { + name: "the same external address twice", + listen: listen, + external: []string{"/ip4/203.0.113.9/udp/4501/quic-v1", "/ip4/203.0.113.9/udp/4501/quic-v1"}, + want: []string{"/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport}, + }, + { + name: "no WebTransport listener", + listen: []string{"/ip4/0.0.0.0/tcp/4501", "/ip4/0.0.0.0/udp/4501/quic-v1"}, + external: []string{"/ip4/203.0.113.9/udp/4501/quic-v1"}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + var got []string + for _, addr := range webTransportAddrs(parseAddrs(t, tc.external), parseAddrs(t, tc.listen)) { + got = append(got, addr.String()) + } + if !slices.Equal(got, tc.want) { + t.Errorf("webTransportAddrs(%v) with listeners %v: got %v, want %v", tc.external, tc.listen, got, tc.want) + } + }) + } +} + +// A lease renewal looks the /dnsaddr up and sends the WebTransport address to +// the control plane, and a peer that dials that address reaches the router. +func TestRouterRenewLeaseSendsADialableWebTransportAddr(t *testing.T) { + var mu sync.Mutex + var leased []string + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + body, err := io.ReadAll(req.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + var lease api.RouterLeaseRequest + if err := proto.Unmarshal(body, &lease); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + mu.Lock() + leased = lease.Addresses + mu.Unlock() + out, err := proto.Marshal(&api.RouterLeaseResponse{Success: true}) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/x-protobuf") + _, _ = w.Write(out) + })) + t.Cleanup(ts.Close) + + h, webTransport := newWebTransportHost(t) + var quic string + for _, addr := range h.Network().ListenAddresses() { + if transport := addr[len(addr)-1].Code(); transport == multiaddr.P_QUIC_V1 { + quic = addr.String() + } + } + useDNSAddrRecords(t, map[string][]string{"_dnsaddr.bootstrap.example": {"dnsaddr=" + quic + "/p2p/" + h.ID().String()}}) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + r := &Router{ + Host: h, + ctx: ctx, + cancel: cancel, + privKey: h.Peerstore().PrivKey(h.ID()), + credential: credential{biscuit: []byte("dummy-biscuit")}, + config: Options{ControlPlaneURL: ts.URL, HighWaterMark: 4000, ExternalAddrs: []string{"/dnsaddr/bootstrap.example"}}, + } + + r.renewLease() + + mu.Lock() + got := slices.Clone(leased) + mu.Unlock() + want := []string{"/dnsaddr/bootstrap.example/p2p/" + h.ID().String(), quic + webTransport + "/p2p/" + h.ID().String()} + if !slices.Equal(got, want) { + t.Fatalf("leased addresses: got %v, want %v", got, want) + } + + dialer, err := libp2p.New(libp2p.NoListenAddrs, libp2p.DisableRelay()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dialer.Close() }) + info, err := peer.AddrInfoFromString(got[1]) + if err != nil { + t.Fatalf("parse the leased address %s: %v", got[1], err) + } + if err := dialer.Connect(ctx, *info); err != nil { + t.Fatalf("dial the leased address %s: %v", got[1], err) + } +} + +func parseAddrs(t *testing.T, addrs []string) []multiaddr.Multiaddr { + t.Helper() + parsed := make([]multiaddr.Multiaddr, 0, len(addrs)) + for _, s := range addrs { + addr, err := multiaddr.NewMultiaddr(s) + if err != nil { + t.Fatalf("parse %s: %v", s, err) + } + parsed = append(parsed, addr) + } + return parsed +} diff --git a/internal/router/reservation_addrs_test.go b/internal/router/reservation_addrs_test.go index 6bdc2a276..c584af2ef 100644 --- a/internal/router/reservation_addrs_test.go +++ b/internal/router/reservation_addrs_test.go @@ -116,18 +116,18 @@ func hasCircuit(ma multiaddr.Multiaddr) bool { return strings.HasSuffix(ma.String(), "/p2p-circuit") } -// The circuit addresses follow the addresses the router leases: the -// configured external ones when set, and a malformed one is a start-up -// error rather than an address silently dropped from the lease. +// The circuit addresses follow the lease: the --external-addr addresses plus +// the WebTransport address of the QUIC one. A malformed --external-addr fails +// at start instead of disappearing from the lease. func TestRouterCircuitAddrsFollowTheExternalAddrs(t *testing.T) { - h := newLoopbackHost(t, libp2p.DisableRelay()) + h, webTransport := newWebTransportHost(t) r := &Router{Host: h, config: Options{ExternalAddrs: []string{"/dns4/router.example/tcp/4501", "/ip4/203.0.113.9/udp/4501/quic-v1"}}} var got []string for _, ma := range r.circuitAddrs() { got = append(got, ma.String()) } suffix := "/p2p/" + h.ID().String() + "/p2p-circuit" - want := []string{"/dns4/router.example/tcp/4501" + suffix, "/ip4/203.0.113.9/udp/4501/quic-v1" + suffix} + want := []string{"/dns4/router.example/tcp/4501" + suffix, "/ip4/203.0.113.9/udp/4501/quic-v1" + suffix, "/ip4/203.0.113.9/udp/4501/quic-v1" + webTransport + suffix} if !slices.Equal(got, want) { t.Errorf("circuitAddrs = %v, want %v", got, want) } diff --git a/internal/router/router.go b/internal/router/router.go index f6e323dae..489475032 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -166,34 +166,6 @@ func (r *Router) reservationTTL() time.Duration { return relay.DefaultResources().ReservationTTL } -// advertisedAddrs are the addresses the router leases to the control plane -// and is reached at: the configured external ones, else what the host -// listens on. -func (r *Router) advertisedAddrs() []multiaddr.Multiaddr { - if len(r.config.ExternalAddrs) == 0 { - return r.Host.Addrs() - } - addrs := make([]multiaddr.Multiaddr, 0, len(r.config.ExternalAddrs)) - for _, s := range r.config.ExternalAddrs { - if ma, err := multiaddr.NewMultiaddr(s); err == nil { - addrs = append(addrs, ma) - } - } - return addrs -} - -// circuitAddrs are advertisedAddrs with /p2p//p2p-circuit appended: -// where a peer that reserved with this router is reached. -func (r *Router) circuitAddrs() []multiaddr.Multiaddr { - via := multiaddr.StringCast("/p2p/" + r.Host.ID().String() + "/p2p-circuit") - advertised := r.advertisedAddrs() - addrs := make([]multiaddr.Multiaddr, 0, len(advertised)) - for _, a := range advertised { - addrs = append(addrs, a.Encapsulate(via)) - } - return addrs -} - func (a *relayACL) AllowConnect(src peer.ID, srcAddr multiaddr.Multiaddr, dest peer.ID) bool { if _, banned := a.r.bannedPeers.Load(src); banned { logger.Debugf("[Relay] Rejecting connect from %s to %s: src is banned", src, dest) @@ -404,8 +376,14 @@ type Router struct { // identityLoggedAt is when the "Router Online" line was last written. identityLoggedAt atomic.Pointer[time.Time] // leasedAddrs is the address list of the last accepted lease, joined. - leasedAddrs atomic.Pointer[string] - authFailureLog perPeerLogLimiter + leasedAddrs atomic.Pointer[string] + // resolvedExternalAddrs are the router's own addresses found in its + // /dnsaddr --external-addr entries at the last lookup. + resolvedExternalAddrs atomic.Pointer[[]multiaddr.Multiaddr] + // externalAddrLookupFailures counts the /dnsaddr lookups that failed + // since the last one that answered. + externalAddrLookupFailures atomic.Int32 + authFailureLog perPeerLogLimiter } // NewRouter initializes the router. @@ -635,6 +613,7 @@ func (r *Router) Start() (retErr error) { }() logger.Infof("Router Online. PeerID: %s, ListenAddrs: %v", r.Host.ID(), r.Host.Addrs()) + r.warnAddrsWithoutWebTransport(r.externalAddrs()) return nil } @@ -1386,6 +1365,7 @@ func (r *Router) renewLease() { if r.shutdown.Load() { return } + r.resolveExternalAddrs(r.ctx) r.sendLease(r.ctx, nil, 2) } diff --git a/sdk/README.md b/sdk/README.md index 6f800ef79..a80992b67 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -69,7 +69,7 @@ Milestones 1 to 5 are implemented and tested in both languages: | Control plane pull before join and on `agentmesh-node`'s interval: `/keys` verified against the trusted set, credential refresh after a rotation, `/info` bans and router catalog (`routers` and `router_addresses`) | yes | yes | | Gossip events from the control plane (`/mesh/events/v1`, StrictSign): ban enforced at once, key rotation adopted, policy update pulls | yes | yes | | Banned peers refused: connections dropped and denied, handshakes and requests refused, dials refused | yes | yes | -| Runs in a browser page: WebSocket and Noise to the router, state in IndexedDB, the agent answered by a fetch handler; `sdk/js/examples/browser` against `agentmesh-one`, tested in Chromium | yes | — | +| Runs in a browser page: WebSocket or WebTransport, with Noise, to the router, state in IndexedDB, the agent answered by a fetch handler; `sdk/js/examples/browser` against `agentmesh-one`, tested in Chromium | yes | — | | Published to a registry from the release workflow | npm `@agentmesh-p2p/sdk` | PyPI `agentmesh-p2p` | A member built this way is on the mesh and uses it in both directions: it @@ -767,7 +767,7 @@ one follows is named so a change on one side can be carried to the others. | `libp2p-http.ts` | `libp2p_http.py` | `/libp2p-http` client (streaming) and the A2A ingress for the agent, as go-libp2p-http and `StartIngressServer`; mesh URLs | | `http1.ts` | — | HTTP/1.1 heads and bodies on a libp2p stream, for `libp2p-http.ts` (Python uses `h11` in `libp2p_http.py`) | | `libp2p-http-node.ts` | — | the ingress for a Node request listener (an Express app), Node's own HTTP server over the stream | -| `platform/*.ts`, `platform/*.browser.ts` | — | what differs between Node and a browser: transports and security (TCP+WebSocket with TLS then Noise; WebSocket with Noise), state (files; IndexedDB), the biscuit WASM loader, the ingress. `package.json`'s `browser` field maps each to its twin; `scripts/bundle-browser.mjs` bundles for a page and fails if the browser graph reaches a `node:` module | +| `platform/*.ts`, `platform/*.browser.ts` | — | what differs between Node and a browser: transports and security (TCP+WebSocket with TLS then Noise; WebSocket and WebTransport with Noise), state (files; IndexedDB), the biscuit WASM loader, the ingress. `package.json`'s `browser` field maps each to its twin; `scripts/bundle-browser.mjs` bundles for a page and fails if the browser graph reaches a `node:` module | | — | `httpx_transport.py` | `MeshTransport`, the mesh as an `httpx.AsyncBaseTransport` (JS has `session.fetch()` instead) | | `sync.ts` | `sync.py` | ban set and mesh event verification, as `reconcileBannedPeers` and `verifyEvent` | | `conformance.ts`, `conformance-join.ts` | `conformance.py`, `conformance_join.py` | the runners the integration tests drive | diff --git a/sdk/js/package-lock.json b/sdk/js/package-lock.json index d4b20a77e..050d995fc 100644 --- a/sdk/js/package-lock.json +++ b/sdk/js/package-lock.json @@ -24,6 +24,7 @@ "@libp2p/tls": "^3.1.10", "@libp2p/utils": "^7.4.1", "@libp2p/websockets": "^10.1.21", + "@libp2p/webtransport": "^6.0.44", "@modelcontextprotocol/sdk": "^1.32.1", "@multiformats/multiaddr": "^13.0.3", "@noble/curves": "^2.0.1", @@ -892,6 +893,34 @@ "uint8arrays": "^6.0.0" } }, + "node_modules/@libp2p/noise": { + "version": "17.0.7", + "resolved": "https://registry.npmjs.org/@libp2p/noise/-/noise-17.0.7.tgz", + "integrity": "sha512-PSqVKlx919Wh+D+VC/y0amUu8t6qCUZmZlzeeTdLszxDOzOOQjZ9Wievzh/b/N5vQIRI9iXEqzhWpn2QFfFvNg==", + "dependencies": { + "@chainsafe/as-chacha20poly1305": "^0.1.0", + "@chainsafe/as-sha256": "^1.2.0", + "@libp2p/crypto": "^5.2.0", + "@libp2p/interface": "^3.4.0", + "@libp2p/peer-id": "^6.0.18", + "@libp2p/utils": "^7.4.5", + "@noble/ciphers": "^2.0.1", + "@noble/curves": "^2.0.1", + "@noble/hashes": "^2.0.1", + "protons-runtime": "^7.0.0", + "uint8arraylist": "^3.0.2", + "uint8arrays": "^6.1.1", + "wherearewe": "^2.0.1" + } + }, + "node_modules/@libp2p/noise/node_modules/uint8arraylist": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/uint8arraylist/-/uint8arraylist-3.0.2.tgz", + "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==", + "dependencies": { + "uint8arrays": "^6.0.0" + } + }, "node_modules/@libp2p/peer-collections": { "version": "7.0.32", "resolved": "https://registry.npmjs.org/@libp2p/peer-collections/-/peer-collections-7.0.32.tgz", @@ -1120,6 +1149,32 @@ "uint8arrays": "^6.0.0" } }, + "node_modules/@libp2p/webtransport": { + "version": "6.0.44", + "resolved": "https://registry.npmjs.org/@libp2p/webtransport/-/webtransport-6.0.44.tgz", + "integrity": "sha512-+8M19ECA8n/M2mGoGbX+HfqnGUhcCLNnbazluJYIjK5RkVjpbjjO5Txdkc74RiSqYcfzdS+vulK39Nqc8J2hjQ==", + "dependencies": { + "@libp2p/interface": "^3.4.0", + "@libp2p/noise": "^17.0.7", + "@libp2p/peer-id": "^6.0.18", + "@libp2p/utils": "^7.4.5", + "@multiformats/multiaddr": "^13.0.3", + "@multiformats/multiaddr-matcher": "^3.0.2", + "multiformats": "^14.0.0", + "progress-events": "^1.0.1", + "race-signal": "^2.0.0", + "uint8arraylist": "^3.0.2", + "uint8arrays": "^6.1.1" + } + }, + "node_modules/@libp2p/webtransport/node_modules/uint8arraylist": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/uint8arraylist/-/uint8arraylist-3.0.2.tgz", + "integrity": "sha512-LDVoq9BQaGJzGDUovEnoX6rpKCvnY/Jbtws4ikwnBzjRbq5qBAFpBZevUEbSmMM87aO0Sp+wOZy2ZXf5yODmXQ==", + "dependencies": { + "uint8arrays": "^6.0.0" + } + }, "node_modules/@modelcontextprotocol/sdk": { "version": "1.32.2", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.2.tgz", diff --git a/sdk/js/package.json b/sdk/js/package.json index c2e1e4feb..0cc377c16 100644 --- a/sdk/js/package.json +++ b/sdk/js/package.json @@ -59,6 +59,7 @@ "@libp2p/tls": "^3.1.10", "@libp2p/utils": "^7.4.1", "@libp2p/websockets": "^10.1.21", + "@libp2p/webtransport": "^6.0.44", "@modelcontextprotocol/sdk": "^1.32.1", "@multiformats/multiaddr": "^13.0.3", "@noble/curves": "^2.0.1", diff --git a/sdk/js/src/host.ts b/sdk/js/src/host.ts index a16a60173..097e019f5 100644 --- a/sdk/js/src/host.ts +++ b/sdk/js/src/host.ts @@ -16,7 +16,7 @@ // agentmesh-node's is (internal/node/node.go): yamux the muxer, circuit relay v2 // for reachability through the routers. Transports and the security // protocol come from the runtime (platform/transports.ts): on Node TCP and -// WebSocket with TLS, in a browser WebSocket with Noise. +// WebSocket with TLS, in a browser WebSocket and WebTransport with Noise. import { yamux } from "@chainsafe/libp2p-yamux"; import { circuitRelayTransport } from "@libp2p/circuit-relay-v2"; diff --git a/sdk/js/src/platform/transports.browser.ts b/sdk/js/src/platform/transports.browser.ts index 0ffaa4d03..12bde4247 100644 --- a/sdk/js/src/platform/transports.browser.ts +++ b/sdk/js/src/platform/transports.browser.ts @@ -12,19 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -// How a member in a browser reaches the mesh: WebSocket, the one transport a -// page can open to a router (agentmesh-one's single port, or a router behind a -// TLS-terminating proxy as wss), secured with Noise. A browser cannot run -// libp2p's TLS, which needs a self-signed certificate over a raw socket; -// routers and nodes accept Noise beside TLS, and both bind the connection to -// the peer ID. +// A browser reaches a router over WebSocket or WebTransport. WebTransport works +// by IP: the browser checks the router's certificate against the certhash in +// its address. A browser can't run libp2p's TLS, so it secures both with Noise. import { noise } from "@chainsafe/libp2p-noise"; import { webSockets } from "@libp2p/websockets"; +import { webTransport } from "@libp2p/webtransport"; import type { Libp2pOptions } from "libp2p"; export function transports(): NonNullable { - return [webSockets()]; + return [webSockets(), webTransport()]; } export function connectionEncrypters(): NonNullable { diff --git a/site/content/docs/guides/native-sdks.md b/site/content/docs/guides/native-sdks.md index 157c8108c..c9c56b3db 100644 --- a/site/content/docs/guides/native-sdks.md +++ b/site/content/docs/guides/native-sdks.md @@ -946,12 +946,17 @@ The JS SDK is the same package in a page. `AgentMesh.enroll`, `join`, `acceptA2A`, `fetch()` and the rest work as above; what differs is how the page reaches the mesh and where it keeps its state: -- The page connects to a router over WebSocket and secures the connection - with Noise. Routers and nodes offer TLS first and accept Noise, so a - Node, Python or Go member reached through a relay meets the page on - Noise, end to end. `agentmesh-one` listens on WebSocket by default; behind - `--tunnel` or any TLS-terminating proxy it advertises the router as - `wss`, which a page served over `https` needs. +- The page connects to a router over WebSocket or WebTransport and secures + the connection with Noise. Routers and nodes offer TLS first and accept + Noise, so a Node, Python or Go member reached through a relay meets the + page on Noise, end to end. `agentmesh-one` listens on WebSocket by default; + behind `--tunnel` or any TLS-terminating proxy it advertises the router as + `wss`, which a page served over `https` needs. A router started with + `--listen /ip4/0.0.0.0/udp//quic-v1/webtransport` beside its QUIC + listener is reached by IP address: the page checks the router's + self-signed certificate against the `certhash` in the address the router + advertises. A page with a Content Security Policy allows `https:` in + `connect-src` for it. - The control plane answers the page's requests from any origin. Enrollment and refresh authenticate by the token or biscuit the request carries, so a page on another origin sends nothing a program could not send already. diff --git a/site/content/docs/reference/router.md b/site/content/docs/reference/router.md index e85a6f16a..db0066e01 100644 --- a/site/content/docs/reference/router.md +++ b/site/content/docs/reference/router.md @@ -35,8 +35,8 @@ replica count. |---|---|---| | `--control-plane` | `http://127.0.0.1:8080` | Control plane URL. `https://` is required unless the host is loopback. | | `--insecure-control-plane` | `false` | Accept plaintext `http://` to a non-loopback host, such as an in-cluster Service. | -| `--listen` | `/ip4/0.0.0.0/tcp/5001`, `/ip6/::/tcp/5001` | libp2p listen addresses. Repeatable. Add `/ip4/0.0.0.0/udp/5001/quic-v1` for QUIC. | -| `--external-addr` | none | Addresses to announce instead of the detected ones, such as `/dnsaddr/bootstrap.example.com` or `/ip4//tcp/5001`. Repeatable. | +| `--listen` | `/ip4/0.0.0.0/tcp/5001`, `/ip6/::/tcp/5001` | libp2p listen addresses. Repeatable. Add `/ip4/0.0.0.0/udp/5001/quic-v1` for QUIC, and `/ip4/0.0.0.0/udp/5001/quic-v1/webtransport` for WebTransport on the same port. | +| `--external-addr` | none | Addresses to announce instead of the detected ones, such as `/dnsaddr/bootstrap.example.com` or `/ip4//tcp/5001`. Repeatable. If the router also listens on `/webtransport`, it announces a `/webtransport` address for each external QUIC address, given here or found under its peer ID in a `/dnsaddr`. A `/dnsaddr` record that names another `/dnsaddr` is not followed. The external QUIC address must reach the port of the `/webtransport` listener. The router adds the certhash, because it changes and cannot be configured. | | `--keys-path` | `router.key` | The router's private key. It fixes the peer ID across restarts and belongs on persistent storage. | | `--control-plane-sync-interval` | `5m` | How often the router's one pass over the control plane runs: it renews the lease, re-reads `/info`, `/keys` and `/policies`, and refreshes its own credential when it nears expiry. A mesh event runs a pass at once. Must be well below the control plane's `--lease-duration` and `--key-grace-period`. | | `--allow-loopback` | `false` | Announce and accept loopback and link-local addresses. For a router and nodes on one host. | diff --git a/tests/ui/browser-sdk.spec.js b/tests/ui/browser-sdk.spec.js index ce5abdced..af6109b3f 100644 --- a/tests/ui/browser-sdk.spec.js +++ b/tests/ui/browser-sdk.spec.js @@ -18,7 +18,8 @@ // a Node member, calls a Node agent, and after a reload resumes the saved // enrollment without a token. Once against agentmesh-one directly and once behind // a TLS-terminating edge reached by name, the topology `agentmesh-one --tunnel` -// leaves the page in, where the router is advertised as wss. +// leaves the page in, where the router is advertised as wss. A last test adds +// a router that the page reaches by IP over WebTransport. const { test, expect } = require('@playwright/test'); const stack = require('./lib/agentmesh-one'); @@ -97,3 +98,43 @@ for (const topology of topologies) { } }); } + +// The router announces a QUIC address by IP and listens on WebTransport on +// the same port; it has no WebSocket listener and no CA certificate. The page +// reads the router's WebTransport address from the control plane, dials it, +// and completes the mesh handshake with the router on that connection. +test('a browser page reaches a router by IP over WebTransport', async ({ page }) => { + const why = stack.missing(); + test.skip(why !== '', why); + + const stops = []; + try { + const samOne = await stack.startSamOne(); + stops.push(() => samOne.stop()); + const router = await stack.startWebTransportRouter(samOne); + stops.push(() => router.stop()); + expect(router.leased.filter((addr) => addr.startsWith(`${router.externalAddr}/webtransport/certhash/`)), `leased: ${router.leased}`).toHaveLength(1); + const site = await stack.serveStatic(stack.PAGE_DIR); + stops.push(() => site.stop()); + + const query = new URLSearchParams({ controlPlaneUrl: samOne.publicUrl, bootstrapToken: samOne.joinToken, allowInsecure: 'true' }); + await page.goto(`${site.url}/?${query}`); + await page.getByRole('button', { name: 'Join' }).click(); + await expect(page.locator('#status')).toContainText('accepting a2a://agent', { timeout: 30_000 }); + + // The page's open connections to the router, then "admitted" once the + // router passed the mesh handshake. + const toRouter = () => + page.evaluate((routerPeer) => { + const { node, routers } = window.agentmesh.session; + const open = node.getConnections().filter((c) => c.remotePeer.toString() === routerPeer && c.status === 'open'); + return [...open.map((c) => c.remoteAddr.toString()), routers.some((r) => r.peerId === routerPeer) ? 'admitted' : 'not admitted'].join(' '); + }, router.peerId); + await expect.poll(toRouter, { timeout: 30_000 }).toMatch(/^\S+\/webtransport\/certhash\/\S+ admitted$/); + expect((await toRouter()).startsWith(`${router.externalAddr}/webtransport/certhash/`)).toBe(true); + } finally { + for (const stop of stops.reverse()) { + stop(); + } + } +}); diff --git a/tests/ui/lib/agentmesh-one.js b/tests/ui/lib/agentmesh-one.js index 05dc17df2..6f76c118b 100644 --- a/tests/ui/lib/agentmesh-one.js +++ b/tests/ui/lib/agentmesh-one.js @@ -15,9 +15,11 @@ // The pieces the browser SDK test stands up around Chromium: agentmesh-one from // bin/, a TLS-terminating edge in front of it that routes by name the way // `agentmesh-one --tunnel` puts one there, a static server for the page, and the -// Node example programs from sdk/js as the other members. +// Node example programs from sdk/js as the other members, and agentmesh-router +// from bin/ as a second router that a page reaches over WebTransport. const { spawn, spawnSync } = require('node:child_process'); +const dgram = require('node:dgram'); const fs = require('node:fs'); const http = require('node:http'); const https = require('node:https'); @@ -35,6 +37,9 @@ function missing() { if (!fs.existsSync(path.join(REPO_ROOT, 'bin', 'agentmesh-one'))) { return 'bin/agentmesh-one is not built (make build)'; } + if (!fs.existsSync(path.join(REPO_ROOT, 'bin', 'agentmesh-router'))) { + return 'bin/agentmesh-router is not built (make build)'; + } if (!fs.existsSync(path.join(PAGE_DIR, 'index.html')) || !fs.existsSync(path.join(SDK_JS, 'build', 'examples', 'a2a-call.js'))) { return 'the sdk/js browser example is not built (tests/ui/run.sh builds it)'; } @@ -52,6 +57,17 @@ function freePort() { }); } +function freeUDPPort() { + return new Promise((resolve, reject) => { + const sock = dgram.createSocket('udp4'); + sock.on('error', reject); + sock.bind(0, '127.0.0.1', () => { + const { port } = sock.address(); + sock.close(() => resolve(port)); + }); + }); +} + async function waitFor(url, what, tries = 100) { for (let i = 0; i < tries; i++) { try { @@ -88,6 +104,7 @@ async function startSamOne({ externalUrl } = {}) { } return { localUrl, + dataDir, publicUrl: externalUrl ?? localUrl, joinToken: fs.readFileSync(path.join(dataDir, 'join-token'), 'utf8').trim(), get output() { @@ -100,6 +117,40 @@ async function startSamOne({ externalUrl } = {}) { }; } +/** + * Runs bin/agentmesh-router against samOne with QUIC and WebTransport on one + * loopback UDP port, announced by --external-addr as an operator announces a + * public address. Resolves once the router has leased its addresses. + */ +async function startWebTransportRouter(samOne) { + const minted = spawnSync(path.join(REPO_ROOT, 'bin', 'agentmesh-one'), ['token', 'create', '--role', 'mesh:role:router', '--data-dir', samOne.dataDir, '--server', samOne.localUrl], { encoding: 'utf8' }); + const token = /^Token:\s+(\S+)/m.exec(minted.stdout ?? '')?.[1]; + if (minted.status !== 0 || !token) { + throw new Error(`agentmesh-one token create exited with ${minted.status}: ${minted.stderr}`); + } + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agentmesh-router-ui-')); + fs.writeFileSync(path.join(dir, 'token'), token + '\n', { mode: 0o600 }); + const externalAddr = `/ip4/127.0.0.1/udp/${await freeUDPPort()}/quic-v1`; + const args = ['--control-plane', samOne.localUrl, '--bootstrap-token-path', path.join(dir, 'token'), '--keys-path', path.join(dir, 'router.key'), '--listen', externalAddr, '--listen', `${externalAddr}/webtransport`, '--external-addr', externalAddr]; + const proc = spawn(path.join(REPO_ROOT, 'bin', 'agentmesh-router'), args, { stdio: ['ignore', 'pipe', 'pipe'] }); + let output = ''; + proc.stdout.on('data', (d) => (output += d)); + proc.stderr.on('data', (d) => (output += d)); + const stop = () => { + proc.kill(); + fs.rmSync(dir, { recursive: true, force: true }); + }; + for (let i = 0; i < 300; i++) { + const leased = /Lease advertises \d+ address\(es\): \[(.*)\]/.exec(output)?.[1]; + if (leased) { + return { externalAddr, leased: leased.split(' '), peerId: /\/p2p\/(12D3Koo\w+)/.exec(leased)[1], stop }; + } + await new Promise((r) => setTimeout(r, 100)); + } + stop(); + throw new Error(`agentmesh-router did not lease its addresses:\n${output}`); +} + /** A self-signed certificate for host, from openssl; null when openssl is not installed. */ function selfSignedCert(host) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sam-edge-')); @@ -246,4 +297,4 @@ function exampleEnv({ publicUrl, joinToken, caFile }, stateName) { }; } -module.exports = { PAGE_DIR, missing, freePort, startSamOne, selfSignedCert, startTLSEdge, serveStatic, runExample, startExampleAgent, exampleEnv }; +module.exports = { PAGE_DIR, missing, freePort, startSamOne, startWebTransportRouter, selfSignedCert, startTLSEdge, serveStatic, runExample, startExampleAgent, exampleEnv };