Skip to main content

waratah_notebook/
proxy.rs

1//! Reverse proxy `/jupyter/*` → loopback jupyter-server sidecar.
2//!
3//! Two paths share one handler. Plain HTTP streams request/response bodies
4//! through untouched (the `waratah_api` cors_proxy machinery, with header
5//! filtering swapped to a hop-by-hop deny-list because jupyter needs
6//! cookies, XSRF headers, `Range`, and friends forwarded). RFC 6455
7//! WebSocket upgrades tunnel as raw upgraded IO: the sidecar's
8//! `101 Switching Protocols` — handshake headers included — is relayed to
9//! the client verbatim, so this engine never computes or parses a
10//! WebSocket handshake; subprotocols, ping/pong, and permessage-deflate
11//! pass through unmodified. Kernel channels stay connected for hours:
12//! connect timeout only, no response or idle timeouts on this path.
13
14use std::net::SocketAddr;
15use std::sync::Arc;
16use std::sync::OnceLock;
17use std::time::Duration;
18
19use axum::Router;
20use axum::body::{Body, HttpBody};
21use axum::extract::{DefaultBodyLimit, OriginalUri, State};
22use axum::http::header::HeaderMap;
23use axum::http::{HeaderName, Request, StatusCode, header};
24use axum::response::Response;
25use axum::routing::any;
26use bytes::Bytes;
27use http_body_util::BodyExt as _;
28use http_body_util::Empty;
29use hyper::client::conn::http1;
30use hyper_util::client::legacy::Client;
31use hyper_util::client::legacy::connect::HttpConnector;
32use hyper_util::rt::{TokioExecutor, TokioIo};
33use tokio::net::TcpStream;
34
35use crate::state::NotebookState;
36
37/// Connect timeout for sidecar calls. Kernel channels and nbconvert output
38/// stay open far longer than any whole-response timeout would allow, so
39/// this is the only deadline on the proxy path.
40const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
41
42/// Request body cap on `/jupyter` — notebook files with embedded images.
43pub const PROXY_BODY_LIMIT: usize = 1024 * 1024 * 1024;
44
45/// Routes mounted at `/jupyter`.
46///
47/// `Router::nest` strips the `/jupyter` prefix before matching, but the
48/// handler re-reads the original URI (which keeps it) — the sidecar's
49/// `base_url` is `/jupyter`, so upstream paths must keep the prefix.
50pub fn router(state: Arc<NotebookState>) -> Router {
51    Router::new()
52        .route("/", any(proxy))
53        .route("/{*path}", any(proxy))
54        .layer(DefaultBodyLimit::max(PROXY_BODY_LIMIT))
55        .with_state(state)
56}
57
58async fn proxy(
59    State(state): State<Arc<NotebookState>>,
60    OriginalUri(original): OriginalUri,
61    mut req: Request<Body>,
62) -> Response {
63    if !state.is_ready() {
64        return plain(
65            StatusCode::SERVICE_UNAVAILABLE,
66            "notebook sidecar not ready",
67        );
68    }
69    let addr = state.sidecar_addr().await;
70    let Ok(uri) = upstream_uri(addr, original.path(), original.query()) else {
71        return plain(StatusCode::BAD_REQUEST, "invalid proxy request");
72    };
73    if wants_websocket(req.headers()) {
74        // Origin-form request target (path + query, no scheme/authority):
75        // hyper's low-level client writes absolute-form URIs verbatim, and
76        // tornado (jupyter-server) only routes origin-form targets.
77        let Ok(tunnel_uri) = origin_form_uri(original.path(), original.query()) else {
78            return plain(StatusCode::BAD_REQUEST, "invalid proxy request");
79        };
80        return tunnel_websocket(addr, tunnel_uri, &mut req).await;
81    }
82    forward(uri, original.path(), req, state.repo()).await
83}
84
85/// Readiness probe for the supervisor: `GET /jupyter/api` with the token.
86pub(crate) async fn probe_ready(addr: SocketAddr, token: &str) -> bool {
87    let Ok(uri) = format!("http://{addr}/jupyter/api").parse::<axum::http::Uri>() else {
88        return false;
89    };
90    let Ok(request) = Request::builder()
91        .uri(uri)
92        .header(header::AUTHORIZATION, format!("token {token}"))
93        .body(Body::empty())
94    else {
95        return false;
96    };
97    matches!(
98        http_client().request(request).await,
99        Ok(response) if response.status() == StatusCode::OK
100    )
101}
102
103/// Plain HTTP: pooled client, bodies streamed both ways, headers forwarded
104/// minus hop-by-hop. The client's `Host` is forwarded as-is — tornado's
105/// WebSocket origin check compares `Origin` against `Host`, and rewriting
106/// it to the sidecar's loopback port would break that comparison.
107///
108/// The one deliberate non-transparency: kernel/session start bodies get
109/// their `env.WARATAH_REPO` translated into a kernelspec name (see
110/// [`rewrite_kernel_env`]) because stock jupyter-server drops request env.
111async fn forward(
112    uri: axum::http::Uri,
113    path: &str,
114    req: Request<Body>,
115    known_repo: &str,
116) -> Response {
117    let (mut parts, body) = req.into_parts();
118    let body = if is_kernel_start(path, &parts.method) {
119        match rewrite_kernel_env(body, known_repo).await {
120            Ok(bytes) => {
121                // The rewrite can change the length; let hyper re-emit it.
122                parts.headers.remove(header::CONTENT_LENGTH);
123                Body::from(bytes)
124            }
125            Err(message) => return plain(StatusCode::BAD_REQUEST, message),
126        }
127    } else {
128        body
129    };
130    let mut builder = Request::builder().method(parts.method).uri(uri);
131    for (name, value) in &parts.headers {
132        if !is_hop_by_hop(name) {
133            builder = builder.header(name.clone(), value.clone());
134        }
135    }
136    let Ok(request) = builder.body(body) else {
137        return plain(StatusCode::BAD_REQUEST, "invalid proxy request");
138    };
139    match http_client().request(request).await {
140        Ok(upstream) => stream_back(upstream),
141        Err(error) => plain(
142            StatusCode::BAD_GATEWAY,
143            &format!("notebook sidecar unavailable: {error}"),
144        ),
145    }
146}
147
148/// The two endpoints a UI uses to start a kernel (directly or via a
149/// session), the only requests whose bodies carry a `WARATAH_REPO` override.
150fn is_kernel_start(path: &str, method: &axum::http::Method) -> bool {
151    use axum::http::Method;
152    *method == Method::POST && (path == "/jupyter/api/kernels" || path == "/jupyter/api/sessions")
153}
154
155/// Kernel-start bodies are tiny; anything past this is not one of ours.
156const KERNEL_START_BODY_LIMIT: usize = 256 * 1024;
157
158/// Translate `env.WARATAH_REPO` in a kernel/session start body into the
159/// matching kernelspec name, dropping the `env` object.
160///
161/// `POST /api/kernels` carries env at the top level; `POST /api/sessions`
162/// nests it inside the `kernel` object. Unparseable or env-free bodies
163/// pass through untouched — jupyter produces its own errors for those. A
164/// repository this compute does not serve is a 400: only the engine-written
165/// `python3-{repo}` kernelspec exists, and silently falling back to the
166/// default would run the kernel against the wrong repository with no
167/// error anywhere.
168async fn rewrite_kernel_env(body: Body, known_repo: &str) -> Result<Bytes, &'static str> {
169    let bytes = axum::body::to_bytes(body, KERNEL_START_BODY_LIMIT)
170        .await
171        .map_err(|_| "could not read kernel start body")?;
172    let Ok(mut json) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
173        return Ok(bytes);
174    };
175    let Some(object) = json.as_object_mut() else {
176        return Ok(bytes);
177    };
178    let container = match object.get_mut("kernel").and_then(|k| k.as_object_mut()) {
179        Some(kernel) => kernel,
180        None => object,
181    };
182    translate_env_to_spec_name(container, known_repo)?;
183    serde_json::to_vec(&json)
184        .map(Into::into)
185        .map_err(|_| "could not re-encode kernel start body")
186}
187
188fn translate_env_to_spec_name(
189    container: &mut serde_json::Map<String, serde_json::Value>,
190    known_repo: &str,
191) -> Result<(), &'static str> {
192    let Some(repo) = container
193        .get("env")
194        .and_then(|env| env.get("WARATAH_REPO"))
195        .and_then(|repo| repo.as_str())
196        .map(str::to_owned)
197    else {
198        return Ok(());
199    };
200    if repo != known_repo {
201        return Err("env.WARATAH_REPO names a repository this compute does not serve");
202    }
203    let name = crate::kernelspec::kernel_spec_name(&repo);
204    container.remove("env");
205    container.insert("name".to_owned(), serde_json::Value::String(name));
206    Ok(())
207}
208
209fn stream_back<B>(upstream: axum::http::Response<B>) -> Response
210where
211    B: HttpBody<Data = Bytes> + Send + 'static,
212    B::Error: Into<axum::BoxError>,
213{
214    let (parts, incoming) = upstream.into_parts();
215    let mut builder = Response::builder().status(parts.status);
216    for (name, value) in &parts.headers {
217        if !is_hop_by_hop(name) {
218            builder = builder.header(name.clone(), value.clone());
219        }
220    }
221    match builder.body(Body::from_stream(incoming.into_data_stream())) {
222        Ok(response) => response,
223        Err(_) => plain(StatusCode::BAD_GATEWAY, "notebook sidecar unavailable"),
224    }
225}
226
227/// WebSocket upgrade tunnel.
228///
229/// Dial the sidecar with a one-shot HTTP/1.1 connection, forward the
230/// client's handshake request with every header verbatim (`Sec-WebSocket-*`
231/// must arrive untouched; the sidecar computes the accept hash), then relay
232/// the sidecar's `101` — status and headers — back to the client unchanged.
233/// After both upgrades land, bytes are copied blindly in both directions
234/// until either side closes.
235async fn tunnel_websocket(
236    addr: SocketAddr,
237    uri: axum::http::Uri,
238    req: &mut Request<Body>,
239) -> Response {
240    // Claim the client-side upgrade handle before anything else touches the
241    // request; it only resolves after the `101` response is flushed.
242    let on_client_upgrade = hyper::upgrade::on(&mut *req);
243
244    // Same connect deadline as the plain path; without it a recycled or
245    // hung sidecar address would hang upgrades indefinitely.
246    let stream = match tokio::time::timeout(CONNECT_TIMEOUT, TcpStream::connect(addr)).await {
247        Ok(Ok(stream)) => stream,
248        Ok(Err(error)) => {
249            return plain(
250                StatusCode::BAD_GATEWAY,
251                &format!("notebook sidecar unavailable: {error}"),
252            );
253        }
254        Err(_) => {
255            return plain(
256                StatusCode::BAD_GATEWAY,
257                &format!("notebook sidecar connect timed out ({addr})"),
258            );
259        }
260    };
261    let (mut sender, connection) = match http1::handshake(TokioIo::new(stream)).await {
262        Ok(pair) => pair,
263        Err(error) => {
264            return plain(
265                StatusCode::BAD_GATEWAY,
266                &format!("notebook sidecar handshake failed: {error}"),
267            );
268        }
269    };
270    // Drive the upstream HTTP/1.1 connection until the tunnel takes over.
271    // `with_upgrades` matters: the plain `Connection` future marks a
272    // pending upgrade "manual" (hyper cannot fulfill it without the tokio
273    // wrapper), which cancels the tunnel's upstream side.
274    tokio::spawn(async move {
275        let _ = connection.with_upgrades().await;
276    });
277
278    let mut builder = Request::builder().method(req.method().clone()).uri(uri);
279    for (name, value) in req.headers() {
280        builder = builder.header(name.clone(), value.clone());
281    }
282    let request = match builder.body(Empty::<Bytes>::new()) {
283        Ok(request) => request,
284        Err(_) => return plain(StatusCode::BAD_REQUEST, "invalid proxy request"),
285    };
286
287    let mut upstream = match sender.send_request(request).await {
288        Ok(response) => response,
289        Err(error) => {
290            return plain(
291                StatusCode::BAD_GATEWAY,
292                &format!("notebook sidecar handshake failed: {error}"),
293            );
294        }
295    };
296    if upstream.status() != StatusCode::SWITCHING_PROTOCOLS {
297        // The sidecar refused the upgrade (bad token, no such kernel…):
298        // relay its answer so the client sees the real error.
299        return stream_back(upstream);
300    }
301    let on_upstream_upgrade = hyper::upgrade::on(&mut upstream);
302
303    let (parts, _) = upstream.into_parts();
304    let mut response = Response::builder().status(parts.status);
305    for (name, value) in &parts.headers {
306        response = response.header(name.clone(), value.clone());
307    }
308    let response = match response.body(Body::empty()) {
309        Ok(response) => response,
310        Err(_) => return plain(StatusCode::BAD_GATEWAY, "notebook sidecar unavailable"),
311    };
312
313    tokio::spawn(async move {
314        let (Ok(client), Ok(upstream)) = (on_client_upgrade.await, on_upstream_upgrade.await)
315        else {
316            return;
317        };
318        let mut client = TokioIo::new(client);
319        let mut upstream = TokioIo::new(upstream);
320        // Raw byte tunnel both ways: frames, control messages, and any
321        // future WebSocket extension pass through uninterpreted.
322        let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await;
323    });
324    response
325}
326
327/// `Connection: upgrade` + `Upgrade: websocket` (RFC 6455 §4.1), matched as
328/// comma-separated tokens, case-insensitively.
329fn wants_websocket(headers: &HeaderMap) -> bool {
330    header_tokens(headers, &header::CONNECTION).any(|token| token.eq_ignore_ascii_case("upgrade"))
331        && header_tokens(headers, &header::UPGRADE)
332            .any(|token| token.eq_ignore_ascii_case("websocket"))
333}
334
335fn header_tokens<'a>(
336    headers: &'a HeaderMap,
337    name: &HeaderName,
338) -> impl Iterator<Item = &'a str> + 'a {
339    headers
340        .get_all(name)
341        .iter()
342        .filter_map(|value| value.to_str().ok())
343        .flat_map(|value| value.split(','))
344        .map(|token| token.trim())
345}
346
347/// RFC 9110 §7.6.1 hop-by-hop headers — never forwarded end to end. The
348/// WebSocket path handles `Connection` / `Upgrade` itself (they must reach
349/// the sidecar), so only the plain path consults this list.
350fn is_hop_by_hop(name: &HeaderName) -> bool {
351    let name = name.as_str();
352    matches!(
353        name,
354        "connection"
355            | "keep-alive"
356            | "proxy-authenticate"
357            | "proxy-authorization"
358            | "te"
359            | "trailer"
360            | "trailers"
361            | "transfer-encoding"
362            | "upgrade"
363    ) || name.starts_with("proxy-")
364}
365
366/// Origin-form target for the upgrade tunnel (see `proxy`).
367fn origin_form_uri(path: &str, query: Option<&str>) -> Result<axum::http::Uri, ()> {
368    if !path.starts_with('/') || path.contains(['\r', '\n', '\0']) {
369        return Err(());
370    }
371    let mut raw = path.to_owned();
372    if let Some(query) = query {
373        if query.contains(['\r', '\n', '\0']) {
374            return Err(());
375        }
376        raw.push('?');
377        raw.push_str(query);
378    }
379    raw.parse().map_err(|_| ())
380}
381
382fn upstream_uri(addr: SocketAddr, path: &str, query: Option<&str>) -> Result<axum::http::Uri, ()> {
383    if !path.starts_with('/') || path.contains(['\r', '\n', '\0']) {
384        return Err(());
385    }
386    let mut raw = format!("http://{addr}{path}");
387    if let Some(query) = query {
388        if query.contains(['\r', '\n', '\0']) {
389            return Err(());
390        }
391        raw.push('?');
392        raw.push_str(query);
393    }
394    raw.parse().map_err(|_| ())
395}
396
397fn http_client() -> &'static Client<HttpConnector, Body> {
398    static CLIENT: OnceLock<Client<HttpConnector, Body>> = OnceLock::new();
399    CLIENT.get_or_init(|| {
400        let mut connector = HttpConnector::new();
401        connector.set_connect_timeout(Some(CONNECT_TIMEOUT));
402        Client::builder(TokioExecutor::new()).build(connector)
403    })
404}
405
406fn plain(status: StatusCode, message: &str) -> Response {
407    Response::builder()
408        .status(status)
409        .header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
410        .body(Body::from(message.to_owned()))
411        .unwrap_or_else(|_| {
412            Response::builder()
413                .status(status)
414                .body(Body::empty())
415                .expect("empty response")
416        })
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422
423    #[test]
424    fn websocket_detection_matches_tokens_case_insensitively() {
425        let mut headers = HeaderMap::new();
426        headers.insert(header::CONNECTION, "Keep-Alive, Upgrade".parse().unwrap());
427        headers.insert(header::UPGRADE, "WebSocket".parse().unwrap());
428        assert!(wants_websocket(&headers));
429
430        let mut headers = HeaderMap::new();
431        headers.insert(header::CONNECTION, "keep-alive".parse().unwrap());
432        headers.insert(header::UPGRADE, "websocket".parse().unwrap());
433        assert!(!wants_websocket(&headers));
434
435        let mut headers = HeaderMap::new();
436        headers.insert(header::CONNECTION, "upgrade".parse().unwrap());
437        headers.insert(header::UPGRADE, "h2c".parse().unwrap());
438        assert!(!wants_websocket(&headers));
439    }
440
441    #[test]
442    fn hop_by_hop_headers_are_recognized_and_content_headers_are_not() {
443        for name in [
444            "connection",
445            "keep-alive",
446            "te",
447            "trailer",
448            "transfer-encoding",
449            "upgrade",
450            "proxy-connection",
451        ] {
452            assert!(is_hop_by_hop(&HeaderName::from_static(name)), "{name}");
453        }
454        for name in ["host", "authorization", "cookie", "content-type"] {
455            assert!(!is_hop_by_hop(&HeaderName::from_static(name)), "{name}");
456        }
457    }
458
459    #[test]
460    fn upstream_uri_keeps_the_jupyter_prefix_and_rejects_crlf() {
461        let addr: SocketAddr = "127.0.0.1:9123".parse().unwrap();
462        let uri = upstream_uri(addr, "/jupyter/api", Some("x=1")).unwrap();
463        assert_eq!(uri.to_string(), "http://127.0.0.1:9123/jupyter/api?x=1");
464        assert!(upstream_uri(addr, "/jupyter/api", Some("x=1\r\nHost: evil")).is_err());
465        assert!(upstream_uri(addr, "jupyter/api", None).is_err());
466    }
467
468    #[test]
469    fn origin_form_uri_has_no_authority() {
470        let uri = origin_form_uri("/jupyter/api/kernels/x/channels", Some("token=t")).unwrap();
471        assert_eq!(uri.to_string(), "/jupyter/api/kernels/x/channels?token=t");
472        assert!(uri.authority().is_none());
473        assert!(origin_form_uri("/p", Some("a\r\nb")).is_err());
474    }
475}