Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions cmd/muster-server/banner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand Down
60 changes: 60 additions & 0 deletions cmd/muster-server/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 —
Expand Down Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/muster-server/features.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
43 changes: 40 additions & 3 deletions cmd/muster-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
}
Expand Down Expand Up @@ -1204,6 +1208,9 @@ func buildApp(ctx context.Context, cfg config, logger *log.Logger) (*app, error)
ReadHeaderTimeout: readHeaderTimeout,
}
}
if cfg.PagesPublicListen != "" {
a.pagesPublic = api.NewPagesPublicServer(cfg.PagesPublicListen, handler, cfg.ClientAddr.Header(), readHeaderTimeout)
}
if cfg.MetricsPort != 0 {
a.metrics = &http.Server{
Addr: net.JoinHostPort("", strconv.Itoa(cfg.MetricsPort)),
Expand Down Expand Up @@ -1379,7 +1386,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()
Expand All @@ -1405,13 +1412,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)
Expand All @@ -1434,6 +1451,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:
Expand Down Expand Up @@ -1656,6 +1680,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
Expand Down Expand Up @@ -1928,6 +1957,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 "+
Expand Down
107 changes: 107 additions & 0 deletions cmd/muster-server/pages_public_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
1 change: 1 addition & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)). 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)).
Expand Down
Loading
Loading