-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxmux_ws_proxy.rs
More file actions
325 lines (293 loc) · 10.7 KB
/
Copy pathproxmux_ws_proxy.rs
File metadata and controls
325 lines (293 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
//! Local WebSocket listener that bridges the Tauri webview to a Proxmox `wss://` console endpoint.
//! Browsers cannot easily trust a self-signed cluster certificate; this path accepts `ws://127.0.0.1`
//! from the webview and connects upstream with `native_tls`. When a trusted PEM is stored for the
//! cluster, verification is skipped (see `http_client` in `proxmux.rs`); `allow_insecure_tls` alone
//! also skips verification.
use crate::sensitive::SecretString;
use futures_util::{SinkExt, StreamExt};
use http::Uri;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tokio::net::{TcpListener, TcpStream};
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
use tokio_tungstenite::{accept_hdr_async, WebSocketStream};
type ConnHandles = Arc<Mutex<Vec<tokio::task::JoinHandle<()>>>>;
/// Tracks the accept-loop task handle and all per-connection task handles for a running proxy.
struct ProxyEntry {
accept_loop: tokio::task::JoinHandle<()>,
conn_handles: ConnHandles,
}
type ProxyMap = Arc<Mutex<HashMap<String, ProxyEntry>>>;
fn proxy_tasks() -> &'static ProxyMap {
static MAP: std::sync::OnceLock<ProxyMap> = std::sync::OnceLock::new();
MAP.get_or_init(|| Arc::new(Mutex::new(HashMap::new())))
}
type UpstreamWs = WebSocketStream<tokio_native_tls::TlsStream<TcpStream>>;
fn apply_upstream_auth_headers(
req: &mut http::Request<()>,
auth_header: Option<&str>,
auth_cookie: Option<&str>,
) {
if let Some(auth) = auth_header {
let trimmed = auth.trim();
if !trimmed.is_empty() {
if let Ok(v) = http::HeaderValue::from_str(trimmed) {
req.headers_mut().insert(http::header::AUTHORIZATION, v);
}
}
}
if let Some(cookie) = auth_cookie {
let trimmed = cookie.trim();
if !trimmed.is_empty() {
if let Ok(v) = http::HeaderValue::from_str(trimmed) {
req.headers_mut().insert(http::header::COOKIE, v);
}
}
}
}
fn build_tls_connector(allow_insecure_tls: bool, tls_trusted_cert_pem: Option<&SecretString>) -> anyhow::Result<native_tls::TlsConnector> {
let mut tls_builder = native_tls::TlsConnector::builder();
let has_trusted_pem = tls_trusted_cert_pem
.map(|s| s.expose_secret().trim())
.filter(|s| !s.is_empty())
.is_some();
if has_trusted_pem || allow_insecure_tls {
tls_builder.danger_accept_invalid_certs(true);
}
Ok(tls_builder.build()?)
}
async fn connect_upstream_wss(
upstream_wss_url: &str,
allow_insecure_tls: bool,
tls_trusted_cert_pem: Option<&SecretString>,
auth_header: Option<&str>,
auth_cookie: Option<&str>,
) -> anyhow::Result<UpstreamWs> {
let parsed = url::Url::parse(upstream_wss_url)?;
let host = parsed.host_str().ok_or_else(|| anyhow::anyhow!("upstream URL missing host"))?;
let port = parsed.port_or_known_default().unwrap_or(443);
let connect_dur = crate::app_prefs::connect_timeout_duration();
let tcp = tokio::time::timeout(connect_dur, TcpStream::connect((host, port)))
.await
.map_err(|_| anyhow::anyhow!("TCP connect timed out."))?
.map_err(|e| anyhow::anyhow!("TCP connect: {e}"))?;
let cx = build_tls_connector(allow_insecure_tls, tls_trusted_cert_pem)?;
let cx = tokio_native_tls::TlsConnector::from(cx);
let tls = cx.connect(host, tcp).await?;
let uri: Uri = upstream_wss_url.parse()?;
let mut req = uri.into_client_request()?;
apply_upstream_auth_headers(&mut req, auth_header, auth_cookie);
req.headers_mut().insert(
http::header::SEC_WEBSOCKET_PROTOCOL,
http::HeaderValue::from_static("binary"),
);
let (ws, _) = tokio_tungstenite::client_async(req, tls).await?;
Ok(ws)
}
async fn proxy_one_browser_connection(
browser_tcp: TcpStream,
expected_path: String,
upstream_wss_url: String,
allow_insecure_tls: bool,
tls_trusted_cert_pem: Option<SecretString>,
auth_header: Option<String>,
auth_cookie: Option<String>,
) {
let callback = move |req: &Request, response: Response| -> Result<Response, http::Response<Option<String>>> {
if req.uri().path() != expected_path.as_str() {
let err = http::Response::builder()
.status(http::StatusCode::FORBIDDEN)
.body(Some("Forbidden: invalid proxy token".to_string()))
.unwrap_or_else(|_| {
// The body above is a static String; this branch is unreachable in practice.
let mut fallback = http::Response::new(None);
*fallback.status_mut() = http::StatusCode::FORBIDDEN;
fallback
});
return Err(err);
}
Ok(response)
};
let browser_ws = match accept_hdr_async(browser_tcp, callback).await {
Ok(ws) => ws,
Err(e) => {
eprintln!("proxmux ws proxy: accept browser ws: {e}");
return;
}
};
let upstream_ws = match connect_upstream_wss(
&upstream_wss_url,
allow_insecure_tls,
tls_trusted_cert_pem.as_ref(),
auth_header.as_deref(),
auth_cookie.as_deref(),
)
.await
{
Ok(ws) => ws,
Err(e) => {
eprintln!("proxmux ws proxy: connect upstream: {e}");
return;
}
};
let (mut b_sink, mut b_stream) = browser_ws.split();
let (mut u_sink, mut u_stream) = upstream_ws.split();
let up = async {
while let Some(msg) = u_stream.next().await {
match msg {
Ok(m) => {
if b_sink.send(m).await.is_err() {
break;
}
}
Err(e) => {
eprintln!("proxmux ws proxy: upstream read: {e}");
break;
}
}
}
let _ = b_sink.close().await;
};
let down = async {
while let Some(msg) = b_stream.next().await {
match msg {
Ok(m) => {
if u_sink.send(m).await.is_err() {
break;
}
}
Err(e) => {
eprintln!("proxmux ws proxy: browser read: {e}");
break;
}
}
}
let _ = u_sink.close().await;
};
tokio::select! {
() = up => {}
() = down => {}
}
}
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProxmuxWsProxyStartResult {
pub proxy_id: String,
pub local_ws_url: String,
}
#[tauri::command]
pub async fn proxmux_ws_proxy_start(
upstream_wss_url: String,
allow_insecure_tls: bool,
tls_trusted_cert_pem: Option<SecretString>,
auth_header: Option<String>,
auth_cookie: Option<String>,
) -> Result<ProxmuxWsProxyStartResult, String> {
let upstream_wss_url = upstream_wss_url.trim().to_string();
if !upstream_wss_url.to_ascii_lowercase().starts_with("wss://") {
return Err("upstream URL must start with wss://".to_string());
}
let listener = TcpListener::bind("127.0.0.1:0").await.map_err(|e| e.to_string())?;
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
let proxy_id = uuid::Uuid::new_v4().to_string();
let expected_path = format!("/{proxy_id}");
let local_ws_url = format!("ws://127.0.0.1:{port}{expected_path}");
let upstream = upstream_wss_url.clone();
let tls_pem = tls_trusted_cert_pem.filter(|s| !s.expose_secret().trim().is_empty());
let conn_handles: ConnHandles = Arc::new(Mutex::new(Vec::new()));
let conn_handles_for_loop = conn_handles.clone();
let accept_loop = tokio::spawn(async move {
loop {
match listener.accept().await {
Ok((stream, _)) => {
let upstream = upstream.clone();
let auth = auth_header.clone();
let cookie = auth_cookie.clone();
let path = expected_path.clone();
let tls = tls_pem.clone();
let conn_handle = tokio::spawn(proxy_one_browser_connection(
stream,
path,
upstream,
allow_insecure_tls,
tls,
auth,
cookie,
));
let mut guard = conn_handles_for_loop
.lock()
.unwrap_or_else(|e| e.into_inner());
guard.retain(|h| !h.is_finished());
guard.push(conn_handle);
}
Err(e) => {
eprintln!("proxmux ws proxy: accept: {e}");
break;
}
}
}
});
proxy_tasks()
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(proxy_id.clone(), ProxyEntry { accept_loop, conn_handles });
Ok(ProxmuxWsProxyStartResult {
proxy_id,
local_ws_url,
})
}
#[tauri::command]
pub fn proxmux_ws_proxy_stop(proxy_id: String) -> Result<(), String> {
let id = proxy_id.trim().to_string();
if id.is_empty() {
return Err("proxyId is required".to_string());
}
let removed = proxy_tasks()
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&id);
if let Some(entry) = removed {
entry.accept_loop.abort();
for h in entry
.conn_handles
.lock()
.unwrap_or_else(|e| e.into_inner())
.drain(..)
{
h.abort();
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::apply_upstream_auth_headers;
#[test]
fn forwards_cookie_header_for_session_auth() {
let mut req = http::Request::builder()
.uri("wss://pve.local:8006/api2/json/nodes/pve/qemu/101/vncwebsocket")
.body(())
.expect("request");
apply_upstream_auth_headers(
&mut req,
None,
Some("PVEAuthCookie=PVE:user@pam:abcdef"),
);
let cookie = req
.headers()
.get(http::header::COOKIE)
.expect("cookie header");
assert_eq!(cookie, "PVEAuthCookie=PVE:user@pam:abcdef");
}
#[test]
fn ignores_blank_auth_values() {
let mut req = http::Request::builder()
.uri("wss://pve.local:8006/api2/json/nodes/pve/lxc/101/vncwebsocket")
.body(())
.expect("request");
apply_upstream_auth_headers(&mut req, Some(" "), Some(" "));
assert!(req.headers().get(http::header::AUTHORIZATION).is_none());
assert!(req.headers().get(http::header::COOKIE).is_none());
}
}