netproxy: Auto goes direct while the system's loopback proxy isn't running (@bitssly on X)
@bitssly (X, magpie 0.1.4519, Windows 11 amd64): with the proxy on Auto,
every model failed with 502 "proxy not reachable" once their VPN app was
off, a restart of magpie too, until they set the proxy Off. A VPN or
proxy app that quits without clearing Internet Options leaves
ProxyEnable=1 and ProxyServer=127.0.0.1:port in HKCU, and Auto took the
system proxy as it was: every request went to a port nothing listens on.
Auto now takes a system proxy on loopback only while its port accepts a
connection (liveSystem, through the same listening check the login
shell's proxy already had: 300ms dial, kept 15s while up, 2s while down,
so the VPN coming back is followed within 2 seconds). Every route that
asks Auto goes through it: For (netproxy.Func for the gateway and every
transport, and http.DefaultClient through Install), EnvWith (the CLIs
magpie starts, Bun, and the plugin host, whose proxy check every 15s/2s
restarts it on a change) and Describe. Settings › Network says it:
source "down" reads "Nothing answers at the proxy found, {proxy};
requests go direct until it runs again", in every language.
Not changed, on purpose:
- A proxy set in magpie is never gone around: a dead one still fails.
- The environment's *_PROXY, set for this process by whoever started
it, is taken as it is, dead or not.
- A system proxy elsewhere than loopback isn't probed: a proxy that is
down can't be told from a network that drops a probe.
- internal/agent/codex_proxy.go reads the raw System(): it predicts what
Codex itself does.
- Going direct while the VPN is off means vendors see the computer's own
address. A user who needs to fail closed sets the proxy in magpie.
Run:
- win-run (xiaomi-gpu, Windows 11) go test ./internal/netproxy: ok.
TestWindowsDeadSystemProxyGoesDirect writes ProxyEnable/ProxyServer to
a scratch key that RegOverridePredefKey puts in place of HKCU, so the
box's own Internet Options are untouched. It reads them through the
real system() and the real 300ms dial: direct while nothing listens,
the proxy again once a listener runs.
- win-run go test ./internal/plugin: TestPiPackage,
TestCachedReadsSavedProvidersOnce (#7197), TestDistReadFailedIsntMissing
(#6075) and TestPluginLeavesTheUserNetworkDirect (#4115) are red on
Windows at origin/main 239da9991 too; the last two pass 3 of 3 here.
- wsl-run (magpie-desktop) go test -timeout 45m ./... at ac4da60cb
(these two commits on origin/main 9bf5848c1): ok except
TestRequestStateKeptAcrossACatalogFetchedAgain (#6572, red at
origin/main too), TestSearchQueueKeepsCodexAlive/cancel (#7090) and
the root, cli and gui packages, which need gtk4 there.
- At the pushed head (rebased on e4e9eb092), mote-run go test
-timeout 45m of netproxy, gui, plugin, gateway, usage, provider and
agent: ok except TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes
(#7117, red 3 of 3 at origin/main e4e9eb092 too) and two TempDir
cleanup reds, TestSetPortServesWhenTheOldOneWasTaken (#7112) and
TestRequestChunksFromDisk (#4390; 3 of 3 alone).
- go vet ./... and GOOS=windows go vet ./... on mote: ok; vet natively
on Windows: ok; Linux vet of netproxy, plugin, gateway, agent and
provider in WSL: ok. gofmt -l clean.
- GUI, wsl-run: proxy-down.test.cjs (5 languages, 1100 and 420px,
chromium and webkit), i18n-keys and every *proxy* and settings-* file
at ac4da60cb. Reds: settings-proxy-auth / settings-proxy-remember 4s
clicks beside a Go suite (#7192, #5562; 30 of 30 alone),
provider-proxy (#7100) and settings-update-source webkit, red the same
at origin/main 9bf5848c1. At the pushed head proxy-down, i18n-keys,
settings-search, settings-proxy-remember, proxy-gaps and
proxy-own-wording: 94 of 94.
Broken by hand: liveSystem returning the system proxy as it is turns
TestDeadLoopbackSystemProxyGoesDirect red (WSL) and the Windows
registry test red (xiaomi-gpu).
Not tried: magpie.exe against the box's real Internet Options (shared
machine), which source the reporter's proxy was in (registry or env), and
whether a connection dialled direct is kept after the VPN comes back
(#4523 is that class for a changed proxy).
This commit is contained in:
@@ -20898,6 +20898,7 @@ function renderProxy(s, keep) {
|
||||
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"),
|
||||
down: t("Nothing answers at the proxy found, {proxy}; requests go direct until it runs again", { proxy: proxyDisplay(s.proxyNow) }),
|
||||
none: t("No system proxy found; requests to vendors without a proxy of their own, and update checks, go direct"),
|
||||
}[s.proxySource] || "";
|
||||
const row = proxyRow(s, keep, {
|
||||
|
||||
@@ -1332,6 +1332,7 @@ const I18N = {
|
||||
"The request through the proxy didn't connect to it and leaves from {where}, the same address as direct ones: the proxy is passed by": "经代理的请求没有连到代理,与直连一样从 {where} 发出:代理被绕过了",
|
||||
"Works: through the proxy requests leave from {where}, {ms} ms; direct ones from {direct}": "已生效:经代理的请求从 {where} 发出,{ms} ms;直连从 {direct} 发出",
|
||||
"Off: requests to vendors without a proxy of their own, and update checks, go direct": "已关闭:未单独设置代理的模型厂商请求和检查更新都直连",
|
||||
"Nothing answers at the proxy found, {proxy}; requests go direct until it runs again": "找到的代理 {proxy} 没有在运行,请求先直连,等它恢复后再走代理",
|
||||
"No system proxy found; requests to vendors without a proxy of their own, and update checks, go direct": "未发现系统代理,未单独设置代理的模型厂商请求和检查更新都直连",
|
||||
"Off": "关闭",
|
||||
"On": "开启",
|
||||
@@ -6842,6 +6843,7 @@ const I18N = {
|
||||
"The request through the proxy didn't connect to it and leaves from {where}, the same address as direct ones: the proxy is passed by": "經代理的請求沒有連到代理,與直連一樣從 {where} 發出:代理被繞過了",
|
||||
"Works: through the proxy requests leave from {where}, {ms} ms; direct ones from {direct}": "已生效:經代理的請求從 {where} 發出,{ms} ms;直連從 {direct} 發出",
|
||||
"Off: requests to vendors without a proxy of their own, and update checks, go direct": "已關閉:未單獨設定代理的模型廠商請求和檢查更新都直連",
|
||||
"Nothing answers at the proxy found, {proxy}; requests go direct until it runs again": "找到的代理 {proxy} 沒有在執行,請求先直連,等它恢復後再走代理",
|
||||
"No system proxy found; requests to vendors without a proxy of their own, and update checks, go direct": "未發現系統代理,未單獨設定代理的模型廠商請求和檢查更新都直連",
|
||||
"Off": "關閉",
|
||||
"On": "開啟",
|
||||
@@ -12318,6 +12320,7 @@ const I18N = {
|
||||
"The request through the proxy didn't connect to it and leaves from {where}, the same address as direct ones: the proxy is passed by": "プロキシ経由のはずのリクエストはプロキシに接続せず、直接と同じく {where} から出ています:プロキシが迂回されています",
|
||||
"Works: through the proxy requests leave from {where}, {ms} ms; direct ones from {direct}": "有効:プロキシ経由のリクエストは {where} から出ます、{ms} ms;直接は {direct} から",
|
||||
"Off: requests to vendors without a proxy of their own, and update checks, go direct": "オフ:独自のプロキシを設定していないベンダーへのリクエストとアップデート確認は直接接続します",
|
||||
"Nothing answers at the proxy found, {proxy}; requests go direct until it runs again": "見つかったプロキシ {proxy} が応答しないため、再び動くまで直接接続します",
|
||||
"No system proxy found; requests to vendors without a proxy of their own, and update checks, go direct": "システムプロキシが見つかりません。独自のプロキシを設定していないベンダーへのリクエストとアップデート確認は直接接続します",
|
||||
"Off": "オフ",
|
||||
"On": "オン",
|
||||
@@ -17811,6 +17814,7 @@ const I18N = {
|
||||
"The request through the proxy didn't connect to it and leaves from {where}, the same address as direct ones: the proxy is passed by": "Die Anfrage über den Proxy hat sich nicht mit ihm verbunden und geht wie direkte von {where} aus: Der Proxy wird umgangen",
|
||||
"Works: through the proxy requests leave from {where}, {ms} ms; direct ones from {direct}": "Funktioniert: Über den Proxy gehen Anfragen von {where} aus, {ms} ms; direkt von {direct}",
|
||||
"Off: requests to vendors without a proxy of their own, and update checks, go direct": "Aus: Anfragen an Anbieter ohne eigenen Proxy und Update-Prüfungen laufen direkt",
|
||||
"Nothing answers at the proxy found, {proxy}; requests go direct until it runs again": "Der gefundene Proxy {proxy} antwortet nicht; Anfragen laufen direkt, bis er wieder läuft",
|
||||
"No system proxy found; requests to vendors without a proxy of their own, and update checks, go direct": "Kein System-Proxy gefunden; Anfragen an Anbieter ohne eigenen Proxy und Update-Prüfungen laufen direkt",
|
||||
"Off": "Aus",
|
||||
"On": "An",
|
||||
|
||||
@@ -1733,6 +1733,12 @@ rest, tagged "proxy not reachable", in English and Chinese, never "an error
|
||||
another account wouldn't fix"; picking the request doesn't move the page.
|
||||
Chromium and WebKit, API faked.
|
||||
|
||||
`proxy-down.test.cjs` opens Settings → Network with the proxy on Auto and
|
||||
a system proxy on loopback that nothing listens on (@bitssly on X: a VPN
|
||||
app turned off left Windows' proxy at its port). The proxy line names the
|
||||
address found and says requests go direct until it runs again, in all five
|
||||
languages, at 1100px and 420px, Chromium and WebKit. The API is faked.
|
||||
|
||||
`s3-sync.test.cjs` sets up sync to an S3 bucket from Settings (#296). It
|
||||
works as follows, in English and Chinese:
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// @bitssly on X (Windows, proxy Auto): a VPN app turned off left the
|
||||
// system's proxy at its loopback port, and every model failed with 502
|
||||
// "proxy not reachable" until Off. Auto now goes direct while nothing
|
||||
// listens there (netproxy.liveSystem), and Settings says so: the proxy
|
||||
// found, by its address without its login, and that requests go direct.
|
||||
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) {
|
||||
const cur = {
|
||||
theme: "light", lang, tray: "panel", currency: "usd", textSize: 100,
|
||||
proxy: "", proxyNow: "http://127.0.0.1:7897", proxySource: "down",
|
||||
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") 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 });
|
||||
};
|
||||
}
|
||||
|
||||
const want = {
|
||||
en: "Nothing answers at the proxy found, http://127.0.0.1:7897; requests go direct until it runs again",
|
||||
zh: "找到的代理 http://127.0.0.1:7897 没有在运行,请求先直连,等它恢复后再走代理",
|
||||
"zh-TW": "找到的代理 http://127.0.0.1:7897 沒有在執行,請求先直連,等它恢復後再走代理",
|
||||
ja: "見つかったプロキシ http://127.0.0.1:7897 が応答しないため、再び動くまで直接接続します",
|
||||
de: "Der gefundene Proxy http://127.0.0.1:7897 antwortet nicht; Anfragen laufen direkt, bis er wieder läuft",
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(want)) {
|
||||
for (const width of [1100, 420]) {
|
||||
test(`${engine} ${lang} ${width}px: Auto with a dead system proxy says it goes direct`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(4000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang));
|
||||
await page.goto("http://magpie.test/?view=settings&tab=network");
|
||||
await page.waitForFunction((s) => document.querySelector("#proxySub")?.textContent === s, want[lang]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// downPort stubs the listening check: addr is down until the returned up
|
||||
// is called; every other port is up. The cache of looks is cleared each
|
||||
// way, so a test sees the move at once.
|
||||
func downPort(t *testing.T, addr string) (up func()) {
|
||||
t.Helper()
|
||||
isUp := false
|
||||
old := dialShell
|
||||
dialShell = func(a string) bool { return a != addr || isUp }
|
||||
forget := func() {
|
||||
shellPorts.Lock()
|
||||
shellPorts.seen = nil
|
||||
shellPorts.Unlock()
|
||||
}
|
||||
forget()
|
||||
t.Cleanup(func() { dialShell = old; forget() })
|
||||
return func() { isUp = true; forget() }
|
||||
}
|
||||
|
||||
// @bitssly on X (Windows, proxy Auto): a VPN app turned off left Internet
|
||||
// Options' proxy at its loopback port, and every request failed with 502
|
||||
// "proxy not reachable", a restart of magpie too, until Off. A system
|
||||
// proxy on loopback that nothing listens on is now none: requests, a
|
||||
// CLI's or a plugin host's env, and the settings page go direct, and
|
||||
// the page says why. The proxy app coming back is taken again.
|
||||
func TestDeadLoopbackSystemProxyGoesDirect(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
shellSays(t, nil)
|
||||
addr := freePort(t)
|
||||
up := downPort(t, addr)
|
||||
sysCache.p = Proxy{URL: "http://" + addr, HTTP: "http://" + addr, Bypass: []string{"<local>"}}
|
||||
|
||||
if got := proxyFor(t, "https://api.example/"); got != "" {
|
||||
t.Fatalf("a dead system proxy was taken: %q", got)
|
||||
}
|
||||
if got, from := Describe(); got != "http://"+addr || from != "down" {
|
||||
t.Fatalf("Describe = %q (%s), want the dead address (down)", got, from)
|
||||
}
|
||||
if env := Env([]string{"PATH=/bin"}); envVal(env, "HTTPS_PROXY") != "" {
|
||||
t.Fatalf("a CLI was given a dead system proxy: %q", env)
|
||||
}
|
||||
|
||||
up()
|
||||
if got := proxyFor(t, "https://api.example/"); got != "http://"+addr {
|
||||
t.Fatalf("the proxy app came back and wasn't taken: %q", got)
|
||||
}
|
||||
if got, from := Describe(); from != "system" || got != "http://"+addr {
|
||||
t.Fatalf("Describe = %q (%s), want system", got, from)
|
||||
}
|
||||
if env := Env([]string{"PATH=/bin"}); envVal(env, "HTTPS_PROXY") != "http://"+addr {
|
||||
t.Fatalf("a CLI wasn't given the live system proxy: %q", env)
|
||||
}
|
||||
}
|
||||
|
||||
// A system proxy elsewhere than loopback is taken as it is: magpie can't
|
||||
// tell a proxy that is down from a network that drops a probe.
|
||||
func TestRemoteSystemProxyIsNotProbed(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
shellSays(t, nil)
|
||||
old := dialShell
|
||||
dialShell = func(a string) bool { t.Errorf("probed %s", a); return false }
|
||||
t.Cleanup(func() { dialShell = old })
|
||||
sysCache.p = Proxy{URL: "http://10.9.8.7:3128"}
|
||||
if got := proxyFor(t, "https://api.example/"); got != "http://10.9.8.7:3128" {
|
||||
t.Fatalf("a remote system proxy was dropped: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The environment's proxy is set for this process by whoever started it,
|
||||
// and taken as it is, dead or not.
|
||||
func TestDeadEnvProxyIsKept(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
shellSays(t, nil)
|
||||
dead := freePort(t)
|
||||
downPort(t, dead)
|
||||
// ALL_PROXY: Go reads HTTPS_PROXY once per process (ProxyFromEnvironment)
|
||||
t.Setenv("ALL_PROXY", "http://"+dead)
|
||||
if got := proxyFor(t, "https://api.example/"); got != "http://"+dead {
|
||||
t.Fatalf("the environment's proxy was gone around: %q", got)
|
||||
}
|
||||
if env := Env([]string{"HTTPS_PROXY=http://" + dead}); envVal(env, "HTTPS_PROXY") != "http://"+dead {
|
||||
t.Fatalf("a CLI's own proxy was taken out: %q", env)
|
||||
}
|
||||
}
|
||||
|
||||
// A proxy set in magpie is never gone around, dead or not: requests fail
|
||||
// through it, so the user sees it, rather than leave from where they said
|
||||
// not to.
|
||||
func TestDeadProxySetInMagpieStillFails(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
shellSays(t, nil)
|
||||
addr := freePort(t)
|
||||
downPort(t, addr)
|
||||
if err := settings.Save(settings.Settings{Proxy: "http://" + addr}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := proxyFor(t, "https://api.example/"); got != "http://"+addr {
|
||||
t.Fatalf("a proxy set in magpie was gone around: %q", got)
|
||||
}
|
||||
if env := Env([]string{"PATH=/bin"}); envVal(env, "HTTPS_PROXY") != "http://"+addr {
|
||||
t.Fatalf("a CLI went around the proxy set in magpie: %q", env)
|
||||
}
|
||||
}
|
||||
@@ -6,5 +6,11 @@ import (
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// The tests run in a home of their own, never the user's real files.
|
||||
func TestMain(m *testing.M) { testenv.Main(m) }
|
||||
// The tests run in a home of their own, never the user's real files. A
|
||||
// loopback proxy a test names is taken as running (listening) unless the
|
||||
// test says it is down (downPort, TestClosedShellProxyGoesDirect): most
|
||||
// name one at a port nothing listens on, as an address and nothing more.
|
||||
func TestMain(m *testing.M) {
|
||||
dialShell = func(string) bool { return true }
|
||||
testenv.Main(m)
|
||||
}
|
||||
|
||||
@@ -402,7 +402,7 @@ func For(u *url.URL) (*url.URL, error) {
|
||||
if p, err := fromEnv(u); p != nil || err != nil {
|
||||
return p, err
|
||||
}
|
||||
sys := System()
|
||||
sys, _ := liveSystem()
|
||||
if sys.URL == "" {
|
||||
return fromShell(u), nil
|
||||
}
|
||||
@@ -450,7 +450,7 @@ func EnvWith(choice string, env []string) []string {
|
||||
return env
|
||||
}
|
||||
}
|
||||
sys := System()
|
||||
sys, _ := liveSystem()
|
||||
p, bypass = sys.URL, sys.Bypass
|
||||
if p == "" {
|
||||
if p, bypass = shellProxy(); p == "" {
|
||||
@@ -537,12 +537,18 @@ func Describe() (proxy, source string) {
|
||||
if p, _ := fromEnv(u); p != nil {
|
||||
return p.String(), "environment"
|
||||
}
|
||||
if sys := System(); sys.URL != "" {
|
||||
sys, dead := liveSystem()
|
||||
if sys.URL != "" {
|
||||
return sys.URL, "system"
|
||||
}
|
||||
if p := fromShell(u); p != nil {
|
||||
return p.String(), "environment"
|
||||
}
|
||||
if dead != "" {
|
||||
// the system's proxy is set, but nothing listens on its port:
|
||||
// requests go direct until something does (liveSystem)
|
||||
return dead, "down"
|
||||
}
|
||||
return "", "none"
|
||||
}
|
||||
|
||||
@@ -712,6 +718,29 @@ func System() Proxy {
|
||||
return sysCache.p
|
||||
}
|
||||
|
||||
// liveSystem is System as Auto takes it, for magpie's own requests and
|
||||
// the CLIs and plugin hosts it starts: a system proxy on this computer's
|
||||
// loopback that nothing listens on is none, and dead is its address. A
|
||||
// VPN or proxy app that quits without clearing Windows' Internet Options
|
||||
// (or the system's on macOS and Linux) leaves 127.0.0.1:port there, and
|
||||
// every request failed with "proxy not reachable", a restart of magpie
|
||||
// too, until the user set the proxy Off (@bitssly on X). The login
|
||||
// shell's proxy is taken so already (shell.go). The environment's
|
||||
// *_PROXY, set for this process by whoever started it, and a proxy set
|
||||
// in magpie are never taken around: a dead one fails, so it shows. A
|
||||
// port is looked at again within 2 seconds while down (listening), so
|
||||
// the proxy app coming back is followed at once.
|
||||
func liveSystem() (p Proxy, dead string) {
|
||||
p = System()
|
||||
if p.URL == "" {
|
||||
return p, ""
|
||||
}
|
||||
if u, err := Parse(p.URL); err == nil && u.Hostname() != "" && !listening(u) {
|
||||
return Proxy{}, p.URL
|
||||
}
|
||||
return p, ""
|
||||
}
|
||||
|
||||
// refreshSystem reads the system proxy into sysCache, then closes done.
|
||||
// A read that fails keeps what was read before, if anything was.
|
||||
func refreshSystem(done chan struct{}) {
|
||||
|
||||
@@ -93,15 +93,18 @@ func liveShell(raw string) *url.URL {
|
||||
var (
|
||||
shellUp = 15 * time.Second
|
||||
shellDown = 2 * time.Second
|
||||
dialShell = func(addr string) bool {
|
||||
c, err := net.DialTimeout("tcp", addr, 300*time.Millisecond)
|
||||
if err == nil {
|
||||
c.Close()
|
||||
}
|
||||
return err == nil
|
||||
}
|
||||
dialShell = dialPort
|
||||
)
|
||||
|
||||
// dialPort is whether something takes a connection at addr.
|
||||
func dialPort(addr string) bool {
|
||||
c, err := net.DialTimeout("tcp", addr, 300*time.Millisecond)
|
||||
if err == nil {
|
||||
c.Close()
|
||||
}
|
||||
return err == nil
|
||||
}
|
||||
|
||||
var shellPorts struct {
|
||||
sync.Mutex
|
||||
seen map[string]shellPort
|
||||
@@ -113,7 +116,8 @@ type shellPort struct {
|
||||
}
|
||||
|
||||
// listening is whether p's port has a listener, for a loopback p; any
|
||||
// other is taken as it is, as a terminal's programs take it.
|
||||
// other is taken as it is, as a terminal's programs take it. Auto asks it
|
||||
// of the login shell's proxy and the system's (liveSystem).
|
||||
func listening(p *url.URL) bool {
|
||||
if !loopback(strings.ToLower(p.Hostname())) {
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
|
||||
var regOverridePredefKey = syscall.NewLazyDLL("advapi32.dll").NewProc("RegOverridePredefKey")
|
||||
|
||||
// hkcu is HKEY_CURRENT_USER as the C headers have it, sign-extended
|
||||
// ((HKEY)(ULONG_PTR)(LONG)0x80000001): RegOverridePredefKey takes no
|
||||
// other form.
|
||||
var hkcuLong int32 = -0x7fffffff
|
||||
|
||||
var hkcu = uintptr(int(hkcuLong))
|
||||
|
||||
// internetSettings points this process's HKEY_CURRENT_USER at a key of
|
||||
// its own (RegOverridePredefKey) and writes Internet Options' proxy
|
||||
// there, so system reads the real registry the way it does on a user's
|
||||
// computer, and the test box's own proxy settings are never touched.
|
||||
func internetSettings(t *testing.T, vals map[string]any) {
|
||||
t.Helper()
|
||||
root := fmt.Sprintf(`Software\magpie-test-%d`, time.Now().UnixNano())
|
||||
base, _, err := registry.CreateKey(registry.CURRENT_USER, root, registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, _, _ := regOverridePredefKey.Call(hkcu, uintptr(base)); r != 0 {
|
||||
base.Close()
|
||||
registry.DeleteKey(registry.CURRENT_USER, root)
|
||||
t.Fatalf("RegOverridePredefKey: %d", r)
|
||||
}
|
||||
path := []string{"Software", "Microsoft", "Windows", "CurrentVersion", "Internet Settings"}
|
||||
t.Cleanup(func() {
|
||||
regOverridePredefKey.Call(hkcu, 0)
|
||||
base.Close()
|
||||
for i := len(path); i >= 0; i-- {
|
||||
k := root
|
||||
for _, p := range path[:i] {
|
||||
k += `\` + p
|
||||
}
|
||||
registry.DeleteKey(registry.CURRENT_USER, k)
|
||||
}
|
||||
})
|
||||
k, _, err := registry.CreateKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.ALL_ACCESS)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer k.Close()
|
||||
for n, v := range vals {
|
||||
switch v := v.(type) {
|
||||
case int:
|
||||
err = k.SetDWordValue(n, uint32(v))
|
||||
case string:
|
||||
err = k.SetStringValue(n, v)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// @bitssly on X, on Windows itself: a VPN app turned off leaves Internet
|
||||
// Options' proxy on, at its loopback port. Read from the registry, with
|
||||
// the real check of the port: direct while nothing listens, the proxy
|
||||
// again once something does.
|
||||
func TestWindowsDeadSystemProxyGoesDirect(t *testing.T) {
|
||||
clearProxyEnv(t)
|
||||
shellSays(t, nil)
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
addr := l.Addr().String()
|
||||
l.Close()
|
||||
internetSettings(t, map[string]any{"ProxyEnable": 1, "ProxyServer": addr, "ProxyOverride": "<local>"})
|
||||
if p, ok := system(); !ok || p.URL != "http://"+addr {
|
||||
t.Fatalf("system() = %+v, %v; want the registry's proxy", p, ok)
|
||||
}
|
||||
oldDial, oldRead := dialShell, readSystem
|
||||
dialShell, readSystem = dialPort, system
|
||||
t.Cleanup(func() { dialShell, readSystem = oldDial, oldRead })
|
||||
sysCache.at = time.Time{}
|
||||
shellPorts.Lock()
|
||||
shellPorts.seen = nil
|
||||
shellPorts.Unlock()
|
||||
|
||||
if got := proxyFor(t, "https://api.example/"); got != "" {
|
||||
t.Fatalf("the dead registry proxy was taken: %q", got)
|
||||
}
|
||||
if got, from := Describe(); from != "down" || got != "http://"+addr {
|
||||
t.Fatalf("Describe = %q (%s), want down", got, from)
|
||||
}
|
||||
if env := Env([]string{"PATH=C:\\"}); envVal(env, "HTTPS_PROXY") != "" {
|
||||
t.Fatalf("a CLI was given the dead registry proxy: %q", env)
|
||||
}
|
||||
|
||||
l, err = net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
t.Skipf("the port was taken meanwhile: %v", err)
|
||||
}
|
||||
defer l.Close()
|
||||
time.Sleep(shellDown + 100*time.Millisecond)
|
||||
if got := proxyFor(t, "https://api.example/"); got != "http://"+addr {
|
||||
t.Fatalf("the proxy came back and wasn't taken: %q", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user