Skip to main content

waratah_notebook/
jupyter_config.rs

1//! Generated jupyter-server config for the sidecar.
2//!
3//! [`render`] produces the `jupyter_server_config.py` written to
4//! `{runtime_dir}/jupyter_server_config.py` and passed as
5//! `--config=<path>`. The file carries the auth token, so it must never
6//! live under the Contents-API root (`NotebookOptions::dir`), where
7//! `GET /jupyter/api/contents/…` would serve it to any token holder —
8//! it belongs behind the token, not beside it.
9
10use std::path::Path;
11
12/// Values the engine controls in the sidecar config.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct JupyterConfigSpec<'a> {
15    /// Loopback port the sidecar must take (engine-picked, `port_retries=0`).
16    pub port: u16,
17    /// Startup-minted auth token.
18    pub token: &'a str,
19    /// Contents-API root (`c.ServerApp.root_dir`).
20    pub root_dir: &'a Path,
21    /// Kernel idle culling timeout, seconds.
22    pub cull_idle_secs: u64,
23    /// This engine's public origin, allowed for origin checks.
24    pub allow_origin: &'a str,
25}
26
27/// Render the sidecar's `jupyter_server_config.py`.
28pub fn render(spec: &JupyterConfigSpec) -> String {
29    let mut out = String::with_capacity(2048);
30    out.push_str("# Generated by waratah at sidecar startup — do not edit.\n");
31    out.push_str("# This file carries the auth token and lives outside the Contents-API\n");
32    out.push_str("# root on purpose; see waratah_notebook::jupyter_config.\n");
33    out.push_str("c = get_config()  # noqa: F821 — provided by jupyter-server\n\n");
34    out.push_str("# Loopback-only dev stub: the engine reverse-proxies /jupyter to this\n");
35    out.push_str("# process, so every URL the sidecar generates already carries the\n");
36    out.push_str("# /jupyter base the browser used.\n");
37    out.push_str(&format!(
38        "c.ServerApp.base_url = {}\n",
39        py_str(crate::options::JUPYTER_PATH)
40    ));
41    out.push_str("c.ServerApp.open_browser = False\n");
42    out.push_str("c.ServerApp.allow_remote_access = False\n");
43    out.push_str("c.ServerApp.ip = \"127.0.0.1\"\n");
44    out.push_str(&format!("c.ServerApp.port = {}\n", spec.port));
45    // The engine owns port allocation; a collision must fail fast so the
46    // supervisor restarts on a fresh port instead of silently moving.
47    out.push_str("c.ServerApp.port_retries = 0\n");
48    // 2.x moved auth tokens to IdentityProvider; ServerApp.token only warns.
49    out.push_str(&format!(
50        "c.IdentityProvider.token = {}\n",
51        py_str(spec.token)
52    ));
53    out.push_str(&format!(
54        "c.ServerApp.root_dir = {}\n",
55        py_str(&spec.root_dir.display().to_string())
56    ));
57    // Runtime files (kernel connection JSONs) land in the runtime dir via
58    // the JUPYTER_RUNTIME_DIR env var set on the sidecar process — 2.x has
59    // no ServerApp.runtime_dir trait.
60    out.push_str("\n# The browser Origin is the engine's own origin while the sidecar sees\n");
61    out.push_str("# the forwarded Host; allow_origin keeps tornado's WebSocket origin\n");
62    out.push_str("# check happy either way.\n");
63    out.push_str(&format!(
64        "c.ServerApp.allow_origin = {}\n",
65        py_str(spec.allow_origin)
66    ));
67    out.push_str("\n# Idle kernels are culled after this many seconds.\n");
68    out.push_str(&format!(
69        "c.MappingKernelManager.cull_idle_timeout = {}\n",
70        spec.cull_idle_secs
71    ));
72    out
73}
74
75/// Quote `value` as a python string literal (paths and tokens only need
76/// backslash and double-quote escaping, but be safe).
77fn py_str(value: &str) -> String {
78    let mut out = String::with_capacity(value.len() + 2);
79    out.push('"');
80    for ch in value.chars() {
81        match ch {
82            '\\' => out.push_str("\\\\"),
83            '"' => out.push_str("\\\""),
84            '\n' => out.push_str("\\n"),
85            '\r' => out.push_str("\\r"),
86            _ => out.push(ch),
87        }
88    }
89    out.push('"');
90    out
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    #[test]
98    fn rendered_config_carries_the_controlled_values() {
99        let spec = JupyterConfigSpec {
100            port: 41234,
101            token: "cafe\"babe",
102            root_dir: Path::new("/data/notebooks"),
103            cull_idle_secs: 3600,
104            allow_origin: "http://127.0.0.1:8080",
105        };
106        let text = render(&spec);
107        assert!(text.contains("c.ServerApp.base_url = \"/jupyter\""));
108        assert!(text.contains("c.ServerApp.port = 41234"));
109        assert!(text.contains("c.ServerApp.port_retries = 0"));
110        assert!(text.contains("c.IdentityProvider.token = \"cafe\\\"babe\""));
111        assert!(text.contains("c.ServerApp.root_dir = \"/data/notebooks\""));
112
113        assert!(text.contains("c.ServerApp.allow_origin = \"http://127.0.0.1:8080\""));
114        assert!(text.contains("c.MappingKernelManager.cull_idle_timeout = 3600"));
115        // No env allowlist is emitted: jupyter-server 2.x has no such trait
116        // (verified against the pin); per-repo kernelspecs carry
117        // WARATAH_REPO instead (waratah_notebook::kernelspec).
118        assert!(!text.contains("env_allowlist"));
119    }
120
121    #[test]
122    fn paths_with_backslashes_are_escaped() {
123        let spec = JupyterConfigSpec {
124            port: 1,
125            token: "t",
126            root_dir: Path::new("C:\\notebooks"),
127            cull_idle_secs: 1,
128            allow_origin: "http://127.0.0.1:1",
129        };
130        assert!(render(&spec).contains("c.ServerApp.root_dir = \"C:\\\\notebooks\""));
131    }
132}