Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Browser proxy: KWNT_BROWSER_PROXY (feature 1) (#707)

Oleksandr Ivanchenkod236b3257d8e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 652f81b5..14616ae5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
+### Added
+- **Browser proxy.** `KWNT_BROWSER_PROXY=socks5://host:port` (or `http://`) sends the bots' browser out through a proxy, so sites see a home connection instead of a datacenter one. It applies to the compose browser, the browser container kwant starts itself and local Chrome; kwant's own services and private ranges always skip it. `kwnt doctor` checks that the proxy answers and that its exit address differs from the direct one. Credentials in the value are refused. See `docs/browser-proxy.md`.
+
## [Mac 0.9.15] - 2026-11-15
kwant 0.9.15: the perch: what needs you and what your bots are doing, at the top of your screen, steadier dictation when several people talk at once, long replies that stream in a block at a time, replies that land without a jump, double-checks you can see wherever they run, customer messages that never count as yours, an island that names the program, never the command, a Pointing line that fits next to Refresh, a Blocked label for a bot that asks you to decide, a Telegram Allow once that never pushes code or runs a command, times that say which day, a hand-back line that fits, Claude bots that stop repeating a kwant tool call that keeps failing and an island Allow once that holds back more risky steps.
diff --git a/docker-compose.yml b/docker-compose.yml
index 6290f272..4ddec433 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -31,6 +31,11 @@ services:
pids_limit: 512
# CDP is full control of the browser: reachable by kwnt on this network only, never published.
expose: ["9222"]
+ environment:
+ # Optional: send the browser's traffic through a proxy (socks5://host:port or http://host:port).
+ # See docs/browser-proxy.md. No credentials: Chromium cannot sign in to SOCKS.
+ KWNT_BROWSER_PROXY: ${KWNT_BROWSER_PROXY:-}
+ KWNT_BROWSER_PROXY_BYPASS: ${KWNT_BROWSER_PROXY_BYPASS:-}
kwnt:
build:
@@ -46,6 +51,9 @@ services:
LAYA_URL: http://laya:8000
KWNT_LAYA_MANAGED: "0"
KWNT_BROWSER_CDP_URL: http://browser:9222
+ # same value as the browser service, so `kwnt doctor` can check the proxy
+ KWNT_BROWSER_PROXY: ${KWNT_BROWSER_PROXY:-}
+ KWNT_BROWSER_PROXY_BYPASS: ${KWNT_BROWSER_PROXY_BYPASS:-}
# Your HTTPS address, e.g. https://kwant.example.com (comma list)
KWNT_ALLOWED_ORIGINS: ${KWNT_ALLOWED_ORIGINS:-}
volumes:
diff --git a/docker/browser-entrypoint.sh b/docker/browser-entrypoint.sh
index 981984cf..cc554f09 100644
--- a/docker/browser-entrypoint.sh
+++ b/docker/browser-entrypoint.sh
@@ -5,10 +5,28 @@ set -eu
# fills, and Google refuses sign-in on that. kwant takes the headless token out over DevTools
# with the browser's own client hints (src/sandbox/identity.rs). AutomationControlled off keeps
# navigator.webdriver false while the debugging port is open.
-chromium --headless=new --no-sandbox --disable-dev-shm-usage \
+set -- --headless=new --no-sandbox --disable-dev-shm-usage \
--disable-blink-features=AutomationControlled \
--remote-debugging-port=9223 --remote-allow-origins='*' \
- --window-size=1280,800 --user-data-dir=/tmp/kwnt-chromium about:blank &
+ --window-size=1280,800 --user-data-dir=/tmp/kwnt-chromium
+# Optional proxy for the browser's traffic (KWNT_BROWSER_PROXY=socks5://host:port or http://host:port).
+# Kwant's own services and private ranges skip it; KWNT_BROWSER_PROXY_BYPASS adds hosts.
+# Never print the value: only whether it was taken.
+if [ -n "${KWNT_BROWSER_PROXY:-}" ]; then
+ case "$KWNT_BROWSER_PROXY" in
+ socks5://*|socks5h://*|http://*|https://*) ;;
+ *) echo "KWNT_BROWSER_PROXY: expected socks5://host:port or http://host:port" >&2; exit 2 ;;
+ esac
+ case "$KWNT_BROWSER_PROXY" in
+ *@*|*' '*|*';'*|*'"'*) echo "KWNT_BROWSER_PROXY: credentials and spaces are not supported" >&2; exit 2 ;;
+ esac
+ bypass="laya;kwnt;browser;localhost;127.0.0.0/8;10.0.0.0/8;172.16.0.0/12;192.168.0.0/16;169.254.0.0/16"
+ extra=$(printf '%s' "${KWNT_BROWSER_PROXY_BYPASS:-}" | tr ',' ';')
+ [ -z "$extra" ] || bypass="$bypass;$extra"
+ set -- "$@" "--proxy-server=$KWNT_BROWSER_PROXY" "--proxy-bypass-list=$bypass"
+ echo "browser proxy: on (${KWNT_BROWSER_PROXY%%://*})"
+fi
+chromium "$@" about:blank &
chrome_pid=$!
socat TCP-LISTEN:9222,fork,reuseaddr TCP:127.0.0.1:9223 &
proxy_pid=$!
diff --git a/docs/browser-proxy.md b/docs/browser-proxy.md
new file mode 100644
index 00000000..702ffd60
--- /dev/null
+++ b/docs/browser-proxy.md
@@ -0,0 +1,46 @@
+# Browser proxy
+
+Sites treat a datacenter address (a VPS) differently from a home one: more CAPTCHAs, blocked sign-ins. Kwant can send the bots' browser, and only the browser, out through a proxy, so sites see the proxy's connection.
+
+## Turn it on
+
+Set `KWNT_BROWSER_PROXY` where kwant runs:
+
+| Value | Meaning |
+|---|---|
+| `socks5://host:port` | SOCKS5. Names are looked up by the proxy, so the local resolver never sees the sites. |
+| `socks5h://host:port` | Same as `socks5`. |
+| `http://host:port`, `https://host:port` | HTTP(S) proxy. |
+
+`KWNT_BROWSER_PROXY_BYPASS` adds hosts that skip the proxy (`;` or `,` separated, Chromium's syntax: `example.com`, `*.corp`, `10.9.0.0/16`).
+
+Kwant's own services always skip the proxy: `laya`, `kwnt`, `browser`, `localhost`, `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.0.0/16`. Private networks therefore are not reachable through the proxy; list a host in the bypass only if it should go direct.
+
+**Docker compose.** Put the value in `.env` next to `docker-compose.yml` (or in the shell) and run `docker compose up -d browser kwnt`. The browser container and `kwnt doctor` both read it:
+
+```
+KWNT_BROWSER_PROXY=socks5://172.17.0.1:1080
+```
+
+From a container, the Docker host is `172.17.0.1` on the default bridge. A proxy that listens only on the host's `127.0.0.1` is not reachable from the container; run a relay on `172.17.0.1` or use a proxy that listens on the bridge address.
+
+**Kwant starting its own browser container** (Docker VM mode without compose). The setting is put into the container; changing or removing it replaces the container the next time a bot opens the browser (open pages close once).
+
+**Local mode** (Chrome on your own computer). Kwant starts its Chrome with the proxy flags. If Chrome is already running from an earlier start (it is reused), close the kwant Chrome once so the next start picks the setting up.
+
+## No credentials
+
+A value with a user name or password (`socks5://user:pass@host:port`) is refused. Chromium cannot sign in to a SOCKS proxy at all, and a password in a command line or container environment would leak. Use a proxy that trusts the network it is reached from: a relay on the Docker bridge, or a WireGuard-to-SOCKS helper next to kwant. The refusal never repeats what you typed.
+
+## Check it
+
+```
+docker compose exec kwnt kwnt doctor
+```
+
+The **Browser proxy** line is OK when the proxy answers and a request through it leaves from another address than a direct one, and shows both addresses. It warns when the address is the same (the proxy does not go anywhere else) or the test request fails, and fails when the proxy does not answer or the value is unusable.
+
+## Notes
+
+- Only the browser uses the proxy. The AI accounts' network traffic and kwnt's own downloads go direct.
+- A reverse proxy hop, WebRTC and the sites' own fingerprinting still exist. A home address helps; it does not make the browser invisible.
diff --git a/docs/browser-service.md b/docs/browser-service.md
index f068d791..760e51c2 100644
--- a/docs/browser-service.md
+++ b/docs/browser-service.md
@@ -48,10 +48,12 @@ The container never restarts on its own (`--restart no`); kwant starts it on the
The browser profile lives on the container's tmpfs, so stopping or removing it loses only the open pages; each bot's cookies are kept in `<data folder>/browser-cookies/`. A container made by an older kwant (no labels, `--restart unless-stopped`) is replaced the next time that kwant opens the browser. Containers from data folders no kwant will open again need a manual `docker rm`.
+To send the browser's traffic through a home or other proxy, see [Browser proxy](browser-proxy.md).
+
Prebuild images to avoid first-use latency:
```bash
-docker build -t kwnt-browser:v3 -f docker/browser.Dockerfile docker
+docker build -t kwnt-browser:v4 -f docker/browser.Dockerfile docker
docker build -t kwnt-executor:v1 -f docker/executor.Dockerfile docker
./target/release/kwnt serve --host 127.0.0.1 --port 8799
```
diff --git a/src/doctor.rs b/src/doctor.rs
index 84a6f238..db1a5612 100644
--- a/src/doctor.rs
+++ b/src/doctor.rs
@@ -158,6 +158,15 @@ pub struct Facts {
pub loopback_bind: bool,
pub token: bool,
pub https_origin: Option<String>,
+ /// `KWNT_BROWSER_PROXY`: unset, unusable (the reason, without the value) or set and probed.
+ pub proxy: ProxyState,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum ProxyState {
+ Unset,
+ Invalid(String),
+ Probed(crate::sandbox::browser_proxy::ProxyFacts),
}
/// Turns the facts into checks with fixes for `p`.
@@ -237,6 +246,8 @@ pub fn checks(f: &Facts, p: Platform) -> Vec<Check> {
.optional_if(true),
});
+ out.extend(proxy_check(&f.proxy));
+
let mut ready = 0;
let any_installed = f.clis.iter().any(|(_, bin, _, key)| bin.is_some() || *key);
for (engine, bin, signed_in, via_key) in &f.clis {
@@ -295,6 +306,43 @@ pub fn checks(f: &Facts, p: Platform) -> Vec<Check> {
out
}
+/// The browser proxy check: nothing when none is set; otherwise set, reachable, and leaving from
+/// another address than a direct request. Shows the credential-free URL and addresses only.
+fn proxy_check(state: &ProxyState) -> Option<Check> {
+ const NAME: &str = "Browser proxy";
+ match state {
+ ProxyState::Unset => None,
+ ProxyState::Invalid(why) => Some(Check::new(
+ NAME,
+ Status::Fail,
+ why.clone(),
+ Some("Set KWNT_BROWSER_PROXY=socks5://host:port (or http://host:port), without a user name or password".into()),
+ )),
+ ProxyState::Probed(f) if !f.reachable => Some(Check::new(
+ NAME,
+ Status::Fail,
+ format!("{} does not answer from here", f.url),
+ Some("Start the proxy or relay, and check the host and port. From the Docker compose network the host is usually 172.17.0.1".into()),
+ )),
+ ProxyState::Probed(f) => Some(match (&f.proxied_ip, &f.direct_ip) {
+ (Some(p), Some(d)) if p == d => Check::new(
+ NAME,
+ Status::Warn,
+ format!("{} answers, but sites still see this server's own address ({p})", f.url),
+ Some("The proxy is not leaving through a different connection: check its upstream (WireGuard or router)".into()),
+ ),
+ (Some(p), Some(d)) => Check::new(NAME, Status::Ok, format!("{} answers; sites see {p} (direct: {d})", f.url), None),
+ (Some(p), None) => Check::new(NAME, Status::Ok, format!("{} answers; sites see {p} (direct address unknown)", f.url), None),
+ (None, _) => Check::new(
+ NAME,
+ Status::Warn,
+ format!("{} answers, but a test request through it failed", f.url),
+ Some("The proxy is up but has no working route out; check its upstream".into()),
+ ),
+ }),
+ }
+}
+
/// Looks at this machine. Network checks time out after a few seconds each.
pub async fn gather(config: &Config) -> Facts {
let http = reqwest::Client::builder().timeout(Duration::from_secs(3)).build().unwrap_or_default();
@@ -337,6 +385,11 @@ pub async fn gather(config: &Config) -> Facts {
let https_origin = std::env::var("KWNT_ALLOWED_ORIGINS")
.ok()
.and_then(|v| v.split(',').map(str::trim).find(|o| o.starts_with("https://")).map(String::from));
+ let proxy = match crate::sandbox::browser_proxy::BrowserProxy::from_env() {
+ Ok(None) => ProxyState::Unset,
+ Ok(Some(p)) => ProxyState::Probed(crate::sandbox::browser_proxy::probe(&p).await),
+ Err(why) => ProxyState::Invalid(why),
+ };
Facts {
data_dir: config.data_dir.display().to_string(),
data_dir_writable: writable(&config.data_dir),
@@ -353,6 +406,7 @@ pub async fn gather(config: &Config) -> Facts {
loopback_bind: Platform::detect() != Platform::Docker && crate::server::auth::is_loopback_bind(&config.host),
token: crate::server::auth::env_token().is_some() || crate::server::auth::read_existing(&config.data_dir).is_ok(),
https_origin,
+ proxy,
}
}
@@ -413,6 +467,7 @@ mod tests {
loopback_bind: false,
token: true,
https_origin: Some("https://kwant.example".into()),
+ proxy: ProxyState::Unset,
}
}
@@ -512,6 +567,36 @@ mod tests {
assert_eq!(by_name(&checks(&f, Platform::Linux), "Access").status, Status::Ok);
}
+ fn probed(reachable: bool, proxied: Option<&str>, direct: Option<&str>) -> ProxyState {
+ ProxyState::Probed(crate::sandbox::browser_proxy::ProxyFacts {
+ url: "socks5://172.17.0.1:1080".into(),
+ reachable,
+ proxied_ip: proxied.map(Into::into),
+ direct_ip: direct.map(Into::into),
+ })
+ }
+
+ #[test]
+ fn the_proxy_check_is_absent_without_a_proxy() {
+ assert!(checks(&healthy(), Platform::Docker).iter().all(|c| c.name != "Browser proxy"));
+ }
+
+ #[test]
+ fn the_proxy_check_wants_reachable_and_a_different_exit_address() {
+ let mut f = healthy();
+ let status = |f: &Facts| by_name(&checks(f, Platform::Docker), "Browser proxy").status;
+ f.proxy = probed(true, Some("203.0.113.7"), Some("198.51.100.2"));
+ assert_eq!(status(&f), Status::Ok);
+ f.proxy = probed(true, Some("198.51.100.2"), Some("198.51.100.2"));
+ assert_eq!(status(&f), Status::Warn);
+ f.proxy = probed(true, None, Some("198.51.100.2"));
+ assert_eq!(status(&f), Status::Warn);
+ f.proxy = probed(false, None, None);
+ assert_eq!(status(&f), Status::Fail);
+ f.proxy = ProxyState::Invalid("KWNT_BROWSER_PROXY is not usable: a port is required".into());
+ assert_eq!(status(&f), Status::Fail);
+ }
+
#[test]
fn render_summarises() {
let out = render(&checks(&healthy(), Platform::Docker), Platform::Docker);
@@ -541,6 +626,7 @@ mod tests {
loopback_bind: true,
token: false,
https_origin: None,
+ proxy: ProxyState::Unset,
};
for p in [Platform::Linux, Platform::Mac] {
let cs = checks(&f, p);
diff --git a/src/sandbox/browser_proxy.rs b/src/sandbox/browser_proxy.rs
new file mode 100644
index 00000000..85231560
--- /dev/null
+++ b/src/sandbox/browser_proxy.rs
@@ -0,0 +1,330 @@
+//! Sending the bots' browser out through a proxy, so sites see a home connection instead of a
+//! datacenter one.
+//!
+//! `KWNT_BROWSER_PROXY` holds the proxy (`socks5://host:port`, `socks5h://…`, `http://host:port`
+//! or `https://host:port`) and `KWNT_BROWSER_PROXY_BYPASS` adds hosts that skip it (`;` or `,`
+//! separated, Chromium's bypass syntax). Kwant's own services are always bypassed.
+//!
+//! Credentials are refused: Chromium cannot sign in to a SOCKS proxy at all, and a password in a
+//! command line, container environment or log would leak. Use a proxy that trusts the network it
+//! is on (a loopback relay, a WireGuard helper). Nothing here ever echoes the value it was given,
+//! so a mistyped secret does not end up in an error message or the log.
+
+use std::time::Duration;
+
+pub const ENV_PROXY: &str = "KWNT_BROWSER_PROXY";
+pub const ENV_BYPASS: &str = "KWNT_BROWSER_PROXY_BYPASS";
+
+/// Hosts that never go through the proxy: Kwant's own compose services, loopback and private
+/// ranges. `docker/browser-entrypoint.sh` carries the same list (a test keeps them equal).
+pub const DEFAULT_BYPASS: &str =
+ "laya;kwnt;browser;localhost;127.0.0.0/8;10.0.0.0/8;172.16.0.0/12;192.168.0.0/16;169.254.0.0/16";
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct BrowserProxy {
+ /// `scheme://host:port`, without credentials, path or query.
+ pub url: String,
+ /// Extra bypass entries (after [`DEFAULT_BYPASS`]).
+ pub bypass: Vec<String>,
+}
+
+impl BrowserProxy {
+ /// Reads the proxy from the environment. `Ok(None)`: not set. `Err`: set but unusable; the
+ /// message never contains the value.
+ pub fn from_env() -> Result<Option<Self>, String> {
+ Self::parse(
+ std::env::var(ENV_PROXY).ok().as_deref().unwrap_or(""),
+ std::env::var(ENV_BYPASS).ok().as_deref().unwrap_or(""),
+ )
+ }
+
+ pub fn parse(raw: &str, bypass: &str) -> Result<Option<Self>, String> {
+ let raw = raw.trim();
+ if raw.is_empty() {
+ return Ok(None);
+ }
+ let bad = |why: &str| Err(format!("{ENV_PROXY} is not usable: {why}"));
+ let Some((scheme, rest)) = raw.split_once("://") else {
+ return bad("expected socks5://host:port or http://host:port");
+ };
+ let scheme = scheme.to_ascii_lowercase();
+ if !matches!(scheme.as_str(), "socks5" | "socks5h" | "http" | "https") {
+ return bad("the scheme must be socks5, socks5h, http or https");
+ }
+ if rest.contains('@') {
+ return bad("credentials are not supported (Chromium cannot sign in to SOCKS, and a password would leak); use a proxy that trusts this network");
+ }
+ let rest = rest.trim_end_matches('/');
+ if rest.is_empty() || rest.contains(['/', '?', '#', ' ', ';', ',', '"', '\'']) {
+ return bad("expected only host:port after the scheme");
+ }
+ let (host, port) = match rest.rsplit_once(':') {
+ Some((h, p)) if !h.ends_with(':') || h.starts_with('[') => (h, p),
+ _ => return bad("a port is required"),
+ };
+ if host.is_empty() || (host.contains(':') && !host.starts_with('[')) || host.contains(['\\', '*']) || port.parse::<u16>().ok().filter(|p| *p > 0).is_none() {
+ return bad("expected a host and a port from 1 to 65535");
+ }
+ let mut extra = Vec::new();
+ for entry in bypass.split([';', ',']).map(str::trim).filter(|e| !e.is_empty()) {
+ if entry.contains(['"', '\'', ' ', '\\']) {
+ return Err(format!("{ENV_BYPASS} is not usable: an entry has a space or quote"));
+ }
+ extra.push(entry.to_string());
+ }
+ Ok(Some(Self { url: format!("{scheme}://{host}:{port}"), bypass: extra }))
+ }
+
+ /// The whole bypass list, Chromium syntax.
+ pub fn bypass_list(&self) -> String {
+ let mut list = DEFAULT_BYPASS.to_string();
+ for entry in &self.bypass {
+ list.push(';');
+ list.push_str(entry);
+ }
+ list
+ }
+
+ /// Chromium's switches for this proxy. `socks5` makes Chromium resolve names through the
+ /// proxy, so site names do not leak to the local resolver.
+ pub fn chromium_args(&self) -> Vec<String> {
+ vec![format!("--proxy-server={}", self.url), format!("--proxy-bypass-list={}", self.bypass_list())]
+ }
+
+ pub fn host_port(&self) -> (String, u16) {
+ let rest = self.url.split_once("://").map_or(self.url.as_str(), |(_, r)| r);
+ let (host, port) = rest.rsplit_once(':').unwrap_or((rest, "0"));
+ (host.trim_matches(['[', ']']).to_string(), port.parse().unwrap_or(0))
+ }
+
+ pub fn is_socks(&self) -> bool {
+ self.url.starts_with("socks5")
+ }
+}
+
+/// The switches for the Chromium kwant starts itself (local mode), or none without a proxy. A
+/// bad value is logged (without the value) and ignored rather than blocking the browser.
+pub fn local_chrome_args() -> Vec<String> {
+ match BrowserProxy::from_env() {
+ Ok(Some(p)) => p.chromium_args(),
+ Ok(None) => Vec::new(),
+ Err(why) => {
+ tracing::warn!("browser proxy ignored: {why}");
+ Vec::new()
+ }
+ }
+}
+
+/// What the doctor learned about the proxy.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ProxyFacts {
+ pub url: String,
+ pub reachable: bool,
+ pub proxied_ip: Option<String>,
+ pub direct_ip: Option<String>,
+}
+
+const IP_HOST: &str = "api.ipify.org";
+
+/// Pulls the address out of an HTTP response from the IP echo service.
+fn ip_from_response(response: &str) -> Option<String> {
+ let body = response.split("\r\n\r\n").nth(1)?.trim();
+ body.parse::<std::net::IpAddr>().ok().map(|ip| ip.to_string())
+}
+
+/// `GET http://api.ipify.org` through a SOCKS5 proxy (no authentication), with the name resolved
+/// by the proxy. A minimal client, so kwant needs no extra SOCKS dependency.
+async fn exit_ip_via_socks(host: &str, port: u16) -> Option<String> {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let work = async {
+ let mut s = tokio::net::TcpStream::connect((host, port)).await.ok()?;
+ s.write_all(&[5, 1, 0]).await.ok()?;
+ let mut reply = [0u8; 2];
+ s.read_exact(&mut reply).await.ok()?;
+ if reply != [5, 0] {
+ return None;
+ }
+ let mut req = vec![5, 1, 0, 3, IP_HOST.len() as u8];
+ req.extend_from_slice(IP_HOST.as_bytes());
+ req.extend_from_slice(&80u16.to_be_bytes());
+ s.write_all(&req).await.ok()?;
+ let mut head = [0u8; 4];
+ s.read_exact(&mut head).await.ok()?;
+ if head[1] != 0 {
+ return None;
+ }
+ let skip = match head[3] {
+ 1 => 4 + 2,
+ 4 => 16 + 2,
+ 3 => {
+ let mut n = [0u8; 1];
+ s.read_exact(&mut n).await.ok()?;
+ n[0] as usize + 2
+ }
+ _ => return None,
+ };
+ let mut rest = vec![0u8; skip];
+ s.read_exact(&mut rest).await.ok()?;
+ s.write_all(format!("GET / HTTP/1.1\r\nHost: {IP_HOST}\r\nConnection: close\r\nUser-Agent: kwnt-doctor\r\n\r\n").as_bytes())
+ .await
+ .ok()?;
+ let mut out = Vec::new();
+ s.take(4096).read_to_end(&mut out).await.ok()?;
+ ip_from_response(&String::from_utf8_lossy(&out))
+ };
+ tokio::time::timeout(Duration::from_secs(8), work).await.ok().flatten()
+}
+
+/// Looks at the proxy from where kwant runs: is it reachable, and does a request through it leave
+/// from another address than a direct one. Never includes anything but the credential-free URL.
+pub async fn probe(proxy: &BrowserProxy) -> ProxyFacts {
+ let (host, port) = proxy.host_port();
+ let reachable = matches!(
+ tokio::time::timeout(Duration::from_secs(3), tokio::net::TcpStream::connect((host.as_str(), port))).await,
+ Ok(Ok(_))
+ );
+ let http_ip = |client: reqwest::Client| async move {
+ let text = client.get(format!("http://{IP_HOST}/")).send().await.ok()?.text().await.ok()?;
+ text.trim().parse::<std::net::IpAddr>().ok().map(|ip| ip.to_string())
+ };
+ let timeout = Duration::from_secs(8);
+ let direct = reqwest::Client::builder().timeout(timeout).no_proxy().build().ok();
+ let direct_ip = match direct {
+ Some(c) => http_ip(c).await,
+ None => None,
+ };
+ let proxied_ip = if !reachable {
+ None
+ } else if proxy.is_socks() {
+ exit_ip_via_socks(&host, port).await
+ } else {
+ match reqwest::Proxy::all(&proxy.url).ok().and_then(|p| reqwest::Client::builder().timeout(timeout).proxy(p).build().ok()) {
+ Some(c) => http_ip(c).await,
+ None => None,
+ }
+ };
+ ProxyFacts { url: proxy.url.clone(), reachable, proxied_ip, direct_ip }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn ok(raw: &str) -> BrowserProxy {
+ BrowserProxy::parse(raw, "").unwrap().unwrap()
+ }
+
+ #[test]
+ fn unset_or_blank_means_no_proxy() {
+ assert_eq!(BrowserProxy::parse("", "").unwrap(), None);
+ assert_eq!(BrowserProxy::parse(" ", "x.com").unwrap(), None);
+ }
+
+ #[test]
+ fn the_four_schemes_are_accepted_and_normalised() {
+ assert_eq!(ok("socks5://172.17.0.1:1080").url, "socks5://172.17.0.1:1080");
+ assert_eq!(ok(" SOCKS5H://proxy.lan:9050/ ").url, "socks5h://proxy.lan:9050");
+ assert_eq!(ok("http://p:3128").url, "http://p:3128");
+ assert_eq!(ok("https://p:443").url, "https://p:443");
+ assert_eq!(ok("socks5://[::1]:1080").host_port(), ("::1".to_string(), 1080));
+ }
+
+ #[test]
+ fn a_bad_value_is_refused_without_repeating_it() {
+ for raw in [
+ "proxy:1080",
+ "ftp://p:1",
+ "socks5://p",
+ "socks5://p:0",
+ "socks5://p:99999",
+ "socks5://:1080",
+ "http://p:80/path",
+ "http://p:80 --no-sandbox",
+ "http://user:hunter2@p:80",
+ "socks5://user:hunter2@p:1080",
+ ] {
+ let err = BrowserProxy::parse(raw, "").unwrap_err();
+ assert!(err.contains(ENV_PROXY), "{err}");
+ assert!(!err.contains("hunter2") && !err.contains("--no-sandbox") && !err.contains(raw), "{err}");
+ }
+ }
+
+ #[test]
+ fn credentials_are_refused_for_every_scheme() {
+ for scheme in ["socks5", "socks5h", "http", "https"] {
+ assert!(BrowserProxy::parse(&format!("{scheme}://a:b@h:1"), "").is_err());
+ assert!(BrowserProxy::parse(&format!("{scheme}://a@h:1"), "").is_err());
+ }
+ }
+
+ #[test]
+ fn kwants_own_services_always_bypass_the_proxy_and_extras_follow() {
+ let p = BrowserProxy::parse("socks5://h:1", "example.com, *.corp;;10.9.0.0/16").unwrap().unwrap();
+ let list = p.bypass_list();
+ assert!(list.starts_with(DEFAULT_BYPASS), "{list}");
+ assert!(list.ends_with(";example.com;*.corp;10.9.0.0/16"), "{list}");
+ for service in ["laya", "kwnt", "browser", "localhost", "172.16.0.0/12"] {
+ assert!(DEFAULT_BYPASS.split(';').any(|e| e == service), "{service}");
+ }
+ assert_eq!(
+ p.chromium_args(),
+ vec!["--proxy-server=socks5://h:1".to_string(), format!("--proxy-bypass-list={list}")]
+ );
+ }
+
+ #[test]
+ fn a_bypass_entry_cannot_smuggle_a_switch() {
+ assert!(BrowserProxy::parse("socks5://h:1", "a.com --no-sandbox").is_err());
+ assert!(BrowserProxy::parse("socks5://h:1", "a\"b").is_err());
+ }
+
+ #[test]
+ fn the_container_entrypoint_uses_the_same_default_bypass() {
+ let script = include_str!("../../docker/browser-entrypoint.sh");
+ assert!(script.contains(DEFAULT_BYPASS), "docker/browser-entrypoint.sh default bypass drifted");
+ }
+
+ #[test]
+ fn the_exit_address_is_read_from_the_echo_response() {
+ assert_eq!(ip_from_response("HTTP/1.1 200 OK\r\nA: b\r\n\r\n203.0.113.7").as_deref(), Some("203.0.113.7"));
+ assert_eq!(ip_from_response("HTTP/1.1 200 OK\r\n\r\n2001:db8::1\n").as_deref(), Some("2001:db8::1"));
+ assert_eq!(ip_from_response("HTTP/1.1 403 Forbidden\r\n\r\n<html>nope</html>"), None);
+ assert_eq!(ip_from_response("garbage"), None);
+ }
+
+ #[tokio::test]
+ async fn a_closed_port_is_reported_unreachable_with_no_addresses() {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+ let facts = probe(&ok(&format!("socks5://127.0.0.1:{port}"))).await;
+ assert!(!facts.reachable);
+ assert_eq!(facts.proxied_ip, None);
+ }
+
+ #[tokio::test]
+ async fn the_socks_probe_does_the_handshake_and_reads_the_address() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ let (mut s, _) = listener.accept().await.unwrap();
+ let mut hello = [0u8; 3];
+ s.read_exact(&mut hello).await.unwrap();
+ assert_eq!(hello, [5, 1, 0]);
+ s.write_all(&[5, 0]).await.unwrap();
+ let mut head = [0u8; 5];
+ s.read_exact(&mut head).await.unwrap();
+ assert_eq!(&head[..4], &[5, 1, 0, 3]);
+ let mut name = vec![0u8; head[4] as usize + 2];
+ s.read_exact(&mut name).await.unwrap();
+ assert_eq!(&name[..name.len() - 2], IP_HOST.as_bytes());
+ s.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0]).await.unwrap();
+ let mut buf = [0u8; 256];
+ let n = s.read(&mut buf).await.unwrap();
+ assert!(String::from_utf8_lossy(&buf[..n]).starts_with("GET / HTTP/1.1"));
+ s.write_all(b"HTTP/1.1 200 OK\r\n\r\n198.51.100.9").await.unwrap();
+ });
+ assert_eq!(exit_ip_via_socks("127.0.0.1", port).await.as_deref(), Some("198.51.100.9"));
+ }
+}
diff --git a/src/sandbox/computer.rs b/src/sandbox/computer.rs
index acf98503..1c19a2d7 100644
--- a/src/sandbox/computer.rs
+++ b/src/sandbox/computer.rs
@@ -913,6 +913,7 @@ fn launch_local_chrome(profile: &Path, headless: bool) -> Result<Launched, Strin
let launched = Launched::tracked(stderr_file.is_some().then_some(stderr_path));
let mut cmd = std::process::Command::new(&chrome);
cmd.args(chrome_args(profile, headless))
+ .args(super::browser_proxy::local_chrome_args())
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(stderr_file.map_or_else(std::process::Stdio::null, std::process::Stdio::from));
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
index e09a3fd5..eec121b0 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -2,6 +2,7 @@ pub mod agent_vm;
pub mod app_links;
pub mod bitwarden;
pub mod browser;
+pub mod browser_proxy;
pub mod browser_downloads;
pub mod browser_history;
pub mod chrome_download;
diff --git a/src/sandbox/service.rs b/src/sandbox/service.rs
index 0f56e7e8..8d73e0ca 100644
--- a/src/sandbox/service.rs
+++ b/src/sandbox/service.rs
@@ -2,6 +2,7 @@
//! The private CDP endpoint is used only by the server, never by the web client.
use super::browser::{outage, BrowserController, BrowserError, Outage};
use super::chrome_download::{self, ChromeSetup};
+use super::browser_proxy::{BrowserProxy, ENV_BYPASS, ENV_PROXY};
use super::computer::{self, ComputerMode};
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -11,7 +12,7 @@ use tokio::{process::Command, sync::Mutex, time::{sleep, timeout}};
/// The VM browser's image. Bump it whenever `docker/browser.Dockerfile` or
/// `docker/browser-entrypoint.sh` change: kwant builds an image only when its tag is missing, and
/// replaces a browser container made from another tag, so the bump is what ships the change.
-pub const BROWSER_IMAGE: &str = "kwnt-browser:v3";
+pub const BROWSER_IMAGE: &str = "kwnt-browser:v4";
const BROWSER_DOCKERFILE: &str = include_str!("../../docker/browser.Dockerfile");
const BROWSER_ENTRYPOINT: &str = include_str!("../../docker/browser-entrypoint.sh");
@@ -308,11 +309,17 @@ impl BrowserService {
async fn managed_endpoint(&self) -> Result<String, BrowserError> {
let name = managed_container_name(&self.root);
let found = Self::docker(&["inspect", "--format",
- &format!("{{{{.Config.Image}}}}|{{{{index .Config.Labels \"{LABEL_BROWSER}\"}}}}"), &name], 5).await.ok();
+ &format!("{{{{.Config.Image}}}}|{{{{index .Config.Labels \"{LABEL_BROWSER}\"}}}}|{{{{index .Config.Labels \"{LABEL_PROXY}\"}}}}"), &name], 5).await.ok();
+ // The proxy is part of the container (env + label): a changed setting makes a new one.
+ let proxy = match BrowserProxy::from_env() {
+ Ok(p) => p,
+ Err(why) => { tracing::warn!("browser proxy ignored: {why}"); None }
+ };
+ let proxy_label = proxy.as_ref().map(|p| format!("{}|{}", p.url, p.bypass.join(";"))).unwrap_or_default();
// A container made from an older image keeps that image's browser, and one made before
// the labels (by an older kwant) restarts on boot and can't be reaped: make a new one.
// Its profile is on tmpfs, so nothing is lost; cookies are kept in the data folder.
- let current = found.as_deref() == Some(&format!("{BROWSER_IMAGE}|1"));
+ let current = found.as_deref() == Some(&format!("{BROWSER_IMAGE}|1|{proxy_label}"));
if found.is_some() && !current {
Self::docker(&["rm", "-f", &name], 30).await?;
}
@@ -331,7 +338,7 @@ impl BrowserService {
.map_err(|e| BrowserError::Http(e.to_string()))?;
Self::docker(&["build", "-t", BROWSER_IMAGE, &build.to_string_lossy()], 600).await?;
}
- let args = managed_run_args(&name, &self.root);
+ let args = managed_run_args(&name, &self.root, proxy.as_ref());
let args: Vec<&str> = args.iter().map(String::as_str).collect();
Self::docker(&args, 30).await?;
}
@@ -795,6 +802,8 @@ impl BrowserService {
/// Labels on every browser container kwant starts: what it is, and whose data folder it serves.
pub const LABEL_BROWSER: &str = "kwnt.browser";
pub const LABEL_ROOT: &str = "kwnt.root";
+/// The proxy the container was made for (credential-free URL and extra bypass), empty without one.
+pub const LABEL_PROXY: &str = "kwnt.browser.proxy";
/// Touched in the data folder whenever a bot uses the browser; its age is the container's idle time.
pub const LAST_USE_FILE: &str = "browser-last-used";
/// A browser container nobody has used for this long is stopped (`KWNT_BROWSER_IDLE_MINUTES`).
@@ -824,15 +833,25 @@ pub fn reap_action(running: bool, root_gone: bool, idle_for: Option<Duration>, l
/// The `docker run` arguments for the browser container of the kwant whose data folder is
/// `root`. It never restarts on its own (kwant starts it on demand), and it carries labels so a
/// later kwant can find it, stop it when idle and remove it once its data folder is gone.
-pub fn managed_run_args(name: &str, root: &Path) -> Vec<String> {
+pub fn managed_run_args(name: &str, root: &Path, proxy: Option<&BrowserProxy>) -> Vec<String> {
let root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
- [
+ let mut args: Vec<String> = [
"run", "-d", "--name", name, "--restart", "no",
"--label", &format!("{LABEL_BROWSER}=1"), "--label", &format!("{LABEL_ROOT}={}", root.display()),
"--init", "--cap-drop=ALL", "--security-opt=no-new-privileges", "--memory=1536m",
"--cpus=2", "--pids-limit=512", "--read-only", "--tmpfs", "/tmp:rw,nosuid,size=512m",
- "-p", "127.0.0.1::9222", BROWSER_IMAGE,
- ].iter().map(|a| a.to_string()).collect()
+ "-p", "127.0.0.1::9222",
+ ].iter().map(|a| a.to_string()).collect();
+ if let Some(p) = proxy {
+ // the URL carries no credentials ([`BrowserProxy::parse`] refuses them)
+ args.extend([
+ "--label".into(), format!("{LABEL_PROXY}={}|{}", p.url, p.bypass.join(";")),
+ "-e".into(), format!("{ENV_PROXY}={}", p.url),
+ "-e".into(), format!("{ENV_BYPASS}={}", p.bypass.join(";")),
+ ]);
+ }
+ args.push(BROWSER_IMAGE.to_string());
+ args
}
/// The VM browser container of the kwant whose data folder is `root`: one name per installation
@@ -877,11 +896,24 @@ mod reaper_tests {
}
}
+ #[test]
+ fn a_proxy_reaches_the_container_as_env_and_label_and_no_proxy_adds_nothing() {
+ let none = managed_run_args("n", Path::new("."), None);
+ assert!(!none.iter().any(|a| a.contains("PROXY") || a.contains("kwnt.browser.proxy")), "{none:?}");
+ let proxy = BrowserProxy::parse("socks5://172.17.0.1:1080", "example.com").unwrap().unwrap();
+ let args = managed_run_args("n", Path::new("."), Some(&proxy));
+ let pairs: Vec<(&str, &str)> = args.windows(2).map(|w| (w[0].as_str(), w[1].as_str())).collect();
+ assert!(pairs.contains(&("-e", "KWNT_BROWSER_PROXY=socks5://172.17.0.1:1080")), "{args:?}");
+ assert!(pairs.contains(&("-e", "KWNT_BROWSER_PROXY_BYPASS=example.com")), "{args:?}");
+ assert!(pairs.contains(&("--label", "kwnt.browser.proxy=socks5://172.17.0.1:1080|example.com")), "{args:?}");
+ assert_eq!(args.last().map(String::as_str), Some(BROWSER_IMAGE));
+ }
+
#[test]
fn the_container_never_restarts_on_its_own_and_carries_its_labels() {
let tmp = tempfile::tempdir().unwrap();
let root = std::fs::canonicalize(tmp.path()).unwrap();
- let args = managed_run_args("kwnt-browser-x", tmp.path());
+ let args = managed_run_args("kwnt-browser-x", tmp.path(), None);
let pairs: Vec<(&str, &str)> = args.windows(2).map(|w| (w[0].as_str(), w[1].as_str())).collect();
assert!(pairs.contains(&("--restart", "no")), "{args:?}");
assert!(!args.iter().any(|a| a.contains("unless-stopped") || a.contains("always")), "{args:?}");
@@ -896,7 +928,7 @@ mod reaper_tests {
#[test]
fn a_relative_data_folder_is_labelled_absolute() {
- let args = managed_run_args("kwnt-browser-x", Path::new("."));
+ let args = managed_run_args("kwnt-browser-x", Path::new("."), None);
let label = args.iter().find(|a| a.starts_with("kwnt.root=")).unwrap();
assert!(Path::new(label.trim_start_matches("kwnt.root=")).is_absolute(), "{label}");
}
@@ -920,7 +952,7 @@ mod image_tests {
use super::{BROWSER_DOCKERFILE, BROWSER_ENTRYPOINT, BROWSER_IMAGE};
use sha2::{Digest, Sha256};
- /// The browser files `kwnt-browser:v3` was built from. A change to them without a new
+ /// The browser files `kwnt-browser:v4` was built from. A change to them without a new
/// [`BROWSER_IMAGE`] would never reach a computer that already has the old tag.
#[test]
fn the_browser_image_tag_moves_with_its_files() {
@@ -930,7 +962,7 @@ mod image_tests {
let hash: String = files.finalize().iter().take(8).map(|b| format!("{b:02x}")).collect();
assert_eq!(
(BROWSER_IMAGE, hash.as_str()),
- ("kwnt-browser:v3", "8176b39255827329"),
+ ("kwnt-browser:v4", "3de3efce1e8d41e4"),
"docker/browser files changed: bump BROWSER_IMAGE, then record the new hash here"
);
}