fix(repeater): preserve raw request-target without URL normalization

- Parse only scheme and authority via WHATWG URL in frontend repeater helpers so raw path and query characters (e.g. `'`, `"`, `<`, `>`, `../`, `%2e%2e`, `\`) are not normalized or percent-encoded.
- Preserve raw request-targets in buildRawRequest, requestFromTraffic, and repeater path filtering.
- Preserve raw path and query targets in backend /api/repeater/send across HTTP/1.1 direct, HTTP proxy, and HTTP/2 while retaining scheme/authority validation and SSRF guards.
- Add frontend and backend regression tests covering raw query and path wire fidelity.

Fixes #163
This commit is contained in:
ji ruo committed 2026-11-23 18:17:45 +08:00
1 parent 7b196bf683
commit bedc8721b4
6 files changed
+398 -49

No files matched your search

+127 -8
View File
@@ -104,15 +104,14 @@ func (s *Server) sendRepeater(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "url 必填")
return
}
u, err := url.Parse(rawURL)
if err != nil || u.Host == "" || u.Hostname() == "" ||
!strings.EqualFold(u.Scheme, "http") && !strings.EqualFold(u.Scheme, "https") {
target, err := parseRepeaterURL(rawURL)
if err != nil {
writeErr(w, http.StatusBadRequest, "仅支持绝对 http/https URL")
return
}
// This check is needed even when a proxy is used: the proxy must remain usable
// for normal targets, while obvious literal metadata/loopback URLs stay blocked.
if err := repeaterCheckURL(u); err != nil {
if err := repeaterCheckURL(target.origin); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
@@ -138,11 +137,12 @@ func (s *Server) sendRepeater(w http.ResponseWriter, r *http.Request) {
}
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(timeoutMs)*time.Millisecond)
defer cancel()
req, err := http.NewRequestWithContext(ctx, method, u.String(), body)
req, err := http.NewRequestWithContext(ctx, method, target.origin.String(), body)
if err != nil {
writeErr(w, http.StatusBadRequest, "构造请求失败")
return
}
req.URL = target.requestURL()
httpidentity.Apply(req)
for key, value := range in.Headers {
name := strings.TrimSpace(key)
@@ -180,7 +180,15 @@ func (s *Server) sendRepeater(w http.ResponseWriter, r *http.Request) {
tr.Protocols = new(http.Protocols)
tr.Protocols.SetHTTP1(in.HTTPVersion == "HTTP/1.1")
tr.Protocols.SetHTTP2(in.HTTPVersion == "HTTP/2.0")
tr.Protocols.SetUnencryptedHTTP2(in.HTTPVersion == "HTTP/2.0" && strings.EqualFold(u.Scheme, "http"))
tr.Protocols.SetUnencryptedHTTP2(in.HTTPVersion == "HTTP/2.0" && strings.EqualFold(target.origin.Scheme, "http"))
}
if target.needsOpaque && strings.EqualFold(req.URL.Scheme, "http") {
if tr, ok := transport.(*http.Transport); ok && tr.Proxy != nil {
if proxyURL, perr := tr.Proxy(req); perr == nil && proxyURL != nil &&
(strings.EqualFold(proxyURL.Scheme, "http") || strings.EqualFold(proxyURL.Scheme, "https")) {
req.URL.Opaque = "//" + req.URL.Host + target.rawPath
}
}
}
client := &http.Client{
@@ -207,16 +215,20 @@ func (s *Server) sendRepeater(w http.ResponseWriter, r *http.Request) {
resp, err := client.Do(req)
if err != nil {
writeJSON(w, http.StatusOK, repeaterSendResponse{
Headers: map[string][]string{}, URL: u.String(),
Headers: map[string][]string{}, URL: target.displayURL,
ElapsedMs: time.Since(started).Milliseconds(), Error: repeaterRedactError(err),
})
return
}
defer resp.Body.Close()
respURL := target.displayURL
if resp.Request != nil && resp.Request.URL != nil && resp.Request.URL.Opaque == "" {
respURL = resp.Request.URL.String()
}
out := repeaterSendResponse{
Status: resp.StatusCode, StatusText: resp.Status, Proto: resp.Proto,
Headers: resp.Header.Clone(), URL: resp.Request.URL.String(),
Headers: resp.Header.Clone(), URL: respURL,
}
if method != http.MethodHead {
// Read one byte beyond the cap so truncation is exact. The MVP keeps the
@@ -236,6 +248,113 @@ func (s *Server) sendRepeater(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, out)
}
type repeaterTargetURL struct {
origin *url.URL
parsed *url.URL
rawPath string
rawQuery string
forceQuery bool
needsOpaque bool
displayURL string
}
func (t *repeaterTargetURL) requestURL() *url.URL {
if !t.needsOpaque {
u := *t.parsed
return &u
}
u := *t.origin
u.Path = ""
u.RawPath = ""
u.RawQuery = t.rawQuery
u.ForceQuery = t.forceQuery
u.Opaque = t.rawPath
return &u
}
// parseRepeaterURL validates the scheme and authority while preserving the raw
// request-target (path and query). Normal targets keep Opaque empty so net/http
// handles proxies, redirects and HTTP/2 natively; Opaque is only engaged when
// rawPath contains characters that net/url would percent-encode or reject.
func parseRepeaterURL(rawURL string) (*repeaterTargetURL, error) {
for i := range len(rawURL) {
if rawURL[i] < 0x20 || rawURL[i] == 0x7f {
return nil, errors.New("control character in URL")
}
}
schemeSep := strings.Index(rawURL, "://")
if schemeSep <= 0 {
return nil, errors.New("missing scheme")
}
scheme := rawURL[:schemeSep]
if !strings.EqualFold(scheme, "http") && !strings.EqualFold(scheme, "https") {
return nil, errors.New("unsupported scheme")
}
afterScheme := rawURL[schemeSep+3:]
restIdx := strings.IndexAny(afterScheme, "/?#")
authority, rest := afterScheme, ""
if restIdx >= 0 {
authority, rest = afterScheme[:restIdx], afterScheme[restIdx:]
}
if authority == "" || strings.Contains(authority, "\\") {
return nil, errors.New("invalid authority")
}
origin, err := url.Parse(rawURL[:schemeSep+3+len(authority)])
if err != nil || origin.Host == "" || origin.Hostname() == "" ||
(!strings.EqualFold(origin.Scheme, "http") && !strings.EqualFold(origin.Scheme, "https")) {
return nil, errors.New("invalid origin")
}
beforeHash := rest
if hash := strings.IndexByte(beforeHash, '#'); hash >= 0 {
beforeHash = beforeHash[:hash]
}
rawPath, rawQuery := beforeHash, ""
hasQuery := false
if q := strings.IndexByte(beforeHash, '?'); q >= 0 {
rawPath = beforeHash[:q]
rawQuery = beforeHash[q+1:]
hasQuery = true
}
if rawPath == "" {
rawPath = "/"
}
u, parseErr := url.Parse(rawURL)
needsOpaque := false
if parseErr != nil {
if strings.HasPrefix(rawPath, "//") {
return nil, parseErr
}
needsOpaque = true
} else {
escapedPath := u.EscapedPath()
if escapedPath == "" {
escapedPath = "/"
}
if escapedPath != rawPath && !strings.HasPrefix(rawPath, "//") {
needsOpaque = true
}
}
displayURL := origin.String() + rawPath
if hasQuery {
displayURL += "?" + rawQuery
}
if !needsOpaque {
displayURL = u.String()
}
return &repeaterTargetURL{
origin: origin,
parsed: u,
rawPath: rawPath,
rawQuery: rawQuery,
forceQuery: hasQuery && rawQuery == "",
needsOpaque: needsOpaque,
displayURL: displayURL,
}, nil
}
// repeaterBodyText keeps the response preview as text for the MVP. Invalid
// UTF-8 and NUL bytes are replaced so a binary response cannot inject control
// characters into the JSON/UI raw view; the original bytes are not base64
+141
View File
@@ -1,6 +1,7 @@
package server
import (
"bufio"
"bytes"
"context"
"crypto/tls"
@@ -440,3 +441,143 @@ func TestRepeaterExplicitHTTP2Cleartext(t *testing.T) {
t.Fatalf("status=%d response=%s", code, raw)
}
}
func startRawWireCaptureServer(t *testing.T) (string, <-chan string) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = ln.Close() })
lines := make(chan string, 16)
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func(c net.Conn) {
defer c.Close()
r := bufio.NewReader(c)
line, err := r.ReadString('\n')
if err != nil {
return
}
for {
h, err := r.ReadString('\n')
if err != nil || h == "\r\n" || h == "\n" {
break
}
}
lines <- strings.TrimRight(line, "\r\n")
_, _ = c.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"))
}(conn)
}
}()
return ln.Addr().String(), lines
}
func TestRepeaterPreservesRawRequestTarget(t *testing.T) {
t.Setenv(repeaterAllowLocalEnv, "1")
addr, wireLines := startRawWireCaptureServer(t)
cases := []string{
"/item?id=1'",
"/item?id=1'\"><`{}|\\",
"/a/../b/./c?id=1'",
"/a/%2e%2e/b?x='",
"//a//b?c=1'",
"/a\\b?id=1'",
"/a\"b?id=1'",
"/a%zz/b?id=1'",
}
for _, target := range cases {
t.Run("h1-direct/"+target, func(t *testing.T) {
rawURL := "http://" + addr + target
code, out, body := repeaterTestSend(t, &Server{}, map[string]any{
"method": "GET", "url": rawURL, "use_recording_proxy": false,
})
if code != http.StatusOK || out.Error != "" || out.Status != http.StatusOK {
t.Fatalf("status=%d out=%+v body=%s", code, out, body)
}
if out.URL != rawURL {
t.Fatalf("response url=%q want %q", out.URL, rawURL)
}
select {
case got := <-wireLines:
want := "GET " + target + " HTTP/1.1"
if got != want {
t.Fatalf("wire request line=%q want %q", got, want)
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for wire request line")
}
})
}
// Plain HTTP through an HTTP proxy must retain proxy-form absolute URI for both normal and opaque raw paths.
proxyAddr, proxyLines := startRawWireCaptureServer(t)
proxiedServer := &Server{m: &Manager{globalProxy: "http://" + proxyAddr}}
for _, target := range []string{"/item?id=1'", "/a\\b?id=1'"} {
t.Run("h1-proxy/"+target, func(t *testing.T) {
rawURL := "http://target.example" + target
code, out, body := repeaterTestSend(t, proxiedServer, map[string]any{
"method": "GET", "url": rawURL, "use_recording_proxy": false,
})
if code != http.StatusOK || out.Error != "" || out.Status != http.StatusOK {
t.Fatalf("status=%d out=%+v body=%s", code, out, body)
}
select {
case got := <-proxyLines:
want := "GET " + rawURL + " HTTP/1.1"
if got != want {
t.Fatalf("proxy request line=%q want %q", got, want)
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for proxy request line")
}
})
}
// HTTP/2 must also preserve raw query and path targets verbatim.
h2srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, r.RequestURI)
}))
h2srv.EnableHTTP2 = true
h2srv.TLS = &tls.Config{NextProtos: []string{"h2"}}
h2srv.StartTLS()
defer h2srv.Close()
for _, target := range []string{"/item?id=1'", "/a/../b?x='", "/a\\b?id=1'"} {
t.Run("h2-direct/"+target, func(t *testing.T) {
rawURL := h2srv.URL + target
code, out, body := repeaterTestSend(t, &Server{}, map[string]any{
"method": "GET", "url": rawURL, "http_version": "HTTP/2.0",
"insecure_skip_verify": true, "use_recording_proxy": false,
})
if code != http.StatusOK || out.Error != "" || out.Body != target {
t.Fatalf("h2 status=%d body=%q raw=%s", code, out.Body, body)
}
})
}
}
func TestRepeaterRawURLValidationAndSSRFGuard(t *testing.T) {
t.Setenv(repeaterAllowLocalEnv, "")
s := &Server{}
for _, bad := range []string{
"http://example.test\\evil/path",
"http://example.test/a\nb",
"http://example.test:abc/path",
} {
code, _, body := repeaterTestSend(t, s, map[string]any{"url": bad, "use_recording_proxy": false})
if code != http.StatusBadRequest {
t.Fatalf("url=%q status=%d want 400 body=%s", bad, code, body)
}
}
code, _, body := repeaterTestSend(t, s, map[string]any{
"url": "http://127.0.0.1/a\\b?id=1'", "use_recording_proxy": false,
})
if code != http.StatusBadRequest || !strings.Contains(body, "拒绝") {
t.Fatalf("opaque loopback status=%d body=%s", code, body)
}
}