Merge pull request #180 from RuoJi6/fix/issue-163-repeater-raw-url

fix(repeater): preserve raw request-target without URL normalization
This commit is contained in:
RuoJi6 authored and GitHub committed 2026-11-23 18:33:03 +08:00
commit d80bf5e801
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)
}
}
@@ -1,4 +1,4 @@
import { buildRawResponse } from "./repeater-http";
import { buildRawResponse, rawRequestTarget } from "./repeater-http";
import type { RepeaterTab } from "./repeater-state";
export type RepeaterFilters = { query: string; method: string; path: string; response: string; status: string };
@@ -7,13 +7,7 @@ export const DEFAULT_FILTERS: RepeaterFilters = { query: "", method: "all", path
export function matchesRepeaterFilters(tab: RepeaterTab, filters: RepeaterFilters): boolean {
const includes = (text: string, query: string) => text.toLowerCase().includes(query.trim().toLowerCase());
if (filters.method !== "all" && tab.method.toUpperCase() !== filters.method) return false;
let path = tab.url;
try {
const url = new URL(tab.url);
path = url.pathname + url.search;
} catch {
/* Incomplete drafts remain searchable. */
}
const path = rawRequestTarget(tab.url) || tab.url;
if (!includes(path, filters.path)) return false;
const rawResponse = tab.response ? `${buildRawResponse(tab.response)}\n${tab.response.error || ""}` : "";
if (!includes(rawResponse, filters.response)) return false;
+63 -26
View File
@@ -103,12 +103,7 @@ export function requestFromTraffic(
if (/…\[truncated\] @blob sha256:[a-f0-9]{64}/.test(request.body)) {
throw new Error("请求正文为截断预览,请下载完整正文后再导入");
}
let host = exchange.host;
try {
host = new URL(exchange.url).host || host;
} catch {
/* Legacy URL uses the indexed host. */
}
const host = extractHttpHost(exchange.url) || exchange.host;
const headersText = getHostHeader(request.headersText)
? request.headersText
: setHostHeader(request.headersText, host);
@@ -124,26 +119,63 @@ export function requestFromTraffic(
};
}
export function connectionOrigin(url: string): string {
type SplitHttpUrl = {
origin: string;
host: string;
base: string;
rest: string;
};
// Parse only the scheme+authority via WHATWG URL so the raw request-target
// (path and query) is never percent-encoded, dot-collapsed, or backslash-rewritten.
function splitRawHttpUrl(raw: string): SplitHttpUrl | null {
const trimmed = raw.trim();
if (!/^https?:\/\//i.test(trimmed)) return null;
const schemeEnd = trimmed.indexOf("://") + 3;
const restOffset = trimmed.slice(schemeEnd).search(/[/?#]/);
const restIndex = restOffset < 0 ? trimmed.length : schemeEnd + restOffset;
const authority = trimmed.slice(schemeEnd, restIndex);
if (!authority || authority.includes("\\")) return null;
try {
const parsed = new URL(url);
return /^https?:$/.test(parsed.protocol) ? parsed.origin : "";
const parsed = new URL(trimmed.slice(0, restIndex));
if (!/^https?:$/.test(parsed.protocol) || !parsed.host) return null;
return {
origin: parsed.origin,
host: parsed.host,
base: parsed.href.replace(/\/$/, ""),
rest: trimmed.slice(restIndex),
};
} catch {
return "";
return null;
}
}
function normalizeRequestTarget(rest: string): string {
if (!rest) return "/";
return rest.startsWith("?") ? `/${rest}` : rest;
}
export function extractHttpHost(url: string): string {
const parsed = splitRawHttpUrl(url);
return parsed ? parsed.host : "";
}
export function rawRequestTarget(url: string): string {
const parsed = splitRawHttpUrl(url);
if (!parsed) return "";
return normalizeRequestTarget(parsed.rest.split("#", 1)[0]);
}
export function connectionOrigin(url: string): string {
const parsed = splitRawHttpUrl(url);
return parsed ? parsed.origin : "";
}
export function buildRawRequest(request: RepeaterInitial): string {
if (request.rawRequest !== undefined) return request.rawRequest;
let target = "/";
let host = "";
try {
const url = new URL(request.url ?? "");
target = url.pathname + url.search;
host = url.host;
} catch {
/* New empty draft. */
}
const parsed = splitRawHttpUrl(request.url ?? "");
const target = parsed ? normalizeRequestTarget(parsed.rest.split("#", 1)[0]) : "/";
const host = parsed ? parsed.host : "";
const headersText = request.headersText?.trim() ? request.headersText : `Host: ${host}`;
return `${request.method ?? "GET"} ${target} HTTP/1.1\n${joinRequestText(headersText, request.body ?? "")}`;
}
@@ -157,19 +189,24 @@ export function parseRawRequest(
const match = /^([A-Za-z]+)\s+(\S+)\s+(HTTP\/(?:1\.[01]|2(?:\.0)?))$/.exec(line);
if (!match) throw new Error("请求首行应为:POST /path HTTP/1.1");
const parts = splitRequestText(newline < 0 ? "" : text.slice(newline + 1));
let url: URL;
if (/^https?:\/\//i.test(match[2])) url = new URL(match[2]);
else {
if (!match[2].startsWith("/")) throw new Error("请求路径必须以 / 开头,或填写完整 http/https URL");
const requestTarget = match[2];
let url: string;
if (/^https?:\/\//i.test(requestTarget)) {
const parsed = splitRawHttpUrl(requestTarget);
if (!parsed) throw new TypeError(`Invalid URL: ${requestTarget}`);
if (parsed.rest.includes("#")) throw new Error("请求路径不能包含 URL 片段,请使用 %23 表示 #");
url = `${parsed.base}${normalizeRequestTarget(parsed.rest)}`;
} else {
if (!requestTarget.startsWith("/")) throw new Error("请求路径必须以 / 开头,或填写完整 http/https URL");
const origin = connectionOrigin(targetOrigin) || connectionOrigin(`https://${getHostHeader(parts.headersText)}`);
if (!origin) throw new Error("请填写 Host 请求头或设置发送目标");
url = new URL(origin + match[2]);
if (requestTarget.includes("#")) throw new Error("请求路径不能包含 URL 片段,请使用 %23 表示 #");
url = `${origin}${requestTarget}`;
}
if (url.hash) throw new Error("请求路径不能包含 URL 片段,请使用 %23 表示 #");
return {
...parts,
method: match[1].toUpperCase(),
url: url.href,
url,
httpVersion: match[3] === "HTTP/2" ? "HTTP/2.0" : match[3],
};
}
@@ -1,6 +1,6 @@
import type { RepeaterSendResponse } from "@/lib/types";
import type { RepeaterInitial } from "./repeater-http";
import { extractHttpHost, type RepeaterInitial } from "./repeater-http";
export const STORAGE_KEY = "artex_repeater_workspace_v1";
export const MAX_HISTORY = 20;
@@ -99,12 +99,7 @@ export function seedWorkspace(
opts: TabOptions = {},
): RepeaterWorkspace {
const method = initial.method?.trim().toUpperCase() || "GET";
let host = "";
try {
host = new URL(initial.url ?? "").host;
} catch {
/* An empty/unfinished URL is a valid draft. */
}
const host = extractHttpHost(initial.url ?? "");
return addTab(
workspace,
{ ...initial, method, source: meta },
@@ -582,3 +582,66 @@ test("evidence import preserves captured request line and protocol rather than r
assert.equal(imported.targetOrigin, "https://example.test");
assert.equal(buildRawRequest(imported), imported.rawRequest);
});
test("raw request-target characters in query and path are preserved without WHATWG URL normalization", () => {
const sqli = parseRawRequest("GET /item?id=1' HTTP/1.1\nHost: example.test\n\n");
assert.equal(sqli.url, "https://example.test/item?id=1'");
const specialQuery = parseRawRequest(
"GET /item?id=1'\"<>`{}\\| HTTP/1.1\nHost: example.test\n\n",
"http://example.test:8080",
);
assert.equal(specialQuery.url, "http://example.test:8080/item?id=1'\"<>`{}\\|");
const traversal = parseRawRequest("GET /a/../b/./c?id=1' HTTP/1.1\nHost: example.test\n\n");
assert.equal(traversal.url, "https://example.test/a/../b/./c?id=1'");
const encodedDots = parseRawRequest("GET /a/%2e%2e/b?x=' HTTP/1.1\nHost: example.test\n\n");
assert.equal(encodedDots.url, "https://example.test/a/%2e%2e/b?x='");
const rawPathChars = parseRawRequest("GET /a\\b\"c?q=' HTTP/1.1\nHost: example.test\n\n");
assert.equal(rawPathChars.url, "https://example.test/a\\b\"c?q='");
const absolute = parseRawRequest("GET http://elsewhere.test:8080/a/../item?id=1'\"<> HTTP/1.1\nHost: vhost.test\n\n");
assert.equal(absolute.url, "http://elsewhere.test:8080/a/../item?id=1'\"<>");
assert.equal(
parseRawRequest("GET http://elsewhere.test HTTP/1.1\nHost: elsewhere.test\n\n").url,
"http://elsewhere.test/",
);
assert.equal(
parseRawRequest("GET http://elsewhere.test?id=1' HTTP/1.1\nHost: elsewhere.test\n\n").url,
"http://elsewhere.test/?id=1'",
);
assert.throws(() => parseRawRequest("GET /item?id=1'#frag HTTP/1.1\nHost: example.test\n\n"), /URL 片段/);
assert.throws(() => parseRawRequest("GET /item# HTTP/1.1\nHost: example.test\n\n"), /URL 片段/);
assert.throws(
() => parseRawRequest("GET http://example.test/item?id=1'#frag HTTP/1.1\nHost: example.test\n\n"),
/URL 片段/,
);
assert.throws(() => parseRawRequest("GET http://example.test\\evil/path HTTP/1.1\nHost: example.test\n\n"));
const built = buildRawRequest({
method: "GET",
url: "https://example.test:8443/a/../item?id=1'",
});
assert.equal(built, "GET /a/../item?id=1' HTTP/1.1\nHost: example.test:8443\n\n");
const fromTraffic = requestFromTraffic("GET /item?id=1' HTTP/1.1\r\nHost: example.test\r\n\r\n", {
method: "GET",
url: "https://example.test/item?id=1'",
host: "example.test",
});
assert.equal(fromTraffic.url, "https://example.test/item?id=1'");
assert.match(fromTraffic.rawRequest, /^GET \/item\?id=1' HTTP\/1\.1\n/);
const tab = {
...defaultWorkspace().tabs[0],
method: "GET",
url: "https://example.test/a/../item?id=1'",
rawRequest: "GET /a/../item?id=1' HTTP/1.1\nHost: example.test\n\n",
};
assert.equal(matchesRepeaterFilters(tab, { ...DEFAULT_FILTERS, path: "id=1'" }), true);
assert.equal(matchesRepeaterFilters(tab, { ...DEFAULT_FILTERS, path: "/a/../item" }), true);
});