| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | use std::net::{Ipv4Addr, SocketAddr}; |
| 17 | use std::sync::Arc; |
| 18 | |
| 19 | use axum::body::Body; |
| 20 | use axum::extract::ws::{Message as AxumMessage, WebSocket, WebSocketUpgrade}; |
| 21 | use axum::extract::{FromRequestParts, Request, State}; |
| 22 | use axum::http::{header, HeaderMap, HeaderValue, StatusCode, Uri}; |
| 23 | use axum::response::{IntoResponse, Response}; |
| 24 | use axum::Router; |
| 25 | use futures_util::{SinkExt, StreamExt}; |
| 26 | use tauri::{AppHandle, Runtime}; |
| 27 | use tokio_tungstenite::tungstenite::client::IntoClientRequest; |
| 28 | use tokio_tungstenite::tungstenite::Message as WsMessage; |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | const PREFERRED_PORT: u16 = 18420; |
| 34 | const PORT_SCAN: u16 = 32; |
| 35 | |
| 36 | struct Inner<R: Runtime> { |
| 37 | app: AppHandle<R>, |
| 38 | http: reqwest::Client, |
| 39 | |
| 40 | backend: String, |
| 41 | |
| 42 | |
| 43 | |
| 44 | dev_url: Option<String>, |
| 45 | } |
| 46 | |
| 47 | type Shared<R> = Arc<Inner<R>>; |
| 48 | |
| 49 | |
| 50 | |
| 51 | pub fn start<R: Runtime>( |
| 52 | app: AppHandle<R>, |
| 53 | backend: String, |
| 54 | dev_url: Option<String>, |
| 55 | ) -> Result<u16, std::io::Error> { |
| 56 | let listener = bind()?; |
| 57 | let port = listener.local_addr()?.port(); |
| 58 | |
| 59 | let state: Shared<R> = Arc::new(Inner { |
| 60 | app, |
| 61 | http: reqwest::Client::builder() |
| 62 | |
| 63 | |
| 64 | |
| 65 | .timeout(std::time::Duration::from_secs(120)) |
| 66 | .build() |
| 67 | .expect("failed to build the HTTP client"), |
| 68 | backend: backend.trim_end_matches('/').to_string(), |
| 69 | dev_url: dev_url.map(|u| u.trim_end_matches('/').to_string()), |
| 70 | }); |
| 71 | |
| 72 | let router = Router::new().fallback(handle::<R>).with_state(state); |
| 73 | |
| 74 | std::thread::Builder::new() |
| 75 | .name("hezarfen-origin".into()) |
| 76 | .spawn(move || { |
| 77 | let rt = tokio::runtime::Builder::new_multi_thread() |
| 78 | .enable_all() |
| 79 | .build() |
| 80 | .expect("failed to start the proxy runtime"); |
| 81 | rt.block_on(async move { |
| 82 | let listener = tokio::net::TcpListener::from_std(listener) |
| 83 | .expect("failed to adopt the listening socket"); |
| 84 | if let Err(err) = axum::serve(listener, router).await { |
| 85 | log::error!("origin server stopped: {err}"); |
| 86 | } |
| 87 | }); |
| 88 | })?; |
| 89 | |
| 90 | Ok(port) |
| 91 | } |
| 92 | |
| 93 | |
| 94 | |
| 95 | fn bind() -> Result<std::net::TcpListener, std::io::Error> { |
| 96 | let mut last = None; |
| 97 | for offset in 0..PORT_SCAN { |
| 98 | let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, PREFERRED_PORT + offset)); |
| 99 | match std::net::TcpListener::bind(addr) { |
| 100 | Ok(listener) => { |
| 101 | listener.set_nonblocking(true)?; |
| 102 | return Ok(listener); |
| 103 | } |
| 104 | Err(err) => last = Some(err), |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | let listener = std::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))) |
| 109 | .map_err(|err| last.unwrap_or(err))?; |
| 110 | listener.set_nonblocking(true)?; |
| 111 | Ok(listener) |
| 112 | } |
| 113 | |
| 114 | fn is_api(path: &str) -> bool { |
| 115 | path == "/api" || path.starts_with("/api/") |
| 116 | } |
| 117 | |
| 118 | |
| 119 | |
| 120 | fn backend_path(uri: &Uri) -> String { |
| 121 | let path = uri.path(); |
| 122 | let stripped = path |
| 123 | .strip_prefix("/api") |
| 124 | .filter(|rest| rest.is_empty() || rest.starts_with('/')) |
| 125 | .unwrap_or(path); |
| 126 | match uri.query() { |
| 127 | Some(q) => format!("{stripped}?{q}"), |
| 128 | None => stripped.to_string(), |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | fn wants_websocket(headers: &HeaderMap) -> bool { |
| 133 | headers |
| 134 | .get(header::UPGRADE) |
| 135 | .and_then(|v| v.to_str().ok()) |
| 136 | .is_some_and(|v| v.eq_ignore_ascii_case("websocket")) |
| 137 | } |
| 138 | |
| 139 | async fn handle<R: Runtime>(State(state): State<Shared<R>>, req: Request) -> Response { |
| 140 | let api = is_api(req.uri().path()); |
| 141 | |
| 142 | if wants_websocket(req.headers()) { |
| 143 | |
| 144 | |
| 145 | let upstream = if api { |
| 146 | format!("{}{}", ws_scheme(&state.backend), backend_path(req.uri())) |
| 147 | } else if let Some(dev) = &state.dev_url { |
| 148 | format!("{}{}", ws_scheme(dev), path_and_query(req.uri())) |
| 149 | } else { |
| 150 | return (StatusCode::NOT_FOUND, "no websocket upstream").into_response(); |
| 151 | }; |
| 152 | return bridge_websocket(req, upstream).await; |
| 153 | } |
| 154 | |
| 155 | if api { |
| 156 | let target = format!("{}{}", state.backend, backend_path(req.uri())); |
| 157 | return proxy_http(&state.http, req, target, true).await; |
| 158 | } |
| 159 | |
| 160 | if let Some(dev) = state.dev_url.clone() { |
| 161 | let target = format!("{dev}{}", path_and_query(req.uri())); |
| 162 | return proxy_http(&state.http, req, target, false).await; |
| 163 | } |
| 164 | |
| 165 | serve_asset(&state.app, req.uri().path()) |
| 166 | } |
| 167 | |
| 168 | fn path_and_query(uri: &Uri) -> &str { |
| 169 | uri.path_and_query().map(|pq| pq.as_str()).unwrap_or("/") |
| 170 | } |
| 171 | |
| 172 | fn ws_scheme(origin: &str) -> String { |
| 173 | if let Some(rest) = origin.strip_prefix("https") { |
| 174 | format!("wss{rest}") |
| 175 | } else if let Some(rest) = origin.strip_prefix("http") { |
| 176 | format!("ws{rest}") |
| 177 | } else { |
| 178 | origin.to_string() |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | |
| 183 | |
| 184 | fn serve_asset<R: Runtime>(app: &AppHandle<R>, path: &str) -> Response { |
| 185 | let resolver = app.asset_resolver(); |
| 186 | let wanted = if path == "/" { "/index.html" } else { path }; |
| 187 | |
| 188 | let asset = resolver |
| 189 | .get(wanted.to_string()) |
| 190 | .or_else(|| resolver.get("/index.html".to_string())); |
| 191 | |
| 192 | let Some(asset) = asset else { |
| 193 | return (StatusCode::NOT_FOUND, "asset not found").into_response(); |
| 194 | }; |
| 195 | |
| 196 | let mut headers = HeaderMap::new(); |
| 197 | if let Ok(mime) = HeaderValue::from_str(&asset.mime_type) { |
| 198 | headers.insert(header::CONTENT_TYPE, mime); |
| 199 | } |
| 200 | |
| 201 | |
| 202 | let cache = if wanted.starts_with("/assets/") { |
| 203 | "public, max-age=31536000, immutable" |
| 204 | } else { |
| 205 | "no-store" |
| 206 | }; |
| 207 | headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache)); |
| 208 | |
| 209 | (headers, asset.bytes).into_response() |
| 210 | } |
| 211 | |
| 212 | async fn proxy_http( |
| 213 | client: &reqwest::Client, |
| 214 | req: Request, |
| 215 | target: String, |
| 216 | rewrite_cookies: bool, |
| 217 | ) -> Response { |
| 218 | let (parts, body) = req.into_parts(); |
| 219 | |
| 220 | let method = match reqwest::Method::from_bytes(parts.method.as_str().as_bytes()) { |
| 221 | Ok(m) => m, |
| 222 | Err(_) => return (StatusCode::BAD_REQUEST, "bad method").into_response(), |
| 223 | }; |
| 224 | |
| 225 | let mut headers = parts.headers.clone(); |
| 226 | |
| 227 | |
| 228 | |
| 229 | for name in [ |
| 230 | header::HOST, |
| 231 | header::CONNECTION, |
| 232 | header::TRANSFER_ENCODING, |
| 233 | header::CONTENT_LENGTH, |
| 234 | header::ACCEPT_ENCODING, |
| 235 | ] { |
| 236 | headers.remove(name); |
| 237 | } |
| 238 | |
| 239 | let has_body = !matches!( |
| 240 | parts.method, |
| 241 | axum::http::Method::GET | axum::http::Method::HEAD |
| 242 | ); |
| 243 | let mut out = client.request(method, &target).headers(headers); |
| 244 | if has_body { |
| 245 | out = out.body(reqwest::Body::wrap_stream(body.into_data_stream())); |
| 246 | } |
| 247 | |
| 248 | let upstream = match out.send().await { |
| 249 | Ok(resp) => resp, |
| 250 | Err(err) => { |
| 251 | log::error!("proxy {target} failed: {err}"); |
| 252 | return (StatusCode::BAD_GATEWAY, "backend unreachable").into_response(); |
| 253 | } |
| 254 | }; |
| 255 | |
| 256 | let status = |
| 257 | StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY); |
| 258 | let mut headers = HeaderMap::new(); |
| 259 | for (name, value) in upstream.headers() { |
| 260 | if matches!( |
| 261 | *name, |
| 262 | header::TRANSFER_ENCODING | header::CONNECTION | header::CONTENT_LENGTH |
| 263 | ) { |
| 264 | continue; |
| 265 | } |
| 266 | if rewrite_cookies && name == header::SET_COOKIE { |
| 267 | if let Some(cookie) = rewrite_set_cookie(value) { |
| 268 | headers.append(header::SET_COOKIE, cookie); |
| 269 | } |
| 270 | continue; |
| 271 | } |
| 272 | headers.append(name.clone(), value.clone()); |
| 273 | } |
| 274 | |
| 275 | let body = Body::from_stream(upstream.bytes_stream()); |
| 276 | (status, headers, body).into_response() |
| 277 | } |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | fn rewrite_set_cookie(value: &HeaderValue) -> Option<HeaderValue> { |
| 286 | let raw = value.to_str().ok()?; |
| 287 | let kept: Vec<&str> = raw |
| 288 | .split(';') |
| 289 | .map(str::trim) |
| 290 | .filter(|attr| { |
| 291 | let lower = attr.to_ascii_lowercase(); |
| 292 | !(lower == "secure" || lower.starts_with("domain=") || lower == "samesite=none") |
| 293 | }) |
| 294 | .collect(); |
| 295 | let mut cookie = kept.join("; "); |
| 296 | if !cookie.to_ascii_lowercase().contains("samesite=") { |
| 297 | cookie.push_str("; SameSite=Lax"); |
| 298 | } |
| 299 | HeaderValue::from_str(&cookie).ok() |
| 300 | } |
| 301 | |
| 302 | |
| 303 | |
| 304 | |
| 305 | async fn bridge_websocket(req: Request, upstream_url: String) -> Response { |
| 306 | let (mut parts, _body) = req.into_parts(); |
| 307 | |
| 308 | let cookie = parts.headers.get(header::COOKIE).cloned(); |
| 309 | let protocol = parts.headers.get("sec-websocket-protocol").cloned(); |
| 310 | |
| 311 | let upgrade = match WebSocketUpgrade::from_request_parts(&mut parts, &()).await { |
| 312 | Ok(upgrade) => upgrade, |
| 313 | Err(rejection) => return rejection.into_response(), |
| 314 | }; |
| 315 | |
| 316 | upgrade.on_upgrade(move |client| async move { |
| 317 | let mut request = match upstream_url.as_str().into_client_request() { |
| 318 | Ok(req) => req, |
| 319 | Err(err) => { |
| 320 | log::error!("bad websocket url {upstream_url}: {err}"); |
| 321 | return; |
| 322 | } |
| 323 | }; |
| 324 | if let Some(cookie) = cookie { |
| 325 | request.headers_mut().insert(header::COOKIE, cookie); |
| 326 | } |
| 327 | if let Some(protocol) = protocol { |
| 328 | request |
| 329 | .headers_mut() |
| 330 | .insert("sec-websocket-protocol", protocol); |
| 331 | } |
| 332 | |
| 333 | let upstream = match tokio_tungstenite::connect_async(request).await { |
| 334 | Ok((stream, _)) => stream, |
| 335 | Err(err) => { |
| 336 | log::error!("websocket upstream {upstream_url} failed: {err}"); |
| 337 | return; |
| 338 | } |
| 339 | }; |
| 340 | |
| 341 | pipe(client, upstream).await; |
| 342 | }) |
| 343 | } |
| 344 | |
| 345 | async fn pipe( |
| 346 | client: WebSocket, |
| 347 | upstream: tokio_tungstenite::WebSocketStream< |
| 348 | tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>, |
| 349 | >, |
| 350 | ) { |
| 351 | let (mut client_tx, mut client_rx) = client.split(); |
| 352 | let (mut up_tx, mut up_rx) = upstream.split(); |
| 353 | |
| 354 | let to_upstream = async { |
| 355 | while let Some(Ok(msg)) = client_rx.next().await { |
| 356 | let msg = match msg { |
| 357 | AxumMessage::Text(text) => WsMessage::Text(text.as_str().into()), |
| 358 | AxumMessage::Binary(bin) => WsMessage::Binary(bin), |
| 359 | AxumMessage::Ping(p) => WsMessage::Ping(p), |
| 360 | AxumMessage::Pong(p) => WsMessage::Pong(p), |
| 361 | AxumMessage::Close(_) => break, |
| 362 | }; |
| 363 | if up_tx.send(msg).await.is_err() { |
| 364 | break; |
| 365 | } |
| 366 | } |
| 367 | let _ = up_tx.close().await; |
| 368 | }; |
| 369 | |
| 370 | let to_client = async { |
| 371 | while let Some(Ok(msg)) = up_rx.next().await { |
| 372 | let msg = match msg { |
| 373 | WsMessage::Text(text) => AxumMessage::Text(text.as_str().into()), |
| 374 | WsMessage::Binary(bin) => AxumMessage::Binary(bin), |
| 375 | WsMessage::Ping(p) => AxumMessage::Ping(p), |
| 376 | WsMessage::Pong(p) => AxumMessage::Pong(p), |
| 377 | WsMessage::Close(_) => break, |
| 378 | WsMessage::Frame(_) => continue, |
| 379 | }; |
| 380 | if client_tx.send(msg).await.is_err() { |
| 381 | break; |
| 382 | } |
| 383 | } |
| 384 | let _ = client_tx.close().await; |
| 385 | }; |
| 386 | |
| 387 | tokio::join!(to_upstream, to_client); |
| 388 | } |
| 389 | |
| 390 | #[cfg(test)] |
| 391 | mod tests { |
| 392 | use super::*; |
| 393 | |
| 394 | #[test] |
| 395 | fn strips_the_api_prefix_like_the_web_deployment() { |
| 396 | let uri: Uri = "/api/exams/1?page=2".parse().unwrap(); |
| 397 | assert_eq!(backend_path(&uri), "/exams/1?page=2"); |
| 398 | assert_eq!(backend_path(&"/api".parse().unwrap()), ""); |
| 399 | |
| 400 | assert_eq!(backend_path(&"/apiary".parse().unwrap()), "/apiary"); |
| 401 | } |
| 402 | |
| 403 | #[test] |
| 404 | fn makes_the_session_cookie_storable_on_a_loopback_origin() { |
| 405 | let raw = HeaderValue::from_static( |
| 406 | "session=abc; Path=/; Domain=api.hezarfen.co; Secure; HttpOnly; SameSite=None", |
| 407 | ); |
| 408 | let out = rewrite_set_cookie(&raw).unwrap(); |
| 409 | let out = out.to_str().unwrap(); |
| 410 | assert!(!out.to_ascii_lowercase().contains("secure")); |
| 411 | assert!(!out.to_ascii_lowercase().contains("domain=")); |
| 412 | assert!(out.contains("SameSite=Lax")); |
| 413 | assert!(out.contains("HttpOnly")); |
| 414 | assert!(out.starts_with("session=abc")); |
| 415 | } |
| 416 | } |