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.
This commit is contained in:
@@ -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, "%")
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user