package main // G1 hardening: the relay policy-checks a URL-path-derived name before it // calls /v1/fs/uploadUrl, but the daemon used to derive the stored name from // the response's Content-Disposition FIRST, so a remote server answering // `Content-Disposition: attachment; filename="evil.bat"` could store a // blocklisted extension the relay never approved. The relay now sends the // approved name in an optional "filename" field; the daemon stores exactly // that name (fixed-point verified) and keeps the legacy derivation for // callers that do not send the field. import ( "bytes" "context" "encoding/json" "fmt" "net" "net/http" "net/http/httptest" "net/netip" "os" "path/filepath" "strings" "testing" "time" ) func TestExplicitUploadFilename(t *testing.T) { cases := []struct { name string in string want string wantOK bool }{ // Panel-sanitized names are fixed points of sanitizeUploadFilename: // stored verbatim. {"plain name", "ok.zip", "ok.zip", true}, {"dotfile", ".env", ".env", true}, {"non-ascii", "café.txt", "café.txt", true}, {"long-but-under-cap", strings.Repeat("a", 200), strings.Repeat("a", 200), true}, // Anything the sanitizer would transform is refused so the daemon can // never store a different name than the relay approved. {"traversal basenamed", "../x", "", false}, {"interior separator", "ok.zip/evil.bat", "", false}, {"parent traversal", "a/..", "", false}, {"self traversal", "a/.", "", false}, {"backslash replaced", "back\\slash.bat", "", false}, {"control char replaced", "a\x01b.bat", "", false}, {"edge whitespace trimmed", " ok.zip ", "", false}, {"over cap", strings.Repeat("a", 201), "", false}, {"dot", ".", "", false}, {"dotdot", "..", "", false}, {"empty", "", "", false}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { got, ok := explicitUploadFilename(tc.in) if ok != tc.wantOK || got != tc.want { t.Fatalf("explicitUploadFilename(%q) = (%q, %v), want (%q, %v)", tc.in, got, ok, tc.want, tc.wantOK) } }) } } // The stored-name resolution: an explicit relay-approved name wins over the // Content-Disposition header; without one the legacy derivation (Content- // Disposition first, URL-path fallback, download.bin last) is byte-identical. func TestUploadURLStoredName(t *testing.T) { cases := []struct { name string explicit string cd string urlPath string want string }{ {"explicit beats evil Content-Disposition", "ok.zip", `attachment; filename="evil.bat"`, "/evil.bat", "ok.zip"}, {"explicit wins even when CD is sane", "ok.zip", `attachment; filename="server.zip"`, "/path.zip", "ok.zip"}, {"legacy CD first", "", `attachment; filename="evil.bat"`, "/ok.zip", "evil.bat"}, {"legacy CD sanitation", "", `attachment; filename="../../evil.bat"`, "/ok.zip", "evil.bat"}, {"legacy URL fallback", "", "", "/archive/ok.zip", "ok.zip"}, {"legacy URL beats junk CD", "", "garbage", "/ok.zip", "ok.zip"}, {"legacy download.bin fallback", "", "", "", "download.bin"}, {"legacy encoded URL segment", "", "", "/a/simple%20file.zip", "simple file.zip"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { got := uploadURLStoredName(tc.explicit, tc.cd, tc.urlPath) if got != tc.want { t.Fatalf("uploadURLStoredName(%q, %q, %q) = %q, want %q", tc.explicit, tc.cd, tc.urlPath, got, tc.want) } }) } } func newURLUploadFilenameTestAgent(t *testing.T) (*Agent, string) { t.Helper() tmp := t.TempDir() vol := filepath.Join(tmp, "servers") if err := os.MkdirAll(vol, 0o750); err != nil { t.Fatalf("mkdir volumes: %v", err) } serverDir := filepath.Join(vol, "alpha") if err := os.MkdirAll(serverDir, 0o750); err != nil { t.Fatalf("mkdir server dir: %v", err) } return &Agent{volumesDir: vol, uploadLimit: 1 << 20}, serverDir } func urlUploadFilenameRequest(t *testing.T, a *Agent, server, dir, urlStr string, filename *string) *httptest.ResponseRecorder { t.Helper() payload := map[string]any{"dir": dir, "server": server, "url": urlStr} if filename != nil { payload["filename"] = *filename } b, err := json.Marshal(payload) if err != nil { t.Fatalf("marshal payload: %v", err) } req := httptest.NewRequest(http.MethodPost, "/v1/fs/uploadUrl", bytes.NewReader(b)) rec := httptest.NewRecorder() a.handleFSUploadURL(rec, req) return rec } func TestProtectedURLUploadDispatch(t *testing.T) { agent, _ := newURLUploadFilenameTestAgent(t) agent.token = fixtureUploadDaemonToken req := httptest.NewRequest(http.MethodPut, "/v1/fs/uploadUrl", strings.NewReader(`{"filename":"."}`)) req.Header.Set("X-Node-Token", fixtureUploadDaemonToken) rec := httptest.NewRecorder() agent.ServeHTTP(rec, req) if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), `"invalid filename"`) { t.Fatalf("protected URL upload was not routed: %d %s", rec.Code, rec.Body) } } // An explicit filename that is not a fixed point of sanitizeUploadFilename is // refused before any URL validation, filesystem work or network I/O. func TestUploadURLRejectsNonFixedPointExplicitFilename(t *testing.T) { a, serverDir := newURLUploadFilenameTestAgent(t) for _, name := range []string{"../x", "", "ok.zip/evil.bat"} { fn := name rec := urlUploadFilenameRequest(t, a, "alpha", serverDir, "http://example.com/x.zip", &fn) if rec.Code != 400 { t.Fatalf("explicit filename %q: status %d, want 400 (body %s)", fn, rec.Code, rec.Body.String()) } var out map[string]any if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { t.Fatalf("decode response: %v", err) } if out["error"] != "invalid filename" { t.Fatalf("explicit filename %q: error %v, want \"invalid filename\"", fn, out["error"]) } } // Nothing was written. ents, err := os.ReadDir(serverDir) if err != nil { t.Fatalf("readdir server dir: %v", err) } if len(ents) != 0 { t.Fatalf("rejected uploads left files behind: %v", ents) } } // uploadURLTestAddress finds a local, non-loopback, non-private address the // daemon's own outbound fetch filter (isBlockedOutboundAddr) considers // fetchable, so the end-to-end URL-upload test can exercise the REAL // validate+fetch path against a local listener. The filter deliberately // refuses loopback/private targets (the panel proxies; see the SSRF residual // note), so most hosts - CI containers, laptops - have no such address and // the end-to-end tests skip there; the offline tests above still cover the // full decision matrix. func uploadURLTestAddress(t *testing.T) net.IP { t.Helper() ifaces, err := net.Interfaces() if err != nil { t.Skipf("enumerate interfaces: %v", err) } for _, ifc := range ifaces { if ifc.Flags&net.FlagUp == 0 || ifc.Flags&net.FlagLoopback != 0 { continue } addrs, err := ifc.Addrs() if err != nil { continue } for _, a := range addrs { var ip net.IP switch v := a.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if ip == nil { continue } nip, ok := netip.AddrFromSlice(ip) if !ok { continue } if !isBlockedOutboundAddr(nip) { return ip } } } t.Skip("no fetchable non-private local address: the daemon's outbound filter (correctly) refuses loopback/private targets") return nil } // serveURLUploadFixture serves one fixed body (with an optional // Content-Disposition header) from a listener bound to a fetchable local // address and returns the base URL for it. func serveURLUploadFixture(t *testing.T, contentDisposition string, body []byte) string { t.Helper() ip := uploadURLTestAddress(t) l, err := net.Listen("tcp", net.JoinHostPort(ip.String(), "0")) if err != nil { t.Skipf("listen on %s: %v", ip, err) } srv := &http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if contentDisposition != "" { w.Header().Set("Content-Disposition", contentDisposition) } w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body))) _, _ = w.Write(body) }), } go func() { _ = srv.Serve(l) }() t.Cleanup(func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() _ = srv.Shutdown(ctx) }) return "http://" + l.Addr().String() } // The end-to-end contract: with the fixture answering // Content-Disposition: filename="evil.bat", // - a request carrying filename:"ok.zip" stores ok.zip (the approved name), // - a request without the field stores evil.bat (legacy behavior kept). func TestUploadURLExplicitFilenameEndToEnd(t *testing.T) { a, serverDir := newURLUploadFilenameTestAgent(t) // The fixture listens on a non-standard port; the any-port escape hatch is // the established, tested way to lift the 80/443 allowlist for it. t.Setenv("REMOTE_FETCH_ALLOW_ANY_PORT", "1") content := bytes.Repeat([]byte("A"), 5120) baseURL := serveURLUploadFixture(t, `attachment; filename="evil.bat"`, content) ok := "ok.zip" rec := urlUploadFilenameRequest(t, a, "alpha", serverDir, baseURL+"/evil.bat", &ok) if rec.Code != 200 { t.Fatalf("explicit filename upload: status %d body %s", rec.Code, rec.Body.String()) } var resp struct { OK bool `json:"ok"` Filename string `json:"filename"` Bytes int64 `json:"bytes"` } if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode response: %v", err) } if !resp.OK || resp.Filename != "ok.zip" || resp.Bytes != int64(len(content)) { t.Fatalf("explicit filename response = %+v, want ok filename ok.zip %d bytes", resp, len(content)) } data, err := os.ReadFile(filepath.Join(serverDir, "ok.zip")) if err != nil { t.Fatalf("read stored file: %v", err) } if !bytes.Equal(data, content) { t.Fatalf("stored ok.zip content mismatch (%d bytes)", len(data)) } if _, err := os.Stat(filepath.Join(serverDir, "evil.bat")); err == nil { t.Fatalf("Content-Disposition name was stored despite explicit filename") } rec = urlUploadFilenameRequest(t, a, "alpha", serverDir, baseURL+"/evil.bat", nil) if rec.Code != 200 { t.Fatalf("legacy upload: status %d body %s", rec.Code, rec.Body.String()) } if _, err := os.Stat(filepath.Join(serverDir, "evil.bat")); err != nil { t.Fatalf("legacy (no filename field) did not store evil.bat: %v", err) } }