From 84f7e33872ad514b754b63394ad7d3563326d4a1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 00:59:39 +0000 Subject: [PATCH] Guard the Go server's request boundary: loopback Host, no Origin on /connect, shared token The server answered any Host, so a DNS-rebinding page reached /connect (101) and could drive terminals. Every route now refuses a non-loopback Host on a loopback connection (421), /connect refuses any Origin (403), and a server started with -token-file requires X-Pipelines-Token (401; /mcp and /healthz exempt). The CLI/TUI send the token only to loopback URLs. --- cmd/pipelines-server/main.go | 18 ++- internal/client/client.go | 7 +- internal/client/token.go | 39 ++++++ internal/client/token_test.go | 101 ++++++++++++++ internal/installation/installation.go | 8 +- internal/installation/installation_test.go | 21 +++ internal/server/request_boundary.go | 84 ++++++++++++ internal/server/request_boundary_test.go | 150 +++++++++++++++++++++ internal/server/websocket.go | 5 +- internal/servertoken/private_other.go | 8 ++ internal/servertoken/private_unix.go | 13 ++ internal/servertoken/servertoken.go | 91 +++++++++++++ internal/servertoken/servertoken_test.go | 45 +++++++ 13 files changed, 585 insertions(+), 5 deletions(-) create mode 100644 internal/client/token.go create mode 100644 internal/client/token_test.go create mode 100644 internal/server/request_boundary.go create mode 100644 internal/server/request_boundary_test.go create mode 100644 internal/servertoken/private_other.go create mode 100644 internal/servertoken/private_unix.go create mode 100644 internal/servertoken/servertoken.go create mode 100644 internal/servertoken/servertoken_test.go diff --git a/cmd/pipelines-server/main.go b/cmd/pipelines-server/main.go index 1300a2bf..3468bfde 100644 --- a/cmd/pipelines-server/main.go +++ b/cmd/pipelines-server/main.go @@ -21,6 +21,7 @@ import ( "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" "git.a-wan.net/alan/pipelines/internal/server" + "git.a-wan.net/alan/pipelines/internal/servertoken" "git.a-wan.net/alan/pipelines/internal/summarise" ) @@ -39,7 +40,22 @@ func main() { db := flag.String("db", defaultDB, "SQLite database path (honors XDG_DATA_HOME)") mdnsOn := flag.Bool("mdns", envEnabled(os.Getenv("PIPELINES_MDNS")), "Advertise the server on the LAN with mDNS/DNS-SD ("+discovery.ServiceType+"); PIPELINES_MDNS=off disables") mdnsPort := flag.Int("mdns-port", envPort(os.Getenv("PIPELINES_MDNS_PORT")), "Port LAN clients dial: the authenticated web proxy fronting this server (default: the -addr port when it is not loopback)") + tokenFile := flag.String("token-file", os.Getenv(servertoken.EnvKey), "Require the shared secret in this private file on every request (the installer's server-token; PIPELINES_SERVER_TOKEN_FILE)") flag.Parse() + accessToken := "" + if *tokenFile != "" { + if absolute, absErr := filepath.Abs(*tokenFile); absErr == nil { + *tokenFile = absolute + } + if accessToken, err = servertoken.Read(*tokenFile); err != nil { + log.Fatalf("server token: %v", err) + } + // Stages, chat harnesses and their `pipelines` CLI calls inherit the + // file's location, never the token itself. + _ = os.Setenv(servertoken.EnvKey, *tokenFile) + } else { + log.Printf("no server token configured (-token-file): local clients reach this server without the shared secret") + } if err := os.MkdirAll(filepath.Dir(*db), 0700); err != nil { log.Fatal(err) } @@ -80,7 +96,7 @@ func main() { // Each new run gets a bounded one-line title from the configured default // harness; the summariser falls back to the prompt's first line, so title // generation never blocks or fails run creation. - options := server.Options{AllowAuthoring: *allowAuthoring, ArtifactsRoot: artifactsRoot, RunTitles: summarise.GenerateTitle, StepVerdicts: summarise.GenerateVerdictReason, VerificationFixtures: server.VerificationFixturesFromEnvironment(os.Getenv), DetachSessions: detach} + options := server.Options{AllowAuthoring: *allowAuthoring, ArtifactsRoot: artifactsRoot, RunTitles: summarise.GenerateTitle, StepVerdicts: summarise.GenerateVerdictReason, VerificationFixtures: server.VerificationFixturesFromEnvironment(os.Getenv), DetachSessions: detach, AccessToken: accessToken} recorded := "" if value, err := store.OpenCodeEndpoint(ctx); err != nil { log.Printf("OpenCode endpoint setting unreadable: %v", err) diff --git a/internal/client/client.go b/internal/client/client.go index 462682ad..8d650bb6 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -19,7 +19,12 @@ import ( func Dial(ctx context.Context, url string) (*websocket.Conn, error) { // O(1) exact string compare; only an explicit, validated Docker transport // alias for this same endpoint is ever rewritten. - conn, _, err := websocket.Dial(ctx, transportTarget(url), nil) + target := transportTarget(url) + options, err := dialOptions(target) + if err != nil { + return nil, err + } + conn, _, err := websocket.Dial(ctx, target, options) if err == nil { conn.SetReadLimit(8 << 20) } diff --git a/internal/client/token.go b/internal/client/token.go new file mode 100644 index 00000000..579e21b6 --- /dev/null +++ b/internal/client/token.go @@ -0,0 +1,39 @@ +package client + +import ( + "net" + "net/http" + "net/url" + "strings" + + "git.a-wan.net/alan/pipelines/internal/servertoken" + "github.com/coder/websocket" +) + +// dialOptions attaches the shared server token (internal/servertoken) when the +// dialed endpoint is this machine's loopback server. The token is never sent to +// another host: a remote server is reached through its web proxy, which has its +// own sign-in. No token file means no header (an unconfigured server needs none). +func dialOptions(target string) (*websocket.DialOptions, error) { + if !loopbackEndpoint(target) { + return nil, nil + } + token, err := servertoken.ForClient() + if err != nil || token == "" { + return nil, err + } + return &websocket.DialOptions{HTTPHeader: http.Header{servertoken.Header: {token}}}, nil +} + +func loopbackEndpoint(target string) bool { + u, err := url.Parse(target) + if err != nil || (u.Scheme != "ws" && u.Scheme != "wss") { + return false + } + host := u.Hostname() + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} diff --git a/internal/client/token_test.go b/internal/client/token_test.go new file mode 100644 index 00000000..ab57a659 --- /dev/null +++ b/internal/client/token_test.go @@ -0,0 +1,101 @@ +package client + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/servertoken" + "github.com/coder/websocket" +) + +const clientTestToken = "client-token-0123456789abcdef0123456789abcdef" + +func writeToken(t *testing.T, mode os.FileMode) string { + t.Helper() + dir := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", dir) + t.Setenv(servertoken.EnvKey, "") + path := filepath.Join(dir, "pipelines", "server-token") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(clientTestToken+"\n"), mode); err != nil { + t.Fatal(err) + } + if err := os.Chmod(path, mode); err != nil { + t.Fatal(err) + } + return path +} + +func TestDialSendsTheServerTokenToTheLoopbackServer(t *testing.T) { + writeToken(t, 0o600) + var got, origin string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got, origin = r.Header.Get(servertoken.Header), r.Header.Get("Origin") + conn, err := websocket.Accept(w, r, nil) + if err == nil { + conn.CloseNow() + } + })) + defer srv.Close() + for _, base := range []string{srv.URL, strings.Replace(srv.URL, "127.0.0.1", "localhost", 1)} { + got = "" + conn, err := Dial(context.Background(), "ws"+strings.TrimPrefix(base, "http")+"/connect") + if err != nil { + t.Fatal(err) + } + conn.CloseNow() + if got != clientTestToken { + t.Fatalf("%s: token header = %q", base, got) + } + if origin != "" { + t.Fatalf("client sent Origin %q", origin) + } + } +} + +func TestDialNeverSendsTheTokenToAnotherHost(t *testing.T) { + writeToken(t, 0o600) + for _, target := range []string{"ws://pipelines.example:8083/connect", "wss://box.tailnet.ts.net/connect", "ws://192.168.1.2:8083/connect", "ws://127.0.0.1.example/connect"} { + options, err := dialOptions(target) + if err != nil || options != nil { + t.Fatalf("%s: options %v err %v", target, options, err) + } + } +} + +func TestDialRefusesAnUnprotectedTokenFile(t *testing.T) { + writeToken(t, 0o644) + if _, err := dialOptions("ws://127.0.0.1:8080/connect"); err == nil { + t.Fatal("a group/other-readable token file was used") + } +} + +func TestDialWithoutATokenFileSendsNothing(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv(servertoken.EnvKey, "") + options, err := dialOptions("ws://127.0.0.1:8080/connect") + if err != nil || options != nil { + t.Fatalf("options %v err %v", options, err) + } +} + +func TestDialUsesTheExplicitTokenFile(t *testing.T) { + path := writeToken(t, 0o600) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv(servertoken.EnvKey, path) + options, err := dialOptions("ws://[::1]:8080/connect") + if err != nil || options == nil || options.HTTPHeader.Get(servertoken.Header) != clientTestToken { + t.Fatalf("options %v err %v", options, err) + } + t.Setenv(servertoken.EnvKey, filepath.Join(t.TempDir(), "missing")) + if _, err := dialOptions("ws://127.0.0.1:8080/connect"); err == nil { + t.Fatal("a missing explicitly named token file was ignored") + } +} diff --git a/internal/installation/installation.go b/internal/installation/installation.go index 9859ce0d..e248cd14 100644 --- a/internal/installation/installation.go +++ b/internal/installation/installation.go @@ -20,6 +20,10 @@ type Config struct { Ntfy struct { Mode string `json:"mode"` } `json:"ntfy"` + Web struct { + // ServerTokenFile is the shared server secret (internal/servertoken). + ServerTokenFile string `json:"server_token_file"` + } `json:"web"` } // Load selects an explicit prefix, or a native installation containing this exact @@ -87,8 +91,8 @@ func (c Config) Environment() error { } } } - for key, value := range map[string]string{"PIPELINES_URL": "ws://127.0.0.1:" + strconv.Itoa(c.ServerPort) + "/connect", "PIPELINES_OPENCODE": c.OpenCode} { - if os.Getenv(key) != "" { + for key, value := range map[string]string{"PIPELINES_URL": "ws://127.0.0.1:" + strconv.Itoa(c.ServerPort) + "/connect", "PIPELINES_OPENCODE": c.OpenCode, "PIPELINES_SERVER_TOKEN_FILE": c.Web.ServerTokenFile} { + if os.Getenv(key) != "" || value == "" { continue } if err := os.Setenv(key, value); err != nil { diff --git a/internal/installation/installation_test.go b/internal/installation/installation_test.go index c9af0f61..ce456445 100644 --- a/internal/installation/installation_test.go +++ b/internal/installation/installation_test.go @@ -39,6 +39,27 @@ func TestCompiledCommandFindsManifestThroughSystemLink(t *testing.T) { } } +func TestEnvironmentPointsLocalClientsAtTheServerToken(t *testing.T) { + var config Config + if err := json.Unmarshal([]byte(`{"server_port":18080,"web":{"server_token_file":"/home/u/.config/pipelines/server-token"}}`), &config); err != nil { + t.Fatal(err) + } + t.Setenv("PIPELINES_URL", "") + t.Setenv("PIPELINES_OPENCODE", "") + t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "") + if err := config.Environment(); err != nil { + t.Fatal(err) + } + if got := os.Getenv("PIPELINES_SERVER_TOKEN_FILE"); got != "/home/u/.config/pipelines/server-token" { + t.Fatalf("token file = %q", got) + } + // A manifest from before the token existed sets nothing. + t.Setenv("PIPELINES_SERVER_TOKEN_FILE", "") + if err := (Config{ServerPort: 18080}).Environment(); err != nil || os.Getenv("PIPELINES_SERVER_TOKEN_FILE") != "" { + t.Fatalf("legacy manifest set a token file: %v", err) + } +} + func TestStandaloneGoInstalledCommandHasNoServiceDependency(t *testing.T) { t.Setenv("PIPELINES_PREFIX", "") binary := filepath.Join(t.TempDir(), "pipelines") diff --git a/internal/server/request_boundary.go b/internal/server/request_boundary.go new file mode 100644 index 00000000..fe04bba6 --- /dev/null +++ b/internal/server/request_boundary.go @@ -0,0 +1,84 @@ +package server + +import ( + "net" + "net/http" + "strings" + + "git.a-wan.net/alan/pipelines/internal/servertoken" +) + +// requestBoundary is the server's HTTP front door, applied before any route +// (docs/notes/security-boundary.md): +// +// - Host: a connection that arrived on a loopback address must name a +// loopback literal (127.0.0.1, localhost, [::1]) with the port it reached, +// so a DNS-rebinding page (Host: rebind.example:8080) is refused with 421. +// A connection that arrived on another interface exists only when the +// server was explicitly bound beyond loopback; its Host is not checked. +// - Origin: /connect refuses any request carrying Origin. Browsers always +// send it on a WebSocket upgrade; the web proxy strips it and the CLI, the +// TUI and the native app send none. +// - Token: when the server is configured with the shared secret, every +// request must carry it in servertoken.Header, except the chat-tools MCP +// endpoint (its own per-chat token, loopback and no-Origin checks) and +// /healthz (a bare liveness boolean). +type requestBoundary struct { + next http.Handler + token string +} + +func guardRequests(next http.Handler, token string) http.Handler { + return requestBoundary{next: next, token: token} +} + +func (b requestBoundary) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if !allowedHost(r) { + http.Error(w, "misdirected request: this server answers only its own loopback address", http.StatusMisdirectedRequest) + return + } + if r.URL.Path == "/connect" && r.Header.Get("Origin") != "" { + http.Error(w, "browser origins may not connect directly; use the web proxy", http.StatusForbidden) + return + } + if b.token != "" && !tokenExempt(r.URL.Path) && !servertoken.Equal(r.Header.Get(servertoken.Header), b.token) { + http.Error(w, "server token required", http.StatusUnauthorized) + return + } + // The secret never reaches a handler, a log line or a forwarded request. + r.Header.Del(servertoken.Header) + b.next.ServeHTTP(w, r) +} + +func tokenExempt(path string) bool { + return path == "/healthz" || strings.HasPrefix(path, chatToolPath) +} + +// allowedHost applies the loopback Host rule. A request with no recorded local +// address (an in-process test handler) has no listener to compare against. +func allowedHost(r *http.Request) bool { + local, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr) + if !ok || local == nil { + return true + } + localHost, localPort, err := net.SplitHostPort(local.String()) + if err != nil { + return false + } + if ip := net.ParseIP(localHost); ip == nil || !ip.IsLoopback() { + return true + } + host, port, err := net.SplitHostPort(r.Host) + if err != nil { + // No port: only the default HTTP port could match. + host, port = strings.TrimSuffix(strings.TrimPrefix(r.Host, "["), "]"), "80" + } + if port != localPort { + return false + } + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() && !strings.Contains(host, "%") +} diff --git a/internal/server/request_boundary_test.go b/internal/server/request_boundary_test.go new file mode 100644 index 00000000..b86be014 --- /dev/null +++ b/internal/server/request_boundary_test.go @@ -0,0 +1,150 @@ +package server + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/servertoken" + "github.com/coder/websocket" +) + +const boundaryTestToken = "0123456789abcdef0123456789abcdef0123456789abcdef" + +func boundaryServer(t *testing.T, token string) *httptest.Server { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + srv := httptest.NewServer(HandlerWithOptions(ctx, Options{AccessToken: token, TerminalWithoutTmux: true})) + t.Cleanup(func() { srv.Close(); cancel() }) + return srv +} + +// raw sends one request to the server's loopback listener with an arbitrary +// Host header (a DNS-rebinding page names its own host). +func raw(t *testing.T, srv *httptest.Server, method, path, host string, header http.Header) int { + t.Helper() + req, err := http.NewRequest(method, srv.URL+path, nil) + if err != nil { + t.Fatal(err) + } + req.Host = host + for name, values := range header { + req.Header[name] = values + } + reply, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + reply.Body.Close() + return reply.StatusCode +} + +func upgradeHeader(extra map[string]string) http.Header { + h := http.Header{ + "Connection": {"Upgrade"}, + "Upgrade": {"websocket"}, + "Sec-Websocket-Version": {"13"}, + "Sec-Websocket-Key": {"dGhlIHNhbXBsZSBub25jZQ=="}, + } + for k, v := range extra { + h.Set(k, v) + } + return h +} + +func TestBoundaryRefusesRebindingHostOnEveryRoute(t *testing.T) { + srv := boundaryServer(t, "") + _, port, _ := net.SplitHostPort(strings.TrimPrefix(srv.URL, "http://")) + for _, path := range []string{"/connect", "/files?path=x", "/chat-uploads", "/discovery", "/mcp/chat/" + strings.Repeat("a", 64), "/healthz", "/artifacts/1/1/x"} { + for _, host := range []string{"rebind.example:" + port, "rebind.example", "127.0.0.1.nip.io:" + port, "127.0.0.1:1", "localhost:1", "[::1]:1", "10.0.0.5:" + port} { + if got := raw(t, srv, http.MethodGet, path, host, upgradeHeader(map[string]string{"Origin": "http://" + host})); got != http.StatusMisdirectedRequest { + t.Errorf("GET %s Host %s = %d, want 421", path, host, got) + } + } + } + // The reported reproduction: a rebinding upgrade must not switch protocols. + if got := raw(t, srv, http.MethodGet, "/connect", "rebind.example:"+port, upgradeHeader(map[string]string{"Origin": "http://rebind.example:" + port})); got == http.StatusSwitchingProtocols { + t.Fatal("rebinding upgrade accepted") + } +} + +func TestBoundaryAcceptsLoopbackHosts(t *testing.T) { + srv := boundaryServer(t, "") + _, port, _ := net.SplitHostPort(strings.TrimPrefix(srv.URL, "http://")) + for _, host := range []string{"127.0.0.1:" + port, "localhost:" + port, "LOCALHOST:" + port, "[::1]:" + port} { + if got := raw(t, srv, http.MethodGet, "/healthz", host, nil); got != http.StatusOK { + t.Errorf("Host %s = %d, want 200", host, got) + } + if got := raw(t, srv, http.MethodGet, "/connect", host, upgradeHeader(nil)); got != http.StatusSwitchingProtocols { + t.Errorf("upgrade Host %s = %d, want 101", host, got) + } + } +} + +func TestBoundaryRefusesOriginOnConnect(t *testing.T) { + srv := boundaryServer(t, "") + host := strings.TrimPrefix(srv.URL, "http://") + for _, origin := range []string{"http://" + host, "http://evil.example", "null"} { + if got := raw(t, srv, http.MethodGet, "/connect", host, upgradeHeader(map[string]string{"Origin": origin})); got != http.StatusForbidden { + t.Errorf("Origin %q = %d, want 403", origin, got) + } + } +} + +func TestBoundaryRequiresTheServerToken(t *testing.T) { + srv := boundaryServer(t, boundaryTestToken) + host := strings.TrimPrefix(srv.URL, "http://") + for _, path := range []string{"/connect", "/files?path=x", "/discovery", "/artifacts/1/1/x"} { + for _, presented := range []string{"", "wrong", boundaryTestToken + "x"} { + header := upgradeHeader(nil) + if presented != "" { + header.Set(servertoken.Header, presented) + } + if got := raw(t, srv, http.MethodGet, path, host, header); got != http.StatusUnauthorized { + t.Errorf("%s with token %q = %d, want 401", path, presented, got) + } + } + } + if got := raw(t, srv, http.MethodGet, "/connect", host, upgradeHeader(map[string]string{servertoken.Header: boundaryTestToken})); got != http.StatusSwitchingProtocols { + t.Errorf("upgrade with token = %d, want 101", got) + } + if got := raw(t, srv, http.MethodGet, "/discovery", host, http.Header{servertoken.Header: {boundaryTestToken}}); got != http.StatusOK { + t.Errorf("discovery with token = %d, want 200", got) + } + // Liveness and the chat-tools MCP endpoint (per-chat tokens) stay reachable + // to local tools that cannot add the header; Host rules still apply to them. + if got := raw(t, srv, http.MethodGet, "/healthz", host, nil); got != http.StatusOK { + t.Errorf("healthz without token = %d, want 200", got) + } + if got := raw(t, srv, http.MethodPost, "/mcp/chat/"+strings.Repeat("a", 64), host, nil); got == http.StatusUnauthorized { + t.Errorf("mcp refused for missing server token") + } +} + +func TestBoundaryTokenNeverReachesHandlers(t *testing.T) { + var seen string + handler := guardRequests(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seen = r.Header.Get(servertoken.Header) + }), boundaryTestToken) + req := httptest.NewRequest(http.MethodGet, "/files", nil) + req.Header.Set(servertoken.Header, boundaryTestToken) + handler.ServeHTTP(httptest.NewRecorder(), req) + if seen != "" { + t.Fatalf("handler saw the server token") + } +} + +// A client dialing through the coder/websocket library (the CLI and TUI +// transport) sends no Origin, so the Origin rule never refuses it. +func TestBoundaryLibraryDialSendsNoOrigin(t *testing.T) { + srv := boundaryServer(t, boundaryTestToken) + conn, _, err := websocket.Dial(context.Background(), "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", + &websocket.DialOptions{HTTPHeader: http.Header{servertoken.Header: {boundaryTestToken}}}) + if err != nil { + t.Fatal(err) + } + conn.CloseNow() +} diff --git a/internal/server/websocket.go b/internal/server/websocket.go index 06d619b6..12b57969 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -72,6 +72,9 @@ type Options struct { // them so they never share the real server's tmux sessions. TerminalTmuxSocket string TerminalWithoutTmux bool + // AccessToken, when set, is required on every request (servertoken.Header) + // except the chat-tools MCP endpoint and /healthz (request_boundary.go). + AccessToken string } // Handler serves the persistent connection with default options. Canceling ctx @@ -576,7 +579,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // runner's collaborators are wired and before any request is served. runs.reattachRuns() } - return &runHandler{Handler: mux, runner: runs, hub: hub} + return &runHandler{Handler: guardRequests(mux, options.AccessToken), runner: runs, hub: hub} } type runHandler struct { diff --git a/internal/servertoken/private_other.go b/internal/servertoken/private_other.go new file mode 100644 index 00000000..71fa7bc9 --- /dev/null +++ b/internal/servertoken/private_other.go @@ -0,0 +1,8 @@ +//go:build !unix + +package servertoken + +import "os" + +// Windows has no POSIX mode bits; the file lives in the user's profile. +func private(info os.FileInfo) bool { return true } diff --git a/internal/servertoken/private_unix.go b/internal/servertoken/private_unix.go new file mode 100644 index 00000000..e2ba66aa --- /dev/null +++ b/internal/servertoken/private_unix.go @@ -0,0 +1,13 @@ +//go:build unix + +package servertoken + +import ( + "os" + "syscall" +) + +func private(info os.FileInfo) bool { + stat, ok := info.Sys().(*syscall.Stat_t) + return ok && int(stat.Uid) == os.Getuid() && info.Mode().Perm()&0o077 == 0 +} diff --git a/internal/servertoken/servertoken.go b/internal/servertoken/servertoken.go new file mode 100644 index 00000000..1de434f2 --- /dev/null +++ b/internal/servertoken/servertoken.go @@ -0,0 +1,91 @@ +// Package servertoken is the shared secret between the Pipelines server and its +// local clients (the authenticated web proxy, the CLI, the TUI and the +// harnesses the server launches). +// +// The installer writes a random token to a private (0600) file next to the web +// sign-in file, by default $XDG_CONFIG_HOME/pipelines/server-token (else +// ~/.config/pipelines/server-token). A server started with the file configured +// (-token-file or PIPELINES_SERVER_TOKEN_FILE) refuses every request that does +// not carry the token in the Header header; local processes of the same OS +// user can read the file, other users, containers and browsers cannot. +package servertoken + +import ( + "crypto/subtle" + "errors" + "fmt" + "os" + "path/filepath" + "strings" +) + +// Header carries the token on every request to the server. +const Header = "X-Pipelines-Token" + +// EnvKey names the token file explicitly; it overrides the default location. +const EnvKey = "PIPELINES_SERVER_TOKEN_FILE" + +// minLength bounds a usable token (the installer writes 64 URL-safe chars). +const minLength = 32 + +// DefaultPath is the installer's default location, beside web-auth.json. +func DefaultPath() (string, error) { + directory := os.Getenv("XDG_CONFIG_HOME") + if directory == "" { + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + directory = filepath.Join(home, ".config") + } + return filepath.Join(directory, "pipelines", "server-token"), nil +} + +// Read loads a token from path. The file must be a regular file (not a +// symlink) owned by this user with no group or other permissions, so a token +// another user could read or replace is refused instead of trusted. +func Read(path string) (string, error) { + info, err := os.Lstat(path) + if err != nil { + return "", err + } + if !info.Mode().IsRegular() { + return "", fmt.Errorf("server token %s is not a regular file", path) + } + if !private(info) { + return "", fmt.Errorf("server token %s must be owned by this user and private (chmod 600)", path) + } + data, err := os.ReadFile(path) + if err != nil { + return "", err + } + token := strings.TrimSpace(string(data)) + if len(token) < minLength || len(token) > 4096 || strings.ContainsAny(token, " \t\r\n") { + return "", fmt.Errorf("server token %s is malformed", path) + } + return token, nil +} + +// ForClient returns the token a local client sends: the explicitly named file +// (PIPELINES_SERVER_TOKEN_FILE) or else the default file when it exists. No +// file means no token (an unconfigured or Docker server needs none); an +// explicitly named file that cannot be read is an error. +func ForClient() (string, error) { + if path := os.Getenv(EnvKey); path != "" { + return Read(path) + } + path, err := DefaultPath() + if err != nil { + return "", nil + } + token, err := Read(path) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + return token, err +} + +// Equal compares a presented token in constant time. +func Equal(presented, want string) bool { + return want != "" && subtle.ConstantTimeCompare([]byte(presented), []byte(want)) == 1 +} diff --git a/internal/servertoken/servertoken_test.go b/internal/servertoken/servertoken_test.go new file mode 100644 index 00000000..eb019a03 --- /dev/null +++ b/internal/servertoken/servertoken_test.go @@ -0,0 +1,45 @@ +//go:build unix + +package servertoken + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestReadAcceptsOnlyAPrivateRegularFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "server-token") + token := strings.Repeat("t", 48) + if err := os.WriteFile(path, []byte(token+"\n"), 0o600); err != nil { + t.Fatal(err) + } + if got, err := Read(path); err != nil || got != token { + t.Fatalf("Read = %q, %v", got, err) + } + if err := os.Chmod(path, 0o640); err != nil { + t.Fatal(err) + } + if _, err := Read(path); err == nil { + t.Fatal("group-readable token accepted") + } + os.Chmod(path, 0o600) + link := filepath.Join(dir, "link") + os.Symlink(path, link) + if _, err := Read(link); err == nil { + t.Fatal("symlinked token accepted") + } + short := filepath.Join(dir, "short") + os.WriteFile(short, []byte("short"), 0o600) + if _, err := Read(short); err == nil { + t.Fatal("short token accepted") + } +} + +func TestEqualIsExact(t *testing.T) { + if Equal("", "") || Equal("a", "") || !Equal("abc", "abc") || Equal("abc", "abd") { + t.Fatal("Equal mismatch") + } +}