From f3f153acc928fb2aed2793ca4baf9c4873ae4c04 Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Mon, 23 Nov 2026 14:42:00 -0600 Subject: [PATCH 1/4] pages: an opt-in public listener that serves share links and nothing else MUSTER_PAGES_PUBLIC_LISTEN=[host]:port opens a listener of its own that passes on only api.PagesPublicRoutes (a link's shell, content, assets, submit and upload, plus the shell's logo and icon) to the same handler the main listener serves; every other request is one 404 there, the UI, /api/, sign-in, /plugin/, MCP, /health and /metrics included. Cookies and credential headers are taken off every request and Set-Cookie off every response, so an owner's session grants nothing on it. Rate limits and caps are the share routes' own. MUSTER_PAGES_PUBLIC_URL is the base every handed-on link is written under (pageLinkURL, the one place a link's address is made); the owner's own view and every other link stay under MUSTER_PUBLIC_URL. The two are a pair, need MUSTER_PAGES=1 and a port of their own, and the URL must be an https origin (http only to loopback), or the server refuses to boot. The allowlist guard walks every route RegisterRoutes records and demands the routes that get through equal a hand-written ledger (grow or shrink fails). Mutation-checked: adding "GET /pages" to the list fails it with its own message; so do dropping a route, an identity surface, no credential strip, no Set-Cookie strip, no canonical-path check, and a link base that ignores the new URL. Co-Authored-By: Claude Opus 5.5 (1M context) --- cmd/muster-server/banner_test.go | 5 + cmd/muster-server/config.go | 60 +++++++ cmd/muster-server/features.go | 2 +- cmd/muster-server/main.go | 47 ++++- cmd/muster-server/pages_public_test.go | 107 +++++++++++ docs/architecture.md | 1 + docs/configuration.md | 4 +- docs/pages.md | 43 ++++- internal/api/ext.go | 6 + internal/api/pages.go | 11 +- internal/api/pages_public.go | 141 +++++++++++++++ internal/api/pages_public_pg_test.go | 217 +++++++++++++++++++++++ internal/api/pages_public_test.go | 236 +++++++++++++++++++++++++ tests/features_config_test.py | 6 + 14 files changed, 878 insertions(+), 8 deletions(-) create mode 100644 cmd/muster-server/pages_public_test.go create mode 100644 internal/api/pages_public.go create mode 100644 internal/api/pages_public_pg_test.go create mode 100644 internal/api/pages_public_test.go diff --git a/cmd/muster-server/banner_test.go b/cmd/muster-server/banner_test.go index de89716e4..fdec8bf2d 100644 --- a/cmd/muster-server/banner_test.go +++ b/cmd/muster-server/banner_test.go @@ -303,6 +303,8 @@ var bannerLedger = []string{ envHookToken, // The metrics listener: one line, both directions. envMetricsPort, + // The public pages listener: one line, both directions, naming both. + envPagesPublicListen, envPagesPublicURL, envServiceToken, envRouterURL, // The approval relay's own gate: its off-state is "every claude-code prompt @@ -858,6 +860,9 @@ func bannerBothDirections(t *testing.T) (onOut, offOut string) { UIPassword: strings.Repeat("p", 40), SecureCookies: true, MetricsPort: 18193, + PagesPublicListen: ":18194", + PagesPublicPort: 18194, + PagesPublicURL: "https://pages.example.invalid", AndroidAllowPINKeys: true, HookToken: "hook", ServiceToken: strings.Repeat("s", 40), diff --git a/cmd/muster-server/config.go b/cmd/muster-server/config.go index 364219900..67ba555d9 100644 --- a/cmd/muster-server/config.go +++ b/cmd/muster-server/config.go @@ -33,6 +33,7 @@ import ( "github.com/ZacxDev/muster/internal/focus" "github.com/ZacxDev/muster/internal/githubapp" "github.com/ZacxDev/muster/internal/jobs" + "github.com/ZacxDev/muster/internal/loopback" "github.com/ZacxDev/muster/internal/mirror" "github.com/ZacxDev/muster/internal/morning" "github.com/ZacxDev/muster/internal/notes" @@ -348,6 +349,12 @@ const ( // The bytes one page's files may hold in all (pages.DefaultUploadBytesPerPage // when unset), a byte count from 1 MiB to 100 GiB. envPagesUploadBytes = "MUSTER_PAGES_UPLOAD_BYTES" + // The public pages listener (api.PagesPublicSurface): an address, + // `[host]:port`, on which ONLY share links are served, and the base URL + // the links handed on are written under. Both or neither, and only with + // MUSTER_PAGES=1. + envPagesPublicListen = "MUSTER_PAGES_PUBLIC_LISTEN" + envPagesPublicURL = "MUSTER_PAGES_PUBLIC_URL" // THE CLAUDE ACCOUNT USAGE POLLER (internal/ccusage, docs/jobs.md "Claude // account usage"; ccusage_config.go parses them): its switch (off by @@ -989,6 +996,13 @@ type config struct { Pages bool // PagesUploadBytes is MUSTER_PAGES_UPLOAD_BYTES (0: the default). PagesUploadBytes int64 + // PagesPublicListen is MUSTER_PAGES_PUBLIC_LISTEN, the public pages + // listener's address ("" : none), and PagesPublicPort its port. + PagesPublicListen string + PagesPublicPort int + // PagesPublicURL is MUSTER_PAGES_PUBLIC_URL without a trailing slash: the + // base of every share link's address while the listener is on. + PagesPublicURL string // CCUsage is the Claude account usage poller's (ccusage_config.go). CCUsage ccUsageConfig @@ -2166,6 +2180,15 @@ func loadConfig(getenv func(string) string) (config, error) { } c.PagesUploadBytes = n } + if v := strings.TrimSpace(getenv(envPagesPublicListen)); v != "" { + _, port, err := net.SplitHostPort(v) + p, perr := strconv.Atoi(port) + if err != nil || perr != nil || p < 1 || p > 65535 { + return config{}, fmt.Errorf("invalid %s %q: want [host]:port with a numeric port 1-65535, e.g. :8108", envPagesPublicListen, v) + } + c.PagesPublicListen, c.PagesPublicPort = v, p + } + c.PagesPublicURL = strings.TrimRight(strings.TrimSpace(getenv(envPagesPublicURL)), "/") if c.AskLog, err = parseAskLog(getenv); err != nil { return config{}, err } @@ -2726,6 +2749,40 @@ func isHexDigits(v string) bool { // than an inconsistency: the assembly path and the deployment policy are // separate claims, and the boot test needs the first without the second. The // policy is HERE, it is tested, and main() applies it. +// validatePagesPublic checks the public pages listener's pair: both or +// neither, only with pages on, a port of its own, and a link base a client +// outside the owner's network can use (https, or http to this machine for a +// local test), with no path, query or credentials. +func (c config) validatePagesPublic() error { + if c.PagesPublicListen == "" && c.PagesPublicURL == "" { + return nil + } + if c.PagesPublicListen == "" || c.PagesPublicURL == "" { + return fmt.Errorf("%s and %s are a pair and only one is set (%s=%s, %s=%s): the listener serves the links "+ + "only if they are written under its address, and the address works only if the listener is there. Set both or neither", + envPagesPublicListen, envPagesPublicURL, envPagesPublicListen, presence(c.PagesPublicListen), envPagesPublicURL, presence(c.PagesPublicURL)) + } + if !c.Pages { + return fmt.Errorf("%s is set but %s is not: the public pages listener would serve only refusals. Set %s=1, or unset %s and %s", + envPagesPublicListen, envPages, envPages, envPagesPublicListen, envPagesPublicURL) + } + for _, o := range []struct { + env string + port int + }{{envPort, c.Port}, {envBrowserPort, c.BrowserPort}, {envConnectPort, c.ConnectPort}, {envMetricsPort, c.MetricsPort}} { + if o.port != 0 && o.port == c.PagesPublicPort { + return fmt.Errorf("%s=%s collides with %s=%d: the public pages listener gets a port of its own", envPagesPublicListen, c.PagesPublicListen, o.env, o.port) + } + } + u, err := url.Parse(c.PagesPublicURL) + if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") || + !(u.Scheme == "https" || u.Scheme == "http" && loopback.Host(u.Hostname())) { + return fmt.Errorf("invalid %s %q: want an https:// origin with no path, query or credentials, e.g. https://pages.example.com "+ + "(http:// only to this machine)", envPagesPublicURL, c.PagesPublicURL) + } + return nil +} + func (c config) validate() error { // Accounts PR 6: an `mst_` value on the machine tier is a personal API // token or nothing, so neither shared secret may live in that namespace — @@ -2856,6 +2913,9 @@ func (c config) validate() error { // // An EMPTY or blank value is unset: a Secret whose key holds "" arms nothing. func (c config) validateListeners() error { + if err := c.validatePagesPublic(); err != nil { + return err + } if c.MetricsPort != 0 && (c.MetricsPort == c.Port || c.MetricsPort == c.BrowserPort || c.MetricsPort == c.ConnectPort) { return fmt.Errorf("%s=%d collides with another listener's port: /metrics gets a listener of its own", envMetricsPort, c.MetricsPort) } diff --git a/cmd/muster-server/features.go b/cmd/muster-server/features.go index d8ae7e1c1..531a5f84b 100644 --- a/cmd/muster-server/features.go +++ b/cmd/muster-server/features.go @@ -196,7 +196,7 @@ func featureCatalog() []features.Feature { OneLine: "Agents make pages for you, such as showcases and forms, that you can share with a link.", Description: "Agents publish pages for you — showcases, questions, forms, uploads, custom script in a sandbox — and share them with a link anyone can open (asking you first, unless you let your agents share without asking on Account).", Enable: []features.Var{is(envPages, "1")}, - Settings: []string{envPublicURL, envPagesUploadBytes, envConnectorEncKey}}, + Settings: []string{envPublicURL, envPagesUploadBytes, envConnectorEncKey, envPagesPublicListen, envPagesPublicURL}}, {ID: features.Plugins, NeedsChief: true, Name: "Plugins", PlainName: "Plugins", OneLine: "Other apps send messages to your chief, which drafts replies for you to approve.", diff --git a/cmd/muster-server/main.go b/cmd/muster-server/main.go index e0718c83e..de571a224 100644 --- a/cmd/muster-server/main.go +++ b/cmd/muster-server/main.go @@ -243,7 +243,10 @@ type app struct { // (api.MetricsHandler); nil unless MUSTER_METRICS_PORT is set. /metrics is // on no other listener. metrics *http.Server - pool *pgxpool.Pool + // pagesPublic is the listener that serves share links and nothing else + // (api.PagesPublicSurface); nil unless MUSTER_PAGES_PUBLIC_LISTEN is set. + pagesPublic *http.Server + pool *pgxpool.Pool // officers is the officer runtime's wake loop; nil when MUSTER_OFFICERS // declares none. officers *officers.Reconciler @@ -367,6 +370,7 @@ func buildApp(ctx context.Context, cfg config, logger *log.Logger) (*app, error) // Provisioner reproduces that defect exactly. AgentNamespacePrefix: cfg.AgentNamespacePrefix, PublicURL: cfg.PublicURL, + PagesPublicURL: cfg.PagesPublicURL, PluginOrigins: cfg.PluginOrigins, ClientAddr: cfg.ClientAddr, } @@ -1204,6 +1208,13 @@ func buildApp(ctx context.Context, cfg config, logger *log.Logger) (*app, error) ReadHeaderTimeout: readHeaderTimeout, } } + if cfg.PagesPublicListen != "" { + a.pagesPublic = &http.Server{ + Addr: cfg.PagesPublicListen, + Handler: api.PagesPublicSurface(handler), + ReadHeaderTimeout: readHeaderTimeout, + } + } if cfg.MetricsPort != 0 { a.metrics = &http.Server{ Addr: net.JoinHostPort("", strconv.Itoa(cfg.MetricsPort)), @@ -1379,7 +1390,7 @@ func (a *app) Run(ctx context.Context, ready func(net.Addr)) error { if err != nil { return fmt.Errorf("listen %s: %w", a.http.Addr, err) } - var connectLn, browserLn, metricsLn net.Listener + var connectLn, browserLn, metricsLn, pagesPublicLn net.Listener if a.connect != nil { if connectLn, err = net.Listen("tcp", a.connect.Addr); err != nil { ln.Close() @@ -1405,13 +1416,23 @@ func (a *app) Run(ctx context.Context, ready func(net.Addr)) error { return fmt.Errorf("listen %s (%s): %w", a.metrics.Addr, envMetricsPort, err) } } + if a.pagesPublic != nil { + if pagesPublicLn, err = net.Listen("tcp", a.pagesPublic.Addr); err != nil { + for _, l := range []net.Listener{ln, connectLn, browserLn, metricsLn} { + if l != nil { + l.Close() + } + } + return fmt.Errorf("listen %s (%s): %w", a.pagesPublic.Addr, envPagesPublicListen, err) + } + } if ready != nil { ready(ln.Addr()) } a.startBackgroundLoops(ctx) - serveErr := make(chan error, 4) + serveErr := make(chan error, 5) go func() { a.logger.Printf("muster %s listening on %s (auth tiers reported above)", api.BuildVersion, ln.Addr()) serveErr <- a.http.Serve(ln) @@ -1434,6 +1455,13 @@ func (a *app) Run(ctx context.Context, ready func(net.Addr)) error { serveErr <- a.metrics.Serve(metricsLn) }() } + if pagesPublicLn != nil { + go func() { + a.logger.Printf("muster public pages listener on %s (%s; share links only, written under %s)", + pagesPublicLn.Addr(), envPagesPublicListen, a.cfg.PagesPublicURL) + serveErr <- a.pagesPublic.Serve(pagesPublicLn) + }() + } select { case err := <-serveErr: @@ -1656,6 +1684,11 @@ func (a *app) shutdown() { a.logger.Printf("metrics listener drain did not complete within %s: %v", shutdownDrainTimeout, err) } } + if a.pagesPublic != nil { + if err := a.pagesPublic.Shutdown(drainCtx); err != nil { + a.logger.Printf("public pages listener drain did not complete within %s: %v", shutdownDrainTimeout, err) + } + } // The machine jobs this process accepted and will now never finish: fail // them, theirs only (api.FailOwnJobs), bounded. AFTER the HTTP drain, so no // submission lands behind it. A crash skips this; the deadline reaper is @@ -1928,6 +1961,14 @@ func (a *app) logBanner(ext api.Extensions, port router.Port) { } else { l.Printf("metrics: OFF — %s is unset, so /metrics is served on no port", envMetricsPort) } + if a.cfg.PagesPublicListen != "" { + l.Printf("public pages listener: ON — %s=%s serves share links and nothing else, and links are written under %s=%s; "+ + "making that port reachable from outside is the operator's step", envPagesPublicListen, a.cfg.PagesPublicListen, + envPagesPublicURL, a.cfg.PagesPublicURL) + } else { + l.Printf("public pages listener: OFF — %s and %s are unset, so share links are served only on muster's own listeners, "+ + "under %s", envPagesPublicListen, envPagesPublicURL, envPublicURL) + } if reason := a.cfg.serviceWriteRefusal(); reason != "" { l.Printf("service-to-service tier: DISABLED (fail-closed) — %s. Those routes answer 503 "+ diff --git a/cmd/muster-server/pages_public_test.go b/cmd/muster-server/pages_public_test.go new file mode 100644 index 000000000..431de03c1 --- /dev/null +++ b/cmd/muster-server/pages_public_test.go @@ -0,0 +1,107 @@ +package main + +import ( + "io" + "net" + "net/http" + "strconv" + "strings" + "testing" +) + +// THE PUBLIC PAGES LISTENER'S CONFIGURATION AND WIRING +// (MUSTER_PAGES_PUBLIC_LISTEN, MUSTER_PAGES_PUBLIC_URL). Every address is +// invented. + +// TestThePublicPagesListenerIsAPairWithPagesOn: both variables or neither, +// only with MUSTER_PAGES=1, on a port of its own, with an https origin (http +// only to this machine) as the link base; the pair is read as written. +func TestThePublicPagesListenerIsAPairWithPagesOn(t *testing.T) { + load := func(env map[string]string) (config, error) { + t.Helper() + full := map[string]string{envDatabase: "postgres://x/y", envStandalone: "1", envHookToken: fixtureHookToken, envPages: "1"} + for k, v := range env { + full[k] = v + } + c, err := loadConfig(func(k string) string { return full[k] }) + if err != nil { + return c, err + } + return c, c.validate() + } + c, err := load(map[string]string{envPagesPublicListen: ":18108", envPagesPublicURL: "https://pages.example.com/"}) + if err != nil { + t.Fatalf("control: the pair is refused: %v", err) + } + if c.PagesPublicListen != ":18108" || c.PagesPublicPort != 18108 || c.PagesPublicURL != "https://pages.example.com" { + t.Fatalf("read as %q / %d / %q", c.PagesPublicListen, c.PagesPublicPort, c.PagesPublicURL) + } + if c, err := load(nil); err != nil || c.PagesPublicListen != "" || c.PagesPublicURL != "" { + t.Fatalf("control: neither set: %v %q %q", err, c.PagesPublicListen, c.PagesPublicURL) + } + if _, err := load(map[string]string{envPagesPublicListen: "127.0.0.1:18108", envPagesPublicURL: "http://localhost:18108"}); err != nil { + t.Fatalf("control: a loopback test pair is refused: %v", err) + } + for name, c := range map[string]struct { + env map[string]string + want string + }{ + "listen alone": {map[string]string{envPagesPublicListen: ":18108"}, envPagesPublicURL}, + "url alone": {map[string]string{envPagesPublicURL: "https://pages.example.com"}, envPagesPublicListen}, + "pages off": {map[string]string{envPages: "", envPagesPublicListen: ":18108", envPagesPublicURL: "https://pages.example.com"}, envPages}, + "no port": {map[string]string{envPagesPublicListen: "18108", envPagesPublicURL: "https://pages.example.com"}, envPagesPublicListen}, + "named port": {map[string]string{envPagesPublicListen: ":http", envPagesPublicURL: "https://pages.example.com"}, envPagesPublicListen}, + "port 0": {map[string]string{envPagesPublicListen: ":0", envPagesPublicURL: "https://pages.example.com"}, envPagesPublicListen}, + "the main port": {map[string]string{envPagesPublicListen: ":8105", envPagesPublicURL: "https://pages.example.com"}, envPort}, + "the metrics port": {map[string]string{envMetricsPort: "18109", envPagesPublicListen: ":18109", envPagesPublicURL: "https://pages.example.com"}, envMetricsPort}, + "the browser port": {map[string]string{envBrowserPort: "18110", envPagesPublicListen: ":18110", envPagesPublicURL: "https://pages.example.com"}, envBrowserPort}, + "plain http": {map[string]string{envPagesPublicListen: ":18108", envPagesPublicURL: "http://pages.example.com"}, envPagesPublicURL}, + "a path": {map[string]string{envPagesPublicListen: ":18108", envPagesPublicURL: "https://pages.example.com/muster"}, envPagesPublicURL}, + "a query": {map[string]string{envPagesPublicListen: ":18108", envPagesPublicURL: "https://pages.example.com?x=1"}, envPagesPublicURL}, + "credentials": {map[string]string{envPagesPublicListen: ":18108", envPagesPublicURL: "https://u:p@pages.example.com"}, envPagesPublicURL}, + "no host": {map[string]string{envPagesPublicListen: ":18108", envPagesPublicURL: "https://"}, envPagesPublicURL}, + } { + if _, err := load(c.env); err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("%s: %v, want a refusal naming %s", name, err, c.want) + } + } +} + +// TestThePublicPagesListenerIsBoundAndServesOnlyShareLinks boots the real +// app with MUSTER_PAGES_PUBLIC_LISTEN: a share-link path there reaches +// muster's own share route (its refusal, with no database here), the UI, the +// API, sign-in and health are the listener's 404, and the main port still +// serves sign-in and health. +func TestThePublicPagesListenerIsBoundAndServesOnlyShareLinks(t *testing.T) { + cfg := testConfig() + port := freePort(t) + cfg.PagesPublicListen = net.JoinHostPort("127.0.0.1", strconv.Itoa(port)) + cfg.PagesPublicPort = port + cfg.PagesPublicURL = "http://localhost:" + strconv.Itoa(port) + main := startServer(t, cfg) + public := "http://" + cfg.PagesPublicListen + get := func(u string) (int, string) { + t.Helper() + resp, err := http.Get(u) + if err != nil { + t.Fatalf("GET %s: %v", u, err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(b) + } + if code, body := get(public + "/s/" + strings.Repeat("Q", 43)); code != http.StatusNotFound || body != "This link does not exist, or no longer works.\n" { + t.Errorf("a share link on the public listener = %d %q, want the share route's own refusal", code, body) + } + for _, p := range []string{"/", "/login", "/api/tasks", "/health", "/metrics", "/tasks", "/static/app.css"} { + if code, body := get(public + p); code != http.StatusNotFound || body != "404 page not found\n" { + t.Errorf("public listener %s = %d %q, want the listener's 404", p, code, body) + } + } + if code, _ := get(main + "/health"); code != http.StatusOK { + t.Errorf("control: the main port's /health = %d", code) + } + if code, _ := get(main + "/login"); code == http.StatusNotFound { + t.Error("control: the main port does not serve /login") + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 2e5234603..24e48023c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -44,6 +44,7 @@ flowchart LR | browser | `MUSTER_BROWSER_PORT` | Browser sessions in gotrue mode. The shared secrets are refused here. | | connect | `MUSTER_CONNECT_PORT` | Only the routes agents need: connectors, approvals, MCP and `/health`. | | metrics | `MUSTER_METRICS_PORT` | `GET /metrics` (Prometheus) and nothing else. Unset: `/metrics` is served nowhere. | +| public pages | `MUSTER_PAGES_PUBLIC_LISTEN` | Only share links: a link's page, its files and a viewer's responses ([pages.md](pages.md#sharing-with-people-outside-your-network)). No cookie or credential reaches muster through it. Unset: there is none. | The server does not start without `MUSTER_HOOK_TOKEN` ([configuration.md](configuration.md#muster-server-sign-in-and-machine-credentials)). diff --git a/docs/configuration.md b/docs/configuration.md index 1c7ccb7ce..5daff6c3d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -207,8 +207,10 @@ Pick the header your proxy **writes**, never one it only passes on: | `MUSTER_ASK_LOG` | off | no | `1` turns on the [ask log](asks.md): every question an agent puts to its owner — a plain-text question at a turn's end, an `AskUserQuestion` picker, an `attention_ask`, an opencode form or permission request — is recorded in `asks` with the owner's answer, who gave it and how long it took. Telemetry only: nothing is answered for you. Text is redacted on the way in and owner-only under row-level security. Needs a database. A failed capture is logged and counted (`muster_ask_capture_errors_total`), never an error to the agent or to you. | | `MUSTER_ASK_LOG_TEXT_TTL` | `720h` | no | How long the ask log keeps question and answer text. A daily sweep clears the text of older rows (the rest of the row is kept 180 days). A Go duration, `1h`–`4320h`; anything else refuses to boot. | | `MUSTER_ASK_LOG_CLASSIFY` | off | no | `1` runs the stall classifier on a plain-text question the [ask log](asks.md) kept, once per turn end (reusing the stall sweep's answer for the streak when it has one), on the owner's OpenRouter key; its scores are stored on the row. Needs `MUSTER_CHIEF_NUDGES=1` (the classifier's configuration). Off by default so the pre-filter's volume (`muster_ask_plain_text_prefilter_total`) is read before the classifier is spent on it. | -| `MUSTER_PAGES` | off | no | `1` turns on [shareable pages](pages.md): agents publish pages for their owner (`page_create`, …) and share them with a link anyone can open (`page_share_request`: the owner approves it on the Asks page or their phone, when that owner turned off **Let my agents share pages without asking** on their own Account page — a per-user switch, on by default (migration 0163), not a server setting; with it on, the agent's link goes live at once and the owner is told. Three exceptions always ask: a user who had saved it off before the default changed keeps that off (no backfill); a team's pages (a team is never auto-shared, whatever is stored); and a call from a machine the step-up gate covers (one running a host officer or starting agents for the chief) or from a session mirrored to another muster; see [pages.md](pages.md#when-an-agent-shares)). Links are served at `/s/` on `MUSTER_PUBLIC_URL`, sandboxed. With `MUSTER_CONNECTOR_ENCRYPTION_KEY` set, each page keeps one reusable link whose address the owner's Share button shows every time (its token encrypted at rest); without it there are no reusable links: the owner's Share makes a new one-off (hash-only) link on every tap, its address shown only then, and each can be revoked on the page's screen. Needs a database; an `upload` block needs [attachments](uploads.md). Off, no page tool is offered and every link answers 404. | +| `MUSTER_PAGES` | off | no | `1` turns on [shareable pages](pages.md): agents publish pages for their owner (`page_create`, …) and share them with a link anyone can open (`page_share_request`: the owner approves it on the Asks page or their phone, when that owner turned off **Let my agents share pages without asking** on their own Account page — a per-user switch, on by default (migration 0163), not a server setting; with it on, the agent's link goes live at once and the owner is told. Three exceptions always ask: a user who had saved it off before the default changed keeps that off (no backfill); a team's pages (a team is never auto-shared, whatever is stored); and a call from a machine the step-up gate covers (one running a host officer or starting agents for the chief) or from a session mirrored to another muster; see [pages.md](pages.md#when-an-agent-shares)). Links are served at `/s/` on `MUSTER_PUBLIC_URL` (or `MUSTER_PAGES_PUBLIC_URL`, with the public pages listener on), sandboxed. With `MUSTER_CONNECTOR_ENCRYPTION_KEY` set, each page keeps one reusable link whose address the owner's Share button shows every time (its token encrypted at rest); without it there are no reusable links: the owner's Share makes a new one-off (hash-only) link on every tap, its address shown only then, and each can be revoked on the page's screen. Needs a database; an `upload` block needs [attachments](uploads.md). Off, no page tool is offered and every link answers 404. | | `MUSTER_PAGES_UPLOAD_BYTES` | `524288000` (500 MiB) | no | The bytes one [shareable page](pages.md#files)'s files may hold in all; an upload that would pass it is refused, saying how much room is left. A byte count from `1048576` (1 MiB) to `107374182400` (100 GiB); anything else refuses to boot. | +| `MUSTER_PAGES_PUBLIC_LISTEN` | none (off) | no | A listener of its own, `[host]:port` with a numeric port (`:8108`, or `127.0.0.1:8108` for a tunnel on the same machine), that serves [shareable pages](pages.md#sharing-with-people-outside-your-network)' share links and nothing else: a link's page, its content and files, and a viewer's submit and upload, plus the shell's logo and icon. Every other path is a 404 there, the UI, `/api/`, sign-in, MCP, `/health` and `/metrics` included, and no cookie or credential header reaches muster through it, so an owner's session grants nothing on it. The rate limits and caps are the share routes' own. muster only opens the port; making it reachable from outside (a reverse proxy, a tunnel, Tailscale Funnel) is yours. Set it with `MUSTER_PAGES_PUBLIC_URL`, or neither; it needs `MUSTER_PAGES=1` and a port no other listener uses, or the server refuses to boot. The Compose stack and the Helm chart do not set or publish it. | +| `MUSTER_PAGES_PUBLIC_URL` | none | with `MUSTER_PAGES_PUBLIC_LISTEN` | The address clients outside your network reach `MUSTER_PAGES_PUBLIC_LISTEN` at, as an `https://` origin with no path (`http://` only to this machine, for a test). Every share link muster hands on (the owner's Share, an agent's `page_share_request`, the page's screen) is written under it instead of `MUSTER_PUBLIC_URL`. Nothing else moves: the owner's own view of a page, sign-in, invites and every other link stay under `MUSTER_PUBLIC_URL`. A link handed on before it was set still names the old address, and the token works on both listeners. | | `MUSTER_CC_USAGE_POLL` | off | no | `1` reads each of the admin's pooled Claude accounts' subscription utilization once per `MUSTER_CC_USAGE_POLL_INTERVAL` and keeps the latest reading per account (numbers only): from the endpoint Claude Code's `/usage` reads when the account's token may use it (one discovery call per token; a `setup-token` is refused there), else from a one-token Messages probe's `anthropic-ratelimit-unified-*` headers, which spends one output token of the account's quota per read. An account the pool marks rate-limited is still read at the same interval and by the same path (so a cooling account read by the probe spends one output token per interval as well), and when that live reading shows it usable — the probe's status `allowed`/`allowed_warning` with the window of the limit the mark names (`5h` for the session limit, `7d` for the weekly one) under its limit, or every usage window below 100% — its rate-limit mark is cleared before the stated reset ([jobs](jobs.md#worker-pools)). Off, nothing clears a mark early; replacing the account's token does not either (a limit is per subscription). Served at `GET /api/cc-accounts/usage` and on Account → Credentials ([jobs](jobs.md#claude-account-usage)). muster-server itself calls `api.anthropic.com:443`. Needs the `claude-code` kind and a database, or boot is refused. Members' own accounts are not read. | | `MUSTER_CC_USAGE_POLL_INTERVAL` | `15m` | no | How often the usage poller reads every account (a Go duration, 5m–24h). A probe answered 429 waits longer (doubling, at least `Retry-After`, at most 6h — or until the window's reset when its status is `rejected`); a token the probe refused (401/403) is not read again until it changes. Refused without `MUSTER_CC_USAGE_POLL`. | | `MUSTER_CC_USAGE_PUSH_URL` | none | no | Turns on the [usage pusher](jobs.md#pushing-the-readings): after each poll cycle muster `PUT`s the readings, exactly as `GET /api/cc-accounts/usage` answers the admin, to this URL, once, with a 10-second timeout, and expects `204`. A failure is logged (never the token or the body; a 4xx's answer as one sanitized line), counted in `muster_cc_usage_push_failures_total{reason}` and not retried until the next cycle; a redirect is not followed. An absolute `https` URL (plain `http` only to a loopback host); credentials in the URL are refused. Refused without `MUSTER_CC_USAGE_POLL` or without `MUSTER_CC_USAGE_PUSH_TOKEN`. | diff --git a/docs/pages.md b/docs/pages.md index 66fb77a22..51d1e9d98 100644 --- a/docs/pages.md +++ b/docs/pages.md @@ -288,7 +288,9 @@ asset with it (their bytes are under the page's own prefix, [below](#files)). ## Share links -A link is `https:///s/`, where the token is 256 +A link is `https:///s/` (or under +`MUSTER_PAGES_PUBLIC_URL`, [for people outside your +network](#sharing-with-people-outside-your-network)), where the token is 256 random bits. It serves the page's current version until it is revoked. A link that is unknown, waiting for approval, declined or revoked answers 404 with one body, whichever it is. @@ -344,6 +346,45 @@ transcript, and so with its model provider: `page_share_request`'s result carries it. Treat a link an agent shared as shared with whatever sees that session. +### Sharing with people outside your network + +A default install is reachable only over your own network (your tailnet), so +a link under `MUSTER_PUBLIC_URL` does not open for a client outside it. To +let it, turn on the **public pages listener**: a port of its own that serves +share links and nothing else. + +```sh +MUSTER_PAGES_PUBLIC_LISTEN=:8108 +MUSTER_PAGES_PUBLIC_URL=https://pages.example.com +``` + +([configuration](configuration.md#muster-server-optional-features)). Then +**you** make that port reachable from outside: a reverse proxy, a tunnel or +Tailscale Funnel pointed at it. muster only opens the port. Keep everything +else as it is: the rest of muster stays on your network. + +- **What it serves**: a link's page (`/s/`), its content and its + images and video, a viewer's submit and upload, and the shell's logo and + icon. That list is one list in the code (`api.PagesPublicRoutes`). Every + other path is a 404 there, including `/`, `/api/`, sign-in, `/plugin/`, + MCP, `/health` and `/metrics`. +- **No credential crosses it.** Cookies and credential headers are taken off + every request before muster sees it, and no response sets a cookie, so + your own signed-in browser gets nothing more there than a stranger does. + There is no CORS on it. +- **The links you hand on** (Share, an agent's `page_share_request`, the + page's screen) are written under `MUSTER_PAGES_PUBLIC_URL`. Your own view + of a page and every other link stay under `MUSTER_PUBLIC_URL`. A token + works on both listeners, so a link handed on earlier keeps working on your + network. +- **The same limits apply**: the rate limits, caps and refusals in + [Limits](#limits) are the share routes' own, on either listener. They are + counted per client address, so behind a proxy or tunnel set + [`MUSTER_TRUSTED_PROXIES`](configuration.md#client-addresses-behind-a-proxy), + or every viewer shares the proxy's one address. +- Prefer a hostname of its own for `MUSTER_PAGES_PUBLIC_URL`, not muster's: + a page link's shell then shares no origin with your muster. + ### When an agent shares What an agent's `page_share_request` does is **the page owner's own choice**, diff --git a/internal/api/ext.go b/internal/api/ext.go index 66d9c7d66..eddedbee4 100644 --- a/internal/api/ext.go +++ b/internal/api/ext.go @@ -205,6 +205,12 @@ type Extensions struct { // (wsAllowedOrigins), for proxy setups that rewrite Host. "" accepts only // the request's own Host. PublicURL string + // PagesPublicURL is MUSTER_PAGES_PUBLIC_URL: the base of every share + // link's address (pageLinkURL) when the public pages listener is on + // (PagesPublicSurface). "" (the default): links are under PublicURL. + // Nothing else is: the owner's own view, sign-in and every other link + // stay under PublicURL. + PagesPublicURL string // NotifyLinkHosts is MUSTER_NOTIFY_LINK_HOSTS, parsed (lower-case, exact // host names): the only external hosts a notify_owner link may open // (notify_owner.go, notifyLinkFor). Empty (the default): muster paths only. diff --git a/internal/api/pages.go b/internal/api/pages.go index 9df4f1552..b22c50000 100644 --- a/internal/api/pages.go +++ b/internal/api/pages.go @@ -681,9 +681,16 @@ func pagePath(id int64) string { return pagesPath + "/" + strconv.FormatInt(id, // pageLinkURL is a NEW link's address, the once it is shown (the link // CreateLink just returned holds its token; no stored link does): absolute -// under MUSTER_PUBLIC_URL, else a path on this server. +// under MUSTER_PAGES_PUBLIC_URL when the public pages listener is on, else +// under MUSTER_PUBLIC_URL, else a path on this server. It is the one place a +// link's address is made, so the owner's Share, an agent's tools and the +// page's screen all hand on the same one. func (s *Server) pageLinkURL(l pages.Link) string { - return strings.TrimRight(s.ext.PublicURL, "/") + pages.LinkPath(l.Token) + base := s.ext.PublicURL + if s.ext.PagesPublicURL != "" { + base = s.ext.PagesPublicURL + } + return strings.TrimRight(base, "/") + pages.LinkPath(l.Token) } // pageViewPath is the owner's own view of page id (ui.PageViewPath). diff --git a/internal/api/pages_public.go b/internal/api/pages_public.go new file mode 100644 index 000000000..b74bde077 --- /dev/null +++ b/internal/api/pages_public.go @@ -0,0 +1,141 @@ +package api + +import ( + "io" + "net/http" + "path" + "strings" + + "github.com/ZacxDev/muster/internal/pages" + "github.com/ZacxDev/muster/internal/ui" +) + +// --------------------------------------------------------------------------- +// THE PUBLIC PAGES LISTENER (MUSTER_PAGES_PUBLIC_LISTEN; docs/pages.md +// "Sharing with people outside your network"). An opt-in listener that serves +// a share link's viewer and NOTHING ELSE, so an operator can make it reachable +// from the internet while the rest of muster stays on their private network. +// +// 🔴 ONE LIST. PagesPublicRoutes is the whole surface: a request whose method +// and path match none of its patterns is answered 404 here, before muster's +// own handler runs at all. TestThePublicPagesListenerServesOnlyItsAllowlist +// walks every route RegisterRoutes records and demands that exactly the +// ledgered ones get through, so a route added to this list, or one of these +// routes removed from muster, fails it. +// +// 🔴 NO CREDENTIAL CROSSES IT. The share-link routes read no cookie already +// (requirePageLink); this listener also takes every cookie and credential +// header off the request before muster sees it, and every Set-Cookie off the +// response, so an owner's session cookie sent to the public address grants +// nothing — not even on the allowlisted routes — and none is ever set there. +// +// It is a filter in front of the SAME handler the main listener serves +// (Server.Handler), not a second registration site: the routes, their rate +// limits, caps and headers are the main listener's own, unchanged. +// --------------------------------------------------------------------------- + +// PagesPublicRoutes is every request the public pages listener passes on, as +// ServeMux patterns (a GET pattern also matches HEAD). Each one is a pattern +// RegisterRoutes registers, except the one static file the shell links, which +// is served by muster's "GET /static/" handler. +var PagesPublicRoutes = []string{ + // The viewer's own routes (pages.go, page_assets.go): the token is their + // only credential. + "GET " + pages.SharePrefix + "{token}", + "GET " + pages.SharePrefix + "{token}/content", + "POST " + pages.SharePrefix + "{token}/submit", + "POST " + pages.SharePrefix + "{token}/upload", + "GET " + pages.SharePrefix + "{token}/assets/{asset}", + // The shell's header logo and its icon on a branded server + // (ShellView.BrandLogo, Brand.Icon192), and muster's own icon on an + // unbranded one. Nothing else under /static/ or /brand/. + "GET " + ui.BrandLogoPath, + "GET " + ui.BrandIcon192Path, + "GET " + pagesPublicStaticIcon, +} + +// pagesPublicStaticIcon is the shell's icon on an unbranded server +// (Brand.Icon192 without a logo), without its ?v= query. +const pagesPublicStaticIcon = "/static/icons/icon-192.png" + +// pagesPublicNotFound is the body of every request the listener refuses. +const pagesPublicNotFound = "404 page not found\n" + +// PagesPublicSurface wraps h (Server.Handler) so it serves only +// PagesPublicRoutes, without any cookie or credential header, and answers 404 +// for everything else. +func PagesPublicSurface(h http.Handler) http.Handler { + allowed := http.NewServeMux() + pass := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h.ServeHTTP(&noCookieWriter{ResponseWriter: w}, withoutCredentials(r)) + }) + for _, p := range PagesPublicRoutes { + allowed.Handle(p, pass) + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Handler reports "" for no match and for a method the path's pattern + // does not take (ServeMux's own 405): both are the one 404 here, so + // nothing says which paths exist. A path that is not canonical + // (ServeMux's redirect) is refused too, rather than redirected. + if !canonicalPath(r.URL.Path) { + refusePagesPublic(w) + return + } + if _, pat := allowed.Handler(r); pat == "" { + refusePagesPublic(w) + return + } + allowed.ServeHTTP(w, r) + }) +} + +// canonicalPath reports whether p is a path ServeMux serves as it is, rather +// than redirecting: absolute, with no empty, "." or ".." segment. +func canonicalPath(p string) bool { + return strings.HasPrefix(p, "/") && path.Clean(p) == strings.TrimSuffix(p, "/") || p == "/" +} + +// refusePagesPublic is the public listener's one refusal. +func refusePagesPublic(w http.ResponseWriter) { + h := w.Header() + h.Set("Content-Type", "text/plain; charset=utf-8") + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Referrer-Policy", "no-referrer") + h.Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, pagesPublicNotFound) +} + +// pagesPublicDroppedHeaders are the request headers that carry a credential +// to some muster route. Every X-Muster-* header is dropped as well. +var pagesPublicDroppedHeaders = []string{"Cookie", "Authorization", "Proxy-Authorization", "X-Api-Key"} + +// withoutCredentials is r without a cookie or a credential header. +func withoutCredentials(r *http.Request) *http.Request { + r2 := r.Clone(r.Context()) + for _, k := range pagesPublicDroppedHeaders { + r2.Header.Del(k) + } + for k := range r2.Header { + if strings.HasPrefix(http.CanonicalHeaderKey(k), "X-Muster-") { + r2.Header.Del(k) + } + } + return r2 +} + +// noCookieWriter drops every Set-Cookie before the header is written. +type noCookieWriter struct{ http.ResponseWriter } + +func (w *noCookieWriter) WriteHeader(code int) { + w.ResponseWriter.Header().Del("Set-Cookie") + w.ResponseWriter.WriteHeader(code) +} + +func (w *noCookieWriter) Write(b []byte) (int, error) { + w.ResponseWriter.Header().Del("Set-Cookie") + return w.ResponseWriter.Write(b) +} + +// Unwrap lets http.ResponseController reach the connection. +func (w *noCookieWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } diff --git a/internal/api/pages_public_pg_test.go b/internal/api/pages_public_pg_test.go new file mode 100644 index 000000000..e9f92aa4a --- /dev/null +++ b/internal/api/pages_public_pg_test.go @@ -0,0 +1,217 @@ +package api + +import ( + "bytes" + "encoding/json" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "regexp" + "strconv" + "strings" + "testing" + + "github.com/ZacxDev/muster/internal/authz" + "github.com/ZacxDev/muster/internal/pages" +) + +// THE PUBLIC PAGES LISTENER, END TO END (pages_public.go; docs/pages.md +// "Sharing with people outside your network"): the real Server.Handler +// behind PagesPublicSurface, as cmd/muster-server builds it, against a real +// database. Every name, address and token is invented. + +const pagesPublicBase = "https://pages.example.test" + +// publicPageFixture is a page fixture with the public listener on. +type publicPageFixture struct { + *pageFixture + public http.Handler +} + +func newPublicPageFixture(t *testing.T) *publicPageFixture { + t.Helper() + f := newPageFixture(t) + f.srv.ext.PagesPublicURL = pagesPublicBase + return &publicPageFixture{pageFixture: f, public: PagesPublicSurface(f.h)} +} + +// pub is a request to the public listener. +func (f *publicPageFixture) pub(method, path string, body io.Reader, hdr map[string]string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, body) + for k, v := range hdr { + r.Header.Set(k, v) + } + w := httptest.NewRecorder() + f.public.ServeHTTP(w, r) + return w +} + +// sameOriginRefs are the shell's own-server references: every src and href +// that is a path on this server. +var sameOriginRef = regexp.MustCompile(`(?:src|href)="(/[^"]*)"`) + +// TestAPageLinkOpensAndTakesAResponseOnThePublicListener: a stranger opens a +// live link on the public listener — the shell, every file it links, the +// sandboxed content — and sends a form and a file through it; both are +// recorded as the link's, even with the owner's session cookie sent along. +// The same link still works on the private listener. +func TestAPageLinkOpensAndTakesAResponseOnThePublicListener(t *testing.T) { + f := newPublicPageFixture(t) + id := f.create(t, f.agent, "Client intake", formBlocks) + l := f.liveLink(t, f.owner, id) + base := pages.LinkPath(l.Token) + + shell := f.pub(http.MethodGet, base, nil, nil) + if shell.Code != http.StatusOK || !strings.Contains(shell.Body.String(), `src="`+base+`/content"`) { + t.Fatalf("the shell on the public listener: %d %s", shell.Code, shell.Body.String()) + } + refs := sameOriginRef.FindAllStringSubmatch(shell.Body.String(), -1) + if len(refs) < 2 { + t.Fatalf("instrument check: %d same-origin reference(s) in the shell, want the frame and the icon at least", len(refs)) + } + for _, m := range refs { + ref := strings.ReplaceAll(m[1], "&", "&") + if w := f.pub(http.MethodGet, ref, nil, map[string]string{"Sec-Fetch-Dest": "iframe"}); w.Code != http.StatusOK { + t.Errorf("the shell links %s, which the public listener answers %d", ref, w.Code) + } + } + content := f.pub(http.MethodGet, base+"/content", nil, map[string]string{"Sec-Fetch-Dest": "iframe"}) + assertContentHeaders(t, content, "content on the public listener") + if !strings.Contains(pageContentBlocks(t, content.Body.String()), "Pick a launch date") { + t.Fatalf("the content: %s", content.Body.String()) + } + + owner := f.ownerHdr() + submit := f.pub(http.MethodPost, base+"/submit", strings.NewReader(`{"component":"f1","data":{"fields":{"email":"client@example.com","seats":"4"}}}`), + map[string]string{"Content-Type": "application/json", "Origin": "null", "Cookie": owner["Cookie"]}) + if submit.Code != http.StatusOK || len(submit.Header().Values("Set-Cookie")) != 0 { + t.Fatalf("the submit on the public listener: %d %v %s", submit.Code, submit.Header().Values("Set-Cookie"), submit.Body.String()) + } + var b bytes.Buffer + mw := multipart.NewWriter(&b) + _ = mw.WriteField("component", "u1") + fw, _ := mw.CreateFormFile("file", "logo.png") + _, _ = fw.Write([]byte("\x89PNG\r\n\x1a\nnot-really-a-png")) + _ = mw.Close() + if w := f.pub(http.MethodPost, base+"/upload", &b, map[string]string{"Content-Type": mw.FormDataContentType(), "Origin": "null"}); w.Code != http.StatusOK { + t.Fatalf("the upload on the public listener: %d %s", w.Code, w.Body.String()) + } + rs, err := f.pages.Responses(f.as(f.owner, authz.ViaSession), id, 0, 10) + if err != nil || len(rs) != 2 { + t.Fatalf("responses: %+v %v", rs, err) + } + for _, r := range rs { + if r.ByOwner || r.LinkID != l.ID { + t.Errorf("not recorded as the link's viewer's: %+v", r) + } + } + if !strings.Contains(string(rs[0].Data), "client@example.com") || rs[1].Kind != pages.KindUpload { + t.Fatalf("what was recorded: %+v", rs) + } + + // The private listener is unchanged: the same link opens there. + if w := f.get(t, base, nil); w.Code != http.StatusOK || w.Body.String() == "" { + t.Fatalf("the link on the private listener: %d", w.Code) + } +} + +// TestARevokedOrUnknownLinkIsTheOne404OnThePublicListener: a revoked link and +// an unknown token get the share routes' own refusal there, as on the +// private listener; a live link is the control. +func TestARevokedOrUnknownLinkIsTheOne404OnThePublicListener(t *testing.T) { + f := newPublicPageFixture(t) + id := f.create(t, f.agent, "Revoked", formBlocks) + revoked := f.liveLink(t, f.owner, id) + if _, err := f.pages.RevokeLink(f.as(f.owner, authz.ViaSession), id, revoked.ID); err != nil { + t.Fatal(err) + } + live := f.liveLink(t, f.owner, id) + for name, tok := range map[string]string{"revoked": revoked.Token, "unknown": strings.Repeat("Q", 43)} { + for _, r := range []struct{ method, suffix string }{{"GET", ""}, {"GET", "/content"}, {"POST", "/submit"}, {"POST", "/upload"}} { + w := f.pub(r.method, pages.LinkPath(tok)+r.suffix, strings.NewReader(`{"component":"q1","data":{"answer":"x"}}`), + map[string]string{"Content-Type": "application/json"}) + if w.Code != http.StatusNotFound || w.Body.String() != pageLinkGone { + t.Errorf("%s %s%s on the public listener: %d %q", name, r.method, r.suffix, w.Code, w.Body.String()) + } + } + } + if w := f.pub(http.MethodGet, pages.LinkPath(live.Token), nil, nil); w.Code != http.StatusOK { + t.Fatalf("control: the live link on the public listener: %d", w.Code) + } +} + +// TestThePublicListenerServesNoAPIOrUIEvenToTheOwner: the UI root, the API, +// sign-in, MCP, health, the owner's Pages screen and the owner's own writes +// are the listener's 404 there, WITH the owner's valid session cookie — which +// the private listener honours on the same paths (the control). +func TestThePublicListenerServesNoAPIOrUIEvenToTheOwner(t *testing.T) { + f := newPublicPageFixture(t) + id := f.create(t, f.agent, "Private screen", formBlocks) + sid := strconv.FormatInt(id, 10) + owner := f.ownerHdr() + for _, c := range []struct{ method, path string }{ + {http.MethodGet, "/"}, + {http.MethodGet, "/pages"}, + {http.MethodGet, "/pages/" + sid}, + {http.MethodGet, "/pages/" + sid + "/view"}, + {http.MethodPost, "/pages/" + sid + "/share"}, + {http.MethodPost, "/pages/" + sid + "/versions/1/submit"}, + {http.MethodGet, "/api/whoami"}, + {http.MethodGet, "/api/tasks"}, + {http.MethodGet, "/login"}, + {http.MethodPost, "/mcp"}, + {http.MethodGet, "/health"}, + {http.MethodGet, "/readyz"}, + {http.MethodGet, "/static/app.css"}, + {http.MethodGet, "/manifest.webmanifest"}, + } { + w := f.pub(c.method, c.path, strings.NewReader(`{}`), merge(owner, map[string]string{"Accept": "application/json", "Content-Type": "application/json"})) + if w.Code != http.StatusNotFound || w.Body.String() != pagesPublicNotFound { + t.Errorf("%s %s on the public listener with the owner's cookie: %d %q", c.method, c.path, w.Code, w.Body.String()) + } + } + // The control: the cookie is a valid owner session on the private listener. + for _, p := range []string{"/pages", "/pages/" + sid} { + if w := f.get(t, p, owner); w.Code != http.StatusOK { + t.Fatalf("control: %s with the owner's cookie on the private listener: %d", p, w.Code) + } + } + if w := f.get(t, "/health", nil); w.Code != http.StatusOK { + t.Fatalf("control: /health on the private listener: %d", w.Code) + } +} + +// TestALinkIsWrittenUnderThePublicPagesURL: with the listener on, the link +// the owner's Share hands back, and the one an agent is given, are under +// MUSTER_PAGES_PUBLIC_URL; the owner's own view stays under MUSTER_PUBLIC_URL. +// Off (no public URL), links are under MUSTER_PUBLIC_URL as before. +func TestALinkIsWrittenUnderThePublicPagesURL(t *testing.T) { + f := newPublicPageFixture(t) + id := f.create(t, f.agent, "Where links point", formBlocks) + sid := strconv.FormatInt(id, 10) + share := func() string { + t.Helper() + w := f.call(t, http.MethodPost, "/pages/"+sid+"/share", nil, merge(f.ownerHdr(), map[string]string{"Accept": "application/json"})) + var out map[string]any + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &out) != nil { + t.Fatalf("Share: %d %s", w.Code, w.Body.String()) + } + u, _ := out["url"].(string) + return u + } + if u := share(); !strings.HasPrefix(u, pagesPublicBase+pages.SharePrefix) { + t.Fatalf("the owner's Share with the public listener on: %q, want under %s", u, pagesPublicBase) + } + got := f.tool(t, f.agent, pageShareRequestTool, map[string]any{"page_id": id, "reason": "for the client"}) + if u, _ := got["url"].(string); !strings.HasPrefix(u, pagesPublicBase+pages.SharePrefix) { + t.Fatalf("an agent's link with the public listener on: %v", got) + } + if v, _ := f.tool(t, f.agent, pageGetTool, map[string]any{"page_id": id})["preview_url"].(string); v != pagesPublicURL+"/pages/"+sid+"/view" { + t.Fatalf("the owner's own view moved: %q", v) + } + f.srv.ext.PagesPublicURL = "" + if u := share(); !strings.HasPrefix(u, pagesPublicURL+pages.SharePrefix) { + t.Fatalf("the owner's Share with the public listener off: %q, want under %s", u, pagesPublicURL) + } +} diff --git a/internal/api/pages_public_test.go b/internal/api/pages_public_test.go new file mode 100644 index 000000000..6049d27d1 --- /dev/null +++ b/internal/api/pages_public_test.go @@ -0,0 +1,236 @@ +package api + +import ( + "io/fs" + "net/http" + "net/http/httptest" + "regexp" + "sort" + "strings" + "testing" + + "github.com/ZacxDev/muster/internal/ui" + "github.com/ZacxDev/muster/web" +) + +// THE PUBLIC PAGES LISTENER'S SURFACE (pages_public.go). Every path and +// token here is invented. + +// pagesPublicLedger is, written out by hand, every REGISTERED route the public +// pages listener passes on. 🔴 It is not derived from PagesPublicRoutes: it is +// what that list is checked against. Growing the public surface means editing +// both, on purpose, in review. +var pagesPublicLedger = []string{ + "GET /brand/icon-192.png", + "GET /brand/logo.png", + "GET /s/{token}", + "GET /s/{token}/assets/{asset}", + "GET /s/{token}/content", + "POST /s/{token}/submit", + "POST /s/{token}/upload", +} + +// pagesPublicStaticLedger is every path under a registered subtree ("GET +// /static/") the listener passes on: the shell's icon on an unbranded server. +var pagesPublicStaticLedger = []string{"/static/icons/icon-192.png"} + +var routeWildcard = regexp.MustCompile(`\{[^}]*\}`) + +// concreteRequest is a request that the registered pattern pat matches: its +// method (GET when the pattern names none), each wildcard filled in, a subtree +// pattern given one segment more. +func concreteRequest(pat string) *http.Request { + method, path := http.MethodGet, pat + if m, p, ok := strings.Cut(pat, " "); ok { + method, path = m, p + } + path = routeWildcard.ReplaceAllString(strings.TrimSuffix(path, "{$}"), "w0rd") + if strings.HasSuffix(path, "/") && path != "/" { + path += "w0rd" + } + return httptest.NewRequest(method, path, nil) +} + +// reachesInner reports whether PagesPublicSurface passed r on to the handler +// behind it. +func reachesInner(r *http.Request) (bool, *httptest.ResponseRecorder) { + reached := false + h := PagesPublicSurface(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + reached = true + w.WriteHeader(http.StatusTeapot) + })) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return reached, w +} + +// TestThePublicPagesListenerServesOnlyItsAllowlist walks every route muster +// registers (RegisterRoutes, the one registration site) and sends a request +// each pattern matches to the public listener's surface: exactly the +// ledgered ones reach muster, and every other one is the listener's 404. The +// set that gets through must EQUAL the ledger, so a route added to +// PagesPublicRoutes fails it, and so does a ledgered route muster no longer +// registers (or the list no longer names). +func TestThePublicPagesListenerServesOnlyItsAllowlist(t *testing.T) { + routes := recordRoutes(t) + // Positive control: the walk sees muster's routes, the UI root and the + // API among them, so a zero below is not a walk over nothing. + have := map[string]bool{} + for _, p := range routes { + have[p] = true + } + for _, must := range []string{"GET /{$}", "GET /health", "GET /api/whoami", "GET /pages", "GET /static/", "POST /mcp"} { + if !have[must] { + t.Fatalf("instrument check: RegisterRoutes recorded %d route(s) without %q", len(routes), must) + } + } + var through []string + for _, p := range routes { + ok, w := reachesInner(concreteRequest(p)) + if ok { + through = append(through, p) + continue + } + if w.Code != http.StatusNotFound || w.Body.String() != pagesPublicNotFound || len(w.Header().Values("Set-Cookie")) != 0 { + t.Errorf("%s: refused with %d %q, want the listener's one 404", p, w.Code, w.Body.String()) + } + } + sort.Strings(through) + want := append([]string(nil), pagesPublicLedger...) + sort.Strings(want) + if strings.Join(through, "\n") != strings.Join(want, "\n") { + t.Fatalf("the public pages listener passes on these registered routes:\n %s\nbut its ledger is:\n %s\n"+ + "A route was added to (or dropped from) PagesPublicRoutes, or muster stopped registering one: the public "+ + "surface changed. Update pagesPublicLedger only if that is meant", + strings.Join(through, "\n "), strings.Join(want, "\n ")) + } + // Every PagesPublicRoutes entry is accounted for: a registered route in the + // ledger, or a ledgered static file that ships. + ledgered := map[string]bool{} + for _, p := range pagesPublicLedger { + ledgered[p] = true + } + for _, p := range pagesPublicStaticLedger { + ledgered["GET "+p] = true + } + for _, p := range PagesPublicRoutes { + if !ledgered[p] { + t.Errorf("PagesPublicRoutes names %q, which no ledger holds", p) + } + } + if len(PagesPublicRoutes) != len(pagesPublicLedger)+len(pagesPublicStaticLedger) { + t.Errorf("PagesPublicRoutes has %d entries, the ledgers %d", len(PagesPublicRoutes), len(pagesPublicLedger)+len(pagesPublicStaticLedger)) + } +} + +// TestThePublicPagesListenerServesOnlyTheShellsOwnStaticFiles: of everything +// under /static/, only the icon the shell links passes, and it ships; the +// app's own stylesheet and scripts do not. +func TestThePublicPagesListenerServesOnlyTheShellsOwnStaticFiles(t *testing.T) { + icon, _, _ := strings.Cut(ui.Brand{}.Icon192(), "?") + if icon != pagesPublicStaticLedger[0] { + t.Fatalf("an unbranded shell links its icon at %q, the ledger names %q", icon, pagesPublicStaticLedger[0]) + } + for _, p := range pagesPublicStaticLedger { + if _, err := fs.Stat(web.Files, strings.TrimPrefix(p, "/")); err != nil { + t.Errorf("%s is ledgered but does not ship: %v", p, err) + } + if ok, _ := reachesInner(httptest.NewRequest(http.MethodGet, p+"?v=0123456789ab", nil)); !ok { + t.Errorf("GET %s is refused", p) + } + } + var others int + _ = fs.WalkDir(web.Files, "static", func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || "/"+p == pagesPublicStaticLedger[0] { + return err + } + others++ + if ok, _ := reachesInner(httptest.NewRequest(http.MethodGet, "/"+p, nil)); ok { + t.Errorf("GET /%s passes the public pages listener", p) + } + return nil + }) + if others < 10 { + t.Fatalf("instrument check: only %d other static file(s) walked", others) + } +} + +// TestThePublicPagesListenerRefusesEveryOtherShape: a method a ledgered path +// does not take, a path with a segment more or less, and a path that is not +// canonical are all the one 404, never a 405 or a redirect that would say +// what exists. +func TestThePublicPagesListenerRefusesEveryOtherShape(t *testing.T) { + for _, c := range []struct{ method, path string }{ + {http.MethodDelete, "/s/w0rd"}, + {http.MethodPost, "/s/w0rd"}, + {http.MethodGet, "/s/w0rd/submit"}, + {http.MethodPut, "/s/w0rd/upload"}, + {http.MethodGet, "/s/"}, + {http.MethodGet, "/s/w0rd/"}, + {http.MethodGet, "/s/w0rd/content/more"}, + {http.MethodGet, "/s//w0rd"}, + {http.MethodGet, "/s/w0rd/../../api/whoami"}, + {http.MethodGet, "/s/w0rd/./content"}, + {http.MethodGet, "/brand/icon-512.png"}, + {http.MethodGet, "/static/app.css"}, + {http.MethodGet, "/"}, + {http.MethodGet, "/metrics"}, + {http.MethodGet, "/health"}, + {http.MethodPost, "/mcp"}, + {http.MethodGet, "/plugin/v1/w0rd"}, + {http.MethodGet, "/login"}, + {http.MethodOptions, "/s/w0rd/submit"}, + } { + r := httptest.NewRequest(c.method, "/", nil) + r.URL.Path = c.path + ok, w := reachesInner(r) + if ok || w.Code != http.StatusNotFound || w.Header().Get("Location") != "" || w.Header().Get("Allow") != "" { + t.Errorf("%s %s: passed=%v %d (Location %q, Allow %q), want the one 404", c.method, c.path, ok, w.Code, + w.Header().Get("Location"), w.Header().Get("Allow")) + } + } + // Positive control: the same surface does pass a ledgered shape. + if ok, _ := reachesInner(httptest.NewRequest(http.MethodHead, "/s/w0rd", nil)); !ok { + t.Fatal("HEAD /s/w0rd is refused: the surface refuses everything") + } +} + +// TestThePublicPagesListenerStripsEveryCredential: what reaches muster +// carries no cookie and no credential header, whatever the client sent, and +// what goes back sets no cookie. +func TestThePublicPagesListenerStripsEveryCredential(t *testing.T) { + var got http.Header + h := PagesPublicSurface(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got = r.Header.Clone() + http.SetCookie(w, &http.Cookie{Name: "muster_session", Value: "w0rd"}) + w.WriteHeader(http.StatusOK) + })) + r := httptest.NewRequest(http.MethodPost, "/s/w0rd/submit", strings.NewReader(`{}`)) + for k, v := range map[string]string{ + "Cookie": "muster_session=w0rd", "Authorization": "Bearer mst_w0rd", "Proxy-Authorization": "Basic w0rd", + "X-Api-Key": "w0rd", "X-Muster-Token": "w0rd", "X-Muster-Step-Up": "w0rd", "X-Muster-Cc-Session": "w0rd", + "Content-Type": "application/json", "Origin": "null", + } { + r.Header.Set(k, v) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if got == nil { + t.Fatal("the submit did not reach muster") + } + for k := range got { + if k == "Cookie" || k == "Authorization" || k == "Proxy-Authorization" || k == "X-Api-Key" || strings.HasPrefix(k, "X-Muster-") { + t.Errorf("%s reached muster through the public listener", k) + } + } + if got.Get("Content-Type") != "application/json" || got.Get("Origin") != "null" { + t.Errorf("the request's own headers were lost: %v", got) + } + if sc := w.Header().Values("Set-Cookie"); len(sc) != 0 { + t.Errorf("the public listener set a cookie: %v", sc) + } + // The client's own request is untouched (the strip works on a copy). + if r.Header.Get("Cookie") == "" { + t.Error("the caller's request was modified") + } +} diff --git a/tests/features_config_test.py b/tests/features_config_test.py index 26d9c5d4c..1cc8bada2 100644 --- a/tests/features_config_test.py +++ b/tests/features_config_test.py @@ -72,6 +72,12 @@ "MUSTER_CC_USAGE_PUSH_URL", "MUSTER_CC_USAGE_PUSH_TOKEN", "MUSTER_CC_USAGE_PUSH_INSTANCE", ]}, "MUSTER_CC_CONSUMER_USAGE": "the consumer usage push; refused without MUSTER_CC_USAGE_PUSH_URL, which the Compose file does not forward", + # The public pages listener (docs/pages.md "Sharing with people outside + # your network"): a port of its own, which the Compose file would also + # have to publish, and an opt-in that exposes it beyond the tailnet. + **{name: "opt-in: the public pages listener needs a published port of its own and an operator's reverse proxy, " + "tunnel or Funnel; the Compose file does not open one" for name in [ + "MUSTER_PAGES_PUBLIC_LISTEN", "MUSTER_PAGES_PUBLIC_URL"]}, "MUSTER_TEST_LLM_UPSTREAM": "test only: the Compose smoke test's fake model; only tests/compose-chief.override.yml sets it", "MUSTER_CHIEF_SPEC_DIR": "the Compose file mounts the chief's spec volume at the runtime's default, /run/muster-spec", "MUSTER_CHIEF_LLM": "the Kubernetes chief's switch onto the LLM proxy; muster refuses it beside MUSTER_CHIEF_RUNTIME=compose, " From 8bea601cc67384fd4bace1a5fbce521b73d2ecba Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Mon, 23 Nov 2026 15:14:00 -0600 Subject: [PATCH 2/4] pages: harden the public listener (timeouts, header allowlist, miss budget, log redaction) From the security audit of the public pages listener: - Timeouts: api.NewPagesPublicServer gives the listener its own ReadTimeout (30s), IdleTimeout (1m) and a WriteTimeout derived from the upload's own budget (its read deadline + the store's 30s + 30s), so it never cuts off an upload its deadlines let through. A submit now sets a read deadline on every listener (15s) and answers 408 past it. - Headers: the credential denylist is replaced by ONE allowlist, api.PagesPublicRequestHeaders, plus the configured MUSTER_CLIENT_IP_HEADER, which clientaddr believes only from MUSTER_TRUSTED_PROXIES, so viewers behind a proxy keep their own budgets and cannot name their own address. - Miss budget: on the public listener an address past the failed-lookup limit is answered 429 before the store is asked. Muster's own listeners keep the earlier contract (a throttled address still opens a live link, TestAThrottledAddressStillOpensALiveLink). The comment says which is which. - Logs: the panic line, the plugin-host refusal and three refusal lines wrote r.URL.Path, so a share link's token reached the log there; they now write accessLogPath like the access log, which already redacted the decoded path (/%73/ included). - Set-Cookie is stripped on Flush as well as WriteHeader and Write, and a hijack is refused. - The matching mux holds a declared no-op handler instead of a local, which TestEveryProvisionerRouteIsDerivedNotDeclared refused. Each new test is red at f3f153acc behind a shim with the old behaviour, except two invariant guards (the client-address test and the slow-upload test); every fix has a mutant its own test kills. Co-Authored-By: Claude Opus 5.5 (1M context) --- cmd/muster-server/main.go | 6 +- docs/architecture.md | 2 +- docs/configuration.md | 2 +- docs/pages.md | 21 +- internal/api/auth.go | 4 +- internal/api/connectors.go | 2 +- internal/api/middleware.go | 9 +- internal/api/pages.go | 48 +++- internal/api/pages_public.go | 169 ++++++++++-- internal/api/pages_public_hardening_test.go | 274 ++++++++++++++++++++ internal/api/pages_public_pg_test.go | 106 +++++++- internal/api/pages_public_test.go | 42 +-- 12 files changed, 593 insertions(+), 92 deletions(-) create mode 100644 internal/api/pages_public_hardening_test.go diff --git a/cmd/muster-server/main.go b/cmd/muster-server/main.go index de571a224..81be50b08 100644 --- a/cmd/muster-server/main.go +++ b/cmd/muster-server/main.go @@ -1209,11 +1209,7 @@ func buildApp(ctx context.Context, cfg config, logger *log.Logger) (*app, error) } } if cfg.PagesPublicListen != "" { - a.pagesPublic = &http.Server{ - Addr: cfg.PagesPublicListen, - Handler: api.PagesPublicSurface(handler), - ReadHeaderTimeout: readHeaderTimeout, - } + a.pagesPublic = api.NewPagesPublicServer(cfg.PagesPublicListen, handler, cfg.ClientAddr.Header(), readHeaderTimeout) } if cfg.MetricsPort != 0 { a.metrics = &http.Server{ diff --git a/docs/architecture.md b/docs/architecture.md index 24e48023c..46aa1e451 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -44,7 +44,7 @@ flowchart LR | browser | `MUSTER_BROWSER_PORT` | Browser sessions in gotrue mode. The shared secrets are refused here. | | connect | `MUSTER_CONNECT_PORT` | Only the routes agents need: connectors, approvals, MCP and `/health`. | | metrics | `MUSTER_METRICS_PORT` | `GET /metrics` (Prometheus) and nothing else. Unset: `/metrics` is served nowhere. | -| public pages | `MUSTER_PAGES_PUBLIC_LISTEN` | Only share links: a link's page, its files and a viewer's responses ([pages.md](pages.md#sharing-with-people-outside-your-network)). No cookie or credential reaches muster through it. Unset: there is none. | +| public pages | `MUSTER_PAGES_PUBLIC_LISTEN` | Only share links: a link's page, its files and a viewer's responses ([pages.md](pages.md#sharing-with-people-outside-your-network)). Only an allowlist of request headers reaches muster through it, never a cookie or a credential, and it has its own read, write and idle timeouts. Unset: there is none. | The server does not start without `MUSTER_HOOK_TOKEN` ([configuration.md](configuration.md#muster-server-sign-in-and-machine-credentials)). diff --git a/docs/configuration.md b/docs/configuration.md index 5daff6c3d..d8b1a473f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -209,7 +209,7 @@ Pick the header your proxy **writes**, never one it only passes on: | `MUSTER_ASK_LOG_CLASSIFY` | off | no | `1` runs the stall classifier on a plain-text question the [ask log](asks.md) kept, once per turn end (reusing the stall sweep's answer for the streak when it has one), on the owner's OpenRouter key; its scores are stored on the row. Needs `MUSTER_CHIEF_NUDGES=1` (the classifier's configuration). Off by default so the pre-filter's volume (`muster_ask_plain_text_prefilter_total`) is read before the classifier is spent on it. | | `MUSTER_PAGES` | off | no | `1` turns on [shareable pages](pages.md): agents publish pages for their owner (`page_create`, …) and share them with a link anyone can open (`page_share_request`: the owner approves it on the Asks page or their phone, when that owner turned off **Let my agents share pages without asking** on their own Account page — a per-user switch, on by default (migration 0163), not a server setting; with it on, the agent's link goes live at once and the owner is told. Three exceptions always ask: a user who had saved it off before the default changed keeps that off (no backfill); a team's pages (a team is never auto-shared, whatever is stored); and a call from a machine the step-up gate covers (one running a host officer or starting agents for the chief) or from a session mirrored to another muster; see [pages.md](pages.md#when-an-agent-shares)). Links are served at `/s/` on `MUSTER_PUBLIC_URL` (or `MUSTER_PAGES_PUBLIC_URL`, with the public pages listener on), sandboxed. With `MUSTER_CONNECTOR_ENCRYPTION_KEY` set, each page keeps one reusable link whose address the owner's Share button shows every time (its token encrypted at rest); without it there are no reusable links: the owner's Share makes a new one-off (hash-only) link on every tap, its address shown only then, and each can be revoked on the page's screen. Needs a database; an `upload` block needs [attachments](uploads.md). Off, no page tool is offered and every link answers 404. | | `MUSTER_PAGES_UPLOAD_BYTES` | `524288000` (500 MiB) | no | The bytes one [shareable page](pages.md#files)'s files may hold in all; an upload that would pass it is refused, saying how much room is left. A byte count from `1048576` (1 MiB) to `107374182400` (100 GiB); anything else refuses to boot. | -| `MUSTER_PAGES_PUBLIC_LISTEN` | none (off) | no | A listener of its own, `[host]:port` with a numeric port (`:8108`, or `127.0.0.1:8108` for a tunnel on the same machine), that serves [shareable pages](pages.md#sharing-with-people-outside-your-network)' share links and nothing else: a link's page, its content and files, and a viewer's submit and upload, plus the shell's logo and icon. Every other path is a 404 there, the UI, `/api/`, sign-in, MCP, `/health` and `/metrics` included, and no cookie or credential header reaches muster through it, so an owner's session grants nothing on it. The rate limits and caps are the share routes' own. muster only opens the port; making it reachable from outside (a reverse proxy, a tunnel, Tailscale Funnel) is yours. Set it with `MUSTER_PAGES_PUBLIC_URL`, or neither; it needs `MUSTER_PAGES=1` and a port no other listener uses, or the server refuses to boot. The Compose stack and the Helm chart do not set or publish it. | +| `MUSTER_PAGES_PUBLIC_LISTEN` | none (off) | no | A listener of its own, `[host]:port` with a numeric port (`:8108`, or `127.0.0.1:8108` for a tunnel on the same machine), that serves [shareable pages](pages.md#sharing-with-people-outside-your-network)' share links and nothing else: a link's page, its content and files, and a viewer's submit and upload, plus the shell's logo and icon. Every other path is a 404 there, the UI, `/api/`, sign-in, MCP, `/health` and `/metrics` included. Only an allowlist of request headers reaches muster through it (`MUSTER_CLIENT_IP_HEADER` among them, believed only from `MUSTER_TRUSTED_PROXIES`), never a cookie or a credential, so an owner's session grants nothing on it. It reads a request for at most 30 s (a submit's body 15 s, an upload its own minute), answers within 2 minutes and closes an idle connection after 1. The rate limits and caps are the share routes' own, except that an address past the failed-lookup limit is refused there before its link is looked up. muster only opens the port; making it reachable from outside (a reverse proxy, a tunnel, Tailscale Funnel) is yours. Set it with `MUSTER_PAGES_PUBLIC_URL`, or neither; it needs `MUSTER_PAGES=1` and a port no other listener uses, or the server refuses to boot. The Compose stack and the Helm chart do not set or publish it. | | `MUSTER_PAGES_PUBLIC_URL` | none | with `MUSTER_PAGES_PUBLIC_LISTEN` | The address clients outside your network reach `MUSTER_PAGES_PUBLIC_LISTEN` at, as an `https://` origin with no path (`http://` only to this machine, for a test). Every share link muster hands on (the owner's Share, an agent's `page_share_request`, the page's screen) is written under it instead of `MUSTER_PUBLIC_URL`. Nothing else moves: the owner's own view of a page, sign-in, invites and every other link stay under `MUSTER_PUBLIC_URL`. A link handed on before it was set still names the old address, and the token works on both listeners. | | `MUSTER_CC_USAGE_POLL` | off | no | `1` reads each of the admin's pooled Claude accounts' subscription utilization once per `MUSTER_CC_USAGE_POLL_INTERVAL` and keeps the latest reading per account (numbers only): from the endpoint Claude Code's `/usage` reads when the account's token may use it (one discovery call per token; a `setup-token` is refused there), else from a one-token Messages probe's `anthropic-ratelimit-unified-*` headers, which spends one output token of the account's quota per read. An account the pool marks rate-limited is still read at the same interval and by the same path (so a cooling account read by the probe spends one output token per interval as well), and when that live reading shows it usable — the probe's status `allowed`/`allowed_warning` with the window of the limit the mark names (`5h` for the session limit, `7d` for the weekly one) under its limit, or every usage window below 100% — its rate-limit mark is cleared before the stated reset ([jobs](jobs.md#worker-pools)). Off, nothing clears a mark early; replacing the account's token does not either (a limit is per subscription). Served at `GET /api/cc-accounts/usage` and on Account → Credentials ([jobs](jobs.md#claude-account-usage)). muster-server itself calls `api.anthropic.com:443`. Needs the `claude-code` kind and a database, or boot is refused. Members' own accounts are not read. | | `MUSTER_CC_USAGE_POLL_INTERVAL` | `15m` | no | How often the usage poller reads every account (a Go duration, 5m–24h). A probe answered 429 waits longer (doubling, at least `Retry-After`, at most 6h — or until the window's reset when its status is `rejected`); a token the probe refused (401/403) is not read again until it changes. Refused without `MUSTER_CC_USAGE_POLL`. | diff --git a/docs/pages.md b/docs/pages.md index 51d1e9d98..d4157566f 100644 --- a/docs/pages.md +++ b/docs/pages.md @@ -368,10 +368,17 @@ else as it is: the rest of muster stays on your network. icon. That list is one list in the code (`api.PagesPublicRoutes`). Every other path is a 404 there, including `/`, `/api/`, sign-in, `/plugin/`, MCP, `/health` and `/metrics`. -- **No credential crosses it.** Cookies and credential headers are taken off - every request before muster sees it, and no response sets a cookie, so - your own signed-in browser gets nothing more there than a stranger does. - There is no CORS on it. +- **No credential crosses it.** Only a short list of request headers is + passed on (`api.PagesPublicRequestHeaders`: the body's type and length, + `Accept*`, the caching headers, `Range`, `Origin`, `Referer`, + `User-Agent` and `Sec-Fetch-*`, plus your `MUSTER_CLIENT_IP_HEADER`, which + muster believes only from `MUSTER_TRUSTED_PROXIES`). Every other header, + cookies included, is removed before muster sees the request, and no + response sets a cookie, so your own signed-in browser gets nothing more + there than a stranger does. There is no CORS on it. +- **A slow client is cut off.** The listener has its own timeouts: 30 s to + read a request (a submit has 15 s for its body, an upload its own minute), + 2 minutes to answer it, and 1 minute for an idle connection. - **The links you hand on** (Share, an agent's `page_share_request`, the page's screen) are written under `MUSTER_PAGES_PUBLIC_URL`. Your own view of a page and every other link stay under `MUSTER_PUBLIC_URL`. A token @@ -381,7 +388,11 @@ else as it is: the rest of muster stays on your network. [Limits](#limits) are the share routes' own, on either listener. They are counted per client address, so behind a proxy or tunnel set [`MUSTER_TRUSTED_PROXIES`](configuration.md#client-addresses-behind-a-proxy), - or every viewer shares the proxy's one address. + or every viewer shares the proxy's one address. One difference: on this + listener an address past the failed-lookup limit is answered 429 for the + minute **before** its link is looked up, so it cannot open even a live + link until then. On your own network a throttled address still opens a + live link, and only its misses are refused. - Prefer a hostname of its own for `MUSTER_PAGES_PUBLIC_URL`, not muster's: a page link's shell then shares no origin with your muster. diff --git a/internal/api/auth.go b/internal/api/auth.go index e8b7304fa..ad715007b 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -348,7 +348,7 @@ func (s *Server) requireSameOrigin(next http.HandlerFunc) http.HandlerFunc { next(w, r) return } - s.logger.Printf("refused a cross-origin %s %s (Origin %q)", r.Method, r.URL.Path, r.Header.Get("Origin")) + s.logger.Printf("refused a cross-origin %s %s (Origin %q)", r.Method, accessLogPath(r.URL), r.Header.Get("Origin")) s.refuseCrossOrigin(w, r) } } @@ -635,7 +635,7 @@ func (s *Server) admitAttributedService(w http.ResponseWriter, r *http.Request, return } if isWriteRequest(r) { - s.logger.Printf(ServiceTierLogPrefix+"%s %s attributed to %q", r.Method, r.URL.Path, actor) + s.logger.Printf(ServiceTierLogPrefix+"%s %s attributed to %q", r.Method, accessLogPath(r.URL), actor) } s.admit(w, r.WithContext(context.WithValue(r.Context(), serviceActorCtxKey{}, actor)), next, s.principalFor(r.Context(), machineUserID(), authz.ViaService)) diff --git a/internal/api/connectors.go b/internal/api/connectors.go index 7ca2a4d93..f7be0639a 100644 --- a/internal/api/connectors.go +++ b/internal/api/connectors.go @@ -204,7 +204,7 @@ func (s *Server) authenticateCallingAgent(w http.ResponseWriter, r *http.Request return agents.Agent{}, false } if auth.ConstantTimeEqual(token, s.auth.HookToken) || auth.ConstantTimeEqual(token, s.auth.ServiceToken) { - s.logger.Printf("agent routes: refused a shared machine token at %s %s", r.Method, r.URL.Path) + s.logger.Printf("agent routes: refused a shared machine token at %s %s", r.Method, accessLogPath(r.URL)) s.writeJSON(w, http.StatusForbidden, map[string]any{"error": SharedTokenRefusal}) return agents.Agent{}, false } diff --git a/internal/api/middleware.go b/internal/api/middleware.go index cfed0978f..98d511bd4 100644 --- a/internal/api/middleware.go +++ b/internal/api/middleware.go @@ -91,7 +91,7 @@ func (s *Server) refusePluginOriginHosts(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if plugins.AnyMatchesHost(s.ext.PluginOrigins, r.Host) { metrics.PluginOriginRefusals.Inc() - s.logger.Printf("refused %s %s for Host %q: it is under MUSTER_PLUGIN_ORIGINS (421)", r.Method, r.URL.Path, r.Host) + s.logger.Printf("refused %s %s for Host %q: it is under MUSTER_PLUGIN_ORIGINS (421)", r.Method, accessLogPath(r.URL), r.Host) h := w.Header() h.Set("Content-Type", "text/plain; charset=utf-8") h.Set("X-Content-Type-Options", "nosniff") @@ -111,7 +111,7 @@ func (s *Server) recoverMiddleware(next http.Handler) http.Handler { defer func() { if rec := recover(); rec != nil { metrics.Panics.WithLabelValues("http").Inc() - s.logger.Printf("PANIC %s %s: %v\n%s", r.Method, r.URL.Path, rec, debug.Stack()) + s.logger.Printf("PANIC %s %s: %v\n%s", r.Method, accessLogPath(r.URL), rec, debug.Stack()) // Best-effort 500; if the handler already wrote a header this is a no-op. w.WriteHeader(http.StatusInternalServerError) } @@ -362,7 +362,10 @@ func (s *Server) accessLog(next http.Handler) http.Handler { // // The same holds for the invite and reset links (accounts PR 5): their tokens // ride in the fragment too, and a hand-made path form is cut the same way. -// accessLogPath is a request's path as the access log writes it. +// accessLogPath is a request's path as the access log writes it — and as +// every other log line that names a request's path must (the 421 refusal, a +// recovered panic, the refusals in auth.go and connectors.go): a share +// link's token, a claim or an invite is a credential wherever it is logged. // // 🔴 REDACT ON THE DECODED PATH, THEN ESCAPE. Redaction must see the path the // mux routes on — the DECODED one — or `/auth/%63laim/` (which reaches diff --git a/internal/api/pages.go b/internal/api/pages.go index b22c50000..93f8ec1ac 100644 --- a/internal/api/pages.go +++ b/internal/api/pages.go @@ -9,6 +9,7 @@ import ( "mime" "net/http" "net/url" + "os" "slices" "strconv" "strings" @@ -64,7 +65,9 @@ const pageLinkGone = "This link does not exist, or no longer works.\n" // a test can lower them. var ( // pageMissLimit: failed lookups per client address per pageLimitWindow, - // then 429 without touching the database. + // then 429. On the public pages listener the 429 comes BEFORE any lookup, + // so a guesser there cannot make the database work; on muster's own + // listeners the lookup comes first (requirePageLink says why). pageMissLimit = 60 // pageSubmitLimit and pageUploadLimit: per link per pageLimitWindow. pageSubmitLimit = 20 @@ -178,10 +181,16 @@ func pageRouteLabel(r *http.Request) string { // owner through authz.ViaPageLink, with the link on its context. // // 🔴 NO OTHER CREDENTIAL IS READ: not a session cookie, not a bearer. The -// failure limit counts only failed lookups, per client address, and is -// applied only to a token that does NOT resolve: the lookup comes first, so -// an address that is throttled (a shared NAT, one guesser behind it) still -// opens a live link, and only its misses are answered 429. +// failure limit counts only failed lookups, per client address. WHERE it is +// checked depends on the listener: +// - on the PUBLIC pages listener (PagesPublicSurface), which can face the +// internet, BEFORE the lookup: an address past it is answered 429 for the +// window without the database being asked anything, whatever token it +// sends. The cost, accepted there: a viewer behind the same address as a +// guesser (a shared NAT) cannot open even a live link until it passes. +// - on muster's own listeners, AFTER it, and only for a token that does not +// resolve: an address that is throttled still opens a live link, and only +// its misses are answered 429 (TestAThrottledAddressStillOpensALiveLink). func (s *Server) requirePageLink(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { route := pageRouteLabel(r) @@ -190,15 +199,24 @@ func (s *Server) requirePageLink(next http.HandlerFunc) http.HandlerFunc { return } key := clientIP(r) + throttled := func() bool { + if s.pageState.misses.count(key, s.now(), pageLimitWindow) < pageMissLimit { + return false + } + metrics.PageLinkRequests.WithLabelValues(route, "throttled").Inc() + w.Header().Set("Retry-After", "60") + http.Error(w, "Too many requests for links that do not exist. Wait a minute.", http.StatusTooManyRequests) + return true + } + if viaPagesPublic(r) && throttled() { + return + } l, err := s.ext.Pages.LinkByToken(r.Context(), r.PathValue("token")) if err != nil { if !errors.Is(err, pages.ErrLinkNotFound) { s.logger.Printf("pages: link lookup failed: %v", err) } - if s.pageState.misses.count(key, s.now(), pageLimitWindow) >= pageMissLimit { - metrics.PageLinkRequests.WithLabelValues(route, "throttled").Inc() - w.Header().Set("Retry-After", "60") - http.Error(w, "Too many requests for links that do not exist. Wait a minute.", http.StatusTooManyRequests) + if throttled() { return } s.pageState.misses.add(key, s.now(), pageLimitWindow) @@ -459,6 +477,10 @@ func (s *Server) pageSubmit(w http.ResponseWriter, r *http.Request, p pageRespon s.pageWriteError(w, http.StatusTooManyRequests, "Too many responses through this link for now. Try again in a minute.") return } + // 🔴 A BOUNDED READ: a body that trickles in is cut off at its deadline + // (408), on every listener, rather than holding this goroutine and its + // connection for as long as the sender likes. + _ = http.NewResponseController(w).SetReadDeadline(time.Now().Add(pageSubmitReadTimeout)) r.Body = http.MaxBytesReader(w, r.Body, pageSubmitBodyMax) var in struct { Component string `json:"component"` @@ -466,6 +488,10 @@ func (s *Server) pageSubmit(w http.ResponseWriter, r *http.Request, p pageRespon } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { metrics.PageResponses.WithLabelValues(string(pages.KindSubmit), "invalid").Inc() + if errors.Is(err, os.ErrDeadlineExceeded) { + s.pageWriteError(w, http.StatusRequestTimeout, "The response took too long to arrive. Send it again.") + return + } s.pageWriteError(w, http.StatusBadRequest, "The request is not {component, data}, or is too large.") return } @@ -1696,6 +1722,10 @@ type teamPageUploadRevoker interface { // whole body: shorter than the composer's (a var so a test can shorten it). var pageUploadReadTimeout = time.Minute +// pageSubmitReadTimeout is how long a submit's body (at most +// pageSubmitBodyMax) has to arrive. A var so a test can shorten it. +var pageSubmitReadTimeout = 15 * time.Second + // pageUploadQuota is the bytes one page's files may hold in all. func (s *Server) pageUploadQuota() int64 { if s.ext.PagesUploadBytes > 0 { diff --git a/internal/api/pages_public.go b/internal/api/pages_public.go index b74bde077..2d8bc2e4b 100644 --- a/internal/api/pages_public.go +++ b/internal/api/pages_public.go @@ -1,10 +1,14 @@ package api import ( + "bufio" + "context" "io" + "net" "net/http" "path" "strings" + "time" "github.com/ZacxDev/muster/internal/pages" "github.com/ZacxDev/muster/internal/ui" @@ -24,10 +28,13 @@ import ( // routes removed from muster, fails it. // // 🔴 NO CREDENTIAL CROSSES IT. The share-link routes read no cookie already -// (requirePageLink); this listener also takes every cookie and credential -// header off the request before muster sees it, and every Set-Cookie off the -// response, so an owner's session cookie sent to the public address grants -// nothing — not even on the allowlisted routes — and none is ever set there. +// (requirePageLink); this listener also passes on ONLY the request headers +// PagesPublicRequestHeaders names (an allowlist: a cookie, a bearer, an +// X-Muster-* or any header a future route reads never reaches muster), and +// takes every Set-Cookie off the response, so an owner's session cookie sent +// to the public address grants nothing — not even on the allowlisted routes — +// and none is ever set there. Its server has its own read, write and idle +// timeouts (NewPagesPublicServer). // // It is a filter in front of the SAME handler the main listener serves // (Server.Handler), not a second registration site: the routes, their rate @@ -62,15 +69,25 @@ const pagesPublicStaticIcon = "/static/icons/icon-192.png" const pagesPublicNotFound = "404 page not found\n" // PagesPublicSurface wraps h (Server.Handler) so it serves only -// PagesPublicRoutes, without any cookie or credential header, and answers 404 -// for everything else. -func PagesPublicSurface(h http.Handler) http.Handler { +// PagesPublicRoutes, with only PagesPublicRequestHeaders on the request, and +// answers 404 for everything else. +// +// clientIPHeader is MUSTER_CLIENT_IP_HEADER (clientaddr.Policy.Header; "" when +// unset), the one header added to the list: muster's client-address policy +// (internal/clientaddr, the outermost layer of h) believes it only from a peer +// in MUSTER_TRUSTED_PROXIES, so passing it on lets a proxy name each viewer +// for the rate limits without letting a viewer name itself. +func PagesPublicSurface(h http.Handler, clientIPHeader string) http.Handler { + keep := pagesPublicHeaderSet(clientIPHeader) allowed := http.NewServeMux() pass := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - h.ServeHTTP(&noCookieWriter{ResponseWriter: w}, withoutCredentials(r)) + r = onlyHeaders(r, keep) + h.ServeHTTP(&noCookieWriter{ResponseWriter: w}, r.WithContext(context.WithValue(r.Context(), pagesPublicKey{}, true))) }) + // The mux only MATCHES (Handler, below); it never serves. Its handler is a + // declared no-op so the package's route analysers can name it. for _, p := range PagesPublicRoutes { - allowed.Handle(p, pass) + allowed.HandleFunc(p, pagesPublicMatchOnly) } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Handler reports "" for no match and for a method the path's pattern @@ -85,10 +102,61 @@ func PagesPublicSurface(h http.Handler) http.Handler { refusePagesPublic(w) return } - allowed.ServeHTTP(w, r) + pass(w, r) }) } +// pagesPublicMatchOnly is the handler PagesPublicSurface's matching mux holds +// for each allowlisted pattern. It is never served: a match is passed to +// muster's own handler instead. +func pagesPublicMatchOnly(http.ResponseWriter, *http.Request) {} + +// pagesPublicKey marks a request that arrived on the public pages listener. +// The key is unexported, so no request can carry the mark any other way. +type pagesPublicKey struct{} + +// viaPagesPublic reports whether r arrived on the public pages listener. +func viaPagesPublic(r *http.Request) bool { + v, _ := r.Context().Value(pagesPublicKey{}).(bool) + return v +} + +// The public pages server's timeouts (NewPagesPublicServer). Vars so a test +// can shorten them. +var ( + // pagesPublicReadTimeout bounds reading a request, its body included, + // unless the route sets its own read deadline: an upload does + // (pageUploadReadTimeout, a longer one), and so does a submit + // (pageSubmitReadTimeout). + pagesPublicReadTimeout = 30 * time.Second + // pagesPublicIdleTimeout bounds a kept-alive connection between requests. + pagesPublicIdleTimeout = time.Minute +) + +// pagesPublicWriteTimeout bounds a request from its headers to the end of +// its answer. 🔴 IT IS DERIVED FROM THE UPLOAD'S OWN BUDGET, so it can never +// cut an upload off that the upload's deadlines let through: the body's read +// deadline (pageUploadReadTimeout), then the store's (30 s after it, +// pageUpload's context), then a margin to write the answer. An asset (at +// most 15 MiB) has the same time to reach a slow viewer. +func pagesPublicWriteTimeout() time.Duration { + return pageUploadReadTimeout + 30*time.Second + 30*time.Second +} + +// NewPagesPublicServer is the public pages listener's server on addr: +// PagesPublicSurface over h, with its own read, write and idle timeouts, so a +// client that sends slowly, reads slowly or idles is cut off. +func NewPagesPublicServer(addr string, h http.Handler, clientIPHeader string, readHeaderTimeout time.Duration) *http.Server { + return &http.Server{ + Addr: addr, + Handler: PagesPublicSurface(h, clientIPHeader), + ReadHeaderTimeout: readHeaderTimeout, + ReadTimeout: pagesPublicReadTimeout, + WriteTimeout: pagesPublicWriteTimeout(), + IdleTimeout: pagesPublicIdleTimeout, + } +} + // canonicalPath reports whether p is a path ServeMux serves as it is, rather // than redirecting: absolute, with no empty, "." or ".." segment. func canonicalPath(p string) bool { @@ -106,36 +174,91 @@ func refusePagesPublic(w http.ResponseWriter) { _, _ = io.WriteString(w, pagesPublicNotFound) } -// pagesPublicDroppedHeaders are the request headers that carry a credential -// to some muster route. Every X-Muster-* header is dropped as well. -var pagesPublicDroppedHeaders = []string{"Cookie", "Authorization", "Proxy-Authorization", "X-Api-Key"} +// PagesPublicRequestHeaders is EVERY request header the public pages +// listener passes on; any other is removed before muster sees the request. +// A name ending in "*" is a prefix. It is what the share routes, the shell's +// files and the middleware in front of them read: the body's type, the +// content negotiation and caching headers, Sec-Fetch-Dest (the content +// document is served only into a frame), Origin, and the two a log or a +// probe may want. No credential header is on it, and none may be added. +var PagesPublicRequestHeaders = []string{ + "Accept", "Accept-Encoding", "Accept-Language", + "Content-Type", "Content-Length", + "If-Modified-Since", "If-None-Match", "Range", + "Origin", "Referer", "User-Agent", + "Sec-Fetch-*", +} -// withoutCredentials is r without a cookie or a credential header. -func withoutCredentials(r *http.Request) *http.Request { - r2 := r.Clone(r.Context()) - for _, k := range pagesPublicDroppedHeaders { - r2.Header.Del(k) +// pagesPublicHeaderSet is PagesPublicRequestHeaders, canonical, plus the +// configured client-address header ("" adds nothing). +func pagesPublicHeaderSet(clientIPHeader string) (set map[string]bool) { + set = map[string]bool{} + for _, k := range append(append([]string(nil), PagesPublicRequestHeaders...), clientIPHeader) { + if prefix, ok := strings.CutSuffix(k, "*"); ok { + set[http.CanonicalHeaderKey(prefix)+"*"] = true + } else if k != "" { + set[http.CanonicalHeaderKey(k)] = true + } } + return set +} + +// keepsHeader reports whether canonical header k is in set. +func keepsHeader(set map[string]bool, k string) bool { + if set[k] { + return true + } + for p := range set { + if strings.HasSuffix(p, "*") && strings.HasPrefix(k, strings.TrimSuffix(p, "*")) { + return true + } + } + return false +} + +// onlyHeaders is a copy of r carrying only the headers in set. +func onlyHeaders(r *http.Request, set map[string]bool) *http.Request { + r2 := r.Clone(r.Context()) for k := range r2.Header { - if strings.HasPrefix(http.CanonicalHeaderKey(k), "X-Muster-") { + if !keepsHeader(set, http.CanonicalHeaderKey(k)) { r2.Header.Del(k) } } return r2 } -// noCookieWriter drops every Set-Cookie before the header is written. +// noCookieWriter drops every Set-Cookie before the header can go out: +// before WriteHeader, a first Write and a Flush, whichever comes first. +// Hijacking is refused, so nothing writes past it. type noCookieWriter struct{ http.ResponseWriter } +func (w *noCookieWriter) strip() { w.ResponseWriter.Header().Del("Set-Cookie") } + func (w *noCookieWriter) WriteHeader(code int) { - w.ResponseWriter.Header().Del("Set-Cookie") + w.strip() w.ResponseWriter.WriteHeader(code) } func (w *noCookieWriter) Write(b []byte) (int, error) { - w.ResponseWriter.Header().Del("Set-Cookie") + w.strip() return w.ResponseWriter.Write(b) } -// Unwrap lets http.ResponseController reach the connection. +// Flush strips, then flushes: http.ResponseController finds this before it +// would unwrap to the connection's own Flush. +func (w *noCookieWriter) Flush() { + w.strip() + if f, ok := w.ResponseWriter.(http.Flusher); ok { + f.Flush() + } +} + +// Hijack is refused: a hijacked connection could write any header. +func (w *noCookieWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return nil, nil, http.ErrNotSupported +} + +// Unwrap lets http.ResponseController reach the connection's read and write +// deadlines (an upload sets its own); Flush and Hijack are answered above, +// before it unwraps. func (w *noCookieWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } diff --git a/internal/api/pages_public_hardening_test.go b/internal/api/pages_public_hardening_test.go new file mode 100644 index 000000000..3e746d7f0 --- /dev/null +++ b/internal/api/pages_public_hardening_test.go @@ -0,0 +1,274 @@ +package api + +import ( + "bytes" + "context" + "errors" + "io" + "log" + "net" + "net/http" + "net/http/httptest" + "sort" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/ZacxDev/muster/internal/clientaddr" + "github.com/ZacxDev/muster/internal/pages" + "github.com/ZacxDev/muster/internal/plugins" +) + +// THE PUBLIC PAGES LISTENER'S HARDENING (pages_public.go, pages.go): what +// reaches muster through it, how long a slow client can hold it, the miss +// budget, and that no log line carries a link's token. No database: the +// share-link store is a counting fake. Every address, header value and token +// is invented. + +// countingLinkStore is a pages.Store whose LinkByToken finds nothing and counts +// its calls; any other method is not expected here (the embedded nil Store +// panics). +type countingLinkStore struct { + pages.Store + lookups atomic.Int64 +} + +func (c *countingLinkStore) LinkByToken(context.Context, string) (pages.Link, error) { + c.lookups.Add(1) + return pages.Link{}, pages.ErrLinkNotFound +} + +// linkServer is a Server with pages on over a counting store, the given +// client-address policy, and its log in buf. +func linkServer(t *testing.T, policy *clientaddr.Policy, buf *bytes.Buffer) (*Server, *countingLinkStore) { + t.Helper() + store := &countingLinkStore{} + s := New(nil, AuthConfig{HookToken: tokTestHook, UIPassword: "public-pages-operator-pw"}, log.New(buf, "", 0)) + s.UseExtensions(Extensions{Pages: store, ClientAddr: policy}) + return s, store +} + +// TestThePublicPagesListenerPassesOnlyItsHeaders: inside, the request carries +// exactly the allowlisted headers it was sent; a cookie, a bearer, an +// act-for, any X-Muster-*, any X-Openclaw-* and every forwarding header are +// gone. The configured client-address header is the one addition. +func TestThePublicPagesListenerPassesOnlyItsHeaders(t *testing.T) { + sent := map[string]string{ + // allowlisted + "Accept": "text/html", "Accept-Encoding": "gzip", "Accept-Language": "en", "Content-Type": "application/json", + "If-None-Match": `"w0rd"`, "If-Modified-Since": "Mon, 02 Jan 2006 15:04:05 GMT", "Range": "bytes=0-1", + "Origin": "null", "Referer": "https://elsewhere.example/", "User-Agent": "fixture/1", + "Sec-Fetch-Dest": "iframe", "Sec-Fetch-Site": "same-origin", + // not + "Cookie": "muster_session=w0rd", "Authorization": "Bearer mst_w0rd", "Proxy-Authorization": "Basic w0rd", + "Muster-Act-For": "1", "X-Muster-Token": "w0rd", "X-Muster-Step-Up": "w0rd", "X-Api-Key": "w0rd", + "X-Openclaw-Session-Key": "w0rd", "X-Openclaw-Model": "w0rd", "X-Forwarded-For": "198.51.100.7", + "X-Real-Ip": "198.51.100.7", "Cf-Connecting-Ip": "198.51.100.7", "X-Forwarded-Proto": "https", + "Hx-Request": "true", "X-Test-User": "1", + } + inside := func(clientIPHeader string) []string { + var got []string + h := PagesPublicSurface(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + for k := range r.Header { + got = append(got, k) + } + }), clientIPHeader) + r := httptest.NewRequest(http.MethodPost, "/s/w0rd/submit", strings.NewReader(`{}`)) + for k, v := range sent { + r.Header.Set(k, v) + } + h.ServeHTTP(httptest.NewRecorder(), r) + sort.Strings(got) + return got + } + want := "Accept Accept-Encoding Accept-Language Content-Type If-Modified-Since If-None-Match Origin Range Referer Sec-Fetch-Dest Sec-Fetch-Site User-Agent" + if got := strings.Join(inside(""), " "); got != want { + t.Errorf("inside, with no client-address header:\n got %s\n want %s", got, want) + } + if got := strings.Join(inside(clientaddr.HeaderXForwardedFor), " "); !strings.Contains(" "+got+" ", " X-Forwarded-For ") || + strings.Contains(got, "X-Real-Ip") || strings.Contains(got, "Cookie") { + t.Errorf("inside, with %s configured: %s", clientaddr.HeaderXForwardedFor, got) + } +} + +// TestThePublicPagesListenerKeepsTheClientAddressRight: behind a trusted +// proxy, the configured header still names each viewer (two viewers have two +// miss budgets); from an untrusted peer it is ignored (a viewer naming a new +// address each time still spends ONE budget). +func TestThePublicPagesListenerKeepsTheClientAddressRight(t *testing.T) { + defer func(m int) { pageMissLimit = m }(pageMissLimit) + pageMissLimit = 1 + policy, err := clientaddr.New(clientaddr.Config{TrustedProxies: "192.0.2.0/24", Header: clientaddr.HeaderXForwardedFor}) + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + s, _ := linkServer(t, policy, &buf) + public := PagesPublicSurface(s.Handler(), policy.Header()) + get := func(peer, xff string) int { + r := httptest.NewRequest(http.MethodGet, "/s/"+strings.Repeat("Q", 43), nil) + r.RemoteAddr = peer + ":40000" + r.Header.Set("X-Forwarded-For", xff) + w := httptest.NewRecorder() + public.ServeHTTP(w, r) + return w.Code + } + // Through the proxy: viewer A spends its budget; viewer B has its own. + if a1, a2, b1 := get("192.0.2.10", "203.0.113.1"), get("192.0.2.10", "203.0.113.1"), get("192.0.2.10", "203.0.113.2"); a1 != http.StatusNotFound || + a2 != http.StatusTooManyRequests || b1 != http.StatusNotFound { + t.Errorf("behind the trusted proxy: A %d then %d, B %d; want 404, 429, 404 (one budget per viewer)", a1, a2, b1) + } + // Direct and untrusted: the header is not believed. + if c1, c2 := get("198.51.100.20", "203.0.113.3"), get("198.51.100.20", "203.0.113.4"); c1 != http.StatusNotFound || c2 != http.StatusTooManyRequests { + t.Errorf("an untrusted peer naming two addresses: %d then %d; want 404, 429 (its own one budget)", c1, c2) + } +} + +// TestTheMissBudgetIsCheckedBeforeTheLookup: on the public pages listener, +// once an address has spent its miss budget its requests are 429 and the +// store is not asked. +func TestTheMissBudgetIsCheckedBeforeTheLookup(t *testing.T) { + defer func(m int) { pageMissLimit = m }(pageMissLimit) + pageMissLimit = 2 + var buf bytes.Buffer + s, store := linkServer(t, nil, &buf) + h := PagesPublicSurface(s.Handler(), "") + codes := []int{} + for i := 0; i < 5; i++ { + r := httptest.NewRequest(http.MethodGet, "/s/"+strings.Repeat("Q", 43), nil) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + codes = append(codes, w.Code) + } + if n := store.lookups.Load(); n != 2 { + t.Errorf("the store was asked %d time(s) for 5 requests with a budget of 2; want 2 (codes %v)", n, codes) + } + if codes[1] != http.StatusNotFound || codes[2] != http.StatusTooManyRequests || codes[4] != http.StatusTooManyRequests { + t.Errorf("codes %v; want 404 404 429 429 429", codes) + } + // The control, and the private listener's own contract: there the lookup + // still comes first (a throttled address opens a live link, + // TestAThrottledAddressStillOpensALiveLink), so every request is a lookup. + s2, store2 := linkServer(t, nil, &buf) + for i := 0; i < 5; i++ { + s2.Handler().ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/s/"+strings.Repeat("Q", 43), nil)) + } + if n := store2.lookups.Load(); n != 5 { + t.Errorf("on the private listener the store was asked %d time(s) for 5 requests; want 5", n) + } +} + +// TestThePublicPagesServerCutsOffASlowBody: a request whose body stops +// arriving, on a route that sets no deadline of its own, is cut off at the +// server's read timeout instead of holding the connection. +func TestThePublicPagesServerCutsOffASlowBody(t *testing.T) { + defer func(d time.Duration) { pagesPublicReadTimeout = d }(pagesPublicReadTimeout) + pagesPublicReadTimeout = 300 * time.Millisecond + readErr := make(chan error, 1) + inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, err := io.ReadAll(r.Body) + readErr <- err + }) + srv := NewPagesPublicServer("127.0.0.1:0", inner, "", 5*time.Second) + ln, err := net.Listen("tcp", srv.Addr) + if err != nil { + t.Fatal(err) + } + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { _ = srv.Close() }) + + c, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer c.Close() + start := time.Now() + _, _ = io.WriteString(c, "POST /s/w0rd/submit HTTP/1.1\r\nHost: pages.example.test\r\nContent-Type: application/json\r\nContent-Length: 100\r\n\r\n{\"comp") + select { + case err := <-readErr: + if err == nil { + t.Fatal("the stalled body read to the end") + } + if took := time.Since(start); took < 250*time.Millisecond { + t.Errorf("cut off after %v, before the read timeout: refused for some other reason (%v)", took, err) + } + case <-time.After(5 * time.Second): + t.Fatal("a stalled body was still being read after 5s; the read timeout is 300ms") + } + if srv.WriteTimeout < pageUploadReadTimeout+30*time.Second || srv.IdleTimeout <= 0 || srv.ReadHeaderTimeout != 5*time.Second { + t.Errorf("timeouts: write %v (want ≥ the upload's %v + 30s), idle %v, header %v", srv.WriteTimeout, pageUploadReadTimeout, srv.IdleTimeout, srv.ReadHeaderTimeout) + } +} + +// TestNoCookieLeavesThePublicListenerByAnyPath: a Set-Cookie the handler adds +// is gone whether the header goes out by WriteHeader, by a first Write, or by +// a Flush through http.ResponseController; a hijack is refused. +func TestNoCookieLeavesThePublicListenerByAnyPath(t *testing.T) { + for name, send := range map[string]func(http.ResponseWriter){ + "WriteHeader": func(w http.ResponseWriter) { w.WriteHeader(http.StatusOK) }, + "Write": func(w http.ResponseWriter) { _, _ = io.WriteString(w, "ok") }, + "Flush": func(w http.ResponseWriter) { _ = http.NewResponseController(w).Flush() }, + } { + h := PagesPublicSurface(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + http.SetCookie(w, &http.Cookie{Name: "muster_session", Value: "w0rd"}) + send(w) + http.SetCookie(w, &http.Cookie{Name: "late", Value: "w0rd"}) + }), "") + w := httptest.NewRecorder() + h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/s/w0rd", nil)) + if sc := w.Result().Header.Values("Set-Cookie"); len(sc) != 0 { + t.Errorf("by %s: the public listener sent Set-Cookie %v", name, sc) + } + } + var hijackErr error + h := PagesPublicSurface(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + var c net.Conn + c, _, hijackErr = http.NewResponseController(w).Hijack() + if c != nil { + _ = c.Close() + } + }), "") + srv := httptest.NewServer(h) + defer srv.Close() + resp, err := (&http.Client{Timeout: 5 * time.Second}).Get(srv.URL + "/s/w0rd") + if err == nil { + resp.Body.Close() + } + if !errors.Is(hijackErr, http.ErrNotSupported) { + t.Errorf("a hijack through the public listener: %v, want ErrNotSupported", hijackErr) + } +} + +// TestNoLogLineCarriesAShareLinksToken: the access log, a recovered panic and +// the plugin-host refusal each name a share-link path, plain or +// percent-encoded, without its token. The access-log case is an INVARIANT +// guard (it was already redacted); the other two are the regression. +func TestNoLogLineCarriesAShareLinksToken(t *testing.T) { + tok := strings.Repeat("T", 43) + paths := []string{"/s/" + tok, "/%73/" + tok + "/content"} + pats, err := plugins.ParseOrigins("https://*.preview.example.net") + if err != nil { + t.Fatal(err) + } + for _, p := range paths { + var buf bytes.Buffer + s := New(nil, AuthConfig{HookToken: tokTestHook, UIPassword: "public-pages-operator-pw"}, log.New(&buf, "", 0)) + s.UseExtensions(Extensions{PluginOrigins: pats}) + panicky := s.withMiddleware(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { panic("fixture panic") })) + panicky.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, p, nil)) + r := httptest.NewRequest(http.MethodGet, p, nil) + r.Host = "app.preview.example.net" + s.Handler().ServeHTTP(httptest.NewRecorder(), r) + s.Handler().ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, p, nil)) + out := buf.String() + for _, want := range []string{"PANIC GET /s/[redacted]", "refused GET /s/[redacted] for Host", "GET /s/[redacted] 404"} { + if !strings.Contains(out, want) { + t.Errorf("%s: no %q line in the log (a positive control: the line must exist):\n%s", p, want, out) + } + } + if strings.Contains(out, tok) { + t.Errorf("%s: the token is in the log:\n%s", p, out) + } + } +} diff --git a/internal/api/pages_public_pg_test.go b/internal/api/pages_public_pg_test.go index e9f92aa4a..6253c370c 100644 --- a/internal/api/pages_public_pg_test.go +++ b/internal/api/pages_public_pg_test.go @@ -5,12 +5,14 @@ import ( "encoding/json" "io" "mime/multipart" + "net" "net/http" "net/http/httptest" "regexp" "strconv" "strings" "testing" + "time" "github.com/ZacxDev/muster/internal/authz" "github.com/ZacxDev/muster/internal/pages" @@ -33,7 +35,7 @@ func newPublicPageFixture(t *testing.T) *publicPageFixture { t.Helper() f := newPageFixture(t) f.srv.ext.PagesPublicURL = pagesPublicBase - return &publicPageFixture{pageFixture: f, public: PagesPublicSurface(f.h)} + return &publicPageFixture{pageFixture: f, public: PagesPublicSurface(f.h, "")} } // pub is a request to the public listener. @@ -215,3 +217,105 @@ func TestALinkIsWrittenUnderThePublicPagesURL(t *testing.T) { t.Fatalf("the owner's Share with the public listener off: %q, want under %s", u, pagesPublicURL) } } + +// TestASlowSubmitIsCutOffAtItsReadDeadline: a submit whose body stops +// arriving is answered 408 once pageSubmitReadTimeout passes, on the private +// listener as on the public one, and the link still takes the next submit. +func TestASlowSubmitIsCutOffAtItsReadDeadline(t *testing.T) { + defer func(d time.Duration) { pageSubmitReadTimeout = d }(pageSubmitReadTimeout) + pageSubmitReadTimeout = 300 * time.Millisecond + f := newPublicPageFixture(t) + id := f.create(t, f.agent, "Slow sender", formBlocks) + l := f.liveLink(t, f.owner, id) + for name, h := range map[string]http.Handler{"private": f.h, "public": f.public} { + srv := httptest.NewServer(h) + pr, pw := io.Pipe() + go func() { _, _ = io.WriteString(pw, `{"component":"q1","da`) }() + req, _ := http.NewRequest(http.MethodPost, srv.URL+pages.LinkPath(l.Token)+"/submit", pr) + req.Header.Set("Content-Type", "application/json") + req.ContentLength = 200 + start := time.Now() + done := make(chan *http.Response, 1) + go func() { + resp, err := http.DefaultClient.Do(req) + if err != nil { + done <- nil + return + } + done <- resp + }() + select { + case resp := <-done: + if resp == nil || resp.StatusCode != http.StatusRequestTimeout { + t.Errorf("%s: a stalled submit was answered %+v; want 408", name, resp) + } else { + resp.Body.Close() + } + if took := time.Since(start); took < 250*time.Millisecond { + t.Errorf("%s: answered after %v, before the deadline", name, took) + } + case <-time.After(5 * time.Second): + t.Errorf("%s: a stalled submit was still being read after 5s; the deadline is 300ms", name) + } + _ = pw.Close() + srv.Close() + } + if w := f.submit(t, l.Token, "q1", `{"answer":"after"}`); w.Code != http.StatusOK { + t.Fatalf("the next submit: %d %s", w.Code, w.Body.String()) + } +} + +// TestAnUploadOutlastsThePublicServersReadTimeout: an upload that takes +// longer than the public server's read timeout — but is inside the upload's +// own read deadline — is recorded: the route's deadline wins, and the write +// timeout leaves room for it. +func TestAnUploadOutlastsThePublicServersReadTimeout(t *testing.T) { + defer func(d time.Duration) { pagesPublicReadTimeout = d }(pagesPublicReadTimeout) + pagesPublicReadTimeout = 300 * time.Millisecond + f := newPublicPageFixture(t) + id := f.create(t, f.agent, "Slow upload", formBlocks) + l := f.liveLink(t, f.owner, id) + srv := NewPagesPublicServer("127.0.0.1:0", f.h, "", 5*time.Second) + ln, err := net.Listen("tcp", srv.Addr) + if err != nil { + t.Fatal(err) + } + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { _ = srv.Close() }) + + var b bytes.Buffer + mw := multipart.NewWriter(&b) + _ = mw.WriteField("component", "u1") + fw, _ := mw.CreateFormFile("file", "logo.png") + _, _ = fw.Write([]byte("\x89PNG\r\n\x1a\nnot-really-a-png")) + _ = mw.Close() + body := b.Bytes() + pr, pw := io.Pipe() + go func() { + // The body arrives over ~900 ms, three times the server's read timeout. + for i, n := 0, len(body)/3; i < 3; i++ { + end := (i + 1) * n + if i == 2 { + end = len(body) + } + _, _ = pw.Write(body[i*n : end]) + time.Sleep(300 * time.Millisecond) + } + _ = pw.Close() + }() + req, _ := http.NewRequest(http.MethodPost, "http://"+ln.Addr().String()+pages.LinkPath(l.Token)+"/upload", pr) + req.Header.Set("Content-Type", mw.FormDataContentType()) + req.ContentLength = int64(len(body)) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("the slow upload: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + out, _ := io.ReadAll(resp.Body) + t.Fatalf("the slow upload: %d %s", resp.StatusCode, out) + } + if rs, err := f.pages.Responses(f.as(f.owner, authz.ViaSession), id, 0, 10); err != nil || len(rs) != 1 || rs[0].Kind != pages.KindUpload { + t.Fatalf("responses: %+v %v", rs, err) + } +} diff --git a/internal/api/pages_public_test.go b/internal/api/pages_public_test.go index 6049d27d1..b83089963 100644 --- a/internal/api/pages_public_test.go +++ b/internal/api/pages_public_test.go @@ -58,7 +58,7 @@ func reachesInner(r *http.Request) (bool, *httptest.ResponseRecorder) { h := PagesPublicSurface(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { reached = true w.WriteHeader(http.StatusTeapot) - })) + }), "") w := httptest.NewRecorder() h.ServeHTTP(w, r) return reached, w @@ -194,43 +194,3 @@ func TestThePublicPagesListenerRefusesEveryOtherShape(t *testing.T) { t.Fatal("HEAD /s/w0rd is refused: the surface refuses everything") } } - -// TestThePublicPagesListenerStripsEveryCredential: what reaches muster -// carries no cookie and no credential header, whatever the client sent, and -// what goes back sets no cookie. -func TestThePublicPagesListenerStripsEveryCredential(t *testing.T) { - var got http.Header - h := PagesPublicSurface(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - got = r.Header.Clone() - http.SetCookie(w, &http.Cookie{Name: "muster_session", Value: "w0rd"}) - w.WriteHeader(http.StatusOK) - })) - r := httptest.NewRequest(http.MethodPost, "/s/w0rd/submit", strings.NewReader(`{}`)) - for k, v := range map[string]string{ - "Cookie": "muster_session=w0rd", "Authorization": "Bearer mst_w0rd", "Proxy-Authorization": "Basic w0rd", - "X-Api-Key": "w0rd", "X-Muster-Token": "w0rd", "X-Muster-Step-Up": "w0rd", "X-Muster-Cc-Session": "w0rd", - "Content-Type": "application/json", "Origin": "null", - } { - r.Header.Set(k, v) - } - w := httptest.NewRecorder() - h.ServeHTTP(w, r) - if got == nil { - t.Fatal("the submit did not reach muster") - } - for k := range got { - if k == "Cookie" || k == "Authorization" || k == "Proxy-Authorization" || k == "X-Api-Key" || strings.HasPrefix(k, "X-Muster-") { - t.Errorf("%s reached muster through the public listener", k) - } - } - if got.Get("Content-Type") != "application/json" || got.Get("Origin") != "null" { - t.Errorf("the request's own headers were lost: %v", got) - } - if sc := w.Header().Values("Set-Cookie"); len(sc) != 0 { - t.Errorf("the public listener set a cookie: %v", sc) - } - // The client's own request is untouched (the strip works on a copy). - if r.Header.Get("Cookie") == "" { - t.Error("the caller's request was modified") - } -} From c2d18cd1888ccfd64fd45ec2e83531145a1f0cb8 Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Mon, 23 Nov 2026 16:55:45 -0600 Subject: [PATCH 3/4] pages: ledger the public listener's no-store refusal in noStoreLiterals refusePagesPublic (the public pages listener's one 404) sets Cache-Control: no-store, like refusePageLink, so no shared proxy in front of the internet-facing port keeps it. TestTheNoStoreLedger requires every function with a no-store literal to be named; it was not. Co-Authored-By: Claude Opus 5.5 (1M context) --- internal/api/nostore_ledger_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/api/nostore_ledger_test.go b/internal/api/nostore_ledger_test.go index c37ee5425..315f65736 100644 --- a/internal/api/nostore_ledger_test.go +++ b/internal/api/nostore_ledger_test.go @@ -126,6 +126,7 @@ var noStoreLiterals = map[string]string{ "handleAgentHeader": "an agent page's status strip, ⋯ menu and notices, live", "handleSessionTagsList": "a session's tags: the viewer's own, private, and changed by any tab", "refusePageLink": "a refused share link: one answer for unknown, revoked and expired alike", + "refusePagesPublic": "the public pages listener's one 404 for every path off its allowlist: no shared proxy keeps it", "handlePageLinkAsset": "a link past its asset-read cap: the refusal (an asset itself is cached, page_assets.go)", "handlePageShare": "the Share button's answer: a page's live link, a bearer capability", "handlePageShareRotate": "New link's answer: a page's new live link, a bearer capability", From 7ad5faa846820fa86a9dc55760a3cdd2c4908135 Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Mon, 23 Nov 2026 17:20:24 -0600 Subject: [PATCH 4/4] pages: set PagesPublicURL in the fully wired registration fixture TestFullyWiredServerSetsEveryExtensionField requires every Extensions field to be set in fullyWiredServer, so a registration branch on it would be visible to TestRegistrationIsIndependentOfDependencies. With it set (a synthetic https URL), that test still passes: the public listener's link base changes no route. Co-Authored-By: Claude Opus 5.5 (1M context) --- internal/api/registration_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/api/registration_test.go b/internal/api/registration_test.go index 3efdb0570..36018c189 100644 --- a/internal/api/registration_test.go +++ b/internal/api/registration_test.go @@ -103,6 +103,7 @@ func fullyWiredServer(t *testing.T) *Server { Outcomes: agentoutcome.NewPG(nil), AgentWatchdog: agentoutcome.Thresholds{NoReply: time.Minute, Silent: time.Hour}, PublicURL: "http://example.test", + PagesPublicURL: "https://pages.example.test", NotifyLinkHosts: []string{"docs.example.com"}, PluginOrigins: []plugins.OriginPattern{{Wildcard: true, Host: "plugin.example.test"}}, ClientAddr: func() *clientaddr.Policy {