settings: a proxy's username and password have fields of their own for every proxy, HTTP too (微雨南山 on Discord)
Settings > Proxy > Custom now shows Username and Password fields beside the
address for every proxy kind. Before, only a SOCKS5 address had them (the
password is masked). An HTTP or HTTPS proxy's login had to go inside the URL,
so a password holding @ : / % # or a space broke it. Each field is
percent-encoded (encodeURIComponent) when the address is saved.
The setting's format is unchanged: still one URL with the login as its
userinfo. A proxy saved before with user:pass@ loads into the fields. It is
split the way Go's url.Parse splits it (last @, then first :), so
"https://al%20ice:se@cr%23et@proxy.example:8443" shows "al ice" and
"se@cr#et". It is not split through WHATWG URL, which would add a "/" or drop
a default port. A part left as it was loaded keeps its own escapes, so
non-UTF-8 bytes survive. A login pasted into the address moves into the
fields. Describe, Redact and the status line already hid the userinfo
(#1886), and a new test checks that again.
Credit: 微雨南山 on Discord (#feedback), who asked for macOS-style
address / username / password fields after a special character in the
password broke the URL.
Tests:
- internal/netproxy/login_test.go: the login "me@corp:x" / "p@ss:w/rd% #1 x",
saved as the page encodes it, reads back as typed. It signs in to a fake HTTP
proxy (Basic Proxy-Authorization), and to a fake SOCKS5 proxy through both Go's
transport and the plugin bridge's socksHandshake. It also reaches a CLI's
HTTPS_PROXY. One character off is refused (407 / SOCKS fails), and Describe and
Redact show no part of it. TestBunProxyLoginWithReservedCharacters signs in with
the real bun 1.4.2's fetch({proxy}). These pass on the old Go code too: the Go
side needed no change.
- internal/gui/tests/settings-proxy-auth.test.cjs, Chromium and WebKit, en zh
zh-TW ja de, at 560 and 375px: an HTTP proxy has the fields, the login
round-trips encoded and comes back decoded, the password is type=password, and
the status hides it. A login saved in the address loads into the fields, and
Enter on it saves nothing. On the old app.js both tests fail in every language
checked ("an HTTP proxy has a username field / false !== true"; the address
still showed 'https://al%20ice:se@cr%23et@proxy.example:8443').
Run:
- gofmt -l: empty.
- go vet (darwin), GOOS=linux go vet -tags nogui, GOOS=windows go vet: clean.
- Full Go suite at c7ad43426 through the suite lock (-tags nogui -timeout 45m):
68 ok, one red, internal/gui TestCoreScriptBudget. The first app.js was
1338904 bytes over 1338084. The helpers and comments were tightened (not the
budget raised): app.js is 172 bytes under its parent. Then internal/gui,
internal/netproxy and internal/settings: ok at the final tree. After the
rebase onto c551a2299, app.js is 1,338,757 against the parent's 1,338,929.
TestCoreScriptBudget, internal/netproxy and the two proxy GUI files (30/30)
pass again.
- settings-proxy-auth + settings-proxy-remember: 30/30, and 30/30 three more
times at load 60-150.
- Whole GUI suite: stopped after ~2h, at 11,507 passes, to free the suite lock.
It ran beside two other sessions' GUI suites (load ~300). It showed 43
top-level reds, whose errors were not printed because the run was cut short.
Three were in the proxy files, and those passed alone afterwards. All are
filed in #3393, not compared against origin/main.
Not tried:
- a real authenticated proxy, and the real app;
- Windows and Linux runs;
- how Codex's reqwest or other agent CLIs decode the percent-encoded *_PROXY
login.
The plugin host's host.js proxyRefuses (auth only when there is a username,
and a decodeURIComponent that can throw), and the per-provider, account, key
and sign-in proxy fields that still take the login inside one URL, are filed
as #3382.
This commit is contained in:
+22
-29
@@ -20421,21 +20421,23 @@ 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, not saved yet
|
||||
// Keep SOCKS credentials in their own fields; URL userinfo is the existing
|
||||
// saved format, with reserved characters escaped before it reaches Go/Bun.
|
||||
// The login has fields of its own; the setting stays one address with it as
|
||||
// userinfo, split as Go's url.Parse does (last @, then first :).
|
||||
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) };
|
||||
const [, scheme = "", auth, rest] = /^([a-z][\w+.-]*:\/\/)?([^/?#]*)(.*)$/is.exec((value || "").trim());
|
||||
const at = auth.lastIndexOf("@"), info = at < 0 ? "" : auth.slice(0, at), c = info.indexOf(":");
|
||||
const eu = c < 0 ? info : info.slice(0, c), ep = c < 0 ? "" : info.slice(c + 1);
|
||||
// non-UTF-8 escapes are kept as saved until edited
|
||||
const dec = (v) => { try { return decodeURIComponent(v); } catch { return v; } };
|
||||
return { address: scheme + auth.slice(at + 1) + rest, username: dec(eu), password: dec(ep), eu, ep };
|
||||
}
|
||||
// each typed part percent-encoded; one left as loaded keeps its escapes
|
||||
function proxyAddress(a, f, user, pass) {
|
||||
a = (a || "").trim();
|
||||
if (!a || !(user || pass)) return a;
|
||||
const enc = (t, l, e) => t === l && e !== undefined ? e : encodeURIComponent(t);
|
||||
const [, scheme = "", rest] = /^([a-z][\w+.-]*:\/\/)?(.*)$/is.exec(a);
|
||||
return scheme + enc(user, f.username, f.eu) + (pass ? ":" + enc(pass, f.password, f.ep) : "") + "@" + rest;
|
||||
}
|
||||
function proxyDisplay(value) {
|
||||
// Also mask an older backend's proxyNow, and environment/system proxies.
|
||||
@@ -20478,29 +20480,20 @@ function renderProxy(s, keep) {
|
||||
field.className = "proxy-credential";
|
||||
field.setAttribute("aria-label", field.placeholder);
|
||||
}
|
||||
const updateAuth = () => {
|
||||
const parsed = proxyFields(i.value.trim());
|
||||
auth.hidden = !parsed.socks;
|
||||
// a pasted login moves into the fields
|
||||
i.oninput = () => {
|
||||
const parsed = proxyFields(i.value);
|
||||
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 = () => {
|
||||
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 (!i.value.trim() || saving) return;
|
||||
let v;
|
||||
try { v = proxyAddress(i.value, fields, username.value, password.value); } catch { return; }
|
||||
if (v === s.proxy) return;
|
||||
saving = true;
|
||||
proxyCustom = false;
|
||||
|
||||
@@ -7,12 +7,14 @@ checks that request hooks have no provider badge. `MAGPIE_GATEWAY_ASSETS` select
|
||||
an older asset directory for a failing regression comparison; user settings and
|
||||
live gateways are never accessed.
|
||||
|
||||
`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.
|
||||
`settings-proxy-auth.test.cjs` checks a proxy's optional username and
|
||||
password in Settings, in fields of their own for SOCKS5/SOCKS5h, HTTP,
|
||||
HTTPS and bare host:port proxies alike, using the real page with isolated
|
||||
API fixtures. It covers saving and reloading, @ : / % # and spaces in a
|
||||
password, escaped and non-UTF-8 credentials, a login saved in the address
|
||||
before loading into the fields, masked addresses/status, clearing
|
||||
authentication, Tab and Escape, mode switches, and narrow windows in all
|
||||
five languages on Chromium and WebKit.
|
||||
## Installed desktop fonts
|
||||
|
||||
`fonts.test.cjs` exercises the interface/code font controls with installed
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
// 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.
|
||||
// A proxy's optional username and password, in fields of their own for
|
||||
// every kind of proxy (SOCKS, and HTTP for 微雨南山 on Discord), survive
|
||||
// saving/reloading, never appear in the address or status, and typing
|
||||
// between fields cannot save a partial login. A login saved in the address
|
||||
// before loads into the fields.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
@@ -51,7 +54,7 @@ const labels = {
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(labels)) {
|
||||
const l = labels[lang];
|
||||
test(`${engine} ${lang}: optional SOCKS credentials in settings`, async (t) => {
|
||||
test(`${engine} ${lang}: optional proxy 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" });
|
||||
@@ -133,12 +136,47 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.equal(await pass.inputValue(), "p%FFss");
|
||||
await saved(() => box.getByRole("button", { name: l.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.
|
||||
// An HTTP proxy has the same fields (微雨南山 on Discord): its login
|
||||
// is typed as it is, @ : / % # and spaces included, and each part is
|
||||
// encoded into the address, which keeps no slash or port of URL's.
|
||||
await address.fill("http://127.0.0.1:7890");
|
||||
assert.equal(await user.isVisible(), false);
|
||||
assert.equal(await user.isVisible(), true, "an HTTP proxy has a username field");
|
||||
assert.equal(await pass.isVisible(), true, "an HTTP proxy has a password field");
|
||||
await user.fill("");
|
||||
await pass.fill("");
|
||||
await saved(() => address.press("Enter"), "http://127.0.0.1:7890");
|
||||
await user.fill("me@corp:x");
|
||||
await pass.fill("p@ss:w/rd% #1 x");
|
||||
// the bytes internal/netproxy's TestProxyLoginWithReservedCharacters signs in with
|
||||
const httpLogin = "http://me%40corp%3Ax:p%40ss%3Aw%2Frd%25%20%231%20x@127.0.0.1:7890";
|
||||
await saved(() => pass.press("Enter"), httpLogin);
|
||||
await page.reload();
|
||||
assert.equal(await address.inputValue(), "http://127.0.0.1:7890");
|
||||
assert.equal(await user.inputValue(), "me@corp:x");
|
||||
assert.equal(await pass.inputValue(), "p@ss:w/rd% #1 x");
|
||||
assert.equal(await pass.getAttribute("type"), "password");
|
||||
for (const secret of ["p@ss", "p%40ss", "corp"]) assert(!(await page.locator("#proxySub").innerText()).includes(secret), `status shows ${secret}`);
|
||||
for (const width of [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, `HTTP proxy field outside ${width}px window`);
|
||||
}
|
||||
if (process.env.ARTIFACT_DIR) await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-http-proxy-${width}.png`) });
|
||||
}
|
||||
await page.setViewportSize({ width: 1100, height: 760 });
|
||||
|
||||
// A bare host:port stays as typed, with or without a login.
|
||||
await user.fill("");
|
||||
await pass.fill("");
|
||||
await address.fill("127.0.0.1:7891");
|
||||
await saved(() => page.locator("#proxySub").click(), "127.0.0.1:7891");
|
||||
await user.fill("u");
|
||||
await pass.fill("p w");
|
||||
await saved(() => pass.press("Enter"), "u:p%20w@127.0.0.1:7891");
|
||||
await page.reload();
|
||||
assert.equal(await address.inputValue(), "127.0.0.1:7891");
|
||||
assert.equal(await pass.inputValue(), "p w");
|
||||
|
||||
await address.fill("socks5://127.0.0.1:1080");
|
||||
await user.fill("unsaved-user");
|
||||
@@ -147,5 +185,30 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await saved(() => box.getByRole("button", { name: l.auto, exact: true }).click(), "");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang}: an HTTP proxy saved with its login in the address loads into the fields`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const context = await browser.newContext({ viewport: { width: 375, height: 760 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(4000);
|
||||
const posts = [], errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
// as one typed whole before: a raw @ in the password, as Go reads it
|
||||
await page.route("**/*", server(lang, posts, "https://al%20ice:se@cr%23et@proxy.example:8443"));
|
||||
await page.goto("http://magpie.test/?view=settings&tab=network");
|
||||
const box = page.locator("#proxySegs");
|
||||
assert.equal(await box.locator("input.proxy").inputValue(), "https://proxy.example:8443");
|
||||
assert.equal(await box.getByRole("textbox", { name: l.user, exact: true }).inputValue(), "al ice");
|
||||
const pass = box.getByLabel(l.pass, { exact: true });
|
||||
assert.equal(await pass.inputValue(), "se@cr#et");
|
||||
assert.equal(await pass.getAttribute("type"), "password");
|
||||
const sub = await page.locator("#proxySub").innerText();
|
||||
assert(!sub.includes("se@cr") && !sub.includes("al%20ice"), `status shows the login: ${sub}`);
|
||||
// left as it was, it is saved as it was
|
||||
await pass.press("Enter");
|
||||
assert.equal(posts.length, 0, "an unchanged login is not saved again");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// The login Settings › Proxy saves (微雨南山 on Discord): a username and
|
||||
// a password typed in fields of their own, each percent-encoded into the
|
||||
// address's userinfo as the page's proxyAddress does
|
||||
// (encodeURIComponent). These are the page's own bytes for them.
|
||||
const (
|
||||
loginUser = "me@corp:x"
|
||||
loginPass = "p@ss:w/rd% #1 x"
|
||||
loginUserEnc = "me%40corp%3Ax"
|
||||
loginPassEnc = "p%40ss%3Aw%2Frd%25%20%231%20x"
|
||||
)
|
||||
|
||||
func clearProxyEnv(t *testing.T) {
|
||||
t.Helper()
|
||||
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 })
|
||||
}
|
||||
|
||||
// fakeHTTPProxy is an HTTP proxy that carries a request only with the
|
||||
// user and password given, answering 407 otherwise.
|
||||
func fakeHTTPProxy(t *testing.T, user, pass string) *httptest.Server {
|
||||
t.Helper()
|
||||
want := "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass))
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Proxy-Authorization") != want {
|
||||
w.Header().Set("Proxy-Authenticate", `Basic realm="fake"`)
|
||||
http.Error(w, "proxy login refused", http.StatusProxyAuthRequired)
|
||||
return
|
||||
}
|
||||
io.WriteString(w, "carried "+r.URL.String())
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
// throughSaved gets target through the proxy settings name, as a vendor
|
||||
// request takes it (For; Func skips the test servers' loopback).
|
||||
func throughSaved(t *testing.T, target string) (string, int) {
|
||||
t.Helper()
|
||||
tr := &http.Transport{Proxy: func(r *http.Request) (*url.URL, error) { return For(r.URL) }}
|
||||
defer tr.CloseIdleConnections()
|
||||
res, err := (&http.Client{Transport: tr}).Get(target)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s through the saved proxy: %v", target, err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
return string(b), res.StatusCode
|
||||
}
|
||||
|
||||
// A password holding @ : / % # and spaces, saved as the Settings page
|
||||
// saves it, reads back as typed and signs in to an HTTP proxy and a
|
||||
// SOCKS5 one; one off by a character is refused, so the fakes check it.
|
||||
// Nothing shown of the address carries either part of the login.
|
||||
func TestProxyLoginWithReservedCharacters(t *testing.T) {
|
||||
vendor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "vendor "+r.URL.Path) }))
|
||||
defer vendor.Close()
|
||||
|
||||
t.Run("http", func(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
p := fakeHTTPProxy(t, loginUser, loginPass)
|
||||
saved := "http://" + loginUserEnc + ":" + loginPassEnc + "@" + strings.TrimPrefix(p.URL, "http://")
|
||||
if err := settings.Save(settings.Settings{Proxy: saved}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := settings.Load().Proxy; got != saved {
|
||||
t.Fatalf("saved %q, read back %q", saved, got)
|
||||
}
|
||||
u, _ := url.Parse("http://vendor.example/v1/models")
|
||||
pu, err := For(u)
|
||||
if err != nil || pu == nil {
|
||||
t.Fatalf("For = %v, %v", pu, err)
|
||||
}
|
||||
if pw, _ := pu.User.Password(); pu.User.Username() != loginUser || pw != loginPass {
|
||||
t.Fatalf("login read back as %q / %q", pu.User.Username(), pw)
|
||||
}
|
||||
if body, code := throughSaved(t, "http://vendor.example/v1/models"); code != 200 || body != "carried http://vendor.example/v1/models" {
|
||||
t.Fatalf("through the HTTP proxy: %d %q", code, body)
|
||||
}
|
||||
// a CLI magpie starts gets the same login in its *_PROXY
|
||||
for _, e := range EnvWith("", []string{}) {
|
||||
if k, v, _ := strings.Cut(e, "="); k == "HTTPS_PROXY" {
|
||||
eu, err := url.Parse(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pw, _ := eu.User.Password(); eu.User.Username() != loginUser || pw != loginPass {
|
||||
t.Fatalf("HTTPS_PROXY's login is %q / %q", eu.User.Username(), pw)
|
||||
}
|
||||
}
|
||||
}
|
||||
// one character off is refused
|
||||
wrong := "http://" + loginUserEnc + ":" + strings.Replace(loginPassEnc, "%23", "%2523", 1) + "@" + strings.TrimPrefix(p.URL, "http://")
|
||||
if err := settings.Save(settings.Settings{Proxy: wrong}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, code := throughSaved(t, "http://vendor.example/"); code != http.StatusProxyAuthRequired {
|
||||
t.Fatalf("a wrong password was carried: %d", code)
|
||||
}
|
||||
assertHidden(t)
|
||||
})
|
||||
|
||||
t.Run("socks5", func(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
socks, n := fakeSOCKS(t, loginUser, loginPass)
|
||||
saved := "socks5://" + loginUserEnc + ":" + loginPassEnc + "@" + socks.Host
|
||||
if err := settings.Save(settings.Settings{Proxy: saved}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Go's transport speaks SOCKS5 itself
|
||||
if body, code := throughSaved(t, vendor.URL+"/go"); code != 200 || body != "vendor /go" {
|
||||
t.Fatalf("through the SOCKS5 proxy: %d %q", code, body)
|
||||
}
|
||||
// and the plugin host's Bun goes through the bridge, whose own
|
||||
// handshake (socksHandshake) sends the login
|
||||
pu, err := Parse(saved)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := Bridge(pu)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bu, _ := url.Parse(b)
|
||||
res, err := (&http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(bu)}}).Get(vendor.URL + "/bridge")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := io.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
if string(got) != "vendor /bridge" {
|
||||
t.Fatalf("through the bridge: %d %q", res.StatusCode, got)
|
||||
}
|
||||
if n.Load() != 2 {
|
||||
t.Fatalf("the SOCKS proxy carried %d connections, want 2", n.Load())
|
||||
}
|
||||
wrong := "socks5://" + loginUserEnc + ":" + strings.TrimSuffix(loginPassEnc, "x") + "@" + socks.Host
|
||||
if err := settings.Save(settings.Settings{Proxy: wrong}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tr := &http.Transport{Proxy: func(r *http.Request) (*url.URL, error) { return For(r.URL) }}
|
||||
defer tr.CloseIdleConnections()
|
||||
if _, err := (&http.Client{Transport: tr}).Get(vendor.URL + "/no"); err == nil {
|
||||
t.Fatal("a wrong SOCKS password was carried")
|
||||
}
|
||||
assertHidden(t)
|
||||
})
|
||||
}
|
||||
|
||||
// assertHidden: what Settings shows of the saved proxy names neither
|
||||
// part of the login, decoded or not.
|
||||
func assertHidden(t *testing.T) {
|
||||
t.Helper()
|
||||
shown, source := Describe()
|
||||
for _, secret := range []string{loginUser, loginPass, loginUserEnc, loginPassEnc, "p@ss", "p%40ss", "corp"} {
|
||||
if strings.Contains(shown, secret) || strings.Contains(Redact(settings.Load().Proxy), secret) {
|
||||
t.Fatalf("Describe (%s) shows %q: %q", source, secret, shown)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Bun, which the plugin host's fetches and Claude Code run on, signs in
|
||||
// to an HTTP proxy with the same login: it decodes the userinfo as Go
|
||||
// does. Run when a bun is at hand ($MAGPIE_BUN or on PATH).
|
||||
func TestBunProxyLoginWithReservedCharacters(t *testing.T) {
|
||||
bun := os.Getenv("MAGPIE_BUN")
|
||||
if bun == "" {
|
||||
bun, _ = exec.LookPath("bun")
|
||||
}
|
||||
if bun == "" {
|
||||
t.Skip("no bun")
|
||||
}
|
||||
p := fakeHTTPProxy(t, loginUser, loginPass)
|
||||
proxy := "http://" + loginUserEnc + ":" + loginPassEnc + "@" + strings.TrimPrefix(p.URL, "http://")
|
||||
js := `console.log(await (await fetch("http://vendor.example/x", { proxy: process.env.P })).text())`
|
||||
cmd := exec.Command(bun, "-e", js)
|
||||
cmd.Env = append(os.Environ(), "P="+proxy)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil || strings.TrimSpace(string(out)) != "carried http://vendor.example/x" {
|
||||
t.Fatalf("bun through the HTTP proxy: %v %s", err, out)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user