mirror of
https://github.com/VallierDev/uu-remote-linux.git
synced 2026-11-16 08:50:40 +01:00
Signaling: honor the REST client's opt-in HTTP proxy policy (#123)
Route host and viewer WebSocket signaling through the shared reqwest client so UU_USE_PROXY=1 applies to signaling as well (HTTP/HTTPS proxies only, no direct fallback, no redirects, strict upgrade validation). ICE/WebRTC media is not proxied. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
825f964f7d
commit
d66937a01c
12 files changed
+383
-20
No files matched your search
@@ -133,7 +133,7 @@ viewer does not reconnect them automatically.
|
||||
| `UU_LOGIN_WINDOW=0` | don't auto-open the login window |
|
||||
| `UU_ENGINE_DIR` | directory holding `libuu-wayland.so` / `libuu-portal.so` (`--features engine-plugins`, used by release packages: engines are dlopen'ed only on Wayland sessions; also searched next to the binary, `../lib/uu-remote-linux`, `~/.local/lib/uu-remote-linux`, `/usr/lib/uu-remote-linux`) |
|
||||
| `UU_WOL_HELPER=1` | experimental: report LAN info (`api-ipv4…/api/v1/device/wake_on_lan/info` {mac, ip, subnet_mask}) after sign-in and answer `wake_on_lan` pushes (`target_device` {mac, ip, subnet_mask}) with a magic packet, like the official Windows host (field names from its log strings; not verified end to end). `wake_on_lan` push key names are always logged |
|
||||
| `UU_USE_PROXY=1` | honor HTTP/SOCKS proxy env vars; cloud API clients bypass env proxies by default |
|
||||
| `UU_USE_PROXY=1` | honor HTTP/HTTPS proxy env vars for REST and WebSocket signaling (not ICE/media); clients bypass env proxies by default |
|
||||
| `UU_REMOTE_ASSIST=0`, `UU_ASSIST_ALLOW=1`, `UU_ASSIST_UI=tty`, `UU_ASSIST_DEBUG=1` | disable assistance / allow at start / terminal UI for `assist` / include the server's short error message in assist errors |
|
||||
|
||||
Token has no expiry field; API code 1120 (HTTP 422) means invalid/expired → re-login. `config.json` is parsed once
|
||||
|
||||
Generated
+2
@@ -2758,12 +2758,14 @@ dependencies = [
|
||||
"nix 0.29.0",
|
||||
"qrcode",
|
||||
"rand 0.8.8",
|
||||
"rcgen",
|
||||
"reqwest",
|
||||
"sdl2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-tungstenite",
|
||||
"webrtc",
|
||||
"x11rb",
|
||||
|
||||
@@ -60,6 +60,11 @@ x11rb = { version = "0.13", features = ["damage", "shm", "allow-unsafe-code"], o
|
||||
|
||||
sdl2 = { version = "0.37", optional = true, features = ["use-pkgconfig"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# Synthetic loopback WSS certificates only; both crates already occur in Cargo.lock.
|
||||
rcgen = "0.11.3"
|
||||
tokio-rustls = { version = "0.26.6", default-features = false, features = ["ring", "tls12"] }
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1.0"
|
||||
|
||||
|
||||
+6
-1
@@ -362,7 +362,12 @@ Common environment variables:
|
||||
| `UU_LOGIN_WINDOW=0` | Do not open the login window automatically when credentials are missing |
|
||||
| `UU_PORT_MAPPING=0` | Disable port mapping (the official host's controlled-side switch) |
|
||||
| `UU_WOL_HELPER=1` | Experimental: act as a remote-boot helper like the official Windows host — report this host's LAN info after sign-in and send a magic packet to the LAN when the cloud asks to wake a PC (not verified end to end) |
|
||||
| `UU_USE_PROXY=1` | Honor HTTP/SOCKS proxy environment variables; by default proxies are ignored and NetEase servers are reached directly |
|
||||
| `UU_USE_PROXY=1` | Share environment HTTP/HTTPS proxy policy between REST and host/viewer WebSocket signaling; proxies are ignored by default |
|
||||
|
||||
|
||||
`UU_USE_PROXY=1` uses only proxy settings already available to the current process. `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` (and lowercase forms) and `NO_PROXY` follow reqwest's standard selection, with uppercase taking precedence. Signaling rejects invalid/unsupported values in the selected variables (HTTP/HTTPS only, not SOCKS), proxy URLs with paths/queries/fragments, and CGI environments that would ignore proxies; this validation is intentionally stricter than silently ignoring bad values. No matching proxy or a `NO_PROXY` match still means direct access; a selected proxy failing does not trigger direct fallback. Certificate verification remains enabled and redirects are not followed, so room authentication is not forwarded to a redirect target.
|
||||
|
||||
**This covers HTTP/WebSocket compatibility only: it does not proxy ICE/WebRTC media, add TURN TCP/TLS, or create network access.** Login, signaling and media each need an allowed network path. Connector errors expose only fixed categories/HTTP status; do not enable dependency TRACE logs that may record URLs or authentication information.
|
||||
|
||||
Host settings such as "lock after remote session" and "mute host" are stored in
|
||||
`~/.config/uuremote/host_settings.json`. The same file stores `video_encoder`
|
||||
|
||||
@@ -330,7 +330,12 @@ systemctl --user restart uuremote-native.service
|
||||
| `UU_ASSIST_ALLOW=1` | 启动时就允许他人远程协助(覆盖窗口里保存的开关状态) |
|
||||
| `UU_PORT_MAPPING=0` | 关闭端口映射(对应官方被控端的开关) |
|
||||
| `UU_WOL_HELPER=1` | 实验性:让这台主机像官方 Windows 被控端一样充当「远程开机」辅助设备——登录后向网易上报本机局域网信息,收到云端唤醒请求时向同一局域网发送唤醒包(未经端到端验证) |
|
||||
| `UU_USE_PROXY=1` | 使用环境变量里的 HTTP/SOCKS 代理;默认忽略代理、直连网易服务器 |
|
||||
| `UU_USE_PROXY=1` | REST API 与 host/viewer WebSocket 信令共用环境 HTTP/HTTPS 代理策略;默认忽略代理、直连 |
|
||||
|
||||
|
||||
`UU_USE_PROXY=1` 仅使用当前进程已有的代理配置;`HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY`(及小写形式)和 `NO_PROXY` 按 reqwest 的标准规则选择,大写优先。信令拒绝选定变量中的无效/不支持的代理 URL(仅 HTTP/HTTPS;不支持 SOCKS)、带路径/查询/片段的代理 URL,以及会忽略代理的 CGI 环境;此校验比 reqwest 默默忽略坏值更严格。未配置匹配代理或命中 `NO_PROXY` 时仍正常直连,选中代理后连接失败不会改为直连。信令保留 TLS 证书校验,不跟随重定向,也不转发认证头到重定向目标。
|
||||
|
||||
**这只解决 HTTP 与 WebSocket 的代理兼容性,不代理 ICE/WebRTC 媒体,也不提供 TURN TCP/TLS 或任何新的网络出口。** 登录、信令和媒体必须分别有允许使用的网络路径。连接器只返回固定错误类别/HTTP 状态;不要为诊断开启会记录 URL/认证信息的依赖库 TRACE 日志。
|
||||
|
||||
「远程结束后自动锁屏」「静音运行」等设置保存在 `~/.config/uuremote/host_settings.json`。同一文件里的 `video_encoder`(`auto`/`cpu`/`vaapi`/`nvenc`)和 `video_codec`(`auto`/`h264`/`h265`)用 `uuremote-server set-encoder`、`uuremote-server set-codec` 写入(非法参数退出码 2)。非 `auto` 的值优先于 `UU_VIDEO_ENCODER` / `UU_VIDEO_CODEC`;`auto` 或留空则落到环境变量,再落到 auto(有 NVIDIA 时 NVENC 优先,失败再 CPU;没有 NVIDIA 时就是 CPU,不探测;codec 仍是硬件优先 H.265、CPU 用 H.264)。探测在启动时后台进行,不挡住第一路出图。成功结果缓存到进程退出,但 NVIDIA 是否存在(`/proc/driver/nvidia/version` 或 `/dev/nvidia0`)与报告不一致时,下一次桌面连接会在后台再探测一次(`warm_auto_probe`),这一路仍用缓存的编码器,直到新结果写入。NVENC 失败只缓存 10 分钟,到期后的桌面连接同样在后台再探测一次,这一路仍用当前结果。`set-encoder` 和 `set-codec` 写完后若 `host.pid` 指向正在运行的本程序,都会发 `SIGUSR2`:编码器变化时进行中的桌面流立刻换编码器(不断开,沿用本会话已协商的 codec;新编码器起不来时按进程内 → FFmpeg 进程 → CPU 回退)。手改文件后可 `kill -USR2 $(cat ~/.config/uuremote/host.pid)`。`SIGUSR2` 不重新探测。codec 偏好仍在下次建立桌面连接时生效(运行中的 host 只记日志,不重开编码)。显式 `vaapi` 请求真彩时仍用 VAAPI、编码 4:2:0,并在 CaptureSettingSync 的 field 3 回报 4:2:0。所选编码器在本机不可用时,建流回退 CPU 并记 warning。VAAPI 进入 auto 要等 #33。
|
||||
|
||||
|
||||
+5
-2
@@ -163,17 +163,20 @@ fn redact_urls(text: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// Cloud API clients ignore ambient HTTP/SOCKS proxy settings by default: a local
|
||||
/// Cloud API and signaling clients ignore ambient HTTP/HTTPS proxy settings by default: a local
|
||||
/// proxy that intercepts TLS breaks login and signaling. `UU_USE_PROXY=1` opts back
|
||||
/// into reqwest's standard proxy environment handling.
|
||||
pub fn http_client_builder() -> reqwest::ClientBuilder {
|
||||
let builder = reqwest::Client::builder();
|
||||
if std::env::var("UU_USE_PROXY").ok().as_deref().is_some_and(proxy_requested) {
|
||||
if proxy_enabled() {
|
||||
builder
|
||||
} else {
|
||||
builder.no_proxy()
|
||||
}
|
||||
}
|
||||
pub(crate) fn proxy_enabled() -> bool {
|
||||
std::env::var("UU_USE_PROXY").ok().as_deref().is_some_and(proxy_requested)
|
||||
}
|
||||
fn proxy_requested(value: &str) -> bool {
|
||||
matches!(value.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! UU Remote Pure Native Linux Server (Rust Edition)
|
||||
//! Zero-Wine, Zero-Python, Single-Binary, 5 Native Tools Integrated
|
||||
|
||||
mod ws_transport;
|
||||
mod engine_plugin;
|
||||
mod doctor;
|
||||
mod wol;
|
||||
|
||||
+2
-9
@@ -7,7 +7,6 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_tungstenite::connect_async;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
@@ -231,14 +230,8 @@ mod refresh_tests {
|
||||
async fn open_socket(
|
||||
req: tokio_tungstenite::tungstenite::handshake::client::Request,
|
||||
limit: Duration,
|
||||
) -> Result<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>, String> {
|
||||
match tokio::time::timeout(limit, connect_async(req)).await {
|
||||
Ok(result) => result.map(|(ws, _)| ws).map_err(|e| format!("WS connect failed: {}", e)),
|
||||
Err(_) => {
|
||||
log::warn!("Signaling connect timed out after {}s", limit.as_secs());
|
||||
Err("WS connect timed out".into())
|
||||
}
|
||||
}
|
||||
) -> Result<crate::ws_transport::Socket, String> {
|
||||
crate::ws_transport::connect(req, limit).await
|
||||
}
|
||||
|
||||
impl SignalingClient {
|
||||
|
||||
@@ -3,13 +3,11 @@
|
||||
use base64::Engine as _;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde_json::Value;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
|
||||
use tokio_tungstenite::tungstenite::{client::IntoClientRequest, Message};
|
||||
use std::{collections::VecDeque,time::Duration};
|
||||
|
||||
pub struct Signal {
|
||||
ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
|
||||
ws: crate::ws_transport::Socket,
|
||||
next_ack:u64,
|
||||
pending:VecDeque<Value>,
|
||||
legacy_prefix:bool,
|
||||
@@ -17,14 +15,14 @@ pub struct Signal {
|
||||
impl Signal {
|
||||
pub async fn connect(urls:&[String], token:&str, timeout:Duration, legacy_prefix:bool)->Result<Self,String> {
|
||||
for url in urls {
|
||||
if let Ok(Ok(signal))=tokio::time::timeout(timeout,Self::one(url,token,legacy_prefix)).await {return Ok(signal)}
|
||||
if let Ok(Ok(signal))=tokio::time::timeout(timeout,Self::one(url,token,legacy_prefix,timeout)).await {return Ok(signal)}
|
||||
}
|
||||
Err("Signaling connection failed (details omitted)".into())
|
||||
}
|
||||
async fn one(url:&str,token:&str,legacy_prefix:bool)->Result<Self,String> {
|
||||
async fn one(url:&str,token:&str,legacy_prefix:bool,timeout:Duration)->Result<Self,String> {
|
||||
let mut request=format!("{}/socket.io/?transport=websocket&EIO=4",url.trim_end_matches('/')).into_client_request().map_err(|_|"Invalid signaling endpoint")?;
|
||||
request.headers_mut().insert("X-NRD-AUTH",token.parse().map_err(|_|"Invalid room authentication header")?);
|
||||
let (ws,_)=connect_async(request).await.map_err(|_|"Signaling transport failed")?;
|
||||
let ws=crate::ws_transport::connect(request,timeout).await?;
|
||||
let mut s=Self{ws,next_ack:10,pending:VecDeque::new(),legacy_prefix};
|
||||
let mut opened=false;
|
||||
loop {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#[path = "auth.rs"] mod auth;
|
||||
#[path = "config.rs"] mod config;
|
||||
#[path = "protocol.rs"] mod protocol;
|
||||
mod ws_transport;
|
||||
mod viewer;
|
||||
#[cfg(test)] #[path="hevc.rs"] mod hevc;
|
||||
use viewer::clipboard;
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Socket.IO's WebSocket transport uses the same opt-in proxy policy as the REST client.
|
||||
//! No proxy addresses, room headers, response text or underlying errors are displayed.
|
||||
use std::time::Duration;
|
||||
use reqwest::header::{HeaderMap, CONNECTION, UPGRADE, SEC_WEBSOCKET_ACCEPT, SEC_WEBSOCKET_KEY,
|
||||
SEC_WEBSOCKET_EXTENSIONS, SEC_WEBSOCKET_PROTOCOL};
|
||||
use tokio_tungstenite::{WebSocketStream, tungstenite::{handshake::{client::Request, derive_accept_key}, protocol::Role}};
|
||||
|
||||
pub type Socket = WebSocketStream<reqwest::Upgraded>;
|
||||
|
||||
/// Validate configuration rather than let reqwest silently ignore an unsupported proxy URL.
|
||||
/// Selection/NO_PROXY matching still belongs to reqwest, not a second proxy implementation.
|
||||
fn validate_proxy_url(value: &str) -> Result<(), &'static str> {
|
||||
if value.is_empty() { return Ok(()); }
|
||||
// Match reqwest's system-proxy parser before URL normalization (which would accept
|
||||
// whitespace/Unicode that http::Uri rejects and the connector would silently ignore).
|
||||
let uri: tokio_tungstenite::tungstenite::http::Uri = value.parse().map_err(|_| "Invalid signaling proxy configuration")?;
|
||||
if uri.authority().is_none() { return Err("Invalid signaling proxy configuration"); }
|
||||
let url = if value.contains("://") { reqwest::Url::parse(value) }
|
||||
else { reqwest::Url::parse(&format!("http://{value}")) }
|
||||
.map_err(|_| "Invalid signaling proxy configuration")?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none()
|
||||
|| url.port_or_known_default().is_none() || url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
|
||||
return Err("Unsupported signaling proxy configuration (HTTP/HTTPS only)");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn client() -> Result<reqwest::Client, String> {
|
||||
if crate::auth::proxy_enabled() {
|
||||
let mut configured = false;
|
||||
for names in [["HTTP_PROXY", "http_proxy"], ["HTTPS_PROXY", "https_proxy"], ["ALL_PROXY", "all_proxy"]] {
|
||||
if let Some(value) = names.iter().find_map(std::env::var_os) {
|
||||
let value = value.to_str().ok_or("Invalid signaling proxy configuration")?;
|
||||
validate_proxy_url(value)?;
|
||||
configured |= !value.is_empty();
|
||||
}
|
||||
}
|
||||
// reqwest disables environment proxies in CGI contexts; don't silently ignore an opt-in.
|
||||
if configured && std::env::var_os("REQUEST_METHOD").is_some() {
|
||||
return Err("Signaling environment proxies are disabled in CGI contexts".into());
|
||||
}
|
||||
}
|
||||
crate::auth::http_client_builder().http1_only().redirect(reqwest::redirect::Policy::none())
|
||||
.retry(reqwest::retry::never()).build().map_err(|_| "Signaling HTTP client setup failed".into())
|
||||
}
|
||||
|
||||
pub async fn connect(request: Request, timeout: Duration) -> Result<Socket, String> {
|
||||
let client = client()?;
|
||||
match tokio::time::timeout(timeout, connect_with_client(&client, request)).await {
|
||||
Ok(result) => result,
|
||||
Err(_) => Err("WS connect failed: timeout".into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_with_client(client: &reqwest::Client, request: Request) -> Result<Socket, String> {
|
||||
let (mut parts, _) = request.into_parts();
|
||||
if parts.method != reqwest::Method::GET || parts.headers.contains_key(SEC_WEBSOCKET_EXTENSIONS)
|
||||
|| parts.headers.contains_key(SEC_WEBSOCKET_PROTOCOL) || parts.headers.contains_key("proxy-authorization") {
|
||||
return Err("Unsupported signaling WebSocket request".into());
|
||||
}
|
||||
let mut url = reqwest::Url::parse(&parts.uri.to_string()).map_err(|_| "Invalid signaling endpoint")?;
|
||||
if !url.username().is_empty() || url.password().is_some() || url.fragment().is_some() {
|
||||
return Err("Invalid signaling endpoint".into());
|
||||
}
|
||||
let scheme = match url.scheme() { "ws" => "http", "wss" => "https", _ => return Err("Unsupported signaling endpoint scheme".into()) };
|
||||
url.set_scheme(scheme).map_err(|_| "Invalid signaling endpoint")?;
|
||||
let key = parts.headers.get(SEC_WEBSOCKET_KEY).ok_or("Missing WebSocket handshake key")?;
|
||||
let accept = derive_accept_key(key.as_bytes());
|
||||
for name in ["x-nrd-auth", "authorization", "cookie"] {
|
||||
if let Some(value) = parts.headers.get_mut(name) { value.set_sensitive(true); }
|
||||
}
|
||||
// reqwest owns DNS/TCP/proxy CONNECT/TLS. No custom relay, direct fallback or redirect.
|
||||
let response = client.get(url).version(reqwest::Version::HTTP_11).headers(parts.headers).send().await
|
||||
.map_err(|e| if e.is_timeout() { "WS connect failed: timeout" } else if e.is_connect() { "WS connect failed: connection" } else { "WS connect failed: request" })?;
|
||||
if response.status() != reqwest::StatusCode::SWITCHING_PROTOCOLS {
|
||||
return Err(format!("WS upgrade refused: http_status={}", response.status().as_u16()));
|
||||
}
|
||||
verify_upgrade(response.version(), response.headers(), &accept)?;
|
||||
let stream = response.upgrade().await.map_err(|_| "WS upgrade failed")?;
|
||||
Ok(WebSocketStream::from_raw_socket(stream, Role::Client, None).await)
|
||||
}
|
||||
|
||||
/// RFC 6455 §4.1: validate before handing upgraded bytes to the frame codec. Socket.IO
|
||||
/// requests no extensions/subprotocols. Unlike a generic HTTP client we never follow redirects.
|
||||
fn verify_upgrade(version: reqwest::Version, headers: &HeaderMap, accept: &str) -> Result<(), &'static str> {
|
||||
let single = |name: reqwest::header::HeaderName| {
|
||||
let mut values = headers.get_all(name).iter();
|
||||
let value = values.next()?.to_str().ok()?;
|
||||
values.next().is_none().then_some(value)
|
||||
};
|
||||
let connection_upgrade = headers.get_all(CONNECTION).iter().all(|value| value.to_str().is_ok())
|
||||
&& headers.get_all(CONNECTION).iter().any(|value|
|
||||
value.to_str().is_ok_and(|value| value.split(',').any(|token| token.trim().eq_ignore_ascii_case("upgrade"))));
|
||||
if version != reqwest::Version::HTTP_11 || !connection_upgrade
|
||||
|| !single(UPGRADE).is_some_and(|v| v.eq_ignore_ascii_case("websocket"))
|
||||
|| single(SEC_WEBSOCKET_ACCEPT) != Some(accept)
|
||||
|| headers.contains_key(SEC_WEBSOCKET_EXTENSIONS) || headers.contains_key(SEC_WEBSOCKET_PROTOCOL) {
|
||||
return Err("Invalid signaling WebSocket upgrade response");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "ws_transport_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,245 @@
|
||||
use super::*;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use tokio::{io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}};
|
||||
use tokio_tungstenite::tungstenite::{client::IntoClientRequest, Message};
|
||||
|
||||
fn request(url: &str) -> Request {
|
||||
let mut request = url.into_client_request().unwrap();
|
||||
request.headers_mut().insert("x-nrd-auth", "fixture-room-secret".parse().unwrap());
|
||||
request
|
||||
}
|
||||
|
||||
fn test_client() -> reqwest::ClientBuilder {
|
||||
reqwest::Client::builder().no_proxy().http1_only()
|
||||
.redirect(reqwest::redirect::Policy::none()).retry(reqwest::retry::never())
|
||||
}
|
||||
|
||||
async fn read_headers<S: AsyncRead + Unpin>(socket: &mut S) -> String {
|
||||
let mut bytes = Vec::new();
|
||||
while !bytes.ends_with(b"\r\n\r\n") {
|
||||
let mut byte = [0];
|
||||
socket.read_exact(&mut byte).await.unwrap();
|
||||
bytes.push(byte[0]);
|
||||
assert!(bytes.len() < 16384);
|
||||
}
|
||||
String::from_utf8(bytes).unwrap()
|
||||
}
|
||||
|
||||
fn header<'a>(request: &'a str, name: &str) -> Option<&'a str> {
|
||||
request.lines().filter_map(|line| line.split_once(':'))
|
||||
.find(|(key, _)| key.eq_ignore_ascii_case(name)).map(|(_, value)| value.trim())
|
||||
}
|
||||
|
||||
async fn accept_upgrade(listener: TcpListener, proxy: bool) -> TcpStream {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let received = read_headers(&mut socket).await;
|
||||
assert!(received.starts_with(if proxy { "GET http://" } else { "GET /" }));
|
||||
assert!(header(&received, "x-nrd-auth") == Some("fixture-room-secret"));
|
||||
if !proxy { assert!(header(&received, "proxy-authorization").is_none()); }
|
||||
let accept = derive_accept_key(header(&received, "sec-websocket-key").unwrap().as_bytes());
|
||||
let mut response = format!("HTTP/1.1 101 Switching Protocols\r\nConnection: keep-alive, Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Accept: {accept}\r\n\r\n").into_bytes();
|
||||
// The first Engine.IO frame shares a single write with the HTTP response.
|
||||
response.extend_from_slice(&[0x81, 3, b'0', b'{', b'}']);
|
||||
socket.write_all(&response).await.unwrap();
|
||||
socket
|
||||
}
|
||||
|
||||
async fn no_connection(listener: &TcpListener) {
|
||||
assert!(tokio::time::timeout(Duration::from_millis(150), listener.accept()).await.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_upgrade_validation_accepts_tokens_and_rejects_unsolicited_or_ambiguous_headers() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONNECTION, "keep-alive, Upgrade".parse().unwrap());
|
||||
headers.insert(UPGRADE, "WebSocket".parse().unwrap());
|
||||
headers.insert(SEC_WEBSOCKET_ACCEPT, "fixture-accept".parse().unwrap());
|
||||
assert!(verify_upgrade(reqwest::Version::HTTP_11, &headers, "fixture-accept").is_ok());
|
||||
headers.append(CONNECTION, "keep-alive".parse().unwrap());
|
||||
assert!(verify_upgrade(reqwest::Version::HTTP_11, &headers, "fixture-accept").is_ok());
|
||||
assert!(verify_upgrade(reqwest::Version::HTTP_2, &headers, "fixture-accept").is_err());
|
||||
assert!(verify_upgrade(reqwest::Version::HTTP_11, &headers, "wrong").is_err());
|
||||
for name in [CONNECTION, UPGRADE, SEC_WEBSOCKET_ACCEPT] {
|
||||
let mut missing = headers.clone(); missing.remove(name);
|
||||
assert!(verify_upgrade(reqwest::Version::HTTP_11, &missing, "fixture-accept").is_err());
|
||||
}
|
||||
for name in [UPGRADE, SEC_WEBSOCKET_ACCEPT, SEC_WEBSOCKET_EXTENSIONS, SEC_WEBSOCKET_PROTOCOL] {
|
||||
let mut invalid = headers.clone(); invalid.append(name, "fixture-server-secret".parse().unwrap());
|
||||
let error = verify_upgrade(reqwest::Version::HTTP_11, &invalid, "fixture-accept").unwrap_err();
|
||||
assert!(!error.contains("fixture"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_configuration_errors_never_echo_proxy_values() {
|
||||
for proxy in ["", "127.0.0.1:3128", "http://127.0.0.1:3128", "https://fixture-user:[email protected]:3128"] {
|
||||
assert!(validate_proxy_url(proxy).is_ok());
|
||||
}
|
||||
for proxy in ["socks5://fixture-user:[email protected]:3128", "http://127.0.0.1:3128/?fixture-token", "http://127.0.0.1:3128/#fixture-token", "http://127.0.0.1:3128/fixture-secret", "http://[fixture-invalid", " http://127.0.0.1:3128", "http://127.0.0.1:3128 ", "http://例子.invalid:3128"] {
|
||||
let error = validate_proxy_url(proxy).unwrap_err();
|
||||
assert!(!error.contains("fixture"));
|
||||
assert!(!error.contains("127.0.0.1"));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn upgrade_keeps_prefetched_frame_and_does_not_limit_socket_lifetime() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/socket.io/?fixture-query-secret", listener.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
let socket = accept_upgrade(listener, false).await;
|
||||
let mut socket = WebSocketStream::from_raw_socket(socket, Role::Server, None).await;
|
||||
tokio::time::sleep(Duration::from_millis(1200)).await;
|
||||
assert!(matches!(socket.next().await, Some(Ok(Message::Text(value))) if value == "fixture-client-frame"));
|
||||
socket.send(Message::Text("fixture-late-frame".into())).await.unwrap();
|
||||
});
|
||||
let http = test_client().build().unwrap();
|
||||
let mut socket = tokio::time::timeout(Duration::from_secs(1), connect_with_client(&http, request(&url))).await.unwrap().unwrap();
|
||||
assert!(matches!(socket.next().await, Some(Ok(Message::Text(value))) if value == "0{}"));
|
||||
// A one-second establishment deadline must not remain attached to the upgraded stream.
|
||||
tokio::time::sleep(Duration::from_millis(1300)).await;
|
||||
socket.send(Message::Text("fixture-client-frame".into())).await.unwrap();
|
||||
let message = tokio::time::timeout(Duration::from_secs(3), socket.next()).await.unwrap();
|
||||
assert!(matches!(message, Some(Ok(Message::Text(value))) if value == "fixture-late-frame"));
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proxy_refusal_never_falls_back_to_origin_or_echoes_server_content() {
|
||||
let origin = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy_url = format!("http://{}", proxy.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = proxy.accept().await.unwrap();
|
||||
let received = read_headers(&mut socket).await;
|
||||
assert!(received.starts_with("GET http://"));
|
||||
assert!(header(&received, "proxy-authorization").is_some());
|
||||
socket.write_all(b"HTTP/1.1 407 Proxy Authentication Required\r\nContent-Length: 19\r\n\r\nfixture-body-secret").await.unwrap();
|
||||
});
|
||||
let proxy = reqwest::Proxy::all(proxy_url).unwrap().basic_auth("fixture-user", "fixture-proxy-secret");
|
||||
let http = test_client().proxy(proxy).build().unwrap();
|
||||
let result = tokio::time::timeout(Duration::from_secs(5),
|
||||
connect_with_client(&http, request(&format!("ws://{}/fixture-path-secret", origin.local_addr().unwrap()))))
|
||||
.await.expect("proxy refusal must not wait on a fallback origin");
|
||||
let error = result.err().expect("proxy refusal must fail");
|
||||
assert!(error.contains("407")); assert!(!error.contains("fixture"));
|
||||
no_connection(&origin).await;
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn redirects_are_not_followed_with_room_credentials() {
|
||||
let origin = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let destination = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/socket.io/", origin.local_addr().unwrap());
|
||||
let location = format!("http://{}/fixture-redirect-secret", destination.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = origin.accept().await.unwrap();
|
||||
let _ = read_headers(&mut socket).await;
|
||||
socket.write_all(format!("HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\n\r\n").as_bytes()).await.unwrap();
|
||||
});
|
||||
let result = tokio::time::timeout(Duration::from_secs(5),
|
||||
connect_with_client(&test_client().build().unwrap(), request(&url)))
|
||||
.await.expect("redirect must not wait on its destination");
|
||||
let error = result.err().expect("redirect must fail");
|
||||
assert!(error.contains("302")); assert!(!error.contains("fixture"));
|
||||
no_connection(&destination).await;
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
// No global environment mutation: the subprocess has only synthetic loopback configuration.
|
||||
#[test]
|
||||
fn environment_policy_probe() {
|
||||
let Ok(url) = std::env::var("UU_WS_TEST_ENDPOINT") else { return; };
|
||||
assert!(url.starts_with("ws://127.0.0.1:"));
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
runtime.block_on(async {
|
||||
let mut socket = connect(request(&url), Duration::from_secs(5)).await.expect("fixture connection failed");
|
||||
let message = tokio::time::timeout(Duration::from_secs(3), socket.next()).await.unwrap();
|
||||
assert!(matches!(message, Some(Ok(Message::Text(value))) if value == "0{}"));
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn environment_proxy_opt_in_and_no_proxy_match_rest_policy() {
|
||||
for (opt_in, bypass, via_proxy) in [(false, false, false), (true, false, true), (true, true, false)] {
|
||||
let origin = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/socket.io/", origin.local_addr().unwrap());
|
||||
let proxy_url = format!("http://fixture-user:fixture-proxy-secret@{}", proxy.local_addr().unwrap());
|
||||
let (selected, unused) = if via_proxy { (proxy, origin) } else { (origin, proxy) };
|
||||
let server = tokio::spawn(async move { let _socket = accept_upgrade(selected, via_proxy).await; });
|
||||
let mut child = tokio::process::Command::new(std::env::current_exe().unwrap());
|
||||
child.args(["--exact", "ws_transport::tests::environment_policy_probe", "--nocapture"])
|
||||
.env_clear().env("UU_WS_TEST_ENDPOINT", url).env("HTTP_PROXY", proxy_url);
|
||||
if opt_in { child.env("UU_USE_PROXY", "1"); }
|
||||
if bypass { child.env("NO_PROXY", "127.0.0.1"); }
|
||||
let output = tokio::time::timeout(Duration::from_secs(10), child.output()).await.unwrap().unwrap();
|
||||
assert!(output.status.success(), "isolated proxy-policy subprocess failed");
|
||||
assert!(!output.stdout.windows(b"fixture-room-secret".len()).any(|s| s == b"fixture-room-secret"));
|
||||
assert!(!output.stderr.windows(b"fixture-proxy-secret".len()).any(|s| s == b"fixture-proxy-secret"));
|
||||
no_connection(&unused).await;
|
||||
server.await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wss_connect_keeps_origin_auth_inside_tls_and_requires_trusted_certificate() {
|
||||
use std::sync::Arc;
|
||||
use tokio_rustls::{rustls, TlsAcceptor};
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
|
||||
// A fresh test certificate/key, kept only in memory. The mock does not relay anywhere:
|
||||
// it accepts CONNECT and then speaks TLS + WebSocket on that same loopback socket.
|
||||
let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
|
||||
let cert_der = cert.serialize_der().unwrap();
|
||||
let root = reqwest::Certificate::from_der(&cert_der).unwrap();
|
||||
let config = rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
||||
.with_safe_default_protocol_versions().unwrap().with_no_client_auth()
|
||||
.with_single_cert(vec![CertificateDer::from(cert_der)],
|
||||
PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert.serialize_private_key_der()))).unwrap();
|
||||
let acceptor = TlsAcceptor::from(Arc::new(config));
|
||||
for trusted in [false, true] {
|
||||
let origin = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = origin.local_addr().unwrap().port();
|
||||
let proxy_url = format!("http://{}", proxy.local_addr().unwrap());
|
||||
let acceptor = acceptor.clone();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = proxy.accept().await.unwrap();
|
||||
let received = read_headers(&mut socket).await;
|
||||
assert!(received.starts_with(&format!("CONNECT localhost:{port} HTTP/1.1\r\n")));
|
||||
assert!(header(&received, "x-nrd-auth").is_none());
|
||||
assert!(header(&received, "proxy-authorization").is_some());
|
||||
assert!(!received.contains("fixture-room-secret"));
|
||||
socket.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n").await.unwrap();
|
||||
let tls = acceptor.accept(socket).await;
|
||||
if !trusted { assert!(tls.is_err()); return; }
|
||||
let mut tls = tls.expect("fixture TLS handshake failed");
|
||||
let received = read_headers(&mut tls).await;
|
||||
assert!(received.starts_with("GET /socket.io/"));
|
||||
assert!(header(&received, "x-nrd-auth") == Some("fixture-room-secret"));
|
||||
assert!(header(&received, "proxy-authorization").is_none());
|
||||
assert!(!received.contains("fixture-proxy-secret"));
|
||||
let accept = derive_accept_key(header(&received, "sec-websocket-key").unwrap().as_bytes());
|
||||
let mut response = format!("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Accept: {accept}\r\n\r\n").into_bytes();
|
||||
response.extend_from_slice(&[0x81, 3, b'0', b'{', b'}']);
|
||||
tls.write_all(&response).await.unwrap();
|
||||
});
|
||||
let proxy = reqwest::Proxy::all(proxy_url).unwrap().basic_auth("fixture-user", "fixture-proxy-secret");
|
||||
let mut builder = test_client().proxy(proxy);
|
||||
if trusted { builder = builder.add_root_certificate(root.clone()); }
|
||||
let client = builder.build().unwrap();
|
||||
let result = tokio::time::timeout(Duration::from_secs(5),
|
||||
connect_with_client(&client, request(&format!("wss://localhost:{port}/socket.io/?fixture-query-secret")))).await.unwrap();
|
||||
if trusted {
|
||||
let mut socket = result.expect("trusted fixture WebSocket failed");
|
||||
let message = tokio::time::timeout(Duration::from_secs(3), socket.next()).await.unwrap();
|
||||
assert!(matches!(message, Some(Ok(Message::Text(value))) if value == "0{}"));
|
||||
} else {
|
||||
let error = result.err().expect("untrusted fixture certificate must fail");
|
||||
assert!(!error.contains("fixture")); assert!(!error.contains("localhost"));
|
||||
}
|
||||
no_connection(&origin).await;
|
||||
tokio::time::timeout(Duration::from_secs(5), server).await.unwrap().unwrap();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user