From 80494a2a9e6943dba5c60ae900da2c683ebf70c3 Mon Sep 17 00:00:00 2001 From: Josh Allmann Date: Sat, 5 Dec 2026 00:47:06 -0800 Subject: [PATCH] Support fixed-query discovery endpoints --- discovery/app.go | 10 +++++- discovery/app_test.go | 43 +++++++++++++++++------ discovery/server.go | 56 +++++++++++------------------- discovery/server_test.go | 21 ++++++++--- discovery/shared/inventory.go | 29 ++++++++++++++-- discovery/shared/inventory_test.go | 14 ++++++++ docs/discovery.md | 19 +++++++--- docs/http-api.md | 11 +++--- docs/signer.md | 17 +++++---- signer/app.go | 4 +-- signer/app_test.go | 19 ++++++++++ signer/discovery_polling_test.go | 9 +++-- signer/discovery_test.go | 27 +++++++++++++- signer/discovery_webhook.go | 2 +- signer/discovery_webhook_test.go | 7 ++-- signer/service.go | 16 ++++++--- 16 files changed, 222 insertions(+), 82 deletions(-) diff --git a/discovery/app.go b/discovery/app.go index f34d60d..ecd53e2 100644 --- a/discovery/app.go +++ b/discovery/app.go @@ -12,6 +12,7 @@ import ( "net/url" "os" "os/signal" + "slices" "sync" "syscall" "time" @@ -54,9 +55,16 @@ func Root(out, errOut io.Writer) *cobra.Command { return boa.NewUserInputError(err) } defer app.Close() + nodes := slices.Clone(p.Nodes) + for i, node := range nodes { + if node.Value.RawQuery != "" { + nodes[i].Value = node.Value.Clone() + nodes[i].Value.RawQuery = "REDACTED" + } + } return toml.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{ "Network": &p.Network, "Listen": &p.Listen, "MetricsListen": &p.MetricsListen, - "Nodes": &p.Nodes, "Grants": &p.Grants, + "Nodes": &nodes, "Grants": &p.Grants, "AdvertiseNodes": &p.AdvertiseNodes, "AdvertiseRunners": &p.AdvertiseRunners, "RefreshInterval": &p.RefreshInterval, "MaxFailedRefreshes": &p.MaxFailedRefreshes, }) diff --git a/discovery/app_test.go b/discovery/app_test.go index 2365ec1..8733700 100644 --- a/discovery/app_test.go +++ b/discovery/app_test.go @@ -88,6 +88,7 @@ func TestDiscoveryConfigDefaultsAndPrecedence(t *testing.T) { t.Setenv("HOME", t.TempDir()) out, err := execute(t, "--config=", "--print-config") require.NoError(t, err) + require.NotContains(t, out, "\nNodes =") for _, value := range []string{`Listen = "127.0.0.1:8939"`, `MetricsListen = "127.0.0.1:8940"`, `AdvertiseNodes = true`, `AdvertiseRunners = true`, `MaxFailedRefreshes = 6`, `RefreshInterval = "5m0s"`} { require.Contains(t, out, value) } @@ -111,6 +112,9 @@ func TestDiscoveryConfigDefaultsAndPrecedence(t *testing.T) { require.NoError(t, err) require.Contains(t, out, `Listen = "unsafe@[::]:8939"`) require.Contains(t, out, `MetricsListen = "unsafe@0.0.0.0:8940"`) + out, err = execute(t, "--nodes=", "--print-config") + require.NoError(t, err) + require.Contains(t, out, "\nNodes = []") } func TestDiscoveryInvalidConfig(t *testing.T) { @@ -119,7 +123,8 @@ func TestDiscoveryInvalidConfig(t *testing.T) { {"--metrics-listen="}, {"--metrics-listen=0.0.0.0:8940"}, {"--listen="}, {"--listen=[::]:8939"}, {"--nodes=ftp://child.example"}, {"--nodes=https://user:secret@child.example"}, - {"--nodes=https://child.example?token=secret"}, {"--nodes=https://child.example#fragment"}, {"--runner-config=unused"}, + {"--nodes=https://child.example?"}, {"--nodes=https://child.example?x=1#fragment"}, {"--runner-config=unused"}, + {"--nodes=https://child.example?region=west coast"}, } { for _, mode := range []string{"--print-config", "--dump"} { out, err := execute(t, append(args, "--config=", mode)...) @@ -216,28 +221,44 @@ func TestDiscoveryDumpResults(t *testing.T) { func TestDiscoveryDumpConfiguration(t *testing.T) { t.Setenv("HOME", t.TempDir()) - paths := make(chan string, 3) + const query = "?orchestrator=0x1111111111111111111111111111111111111111&tag=a%2Fb&tag=c%20d" + const fileEndpoint = "/file%2Fdeploy/%64iscovery" + requests := make(chan string, 3) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - paths <- r.URL.Path + requests <- r.RequestURI _, _ = io.WriteString(w, "[]") })) defer upstream.Close() config := filepath.Join(t.TempDir(), "discovery.toml") - require.NoError(t, os.WriteFile(config, fmt.Appendf(nil, "Nodes = [%q]\nGrants = [%q]\nAdvertiseNodes = false\n", upstream.URL+"/file", strings.TrimPrefix(upstream.URL, "http://")), 0600)) - for _, source := range []string{"file", "env", "cli"} { - if source == "env" { + require.NoError(t, os.WriteFile(config, fmt.Appendf(nil, "Nodes = [%q]\nGrants = [%q]\n", upstream.URL+fileEndpoint+query, strings.TrimPrefix(upstream.URL, "http://")), 0600)) + printed, err := execute(t, "--print-config", "--config", config) + require.NoError(t, err) + require.Contains(t, printed, upstream.URL+fileEndpoint+"?REDACTED") + require.NotContains(t, printed, "orchestrator=") + schema := discoverySchema(t) + for _, tc := range []struct{ source, request, advertised string }{ + {"file", fileEndpoint + query, "/file%2Fdeploy"}, + {"env", "/env/discovery", "/env"}, + {"cli", "/cli/catalog/" + query, "/cli/catalog/"}, + } { + if tc.source == "env" { t.Setenv("LIVEPEER_DISCOVERY_NODES", upstream.URL+"/env") } args := []string{"--dump", "--config", config} - if source == "cli" { - args = append(args, "--nodes", upstream.URL+"/cli") + if tc.source == "cli" { + args = append(args, "--nodes", upstream.URL+tc.request) } out, err := execute(t, args...) require.NoError(t, err) - require.Equal(t, "[]\n", out) + require.NoError(t, validateDiscoveryJSON(t, schema, []byte(out))) + var entries []struct{ Nodes []discoveryNode } + require.NoError(t, json.Unmarshal([]byte(out), &entries)) + require.Len(t, entries, 1) + require.Len(t, entries[0].Nodes, 1) + require.Equal(t, upstream.URL+tc.advertised, entries[0].Nodes[0].URL) select { - case path := <-paths: - require.Equal(t, "/"+source+"/discovery", path) + case request := <-requests: + require.Equal(t, tc.request, request) default: t.Fatal("configured source was not queried") } diff --git a/discovery/server.go b/discovery/server.go index 89e3e44..3d7b85b 100644 --- a/discovery/server.go +++ b/discovery/server.go @@ -27,30 +27,12 @@ type Server struct { metrics *observability.Metrics logger *slog.Logger mux *http.ServeMux - urls []*url.URL + hasSources bool interval time.Duration advertiseNodes, advertiseRunners bool collector *discovery.Collector[discoveryRunner] } -func discoveryBases(p Params) ([]*url.URL, error) { - urls := make([]*url.URL, 0, len(p.Nodes)) - seen := map[string]bool{} - for _, item := range p.Nodes { - if err := discovery.ValidateURL(item.Value); err != nil { - return nil, err - } - u := item.Value.Clone() - u.RawPath = strings.TrimRight(u.EscapedPath(), "/") - u.Path, _ = url.PathUnescape(u.RawPath) - if !seen[u.String()] { - seen[u.String()] = true - urls = append(urls, u) - } - } - return urls, nil -} - // NewServer configures an inventory collector without runner or payment dependencies. func NewServer(p Params, logger *slog.Logger) (*Server, error) { if !p.Listen.IsValid() || !p.MetricsListen.IsValid() { @@ -62,9 +44,13 @@ func NewServer(p Params, logger *slog.Logger) (*Server, error) { if p.MaxFailedRefreshes < 0 { return nil, errors.New("--max-failed-refreshes must be nonnegative") } - urls, err := discoveryBases(p) - if err != nil { - return nil, err + endpoints := make([]*url.URL, 0, len(p.Nodes)) + for _, node := range p.Nodes { + endpoint, err := discovery.StaticEndpoint(node.Value) + if err != nil { + return nil, err + } + endpoints = append(endpoints, endpoint) } policy, err := destination.New("discovery", p.Grants) if err != nil { @@ -75,18 +61,9 @@ func NewServer(p Params, logger *slog.Logger) (*Server, error) { client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } metrics := observability.New("discovery") s := &Server{metrics: metrics, logger: logger.With("component", "discovery"), mux: http.NewServeMux(), - urls: urls, interval: p.RefreshInterval, + hasSources: len(endpoints) > 0, interval: p.RefreshInterval, advertiseNodes: p.AdvertiseNodes, advertiseRunners: p.AdvertiseRunners, collector: &discovery.Collector[discoveryRunner]{Client: client, MaxFailures: max(1, p.MaxFailedRefreshes), Logger: logger.With("component", "discovery"), Observe: metrics.Discovery}} - endpoints := make([]*url.URL, 0, len(urls)) - for _, base := range urls { - endpoint := base.Clone() - endpoint.Path += "/discovery" - if endpoint.RawPath != "" { - endpoint.RawPath += "/discovery" - } - endpoints = append(endpoints, endpoint) - } s.collector.SetSources(endpoints) s.mux.HandleFunc("GET /discovery", s.discovery) metrics.Snapshot(s.collector.CollectMetrics) @@ -129,7 +106,7 @@ func (s *Server) discoveryBody(ctx context.Context) ([]byte, error) { // dump collects one complete inventory on a fresh server, then closes it. func (s *Server) dump(ctx context.Context, out io.Writer) error { defer s.Close() - collect := len(s.urls) > 0 && (s.advertiseNodes || s.advertiseRunners) + collect := s.hasSources && (s.advertiseNodes || s.advertiseRunners) if collect { s.collector.Refresh(ctx, false) } @@ -159,7 +136,7 @@ func (s *Server) dump(ctx context.Context, out io.Writer) error { // Run refreshes immediately and periodically until ctx ends. Run it once and // wait for it to return before closing the server. func (d *Server) Run(ctx context.Context) { - if (!d.advertiseNodes && !d.advertiseRunners) || len(d.urls) == 0 { + if (!d.advertiseNodes && !d.advertiseRunners) || !d.hasSources { return } d.collector.Run(ctx, d.interval) @@ -170,7 +147,16 @@ func (s *Server) discoveryResponse() []map[string]any { entries := []discoveryEntry{} for _, snapshot := range s.collector.Snapshots() { if s.advertiseNodes { - nodes = append(nodes, discoveryNode{URL: strings.TrimSuffix(snapshot.URL, "/discovery"), QueriedAt: snapshot.QueriedAt}) + u, _ := url.Parse(snapshot.URL) // A successful snapshot came from a parsed HTTP request. + u.RawQuery = "" + path := u.EscapedPath() + lastSlash := strings.LastIndexByte(path, '/') + lastSegment, _ := url.PathUnescape(path[lastSlash+1:]) + if lastSlash >= 0 && lastSegment == "discovery" { + u.RawPath = path[:lastSlash] + u.Path, _ = url.PathUnescape(u.RawPath) + } + nodes = append(nodes, discoveryNode{URL: u.String(), QueriedAt: snapshot.QueriedAt}) } if s.advertiseRunners { entries = append(entries, snapshot.Entries...) diff --git a/discovery/server_test.go b/discovery/server_test.go index 6268931..8eb5135 100644 --- a/discovery/server_test.go +++ b/discovery/server_test.go @@ -177,11 +177,22 @@ func TestDiscoveryBoundedConcurrencyAndPartialResults(t *testing.T) { } func TestDiscoverySources(t *testing.T) { - s := discoveryTestServer(t, "https://child.example/", "https://child.example") - require.Len(t, s.urls, 1) - encoded := discoveryTestServer(t, "https://child.example/deploy%2F/", "https://child.example/deploy%2F") - require.Len(t, encoded.urls, 1) - require.Equal(t, "https://child.example/deploy%2F", encoded.urls[0].String()) + const base = "https://child.example" + const catalog = base + "/catalog?orchestrator=" + sources := []string{base, base + "/", base + "/deploy%2F/", base + "/deploy%2F", catalog + "a", catalog + "a", catalog + "b"} + s := discoveryTestServer(t, sources...) + requests := make(chan string, len(sources)) + s.collector.Client.Transport = discoveryRoundTrip(func(r *http.Request) (*http.Response, error) { + requests <- r.URL.RequestURI() + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("[]"))}, nil + }) + s.collector.Refresh(t.Context(), false) + close(requests) + var queried []string + for uri := range requests { + queried = append(queried, uri) + } + require.ElementsMatch(t, []string{"/discovery", "/deploy%2F/discovery", "/catalog?orchestrator=a", "/catalog?orchestrator=b"}, queried) } func TestDiscoveryFailureThreshold(t *testing.T) { diff --git a/discovery/shared/inventory.go b/discovery/shared/inventory.go index 2836232..e7a9a9f 100644 --- a/discovery/shared/inventory.go +++ b/discovery/shared/inventory.go @@ -24,14 +24,39 @@ type Entry[R Runner] struct { Runners []R `json:"runners"` } -// ValidateURL checks discovery base URLs, retaining deployment paths. +// ValidateURL checks the query-free base URLs carried in inventories. func ValidateURL(u *url.URL) error { - if destination.ValidateURL(u) != nil || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" { + if ValidateEndpointURL(u) != nil || u.RawQuery != "" { return errors.New("discovery URL must be absolute HTTP(S) without credentials, query or fragment") } return nil } +// ValidateEndpointURL checks polling URLs, which may carry a fixed query. +func ValidateEndpointURL(u *url.URL) error { + if destination.ValidateURL(u) != nil || u.User != nil || u.Fragment != "" || u.ForceQuery && u.RawQuery == "" { + return errors.New("discovery URL must be absolute HTTP(S) without credentials, an empty query, or a fragment") + } + if strings.ContainsFunc(u.RawQuery, func(r rune) bool { return r <= ' ' || r == '\x7f' }) { + return errors.New("discovery URL query contains an unescaped space or control character") + } + return nil +} + +// StaticEndpoint adds /discovery to a configured base URL and preserves complete +// endpoints identified by a nonempty query. +func StaticEndpoint(u *url.URL) (*url.URL, error) { + if err := ValidateEndpointURL(u); err != nil { + return nil, err + } + endpoint := u.Clone() + if endpoint.RawQuery == "" { + endpoint.RawPath = strings.TrimRight(endpoint.EscapedPath(), "/") + "/discovery" + endpoint.Path, _ = url.PathUnescape(endpoint.RawPath) + } + return endpoint, nil +} + func Read(body io.Reader) ([]byte, error) { data, err := io.ReadAll(io.LimitReader(body, MaxBody+1)) if err != nil || len(data) > MaxBody { diff --git a/discovery/shared/inventory_test.go b/discovery/shared/inventory_test.go index 8d63f67..d34d46e 100644 --- a/discovery/shared/inventory_test.go +++ b/discovery/shared/inventory_test.go @@ -2,6 +2,7 @@ package shared import ( "fmt" + "net/url" "strings" "testing" "time" @@ -9,6 +10,18 @@ import ( "github.com/stretchr/testify/require" ) +func TestStaticEndpointQuery(t *testing.T) { + configured := &url.URL{ + Scheme: "https", Host: "catalog.example", Path: "/inventory", ForceQuery: true, RawQuery: "orchestrator=one", + } + endpoint, err := StaticEndpoint(configured) + require.NoError(t, err) + require.Equal(t, "https://catalog.example/inventory?orchestrator=one", endpoint.String()) + configured.RawQuery += "\t" + _, err = StaticEndpoint(configured) + require.ErrorContains(t, err, "control character") +} + type record struct { URL string `json:"url"` App string `json:"app"` @@ -42,6 +55,7 @@ func TestDecodeValidation(t *testing.T) { {"missing timestamp", envelope(`{"url":"https://r.example","app":"test"}`), 0, true}, {"wrong timestamp type", envelope(`{"url":"https://r.example","app":"test","observed_at":123}`), 0, true}, {"bad address", strings.ReplaceAll(envelope(valid), "https://orch.example", "file:///bad"), 0, true}, + {"address with query", strings.ReplaceAll(envelope(valid), "https://orch.example", "https://orch.example?orchestrator=test"), 0, true}, {"wrong runner list", `[{"address":"https://orch.example","runners":{}}]`, 0, true}, {"trailing JSON", envelope(valid) + `[]`, 0, true}, {"null", "null", 0, true}, {"before skew", envelope(candidate(now.Add(ClockSkew - time.Nanosecond).Format(time.RFC3339Nano))), 1, false}, diff --git a/docs/discovery.md b/docs/discovery.md index 6a6011e..520fecb 100644 --- a/docs/discovery.md +++ b/docs/discovery.md @@ -4,7 +4,7 @@ Discovery collects and caches runner inventories from orchestrators and other discovery sources. It owns no runners and needs no runner or payment credentials. Copy the [configuration example](../configs/discovery/config.example.toml), set -`Nodes` to your source base URLs, and run: +`Nodes` to your discovery base URLs, and run: ```sh livepeer discovery --config /etc/livepeer/discovery.toml @@ -22,10 +22,19 @@ partial output. `--dump` is CLI-only and conflicts with `--print-config`. ## Sources and cache -Each source is queried at `/discovery`, retaining any deployment path. -Duplicate URLs are skipped. Private sources require -`Grants`, such as `127.0.0.1:8935` for a local orchestrator. Redirects and URLs in -returned node metadata are not followed. +Each entry in `Nodes` (`--nodes`) is normally a discovery base URL, queried at +`/discovery` while retaining any deployment path. A configured URL +with a nonempty query, such as +`https://catalog.example/deployment/discovery?orchestrator=0x1111111111111111111111111111111111111111`, +is polled as a complete endpoint. The upstream service interprets the query. +A bare `?` is invalid. The signer's `Orchestrators` (`--orchestrators`) follows +the same rules. For literal commas in URLs, the flags accept CSV with quoting, +environment lists split on commas, and TOML arrays preserve literal commas. + +Duplicate polling URLs are skipped. Standalone discovery's `--print-config` +replaces source queries with `REDACTED`. Private sources require `Grants`, such +as `127.0.0.1:8935` for a local orchestrator. Redirects and URLs in returned +node metadata are not followed. Refreshes run at startup and every `RefreshInterval` (default `5m`), with at most five concurrent requests, a three-second timeout, and a 3 MiB limit per response. diff --git a/docs/http-api.md b/docs/http-api.md index 1e7657f..bc7c41f 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -79,10 +79,13 @@ metadata/GPU fields. Known fields must use the documented casing and types. Discovery skips malformed records, including duplicate keys and invalid Unicode. Discovery preserves complete runner records. `nodes` lists successfully queried, -non-evicted sources, and `queried_at` records each source's last successful query -time. Empty node and runner lists are omitted. With neither to advertise, discovery -returns `[]`. See [discovery setup](discovery.md) for caching, -advertising switches, limits, and metrics. +non-evicted sources, with `queried_at` recording each source's last successful +query time. Each advertised `url` strips any query and an exact final +`/discovery` path segment (including percent-encoded spellings), while retaining +other paths and trailing slashes. Empty node and runner lists are omitted. With +neither to advertise, discovery returns `[]`. See +[discovery setup](discovery.md) for caching, advertising switches, limits, and +metrics. `observed_at` is an RFC3339 timestamp, allowing fractional seconds. Orchestrators stamp local runners at response time; discovery preserves that timestamp. diff --git a/docs/signer.md b/docs/signer.md index b905f50..7e62f9a 100644 --- a/docs/signer.md +++ b/docs/signer.md @@ -55,16 +55,20 @@ and configure TLS termination at the proxy. ## Configure discovery -Set `Orchestrators` to orchestrator or standalone [discovery](discovery.md) -base URLs to query. Both expose the same inventory API. Local or private sources -also need [destination grants](configuration.md#destination-grants). For example: +Set `Orchestrators` (`--orchestrators`) to orchestrator or standalone +[discovery](discovery.md) base URLs to query. Both expose the same inventory +API. Local or private sources also need +[destination grants](configuration.md#destination-grants). For example: ```toml Orchestrators = ["http://127.0.0.1:8935"] DiscoveryGrants = ["127.0.0.1:8935"] ``` -The signer appends `/discovery` to static base URLs and uses webhook URLs unchanged. +The signer appends `/discovery` to static base URLs and uses webhook URLs as +provided. See the [discovery source URL rules](discovery.md#sources-and-cache) +for fixed-query endpoints and URLs containing commas. + It polls at startup and every `DiscoveryRefreshInterval` (positive, default `5m`). Inventory fetches have a five-second timeout and a 3 MiB limit. Failed polls retain the last inventory until `DiscoveryMaxFailedRefreshes` consecutive failures @@ -97,8 +101,9 @@ Use the [credential-file rules](configuration.md#credential-files) for URL and header secrets; private destinations need `DiscoveryGrants`. GET at the webhook URL returns `[{"address":"https://orch.example.com/discovery"}]`. -Addresses are complete HTTP(S) discovery URLs without credentials, queries, or -fragments. Invalid addresses and extra fields are ignored. +Addresses are complete HTTP(S) discovery endpoints, with or without a fixed +query. Credentials, fragments, and a bare `?` are invalid. Invalid addresses and +extra fields are ignored. Fetches run at startup and every positive `OrchestratorWebhookRefreshInterval` (default `5m`), with a three-second timeout, 1 MiB limit, and no redirects. diff --git a/signer/app.go b/signer/app.go index 9212d66..364dfb0 100644 --- a/signer/app.go +++ b/signer/app.go @@ -138,8 +138,8 @@ func (p Params) Validate() error { return errors.New("--eth-usd-feed requires positive --eth-usd-max-age") } for _, endpoint := range p.discoveryURLs() { - if err := discovery.ValidateURL(endpoint); err != nil { - return errors.New("--orchestrators must contain absolute HTTP or HTTPS URLs without credentials, query or fragment") + if err := discovery.ValidateEndpointURL(endpoint); err != nil { + return fmt.Errorf("invalid --orchestrators entry: %w", err) } } if _, err := destination.New("signer-discovery", p.DiscoveryGrants); err != nil { diff --git a/signer/app_test.go b/signer/app_test.go index e8ec4c5..6121a29 100644 --- a/signer/app_test.go +++ b/signer/app_test.go @@ -205,6 +205,25 @@ func loadSignerParams(t *testing.T, args []string, config string) (Params, error return p, err } +func TestSignerDiscoveryEndpointConfiguration(t *testing.T) { + const endpoint = "https://catalog.example/deployment/discovery?orchestrator=0x1111111111111111111111111111111111111111" + cli, err := loadSignerParams(t, []string{"--orchestrators", endpoint}, "") + require.NoError(t, err) + file, err := loadSignerParams(t, nil, fmt.Sprintf("Orchestrators = [%q]\n", endpoint)) + require.NoError(t, err) + for _, p := range []Params{cli, file} { + require.Len(t, p.Orchestrators, 1) + require.Equal(t, endpoint, p.Orchestrators[0].Value.String()) + } + const invalid = "https://catalog.example/discovery?token=private#fragment" + _, cliErr := loadSignerParams(t, []string{"--orchestrators", invalid}, "") + _, fileErr := loadSignerParams(t, nil, fmt.Sprintf("Orchestrators = [%q]\n", invalid)) + for _, err := range []error{cliErr, fileErr} { + require.ErrorContains(t, err, "invalid --orchestrators entry") + require.NotContains(t, err.Error(), "token=private") + } +} + func TestSignerDiscoveryGrantConfiguration(t *testing.T) { for _, test := range []struct { name string diff --git a/signer/discovery_polling_test.go b/signer/discovery_polling_test.go index 033d601..65d9a8d 100644 --- a/signer/discovery_polling_test.go +++ b/signer/discovery_polling_test.go @@ -21,10 +21,15 @@ func TestDiscoveryPollingStartupAndCache(t *testing.T) { for name, body := range map[string]string{"empty": "[]", "populated": `[{"address":"https://orch.example","runners":[{"url":"https://runner.example","app":"test","observed_at":"1999-01-01T00:00:00Z"}]}]`} { t.Run(name, func(t *testing.T) { synctest.Test(t, func(t *testing.T) { + source, request := "https://source.example/deployment/", "/deployment/discovery" + if name == "populated" { + request = "/deployment%2Fone/catalog/?orchestrator=0x1111111111111111111111111111111111111111&tag=a%2Fb&tag=c+d" + source = "https://source.example" + request + } s := newService(nil) defer s.Close() require.NoError(t, s.SetDiscoveryPolling(time.Minute, 5)) - require.NoError(t, s.SetDiscovery([]*url.URL{testURL(t, "https://source.example")})) + require.NoError(t, s.SetDiscovery([]*url.URL{testURL(t, source)})) var calls, cancellations, status atomic.Int32 status.Store(500) var gate atomic.Pointer[chan struct{}] @@ -32,7 +37,7 @@ func TestDiscoveryPollingStartupAndCache(t *testing.T) { gate.Store(&initial) s.collector.Client.Transport = webhookTransport(func(r *http.Request) (*http.Response, error) { calls.Add(1) - require.Empty(t, r.URL.RawQuery) + require.Equal(t, request, r.URL.RequestURI()) if waiting := gate.Load(); waiting != nil { select { case <-*waiting: diff --git a/signer/discovery_test.go b/signer/discovery_test.go index 80650d6..2684449 100644 --- a/signer/discovery_test.go +++ b/signer/discovery_test.go @@ -180,7 +180,7 @@ func TestSignerDiscoveryReplacement(t *testing.T) { previousCollector := s.collector tracker := new(discoveryCloseTracker) previous.Transport = tracker - for _, invalid := range []*url.URL{nil, testURL(t, "file:///discovery"), testURL(t, "https://user:password@orch.example"), testURL(t, "https://orch.example?token=secret"), testURL(t, "https://orch.example?"), testURL(t, "https://orch.example#fragment")} { + for _, invalid := range []*url.URL{nil, testURL(t, "file:///discovery"), testURL(t, "https://user:password@orch.example"), testURL(t, "https://orch.example?"), testURL(t, "https://orch.example?x=1#fragment")} { require.Error(t, s.SetDiscovery([]*url.URL{invalid})) require.Same(t, previous, s.collector.Client) } @@ -193,6 +193,31 @@ func TestSignerDiscoveryReplacement(t *testing.T) { require.True(t, tracker.closed) } +func TestSignerDiscoveryRedirectReferer(t *testing.T) { + const source = "https://catalog%CF%83.example/start?token=private" + for _, tc := range []struct{ name, location, referer string }{ + {"same origin", "/inventory", source}, + {"different port", "https://catalogσ.example:8443/inventory", ""}, + {"different hostname", "https://catalogĻ‚.example/inventory", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + s := newService(nil) + defer s.Close() + require.NoError(t, s.SetDiscovery([]*url.URL{testURL(t, source)})) + var referer string + s.collector.Client.Transport = webhookTransport(func(r *http.Request) (*http.Response, error) { + if r.URL.Path == "/start" { + return &http.Response{StatusCode: http.StatusFound, Header: http.Header{"Location": {tc.location}}, Body: http.NoBody}, nil + } + referer = r.Referer() + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("[]"))}, nil + }) + require.Equal(t, http.StatusOK, discoveryResponse(s, "").Code) + require.Equal(t, tc.referer, referer) + }) + } +} + func TestSignerDiscoveryFreshnessMerge(t *testing.T) { s := newService(nil) defer s.Close() diff --git a/signer/discovery_webhook.go b/signer/discovery_webhook.go index d2314e1..22678d9 100644 --- a/signer/discovery_webhook.go +++ b/signer/discovery_webhook.go @@ -147,7 +147,7 @@ func (h *orchestratorWebhook) fetch(ctx context.Context, transport http.RoundTri urls := make([]*url.URL, 0, len(entries)) for _, entry := range entries { candidate, err := url.Parse(entry.Address) - if err == nil && discovery.ValidateURL(candidate) == nil { + if err == nil && discovery.ValidateEndpointURL(candidate) == nil { urls = append(urls, candidate) } } diff --git a/signer/discovery_webhook_test.go b/signer/discovery_webhook_test.go index 9692e3a..951c5bd 100644 --- a/signer/discovery_webhook_test.go +++ b/signer/discovery_webhook_test.go @@ -20,6 +20,7 @@ import ( ) func TestOrchestratorWebhookDiscovery(t *testing.T) { + const query = "orchestrator=0x1111111111111111111111111111111111111111&tag=a%2Fb&tag=c+d" var webhookCalls, runnerCalls, staticCalls atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { base := "http://" + r.Host @@ -31,13 +32,13 @@ func TestOrchestratorWebhookDiscovery(t *testing.T) { require.Equal(t, "Bearer configured", r.Header.Get("Authorization")) require.Equal(t, []string{"one", "two"}, r.Header.Values("X-Webhook")) w.WriteHeader(http.StatusCreated) - _, _ = fmt.Fprintf(w, `[{"address":%q,"score":"ignored"},{"address":"http://%%private-token"},{"address":"file:///bad"}]`, base+"/orch%2Fdeployment/catalog") + _, _ = fmt.Fprintf(w, `[{"address":%q,"score":"ignored"},{"address":"http://%%private-token"},{"address":"file:///bad"},{"address":%q}]`, base+"/orch%2Fdeployment/catalog?"+query, base+"/bare?") case "/orch/deployment/catalog": require.Equal(t, "/orch%2Fdeployment/catalog", r.URL.EscapedPath()) calls := runnerCalls.Add(1) require.Empty(t, r.Header.Get("Authorization")) require.Empty(t, r.Header.Get("X-Webhook")) - require.Empty(t, r.URL.RawQuery, "fetch complete inventories before filtering") + require.Equal(t, query, r.URL.RawQuery, "client filters must not alter the inventory URL") _, _ = fmt.Fprintf(w, `[{"address":%q,"score":{"ignored":true},"runners":[{"url":%q,"observed_at":"2026-01-01T00:00:00Z","app":"example","gpu":{"name":" H100 "},"capacity_used":%d},{"url":%q,"observed_at":"2026-01-01T00:00:00Z","app":"other"}]}]`, base, base+"/app", calls, base+"/other") default: staticCalls.Add(1) @@ -65,6 +66,8 @@ func TestOrchestratorWebhookDiscovery(t *testing.T) { } require.Equal(t, int32(1), webhookCalls.Load()) require.Equal(t, int32(1), runnerCalls.Load()) + s.collector.Refresh(t.Context(), false) + require.Equal(t, int32(2), runnerCalls.Load()) require.Zero(t, staticCalls.Load()) } diff --git a/signer/service.go b/signer/service.go index 49bf650..48c09b0 100644 --- a/signer/service.go +++ b/signer/service.go @@ -84,16 +84,22 @@ func (s *Service) SetDiscovery(orchestrators []*url.URL, grants ...string) error } urls := make([]*url.URL, 0, len(orchestrators)) for _, candidate := range orchestrators { - if err := discovery.ValidateURL(candidate); err != nil { + endpoint, err := discovery.StaticEndpoint(candidate) + if err != nil { return err } - parsed := candidate.Clone() - parsed.RawPath = strings.TrimRight(parsed.EscapedPath(), "/") + "/discovery" - parsed.Path, _ = url.PathUnescape(parsed.RawPath) - urls = append(urls, parsed) + urls = append(urls, endpoint) } client := policy.Client() client.Timeout = 5 * time.Second + checkRedirect := client.CheckRedirect + client.CheckRedirect = func(req *http.Request, via []*http.Request) error { + previous := via[len(via)-1].URL + if previous.RawQuery != "" && (previous.Scheme != req.URL.Scheme || previous.Host != req.URL.Host) { + req.Header.Del("Referer") + } + return checkRedirect(req, via) + } s.collector.Close() s.collector = &discovery.Collector[discoveredRunner]{Client: client, MaxFailures: s.collector.MaxFailures, Observe: s.metrics.Discovery} if s.orchWebhook == nil {