From 7e275e6e132f98f7d7608a3b5189ebf96b81f29d Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Sun, 22 Nov 2026 16:30:21 -0800 Subject: [PATCH 1/2] Add configurable SQLNB browser sign-in --- README.md | 20 +++ http/Cargo.lock | 1 + http/Cargo.toml | 1 + http/src/browser_auth.rs | 234 +++++++++++++++++++++++++++++++++ http/src/imports/tests.rs | 1 + http/src/lib.rs | 12 ++ http/src/tests.rs | 108 +++++++++++++++ src/sidequery_ui_extension.cpp | 15 ++- 8 files changed, 386 insertions(+), 6 deletions(-) create mode 100644 http/src/browser_auth.rs diff --git a/README.md b/README.md index 8228e4d..8725b5e 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,26 @@ configured loopback port and preserve the browser's `Host` and `Origin` headers. The returned launch URL uses the configured HTTPS origin and includes the session token. Allow only trusted users to reach the proxy. +For a stable browser URL, pass `browser_auth_file := '/path/to/auth.json'` along +with `browser_origin`. The file can configure either or both sign-in methods: + +```json +{ + "accessKeySha256": "", + "trustedProxy": { + "header": "X-Authenticated-User", + "value": "owner@example.net" + } +} +``` + +Generate an access key with `openssl rand -hex 32`, store it securely, and put +only its hash in the JSON. Access-key sign-in remembers the browser for seven +days. With a trusted proxy, the ordinary URL opens the notebook for the +specified identity. The proxy must authenticate the user and remove incoming +copies of the identity header before setting its own. Keep untrusted clients +away from the loopback listener. Existing launch links work with either mode. + To connect an MCP client, start with `mcp := true` and follow the [MCP setup guide](docs/mcp.md). MCP is disabled by default. diff --git a/http/Cargo.lock b/http/Cargo.lock index 922e1dd..2197e0c 100644 --- a/http/Cargo.lock +++ b/http/Cargo.lock @@ -1472,6 +1472,7 @@ dependencies = [ "libc", "mime_guess", "reqwest", + "ring", "rmcp", "serde", "serde_json", diff --git a/http/Cargo.toml b/http/Cargo.toml index 13bdbc0..6b9af3d 100644 --- a/http/Cargo.toml +++ b/http/Cargo.toml @@ -22,6 +22,7 @@ http-body-util = "0.1" libc = "0.2" mime_guess = "2" reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls"] } +ring = "0.17" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" diff --git a/http/src/browser_auth.rs b/http/src/browser_auth.rs new file mode 100644 index 0000000..c464fb4 --- /dev/null +++ b/http/src/browser_auth.rs @@ -0,0 +1,234 @@ +use super::{header, ApiError, AppState, HeaderMap, HeaderValue, Json, State, StatusCode}; +use ring::hmac; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + fs::File, + io::Read, + time::{SystemTime, UNIX_EPOCH}, +}; +use subtle::ConstantTimeEq; + +const SESSION_SECONDS: u64 = 7 * 24 * 60 * 60; + +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct BrowserAuthConfig { + access_key_sha256: Option, + trusted_proxy: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct TrustedProxyConfig { + header: String, + value: String, +} + +#[derive(Clone, Default)] +pub(super) struct BrowserAuth { + access_key_digest: Option, + trusted_proxy: Option<(header::HeaderName, HeaderValue)>, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct Methods { + access_key: bool, + trusted_proxy: bool, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Credentials { + access_key: Option, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct Session { + launch_capability: String, +} + +impl BrowserAuth { + pub(super) fn load(path: &str, origin: &str) -> Result { + if path.is_empty() { + return Ok(Self::default()); + } + if !origin.starts_with("https://") { + return Err("browser_auth_file requires an HTTPS browser_origin".into()); + } + let mut bytes = Vec::new(); + File::open(path) + .and_then(|file| file.take(16_385).read_to_end(&mut bytes)) + .map_err(|error| format!("could not read browser_auth_file: {error}"))?; + if bytes.len() > 16_384 { + return Err("browser_auth_file exceeds 16 KiB".into()); + } + let config: BrowserAuthConfig = + serde_json::from_slice(&bytes).map_err(|_| "invalid browser_auth_file JSON")?; + if config + .access_key_sha256 + .as_deref() + .is_some_and(|digest| !is_key(digest)) + { + return Err("accessKeySha256 must be 64 lowercase hexadecimal characters".into()); + } + let trusted_proxy = config + .trusted_proxy + .map(|proxy| { + let name = header::HeaderName::from_bytes(proxy.header.as_bytes()) + .map_err(|_| "trustedProxy.header is not a valid header name")?; + if matches!( + name.as_str(), + "host" | "origin" | "authorization" | "cookie" + ) || name.as_str().starts_with("sec-") + { + return Err("trustedProxy.header must be a dedicated identity header"); + } + let value = HeaderValue::from_str(&proxy.value) + .map_err(|_| "trustedProxy.value is not a valid header value")?; + if value.is_empty() { + return Err("trustedProxy.value must not be empty"); + } + Ok((name, value)) + }) + .transpose()?; + Ok(Self { + access_key_digest: config.access_key_sha256, + trusted_proxy, + }) + } + + fn accepts_proxy(&self, headers: &HeaderMap) -> bool { + let Some((name, expected)) = &self.trusted_proxy else { + return false; + }; + let mut values = headers.get_all(name).iter(); + values.next() == Some(expected) && values.next().is_none() + } +} + +pub(super) async fn methods(State(state): State) -> Json { + Json(Methods { + access_key: state.browser_auth.access_key_digest.is_some(), + trusted_proxy: state.browser_auth.trusted_proxy.is_some(), + }) +} + +pub(super) async fn sign_in( + State(state): State, + headers: HeaderMap, + Json(credentials): Json, +) -> Result { + let unauthorized = || { + ApiError::new( + StatusCode::UNAUTHORIZED, + "sign_in_required", + "Sign in to open this notebook.", + ) + }; + if headers + .get(header::ORIGIN) + .and_then(|value| value.to_str().ok()) + != Some(&state.origin) + { + return Err(unauthorized()); + } + + let mut output_headers = HeaderMap::new(); + if let Some(access_key) = credentials.access_key { + let digest = state + .browser_auth + .access_key_digest + .as_deref() + .ok_or_else(unauthorized)?; + if !is_key(&access_key) + || !bool::from( + format!("{:x}", Sha256::digest(access_key)) + .as_bytes() + .ct_eq(digest.as_bytes()), + ) + { + return Err(unauthorized()); + } + set_cookie(&mut output_headers, &state.origin, digest); + } else if !state.browser_auth.accepts_proxy(&headers) + && !state + .browser_auth + .access_key_digest + .as_deref() + .is_some_and(|digest| accepts_cookie(&headers, &state.origin, digest)) + { + return Err(unauthorized()); + } + Ok(( + output_headers, + Json(Session { + launch_capability: state.token, + }), + )) +} + +fn is_key(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +fn unix_seconds() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} + +fn cookie_name(origin: &str) -> String { + let hash = format!("{:x}", Sha256::digest(origin)); + format!("__Host-sqlnb-{}", &hash[..16]) +} + +fn signature(origin: &str, digest: &str, expiry: u64) -> String { + let key = hmac::Key::new(hmac::HMAC_SHA256, digest.as_bytes()); + let message = format!("sqlnb-session-v1\n{origin}\n{expiry}"); + hmac::sign(&key, message.as_bytes()) + .as_ref() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +fn set_cookie(headers: &mut HeaderMap, origin: &str, digest: &str) { + let expiry = unix_seconds() + SESSION_SECONDS; + let cookie = format!( + "{}={expiry}.{}; Max-Age={SESSION_SECONDS}; Path=/; Secure; HttpOnly; SameSite=Strict", + cookie_name(origin), + signature(origin, digest, expiry), + ); + headers.insert(header::SET_COOKIE, HeaderValue::from_str(&cookie).unwrap()); +} + +fn accepts_cookie(headers: &HeaderMap, origin: &str, digest: &str) -> bool { + let name = cookie_name(origin); + let value = headers + .get_all(header::COOKIE) + .iter() + .filter_map(|header| header.to_str().ok()) + .flat_map(|header| header.split(';')) + .filter_map(|cookie| cookie.trim().split_once('=')) + .find_map(|(key, value)| (key == name).then_some(value)); + let Some((expiry, mac)) = value.and_then(|value| value.split_once('.')) else { + return false; + }; + let Ok(expiry) = expiry.parse::() else { + return false; + }; + expiry > unix_seconds() + && is_key(mac) + && bool::from( + signature(origin, digest, expiry) + .as_bytes() + .ct_eq(mac.as_bytes()), + ) +} diff --git a/http/src/imports/tests.rs b/http/src/imports/tests.rs index 25b8d09..47e67b8 100644 --- a/http/src/imports/tests.rs +++ b/http/src/imports/tests.rs @@ -28,6 +28,7 @@ fn config(temp: &TempDir, port: u16) -> ServerConfig { notebook_root: temp.path().join("notebooks").display().to_string(), mcp_token: String::new(), browser_origin: String::new(), + browser_auth_file: String::new(), } } diff --git a/http/src/lib.rs b/http/src/lib.rs index cfaa893..36a74f8 100644 --- a/http/src/lib.rs +++ b/http/src/lib.rs @@ -16,6 +16,7 @@ mod platform; #[cfg(windows)] mod windows_process; use platform::*; +mod browser_auth; mod duckdb_ui; mod history; mod imports; @@ -71,12 +72,15 @@ struct ServerConfig { mcp_token: String, #[serde(default)] browser_origin: String, + #[serde(default)] + browser_auth_file: String, } #[derive(Clone)] struct AppState { origin: String, allowed_hosts: Vec, + browser_auth: browser_auth::BrowserAuth, token: String, duckdb_version: String, quack_url: Url, @@ -337,6 +341,7 @@ fn build_state(config: ServerConfig, port: u16) -> Result { return Err("local UI capability must not be empty".into()); } let (origin, allowed_hosts) = browser_origin_and_hosts(&config.browser_origin, port)?; + let browser_auth = browser_auth::BrowserAuth::load(&config.browser_auth_file, &origin)?; let mut quack_url = parse_loopback_url(&config.quack_url, "Quack URL")?; if quack_url.path().is_empty() || quack_url.path() == "/" { quack_url.set_path("/quack"); @@ -372,6 +377,7 @@ fn build_state(config: ServerConfig, port: u16) -> Result { Ok(AppState { origin, allowed_hosts, + browser_auth, token: config.token, duckdb_version: config.duckdb_version, quack_url, @@ -2302,6 +2308,12 @@ async fn static_asset( fn router(state: AppState) -> Router { let mut router = Router::new() .route("/api/v1/bootstrap", get(bootstrap)) + .route( + "/api/v1/session", + get(browser_auth::methods) + .post(browser_auth::sign_in) + .layer(DefaultBodyLimit::max(4096)), + ) .route("/api/v1/files", get(list_files)) .route("/api/v1/git", get(git_status)) .route("/api/v1/git/diff", get(git_diff)) diff --git a/http/src/tests.rs b/http/src/tests.rs index 2d80dae..ebae5bb 100644 --- a/http/src/tests.rs +++ b/http/src/tests.rs @@ -611,6 +611,7 @@ impl Fixture { notebook_root: root.display().to_string(), mcp_token: String::new(), browser_origin: browser_origin.into(), + browser_auth_file: String::new(), }; let mut state = build_state(config, 4777).unwrap(); Arc::get_mut(&mut state.notebooks).unwrap().recent_path = @@ -718,6 +719,112 @@ async fn browser_origin_controls_host_origin_and_capability_checks() { } } +#[tokio::test] +async fn browser_sign_in_accepts_configured_methods_and_renews_after_restart() { + const ORIGIN: &str = "https://notebooks.example.net:8443"; + const HOST: &str = "notebooks.example.net:8443"; + let mut fixture = Fixture::with_browser_origin(ORIGIN); + let access_key = "1".repeat(64); + let config = fixture._temp.path().join("auth.json"); + fs::write( + &config, + json!({ + "accessKeySha256": format!("{:x}", Sha256::digest(&access_key)), + "trustedProxy": {"header": "X-Authenticated-User", "value": "owner@example.net"}, + }) + .to_string(), + ) + .unwrap(); + assert!( + browser_auth::BrowserAuth::load(config.to_str().unwrap(), "http://127.0.0.1:4777").is_err() + ); + fixture.state.browser_auth = + browser_auth::BrowserAuth::load(config.to_str().unwrap(), ORIGIN).unwrap(); + let app = router(fixture.state.clone()); + let request = |origin: &str, body: Value| { + Request::builder() + .method("POST") + .uri("/api/v1/session") + .header(header::HOST, HOST) + .header(header::ORIGIN, origin) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body.to_string())) + .unwrap() + }; + + let info = app + .clone() + .oneshot( + Request::builder() + .uri("/api/v1/session") + .header(header::HOST, HOST) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + json_body(info).await, + json!({"accessKey": true, "trustedProxy": true}) + ); + + for (origin, body) in [ + (ORIGIN, json!({})), + (ORIGIN, json!({"accessKey": "2".repeat(64)})), + ( + "https://foreign.example.net", + json!({"accessKey": access_key}), + ), + ] { + let response = app.clone().oneshot(request(origin, body)).await.unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert!(!response.headers().contains_key(header::SET_COOKIE)); + } + for identity in ["other@example.net", "owner@example.net"] { + let mut proxy = request(ORIGIN, json!({})); + proxy.headers_mut().insert( + "x-authenticated-user", + HeaderValue::from_str(identity).unwrap(), + ); + let response = app.clone().oneshot(proxy).await.unwrap(); + let expected = if identity == "owner@example.net" { + StatusCode::OK + } else { + StatusCode::UNAUTHORIZED + }; + assert_eq!(response.status(), expected); + } + + let response = app + .oneshot(request(ORIGIN, json!({"accessKey": access_key}))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let cookie = response.headers()[header::SET_COOKIE].to_str().unwrap(); + assert!(cookie.contains("Secure; HttpOnly; SameSite=Strict")); + let cookie = cookie.split(';').next().unwrap().to_owned(); + assert_eq!( + json_body(response).await, + json!({"launchCapability":"test-capability"}) + ); + + // A restart rotates the Quack token while keeping the configured access key. + fixture.state.token = "rotated-capability".into(); + let mut renewed = request(ORIGIN, json!({})); + renewed + .headers_mut() + .insert(header::COOKIE, HeaderValue::from_str(&cookie).unwrap()); + let response = router(fixture.state.clone()) + .oneshot(renewed) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + json_body(response).await, + json!({"launchCapability":"rotated-capability"}) + ); +} + #[tokio::test] async fn remote_assets_are_served_through_a_symlinked_cache() { let mut fixture = Fixture::new(); @@ -1483,6 +1590,7 @@ fn history_polling_captures_external_changes_and_stops_with_server() { duckdb_version: "test".into(), notebook_root: notebooks.display().to_string(), browser_origin: String::new(), + browser_auth_file: String::new(), }) .unwrap(); let store = NotebookStore::open(notebooks.canonicalize().unwrap()).unwrap(); diff --git a/src/sidequery_ui_extension.cpp b/src/sidequery_ui_extension.cpp index 9d0a2bf..5662ba8 100644 --- a/src/sidequery_ui_extension.cpp +++ b/src/sidequery_ui_extension.cpp @@ -506,7 +506,7 @@ class SqlnbServer { public: SqlnbServer(shared_ptr database_p, const string &remote_url, const string &local_dir, int requested_port, const string ¬ebook_root, bool mcp, - const string &browser_origin) + const string &browser_origin, const string &browser_auth_file) : database(database_p), quack(StartQuack(*database_p)) { if (local_dir.empty() && remote_url.empty()) { StopQuack(*database_p, quack.listen_uri); @@ -529,7 +529,8 @@ class SqlnbServer { ",\"duckdbVersion\":" + JSONEscape(DuckDB::LibraryVersion()) + ",\"notebookRoot\":" + JSONEscape(notebook_root) + ",\"mcpToken\":" + JSONEscape(mcp_token) + - ",\"browserOrigin\":" + JSONEscape(browser_origin) + "}"; + ",\"browserOrigin\":" + JSONEscape(browser_origin) + + ",\"browserAuthFile\":" + JSONEscape(browser_auth_file) + "}"; char *error = nullptr; http_server = sidequery_http_start_with_query(config.c_str(), mcp_connection.get(), McpConnection::Query, McpConnection::Interrupt, @@ -600,13 +601,13 @@ class SqlnbState : public StorageExtensionInfo { string Start(shared_ptr database, const string &remote_url, const string &local_dir, int port, bool open_browser, const string ¬ebook_root, bool mcp, - const string &browser_origin, connection_t caller) { + const string &browser_origin, const string &browser_auth_file, connection_t caller) { std::lock_guard guard(lock); if (server) { throw InvalidInputException("SQLNB is already running"); } auto candidate = make_uniq(std::move(database), remote_url, local_dir, port, - notebook_root, mcp, browser_origin); + notebook_root, mcp, browser_origin, browser_auth_file); auto launch_url = candidate->LaunchURL(); if (open_browser) { OpenBrowser(launch_url); @@ -727,6 +728,7 @@ static void StartFunction(DataChunk &args, ExpressionState &state, Vector &resul auto notebook_root = args.ColumnCount() > 4 ? args.data[4].GetValue(0).GetValue() : string(); auto mcp = args.ColumnCount() > 5 ? args.data[5].GetValue(0).GetValue() : false; auto browser_origin = args.ColumnCount() > 6 ? args.data[6].GetValue(0).GetValue() : string(); + auto browser_auth_file = args.ColumnCount() > 7 ? args.data[7].GetValue(0).GetValue() : string(); if (port < 0 || port > 65535) { throw InvalidInputException("port must be between 0 and 65535"); } @@ -735,7 +737,7 @@ static void StartFunction(DataChunk &args, ExpressionState &state, Vector &resul } auto &database = *state.GetContext().db; result.SetValue(0, Value(GetState(database).Start(state.GetContext().db, remote_url, local_dir, port, - open_browser, notebook_root, mcp, browser_origin, + open_browser, notebook_root, mcp, browser_origin, browser_auth_file, state.GetContext().GetConnectionId()))); if (mcp) { state.GetContext().registered_state->GetOrCreate( @@ -774,7 +776,8 @@ static void LoadInternal(ExtensionLoader &loader) { FunctionParameter("open_browser", LogicalType::BOOLEAN, Value::BOOLEAN(true)), FunctionParameter("notebook_root", LogicalType::VARCHAR, Value("")), FunctionParameter("mcp", LogicalType::BOOLEAN, Value::BOOLEAN(false)), - FunctionParameter("browser_origin", LogicalType::VARCHAR, Value(""))}, + FunctionParameter("browser_origin", LogicalType::VARCHAR, Value("")), + FunctionParameter("browser_auth_file", LogicalType::VARCHAR, Value(""))}, LogicalType::VARCHAR); ScalarFunction sqlnb_start("sqlnb_start", std::move(sqlnb_start_signature), StartFunction); sqlnb_start.SetVolatile(); From 9a165fe592d8a945a661f795d96cb8a768799d98 Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Sun, 22 Nov 2026 16:33:23 -0800 Subject: [PATCH 2/2] Document SQLNB sign-in behavior --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8725b5e..16f5def 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,10 @@ only its hash in the JSON. Access-key sign-in remembers the browser for seven days. With a trusted proxy, the ordinary URL opens the notebook for the specified identity. The proxy must authenticate the user and remove incoming copies of the identity header before setting its own. Keep untrusted clients -away from the loopback listener. Existing launch links work with either mode. +away from the loopback listener. SQLNB tries an existing sign-in automatically +and shows the access-key form if that method is configured and a browser still +needs to sign in. Deployments with neither method use launch links. A valid +launch link can still open SQLNB with any configuration. To connect an MCP client, start with `mcp := true` and follow the [MCP setup guide](docs/mcp.md). MCP is disabled by default.