diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index b045abfc6..6963df111 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3004,10 +3004,14 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } .session-terminal-select, .pref-pick { max-width: min(230px, 45%); height: 29px; color: var(--fg); } .session-terminal-select:focus-visible, .pref-pick:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } .row.pref .segs { flex: none; margin-left: auto; } -.proxy-segs { display: flex; align-items: center; gap: 8px; margin-left: auto; min-width: 0; } -.proxy-segs input.proxy, input.words { width: 180px; min-width: 0; height: 27px; padding: 0 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); font-size: 12.5px; outline: none; transition: border-color .12s, box-shadow .12s; } -.proxy-segs input.proxy:focus, input.words:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); } -.proxy-segs input.proxy::placeholder, input.words::placeholder { color: var(--faint); } +.proxy-segs { display: flex; flex-direction: column; align-items: flex-end; gap: 8px; margin-left: auto; min-width: 0; max-width: 100%; } +.proxy-controls, .proxy-auth { display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: 8px; min-width: 0; max-width: 100%; } +.proxy-auth[hidden] { display: none; } +.proxy-segs input.proxy, .proxy-segs input.proxy-credential, input.words { width: 180px; max-width: 100%; min-width: 0; height: 27px; padding: 0 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); font-size: 12.5px; outline: none; transition: border-color .12s, box-shadow .12s; } +.proxy-segs input.proxy-credential { width: 140px; } +.proxy-auth .text { flex: none; } +.proxy-segs input:focus, input.words:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); } +.proxy-segs input::placeholder, input.words::placeholder { color: var(--faint); } input.words { width: 240px; max-width: 100%; } /* Settings → Long conversations: 272K or the size typed, beside it (#876) */ .compact-at { display: flex; align-items: center; gap: 8px; margin-left: auto; flex: none; } @@ -3245,7 +3249,8 @@ body.panel .modal { padding: 16px 12px; } body.web .row.pref .sub { white-space: normal; } body.web .row.pref .segs { margin-left: 0; max-width: 100%; flex-wrap: wrap; } body.web .row.pref .warm-at.times { max-width: 100%; } - body.web .proxy-segs { margin-left: 0; flex-wrap: wrap; justify-content: flex-start; } + body.web .proxy-segs { margin-left: 0; align-items: flex-start; } + body.web .proxy-controls, body.web .proxy-auth { justify-content: flex-start; } body.web .usage-head { height: auto; min-height: 44px; flex-wrap: wrap; gap: 8px; } body.web .usage-head > .segs { max-width: 100%; flex-wrap: wrap; } body.web .usage-head > .grow, body.web .sess-tools > .grow { display: none; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 0897cee2a..5ce908f38 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -21594,19 +21594,43 @@ const UPDATE_EVERY = [30, 60, 360, 1440]; // that names a proxy of its own (or Direct) keeps it whatever this says (netproxy.With), so the // line says it holds for those without one (#1832). let proxyCustom = false; // Custom picked, nothing typed yet +// Keep SOCKS credentials in their own fields; URL userinfo is the existing +// saved format, with reserved characters escaped before it reaches Go/Bun. +function proxyFields(value) { + try { + const u = new URL(value); + if (/^socks5h?:$/.test(u.protocol)) { + const encodedUsername = u.username, encodedPassword = u.password; + // A saved proxy can contain non-UTF-8 credential bytes. Keep their + // escapes, still masked, and preserve those bytes until edited. + const decode = (v) => { try { return decodeURIComponent(v); } catch { return v; } }; + u.username = ""; u.password = ""; + return { address: u.href, username: decode(encodedUsername), password: decode(encodedPassword), encodedUsername, encodedPassword, socks: true }; + } + } catch {} + return { address: value, username: "", password: "", socks: /^socks5h?:\/\//i.test(value) }; +} +function proxyDisplay(value) { + // Also mask an older backend's proxyNow, and environment/system proxies. + return (value || "").replace(/^(\w+:\/\/)?[^/?#]*@/, "$1"); +} function renderProxy(s, keep) { const cur = !s.proxy ? "auto" : s.proxy === "direct" ? "off" : "custom"; const mode = proxyCustom ? "custom" : cur; const sub = $("#proxySub"); sub.textContent = { - settings: t("Requests to vendors without a proxy of their own, and update checks, go through {proxy}", { proxy: s.proxyNow }), - system: t("Following the system proxy, {proxy}", { proxy: s.proxyNow }), - environment: t("Following HTTPS_PROXY, {proxy}", { proxy: s.proxyNow }), + settings: t("Requests to vendors without a proxy of their own, and update checks, go through {proxy}", { proxy: proxyDisplay(s.proxyNow) }), + system: t("Following the system proxy, {proxy}", { proxy: proxyDisplay(s.proxyNow) }), + environment: t("Following HTTPS_PROXY, {proxy}", { proxy: proxyDisplay(s.proxyNow) }), off: t("Off: requests to vendors without a proxy of their own, and update checks, go direct"), none: t("No system proxy found; requests to vendors without a proxy of their own, and update checks, go direct"), }[s.proxySource] || ""; const box = $("#proxySegs"); box.replaceChildren(); + const row = el("div", "proxy-controls"); + box.append(row); + let picking = false; + let saveOnLeave = null; const pick = (id) => { proxyCustom = id === "custom"; if (id === "auto") savePrefs({ ...keep, proxy: "" }); @@ -21614,20 +21638,70 @@ function renderProxy(s, keep) { else renderProxy(s, keep); }; if (mode === "custom") { - const i = input(cur === "custom" ? s.proxy : "", "http://127.0.0.1:7890"); + let fields = proxyFields(cur === "custom" ? s.proxy : ""); + const i = input(fields.address, "http://127.0.0.1:7890"); i.className = "proxy"; + i.setAttribute("aria-label", t("Proxy address")); + const auth = el("div", "proxy-auth"); + const username = input(fields.username, t("Username (optional)")); + const password = input(fields.password, t("Password (optional)"), "password"); + for (const field of [username, password]) { + field.className = "proxy-credential"; + field.setAttribute("aria-label", field.placeholder); + } + const updateAuth = () => { + const parsed = proxyFields(i.value.trim()); + auth.hidden = !parsed.socks; + if (parsed.username || parsed.password) { + fields = parsed; + i.value = parsed.address; + username.value = parsed.username; password.value = parsed.password; + } + }; + i.oninput = updateAuth; + updateAuth(); + let saving = false; const save = () => { - const v = i.value.trim(); - if (!v || v === s.proxy) return; + let v = i.value.trim(); + if (!v || saving) return; + if (!auth.hidden) { + try { + const u = new URL(v); + u.username = username.value === fields.username && fields.encodedUsername !== undefined ? fields.encodedUsername : encodeURIComponent(username.value); + u.password = password.value === fields.password && fields.encodedPassword !== undefined ? fields.encodedPassword : encodeURIComponent(password.value); + v = u.href; + } catch {} // the settings API explains an invalid address + } + if (v === s.proxy) return; + saving = true; proxyCustom = false; savePrefs({ ...keep, proxy: v }); }; - i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") save(); else if (e.key === "Escape") { proxyCustom = false; renderProxy(s, keep); } }; - i.onblur = save; - box.append(i); + // Moving between fields must not redraw the row with a partial login. + // A mode click makes its own save and must not also save the old draft. + saveOnLeave = (e) => { + if (box.contains(e.relatedTarget)) return; + queueMicrotask(() => { if (i.isConnected && !picking) save(); }); + }; + for (const field of [i, username, password]) { + field.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") save(); else if (e.key === "Escape") { proxyCustom = false; renderProxy(s, keep); } }; + field.onfocus = () => { picking = false; }; + field.onblur = saveOnLeave; + } + const apply = el("button", "text", t("Save")); + apply.onclick = save; + apply.onblur = saveOnLeave; + auth.append(username, password, apply); + row.append(i); + box.append(auth); if (proxyCustom) queueMicrotask(() => i.focus()); } - box.append(segs([["auto", t("Auto")], ["off", t("Off")], ["custom", t("Custom")]], mode, pick)); + const modes = segs([["auto", t("Auto")], ["off", t("Off")], ["custom", t("Custom")]], mode, pick); + // WebKit doesn't focus clicked buttons, so relatedTarget alone can't tell + // a mode click from leaving the proxy editor. + modes.onpointerdown = () => { picking = true; }; + for (const button of modes.querySelectorAll("button")) button.onblur = saveOnLeave; + row.append(modes); } // renderGitHubToken: the GitHub token the library's requests to GitHub's diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index ecab3b346..2a70c08ee 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -735,6 +735,9 @@ const I18N = { "A closed panel or window frees about 100 MB after a minute; opening it loads it again": "面板或窗口关闭一分钟后释放约 100 MB,再次打开时重新加载", "With window": "跟随窗口", "Proxy": "代理", + "Proxy address": "代理地址", + "Username (optional)": "用户名(可选)", + "Password (optional)": "密码(可选)", "Requests to vendors without a proxy of their own, and update checks, go through {proxy}": "未单独设置代理的模型厂商请求和检查更新都经由 {proxy}", "Following the system proxy, {proxy}": "跟随系统代理:{proxy}", "Following HTTPS_PROXY, {proxy}": "跟随 HTTPS_PROXY:{proxy}", @@ -9814,6 +9817,9 @@ const I18N = { "A closed panel or window frees about 100 MB after a minute; opening it loads it again": "閉じたパネルやウィンドウは 1 分後に約 100 MB を解放し、開くと読み込み直します", "With window": "ウィンドウと連動", "Proxy": "プロキシ", + "Proxy address": "プロキシアドレス", + "Username (optional)": "ユーザー名(任意)", + "Password (optional)": "パスワード(任意)", "Requests to vendors without a proxy of their own, and update checks, go through {proxy}": "独自のプロキシを設定していないベンダーへのリクエストとアップデート確認は {proxy} を経由します", "Following the system proxy, {proxy}": "システムプロキシに従う:{proxy}", "Following HTTPS_PROXY, {proxy}": "HTTPS_PROXY に従う:{proxy}", @@ -14354,6 +14360,9 @@ const I18N = { "A closed panel or window frees about 100 MB after a minute; opening it loads it again": "Ein geschlossenes Panel oder Fenster gibt nach einer Minute etwa 100 MB frei und lädt beim Öffnen neu", "With window": "Mit Fenster", "Proxy": "Proxy", + "Proxy address": "Proxy-Adresse", + "Username (optional)": "Benutzername (optional)", + "Password (optional)": "Passwort (optional)", "Requests to vendors without a proxy of their own, and update checks, go through {proxy}": "Anfragen an Anbieter ohne eigenen Proxy und Update-Prüfungen laufen über {proxy}", "Following the system proxy, {proxy}": "Folgt dem System-Proxy, {proxy}", "Following HTTPS_PROXY, {proxy}": "Folgt HTTPS_PROXY, {proxy}", diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 839f874ea..e60012f6a 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -1,5 +1,11 @@ # Dropdown browser regression +`settings-proxy-auth.test.cjs` checks optional SOCKS5/SOCKS5h usernames and +passwords in Settings, using the real page with isolated API fixtures. It +covers saving and reloading, escaped and non-UTF-8 credentials, masked +addresses/status, clearing authentication, Tab and Escape, mode switches, +HTTP compatibility, and narrow windows in English and Chinese on Chromium +and WebKit. ## Installed desktop fonts `fonts.test.cjs` exercises the interface/code font controls with installed diff --git a/internal/gui/tests/settings-proxy-auth.test.cjs b/internal/gui/tests/settings-proxy-auth.test.cjs new file mode 100644 index 000000000..d3dcb6a4d --- /dev/null +++ b/internal/gui/tests/settings-proxy-auth.test.cjs @@ -0,0 +1,142 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Optional SOCKS credentials survive saving/reloading, never appear in the +// address or status, and typing between fields cannot save a partial login. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +function server(lang, posts, proxy = "") { + let cur = { + theme: "light", lang, tray: "panel", currency: "usd", textSize: 100, + proxy, proxyNow: proxy, proxySource: proxy ? "settings" : "none", + trayUsageEvery: 3, version: "test", dir: "/test", lanURLs: [], + visionModels: [], imageGenModels: [], workbuddyCheckins: [], + fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, + }; + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ lang, theme: "light", web: true })};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: cur.fx }); + if (url.pathname === "/api/settings") { + if (req.method() === "POST") { + const body = req.postDataJSON(); + posts.push(body); + cur = { ...cur, ...body, proxyNow: body.proxy, proxySource: body.proxy === "direct" ? "off" : body.proxy ? "settings" : "none" }; + } + return json(cur); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + return route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + test(`${engine} ${lang}: optional SOCKS credentials in settings`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const context = await browser.newContext({ viewport: { width: 1100, height: 760 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(4000); + const posts = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, posts)); + await page.goto("http://magpie.test/?view=settings&tab=network"); + const box = page.locator("#proxySegs"); + const address = box.locator("input.proxy"); + const user = box.getByRole("textbox", { name: lang === "zh" ? "用户名(可选)" : "Username (optional)", exact: true }); + const pass = box.getByLabel(lang === "zh" ? "密码(可选)" : "Password (optional)", { exact: true }); + const saved = async (action, want) => { + const count = posts.length; + const response = page.waitForResponse((r) => r.url().endsWith("/api/settings") && r.request().method() === "POST"); + await action(); + await response; + await page.waitForFunction(() => document.querySelector("#status")?.textContent.includes("Saved") || document.querySelector("#status")?.textContent.includes("已保存")); + assert.equal(posts.length, count + 1, "save once for the whole proxy"); + assert.equal(posts.at(-1).proxy, want); + }; + + await box.getByRole("button", { name: lang === "zh" ? "自定义" : "Custom", exact: true }).click(); + await address.fill("socks5://127.0.0.1:1080"); + await user.fill("a@b:/% 用户"); + await user.press("Tab"); + assert.equal(posts.length, 0, "tabbing from username to password must not save half a login"); + await pass.fill("p@ss:/% #密码"); + assert.equal(await pass.getAttribute("type"), "password"); + const encoded = "socks5://a%40b%3A%2F%25%20%E7%94%A8%E6%88%B7:p%40ss%3A%2F%25%20%23%E5%AF%86%E7%A0%81@127.0.0.1:1080"; + await saved(async () => { + // WebKit may skip Save when tabbing, leaving the editor and saving + // now. If Tab stays inside, clicking outside saves the same login. + await pass.press("Tab"); + await page.locator("#proxySub").click(); + }, encoded); + await page.reload(); + assert.equal(await address.inputValue(), "socks5://127.0.0.1:1080"); + assert.equal(await user.inputValue(), "a@b:/% 用户"); + assert.equal(await pass.inputValue(), "p@ss:/% #密码"); + assert(!((await page.locator("#proxySub").innerText()).includes("p%40ss")), "status exposes the encoded password"); + assert(!((await page.locator("#proxySub").innerText()).includes("p@ss")), "status exposes the password"); + + for (const width of [1100, 560, 375]) { + await page.setViewportSize({ width, height: 760 }); + for (const field of [address, user, pass]) { + const rect = await field.boundingBox(); + assert(rect && rect.x >= 0 && rect.x + rect.width <= width, `proxy field outside ${width}px window`); + } + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-proxy-${width}.png`) }); + } + } + + await user.fill(""); + await pass.fill(""); + await saved(() => pass.press("Enter"), "socks5://127.0.0.1:1080"); + await page.reload(); + assert.equal(await user.inputValue(), ""); + assert.equal(await pass.inputValue(), ""); + + // Pasting an existing URL separates and decodes the login, including IPv6. + await address.fill("socks5h://name:p%40ss@[::1]:1080"); + assert.equal(await address.inputValue(), "socks5h://[::1]:1080"); + assert.equal(await user.inputValue(), "name"); + assert.equal(await pass.inputValue(), "p@ss"); + await saved(() => pass.press("Enter"), "socks5h://name:p%40ss@[::1]:1080"); + await pass.fill("discard-me"); + const beforeEscape = posts.length; + await pass.press("Escape"); + assert.equal(await pass.inputValue(), "p@ss"); + assert.equal(posts.length, beforeEscape, "Escape must discard, not save, the draft"); + + // Arbitrary encoded bytes in an existing password remain masked and intact. + await address.fill("socks5://name:p%FFss@127.0.0.1:1080"); + assert.equal(await address.inputValue(), "socks5://127.0.0.1:1080"); + assert.equal(await pass.inputValue(), "p%FFss"); + await saved(() => box.getByRole("button", { name: lang === "zh" ? "保存" : "Save", exact: true }).click(), "socks5://name:p%FFss@127.0.0.1:1080"); + + // HTTP and bare addresses still work; a hidden SOCKS login isn't attached. + await address.fill("http://127.0.0.1:7890"); + assert.equal(await user.isVisible(), false); + await saved(() => address.press("Enter"), "http://127.0.0.1:7890"); + await address.fill("127.0.0.1:7891"); + await saved(() => page.locator("#proxySub").click(), "127.0.0.1:7891"); + + await address.fill("socks5://127.0.0.1:1080"); + await user.fill("unsaved-user"); + await pass.fill("unsaved-password"); + await saved(() => box.getByRole("button", { name: lang === "zh" ? "关闭" : "Off", exact: true }).click(), "direct"); + await saved(() => box.getByRole("button", { name: lang === "zh" ? "自动" : "Auto", exact: true }).click(), ""); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/netproxy/describe_test.go b/internal/netproxy/describe_test.go new file mode 100644 index 000000000..635da4ce8 --- /dev/null +++ b/internal/netproxy/describe_test.go @@ -0,0 +1,58 @@ +package netproxy + +import ( + "net/url" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +// The settings status must not display credentials; requests still need them. +func TestDescribeHidesProxyCredentials(t *testing.T) { + for _, source := range []string{"settings", "environment", "system"} { + for _, tc := range []struct{ name, raw, want string }{ + {"plain", "socks5://127.0.0.1:1080", "socks5://127.0.0.1:1080"}, + {"authenticated", "socks5://alice:secret@127.0.0.1:1080", "socks5://127.0.0.1:1080"}, + {"encoded", "socks5h://ali%40ce:p%3Aa%2Fss%25@[::1]:1080", "socks5h://[::1]:1080"}, + {"username", "http://alice@127.0.0.1:7890", "http://127.0.0.1:7890"}, + } { + t.Run(source+"/"+tc.name, func(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} { + t.Setenv(k, "") + } + sysCache.at, sysCache.p = farFuture, Proxy{} + t.Cleanup(func() { sysCache.at = zero }) + switch source { + case "settings": + if err := settings.Save(settings.Settings{Proxy: tc.raw}); err != nil { + t.Fatal(err) + } + case "environment": + t.Setenv("ALL_PROXY", tc.raw) + case "system": + sysCache.p.URL = tc.raw + } + if got, from := Describe(); got != tc.want || from != source { + t.Fatalf("description = %q (%s), want %q (%s)", got, from, tc.want, source) + } + u, _ := url.Parse("https://vendor.example/request") + if p, err := For(u); err != nil || p == nil || p.String() != tc.raw { + t.Fatalf("description changed the proxy used by requests: %v", err) + } + }) + } + } +} + +func TestDescribeHidesMalformedSystemProxy(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} { + t.Setenv(k, "") + } + sysCache.at, sysCache.p = farFuture, Proxy{URL: "socks5://alice:secret%zz@127.0.0.1:1080"} + t.Cleanup(func() { sysCache.at = zero }) + if got, from := Describe(); got != "" || from != "system" { + t.Fatalf("malformed proxy description = %q (%s)", got, from) + } +} diff --git a/internal/netproxy/netproxy.go b/internal/netproxy/netproxy.go index d3d5483e4..28adecd18 100644 --- a/internal/netproxy/netproxy.go +++ b/internal/netproxy/netproxy.go @@ -316,6 +316,7 @@ func Parse(s string) (*url.URL, error) { // Describe says, for the settings page, what a request to u would use. func Describe() (proxy, source string) { + defer func() { proxy = proxyAddress(proxy) }() switch s := strings.TrimSpace(settings.Load().Proxy); s { case "direct": return "", "off" @@ -333,6 +334,24 @@ func Describe() (proxy, source string) { return "", "none" } +// proxyAddress keeps credentials out of the settings status. A malformed +// address is omitted because its userinfo cannot be safely separated. +func proxyAddress(raw string) string { + u, err := Parse(raw) + if err != nil { + return "" + } + if u.User == nil { + return raw + } + u.User = nil + address := u.String() + if !strings.Contains(raw, "://") { + address = strings.TrimPrefix(address, "http://") + } + return address +} + // fromEnv is the proxy the environment names for u: HTTPS_PROXY or // HTTP_PROXY as Go reads them, else ALL_PROXY (curl's, which Go doesn't // read: a shell with only ALL_PROXY=socks5://… set has curl go through it, diff --git a/internal/settings/proxy_test.go b/internal/settings/proxy_test.go new file mode 100644 index 000000000..ab36c4e25 --- /dev/null +++ b/internal/settings/proxy_test.go @@ -0,0 +1,39 @@ +package settings + +import ( + "strings" + "testing" +) + +func TestCheckProxyDoesNotExposeCredentials(t *testing.T) { + for _, raw := range []string{ + "socks5://private-user:private-password%zz@127.0.0.1:1080", + "ftp://private-user:private-password@127.0.0.1:1080", + "socks5://private-user:private-password@", + "socks5://private-user:private-password@127.0.0.1:bad-port", + } { + err := CheckProxy(raw) + if err == nil { + t.Fatal("invalid proxy was accepted") + } + msg := err.Error() + if strings.Contains(msg, "private-user") || strings.Contains(msg, "private-password") { + t.Error("invalid proxy error exposed credentials") + } + if !strings.Contains(msg, "http://") || !strings.Contains(msg, "socks5://") { + t.Errorf("invalid proxy error lost address guidance: %s", msg) + } + } +} + +func TestCheckProxyAcceptsEncodedCredentials(t *testing.T) { + for _, raw := range []string{ + "socks5://ali%40ce:p%3Aa%2Fss%25@127.0.0.1:1080", + "socks5h://ali%40ce:p%3Aa%2Fss%25@[::1]:1080", + "socks5://127.0.0.1:1080", + } { + if err := CheckProxy(raw); err != nil { + t.Errorf("valid proxy was refused: %v", err) + } + } +} diff --git a/internal/settings/settings.go b/internal/settings/settings.go index c741b7347..71188ead5 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -942,7 +942,7 @@ func CheckProxy(p string) error { } u, err := url.Parse(raw) if err != nil || u.Host == "" || !slices.Contains([]string{"http", "https", "socks5", "socks5h"}, u.Scheme) { - return fmt.Errorf("proxy must look like http://127.0.0.1:7890 or socks5://127.0.0.1:1080, not %q", p) + return fmt.Errorf("proxy must look like http://127.0.0.1:7890 or socks5://127.0.0.1:1080") } return nil }