From 3c444377e39e5d2759fe11c4fce722ea91540aec Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 15:10:27 +0100 Subject: [PATCH 01/21] Point MCP clients at the Writebook to sign in with writebook mcp --serve publishes the protected resource metadata (RFC 9728) at /.well-known/oauth-protected-resource, naming the Writebook it serves as the authorization server, and a request without a token gets a 401 whose WWW-Authenticate points there. MCP clients that sign in with OAuth, like hosted connectors, can find where to sign the person in. --- src/mcp.rs | 53 ++++++++++++++++++++++++++++++-- tests/mcp.rs | 85 ++++++++++++++++++++++++++++++++++++++++------------ 2 files changed, 116 insertions(+), 22 deletions(-) diff --git a/src/mcp.rs b/src/mcp.rs index 7365993..612b148 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -76,13 +76,14 @@ async fn serve_http(host: String, read_only: bool, address: &str) -> Result<()> .await .with_context(|| format!("could not listen on {address}"))?; let served = host.clone(); + let logged = host.clone(); let writebook = Writebook { origin: Origin::Served { host }, read_only, }; log::serving( - &served, + &logged, "http", Some(format!("http://{}/mcp", listener.local_addr()?)), read_only, @@ -96,9 +97,21 @@ async fn serve_http(host: String, read_only: bool, address: &str) -> Result<()> .with_json_response(true); let service: StreamableHttpService = StreamableHttpService::new(move || Ok(writebook.clone()), Default::default(), config); + let metadata = move |headers: axum::http::HeaderMap| { + let served = served.clone(); + async move { resource_metadata(&headers, &served) } + }; let router = axum::Router::new() .route_service("/mcp", service) - .layer(middleware::from_fn(require_token)) + .route_layer(middleware::from_fn(require_token)) + .route( + "/.well-known/oauth-protected-resource", + axum::routing::get(metadata.clone()), + ) + .route( + "/.well-known/oauth-protected-resource/mcp", + axum::routing::get(metadata), + ) .layer(middleware::from_fn(log_request)); axum::serve(listener, router) @@ -120,19 +133,53 @@ async fn log_request(request: Request, next: Next) -> Response { response } +// A request without a token is pointed at the resource metadata, which names +// the Writebook to sign in with (RFC 9728), so an MCP client can sign the +// person in there. async fn require_token(request: Request, next: Next) -> Response { if bearer(request.headers()).is_some() { next.run(request).await } else { + let challenge = format!( + r#"Bearer resource_metadata="{}/.well-known/oauth-protected-resource""#, + public_url(request.headers()) + ); + ( StatusCode::UNAUTHORIZED, - [(header::WWW_AUTHENTICATE, "Bearer")], + [(header::WWW_AUTHENTICATE, challenge)], "a Writebook token is required\n", ) .into_response() } } +fn resource_metadata(headers: &axum::http::HeaderMap, writebook: &str) -> Response { + let metadata = serde_json::json!({ + "resource": format!("{}/mcp", public_url(headers)), + "resource_name": "Writebook", + "authorization_servers": [writebook], + "scopes_supported": ["read", "write"], + "bearer_methods_supported": ["header"], + }); + + ([(header::CONTENT_TYPE, "application/json")], metadata.to_string()).into_response() +} + +// Behind a proxy that ends https, like ONCE's, X-Forwarded-Proto says so. +fn public_url(headers: &axum::http::HeaderMap) -> String { + let scheme = match headers.get("x-forwarded-proto").and_then(|it| it.to_str().ok()) { + Some("https") => "https", + _ => "http", + }; + let host = headers + .get(header::HOST) + .and_then(|it| it.to_str().ok()) + .unwrap_or("localhost"); + + format!("{scheme}://{host}") +} + fn bearer(headers: &axum::http::HeaderMap) -> Option { let value = headers.get(header::AUTHORIZATION)?.to_str().ok()?; let token = value diff --git a/tests/mcp.rs b/tests/mcp.rs index adc76df..bbc8186 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -182,25 +182,7 @@ fn needs_an_instance_on_stdio() { fn serves_each_http_caller_with_their_own_token() { let server = fake_writebook(); let config = tempdir(); - let mut child = Command::new(env!("CARGO_BIN_EXE_writebook")) - .args(["mcp", "--instance", &server.url, "--serve", "127.0.0.1:0"]) - .env_remove("WRITEBOOK_TOKEN") - .env("XDG_CONFIG_HOME", &config) - .env("WRITEBOOK_NO_KEYRING", "1") - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - let mut logs = BufReader::new(child.stderr.take().unwrap()); - let mut serving = String::new(); - logs.read_line(&mut serving).unwrap(); - let serving: Value = serde_json::from_str(&serving).unwrap(); - assert_eq!( - (&serving["event"], &serving["instance"], &serving["transport"]), - (&json!("serving"), &json!(server.url), &json!("http")) - ); - let endpoint = serving["address"].as_str().unwrap().to_string(); + let (mut child, mut logs, endpoint) = serve(&server, &config); let anonymous = post( &endpoint, @@ -425,6 +407,71 @@ fn initialize() -> Value { }) } +#[test] +fn points_mcp_clients_at_the_writebook_to_sign_in_with() { + let server = fake_writebook(); + let config = tempdir(); + let (mut child, _logs, endpoint) = serve(&server, &config); + let base = endpoint.trim_end_matches("/mcp"); + let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); + + let anonymous = agent.post(&endpoint).send_json(initialize()).unwrap(); + assert_eq!(anonymous.status().as_u16(), 401); + assert_eq!( + anonymous.headers().get("www-authenticate").unwrap().to_str().unwrap(), + format!(r#"Bearer resource_metadata="{base}/.well-known/oauth-protected-resource""#) + ); + + for path in [ + "/.well-known/oauth-protected-resource", + "/.well-known/oauth-protected-resource/mcp", + ] { + let mut response = agent.get(&format!("{base}{path}")).call().unwrap(); + assert_eq!(response.status().as_u16(), 200, "{path}"); + let metadata: Value = serde_json::from_str(&response.body_mut().read_to_string().unwrap()).unwrap(); + assert_eq!(metadata["resource"], json!(endpoint)); + assert_eq!(metadata["authorization_servers"], json!([server.url])); + } + + let mut behind_https = agent + .get(&format!("{base}/.well-known/oauth-protected-resource")) + .header("X-Forwarded-Proto", "https") + .call() + .unwrap(); + let metadata: Value = serde_json::from_str(&behind_https.body_mut().read_to_string().unwrap()).unwrap(); + assert_eq!(metadata["resource"], json!(endpoint.replace("http://", "https://"))); + + child.kill().unwrap(); + child.wait().unwrap(); +} + +fn serve( + server: &Server, + config: &std::path::Path, +) -> (std::process::Child, BufReader, String) { + let mut child = Command::new(env!("CARGO_BIN_EXE_writebook")) + .args(["mcp", "--instance", &server.url, "--serve", "127.0.0.1:0"]) + .env_remove("WRITEBOOK_TOKEN") + .env("XDG_CONFIG_HOME", config) + .env("WRITEBOOK_NO_KEYRING", "1") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut logs = BufReader::new(child.stderr.take().unwrap()); + let mut serving = String::new(); + logs.read_line(&mut serving).unwrap(); + let serving: Value = serde_json::from_str(&serving).unwrap(); + assert_eq!( + (&serving["event"], &serving["instance"], &serving["transport"]), + (&json!("serving"), &json!(server.url), &json!("http")) + ); + let endpoint = serving["address"].as_str().unwrap().to_string(); + + (child, logs, endpoint) +} + fn post(endpoint: &str, token: Option<&str>, body: &Value) -> (u16, String) { let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); let mut request = agent From af38cd643e76b776ead91522675da4b490823fb3 Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 15:13:52 +0100 Subject: [PATCH 02/21] Describe OAuth discovery in the README and skill, and drop narrating comments --- README.md | 3 +++ skills/writebook/SKILL.md | 8 +++++--- src/mcp.rs | 5 +---- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index cb4ddf9..ba9a3df 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,9 @@ Or run it with Docker: docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli mcp --instance https://books.example.com --serve 0.0.0.0:8080 ``` +Agents that sign in with OAuth are sent to your Writebook to sign in. Put the +server behind https, with the proxy sending `X-Forwarded-Proto: https`. + To browse your books in the terminal, and add, delete, move and publish pages, run: diff --git a/skills/writebook/SKILL.md b/skills/writebook/SKILL.md index 319a3d1..093f3ed 100644 --- a/skills/writebook/SKILL.md +++ b/skills/writebook/SKILL.md @@ -287,10 +287,12 @@ To give other people's agents access to one instance, run it as a server: writebook mcp --instance https://books.example.com --serve 0.0.0.0:8080 ``` -The server doesn't use the user's sign-in. Each request must send a Writebook -token as a Bearer header. The server sends the token only to that instance. The +The server doesn't use the user's sign-in. Each request to `/mcp` must send a +Writebook token as a Bearer header. The server sends the token only to that +instance. MCP clients that sign in with OAuth find that instance through +`/.well-known/oauth-protected-resource`, which answers without a token. The server uses plain HTTP, so put it behind https unless it listens only on this -computer. The Docker image `ghcr.io/basecamp/writebook-cli` runs the same +computer; a proxy that ends https should send `X-Forwarded-Proto: https`. The Docker image `ghcr.io/basecamp/writebook-cli` runs the same command. If you already use the CLI, you don't need the MCP server. diff --git a/src/mcp.rs b/src/mcp.rs index 612b148..4384778 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -133,13 +133,11 @@ async fn log_request(request: Request, next: Next) -> Response { response } -// A request without a token is pointed at the resource metadata, which names -// the Writebook to sign in with (RFC 9728), so an MCP client can sign the -// person in there. async fn require_token(request: Request, next: Next) -> Response { if bearer(request.headers()).is_some() { next.run(request).await } else { + // https://www.rfc-editor.org/rfc/rfc9728#section-5.1 let challenge = format!( r#"Bearer resource_metadata="{}/.well-known/oauth-protected-resource""#, public_url(request.headers()) @@ -166,7 +164,6 @@ fn resource_metadata(headers: &axum::http::HeaderMap, writebook: &str) -> Respon ([(header::CONTENT_TYPE, "application/json")], metadata.to_string()).into_response() } -// Behind a proxy that ends https, like ONCE's, X-Forwarded-Proto says so. fn public_url(headers: &axum::http::HeaderMap) -> String { let scheme = match headers.get("x-forwarded-proto").and_then(|it| it.to_str().ok()) { Some("https") => "https", From 2068908582379caa06a1f1cf439a9490bfda8bd8 Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 15:16:16 +0100 Subject: [PATCH 03/21] Follow RFC 9728's resource paths, refuse metadata without a Host, and say only /mcp needs a token --- src/mcp.rs | 64 ++++++++++++++++++++++++++++------------------------ tests/mcp.rs | 25 +++++++++++++++----- 2 files changed, 54 insertions(+), 35 deletions(-) diff --git a/src/mcp.rs b/src/mcp.rs index 4384778..f555cbf 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -2,9 +2,9 @@ //! //! On stdio it serves every instance in the inventory, with the person's own //! sign-ins, to an MCP client on the same machine. With --serve it serves one -//! instance over HTTP, and every request has to include a Writebook token. The -//! server sends that token only to that instance and uses no stored -//! login, so a request without a token can't use anyone else's. +//! instance over HTTP, and every request to /mcp has to include a Writebook +//! token. The server sends that token only to that instance and uses no +//! stored login, so a request without a token can't use anyone else's. mod log; mod tools; @@ -97,20 +97,21 @@ async fn serve_http(host: String, read_only: bool, address: &str) -> Result<()> .with_json_response(true); let service: StreamableHttpService = StreamableHttpService::new(move || Ok(writebook.clone()), Default::default(), config); - let metadata = move |headers: axum::http::HeaderMap| { - let served = served.clone(); - async move { resource_metadata(&headers, &served) } - }; + let root = served.clone(); let router = axum::Router::new() .route_service("/mcp", service) .route_layer(middleware::from_fn(require_token)) .route( "/.well-known/oauth-protected-resource", - axum::routing::get(metadata.clone()), + axum::routing::get( + move |headers: axum::http::HeaderMap| async move { resource_metadata(&headers, "", &root) }, + ), ) .route( "/.well-known/oauth-protected-resource/mcp", - axum::routing::get(metadata), + axum::routing::get(move |headers: axum::http::HeaderMap| async move { + resource_metadata(&headers, "/mcp", &served) + }), ) .layer(middleware::from_fn(log_request)); @@ -138,10 +139,10 @@ async fn require_token(request: Request, next: Next) -> Response { next.run(request).await } else { // https://www.rfc-editor.org/rfc/rfc9728#section-5.1 - let challenge = format!( - r#"Bearer resource_metadata="{}/.well-known/oauth-protected-resource""#, - public_url(request.headers()) - ); + let challenge = match public_url(request.headers()) { + Some(url) => format!(r#"Bearer resource_metadata="{url}/.well-known/oauth-protected-resource/mcp""#), + None => "Bearer".to_string(), + }; ( StatusCode::UNAUTHORIZED, @@ -152,29 +153,34 @@ async fn require_token(request: Request, next: Next) -> Response { } } -fn resource_metadata(headers: &axum::http::HeaderMap, writebook: &str) -> Response { - let metadata = serde_json::json!({ - "resource": format!("{}/mcp", public_url(headers)), - "resource_name": "Writebook", - "authorization_servers": [writebook], - "scopes_supported": ["read", "write"], - "bearer_methods_supported": ["header"], - }); - - ([(header::CONTENT_TYPE, "application/json")], metadata.to_string()).into_response() +// The resource is the path the metadata was asked for under, so the bare +// well-known path describes the server's root. +// https://www.rfc-editor.org/rfc/rfc9728#section-3.3 +fn resource_metadata(headers: &axum::http::HeaderMap, path: &str, writebook: &str) -> Response { + match public_url(headers) { + Some(url) => { + let metadata = serde_json::json!({ + "resource": format!("{url}{path}"), + "resource_name": "Writebook", + "authorization_servers": [writebook], + "scopes_supported": ["read", "write"], + "bearer_methods_supported": ["header"], + }); + + ([(header::CONTENT_TYPE, "application/json")], metadata.to_string()).into_response() + } + None => (StatusCode::BAD_REQUEST, "a Host header is required\n").into_response(), + } } -fn public_url(headers: &axum::http::HeaderMap) -> String { +fn public_url(headers: &axum::http::HeaderMap) -> Option { let scheme = match headers.get("x-forwarded-proto").and_then(|it| it.to_str().ok()) { Some("https") => "https", _ => "http", }; - let host = headers - .get(header::HOST) - .and_then(|it| it.to_str().ok()) - .unwrap_or("localhost"); + let host = headers.get(header::HOST)?.to_str().ok()?; - format!("{scheme}://{host}") + Some(format!("{scheme}://{host}")) } fn bearer(headers: &axum::http::HeaderMap) -> Option { diff --git a/tests/mcp.rs b/tests/mcp.rs index bbc8186..afd18d3 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -419,28 +419,41 @@ fn points_mcp_clients_at_the_writebook_to_sign_in_with() { assert_eq!(anonymous.status().as_u16(), 401); assert_eq!( anonymous.headers().get("www-authenticate").unwrap().to_str().unwrap(), - format!(r#"Bearer resource_metadata="{base}/.well-known/oauth-protected-resource""#) + format!(r#"Bearer resource_metadata="{base}/.well-known/oauth-protected-resource/mcp""#) ); - for path in [ - "/.well-known/oauth-protected-resource", - "/.well-known/oauth-protected-resource/mcp", + for (path, resource) in [ + ("/.well-known/oauth-protected-resource/mcp", endpoint.as_str()), + ("/.well-known/oauth-protected-resource", base), ] { let mut response = agent.get(&format!("{base}{path}")).call().unwrap(); assert_eq!(response.status().as_u16(), 200, "{path}"); let metadata: Value = serde_json::from_str(&response.body_mut().read_to_string().unwrap()).unwrap(); - assert_eq!(metadata["resource"], json!(endpoint)); + assert_eq!(metadata["resource"], json!(resource), "{path}"); assert_eq!(metadata["authorization_servers"], json!([server.url])); } let mut behind_https = agent - .get(&format!("{base}/.well-known/oauth-protected-resource")) + .get(&format!("{base}/.well-known/oauth-protected-resource/mcp")) .header("X-Forwarded-Proto", "https") .call() .unwrap(); let metadata: Value = serde_json::from_str(&behind_https.body_mut().read_to_string().unwrap()).unwrap(); assert_eq!(metadata["resource"], json!(endpoint.replace("http://", "https://"))); + let mut without_host = std::net::TcpStream::connect(base.trim_start_matches("http://")).unwrap(); + std::io::Write::write_all( + &mut without_host, + b"GET /.well-known/oauth-protected-resource/mcp HTTP/1.0\r\n\r\n", + ) + .unwrap(); + let mut answer = String::new(); + std::io::Read::read_to_string(&mut without_host, &mut answer).unwrap(); + assert!( + answer.starts_with("HTTP/1.0 400"), + "a request with no Host gets no made-up address: {answer}" + ); + child.kill().unwrap(); child.wait().unwrap(); } From dd5bcb5ff4df12420a8e68231e8189894e354386 Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 15:22:02 +0100 Subject: [PATCH 04/21] Check the scopes and bearer methods the resource metadata advertises --- tests/mcp.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/mcp.rs b/tests/mcp.rs index afd18d3..5399b55 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -431,6 +431,8 @@ fn points_mcp_clients_at_the_writebook_to_sign_in_with() { let metadata: Value = serde_json::from_str(&response.body_mut().read_to_string().unwrap()).unwrap(); assert_eq!(metadata["resource"], json!(resource), "{path}"); assert_eq!(metadata["authorization_servers"], json!([server.url])); + assert_eq!(metadata["scopes_supported"], json!(["read", "write"]), "{path}"); + assert_eq!(metadata["bearer_methods_supported"], json!(["header"]), "{path}"); } let mut behind_https = agent From fc9d5dae549cd262b2f4075871ccfea7086b2846 Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 15:26:31 +0100 Subject: [PATCH 05/21] Leave the skill out of the discovery change --- skills/writebook/SKILL.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/skills/writebook/SKILL.md b/skills/writebook/SKILL.md index 093f3ed..319a3d1 100644 --- a/skills/writebook/SKILL.md +++ b/skills/writebook/SKILL.md @@ -287,12 +287,10 @@ To give other people's agents access to one instance, run it as a server: writebook mcp --instance https://books.example.com --serve 0.0.0.0:8080 ``` -The server doesn't use the user's sign-in. Each request to `/mcp` must send a -Writebook token as a Bearer header. The server sends the token only to that -instance. MCP clients that sign in with OAuth find that instance through -`/.well-known/oauth-protected-resource`, which answers without a token. The +The server doesn't use the user's sign-in. Each request must send a Writebook +token as a Bearer header. The server sends the token only to that instance. The server uses plain HTTP, so put it behind https unless it listens only on this -computer; a proxy that ends https should send `X-Forwarded-Proto: https`. The Docker image `ghcr.io/basecamp/writebook-cli` runs the same +computer. The Docker image `ghcr.io/basecamp/writebook-cli` runs the same command. If you already use the CLI, you don't need the MCP server. From fe3193e6d1a1e07d0408b095c1a5f8b9e6bdb949 Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 15:45:36 +0100 Subject: [PATCH 06/21] Say to run the MCP server yourself, since tokens pass through it --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ba9a3df..cd7baad 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,8 @@ docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli mcp --instance https://bo ``` Agents that sign in with OAuth are sent to your Writebook to sign in. Put the -server behind https, with the proxy sending `X-Forwarded-Proto: https`. +server behind https, with the proxy sending `X-Forwarded-Proto: https`. Run it +yourself, next to your Writebook: every request's token passes through it. To browse your books in the terminal, and add, delete, move and publish pages, run: From a9eec63d38cce865f62b0a55596fd7aa180f321d Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 15:47:30 +0100 Subject: [PATCH 07/21] Keep the server's answer out of the no-Host test's message --- tests/mcp.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/mcp.rs b/tests/mcp.rs index 5399b55..1bb8097 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -453,7 +453,7 @@ fn points_mcp_clients_at_the_writebook_to_sign_in_with() { std::io::Read::read_to_string(&mut without_host, &mut answer).unwrap(); assert!( answer.starts_with("HTTP/1.0 400"), - "a request with no Host gets no made-up address: {answer}" + "a request with no Host gets no made-up address" ); child.kill().unwrap(); From cd672ee2c10fa165c95026651c179e07a9f27626 Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 16:20:09 +0100 Subject: [PATCH 08/21] Ask for the admin scope, and say to sign in again when a sign-in lacks it Writebook now has an admin scope for managing people and settings. The CLI's sign-in asks for read write admin, so an administrator's TUI keeps managing people; anyone else gets read write. A sign-in that lacks the scope gets an insufficient_scope 403, which the CLI now explains with a note to sign in again. --- src/api.rs | 29 ++++++++++++++++++++++++++++- src/creds.rs | 2 +- src/tui/flows/people.rs | 19 +++++++++++++++++++ tests/read_only.rs | 3 ++- 4 files changed, 50 insertions(+), 3 deletions(-) diff --git a/src/api.rs b/src/api.rs index 19fa6f5..c2a16d2 100644 --- a/src/api.rs +++ b/src/api.rs @@ -77,6 +77,21 @@ impl std::fmt::Display for ApiError { impl std::error::Error for ApiError {} +/// Writebook turned the request down because the sign-in's scope doesn't cover it. +#[derive(Debug)] +pub struct ScopeTooNarrow; + +impl std::fmt::Display for ScopeTooNarrow { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Writebook says this sign-in can't do that. To manage people and settings, sign in again as an administrator with `writebook instance add `" + ) + } +} + +impl std::error::Error for ScopeTooNarrow {} + /// The site turned the token away. #[derive(Debug)] pub struct TokenRejected { @@ -349,8 +364,20 @@ pub fn url_on(host: &str, path: &str) -> Result { fn response_json(path: &str, mut response: Response) -> Result { let status = response.status().as_u16(); - let text = response.body_mut().read_to_string(); + let scope_too_narrow = response + .headers() + .get("www-authenticate") + .and_then(|it| it.to_str().ok()) + .is_some_and(|it| it.contains("insufficient_scope")); + + if status == 403 && scope_too_narrow { + Err(ScopeTooNarrow.into()) + } else { + answer_json(path, status, response.body_mut().read_to_string()) + } +} +fn answer_json(path: &str, status: u16, text: Result) -> Result { if (200..300).contains(&status) { let text = text.with_context(|| format!("could not read the answer to {path}"))?; diff --git a/src/creds.rs b/src/creds.rs index 83bb8fd..338e200 100644 --- a/src/creds.rs +++ b/src/creds.rs @@ -484,7 +484,7 @@ fn access_from(body: &Value) -> Access { fn request_device_authorization(host: &str, access: Access) -> Result { let scope = match access { - Access::Full => "read write", + Access::Full => "read write admin", Access::ReadOnly => "read", }; diff --git a/src/tui/flows/people.rs b/src/tui/flows/people.rs index 81cd41d..e4a1462 100644 --- a/src/tui/flows/people.rs +++ b/src/tui/flows/people.rs @@ -10,6 +10,7 @@ struct Workplace { invite: &'static str, can_administer: bool, failing: bool, + scope_too_narrow: bool, profile_email: String, wrong_password: bool, } @@ -24,6 +25,7 @@ fn workplace(can_administer: bool) -> (Tui, Arc>) { invite: "abc", can_administer, failing: false, + scope_too_narrow: false, profile_email: "me@example.com".to_string(), wrong_password: false, })); @@ -36,6 +38,12 @@ fn workplace(can_administer: bool) -> (Tui, Arc>) { if write && state.failing && request.path != "/users/1/profile.json" { reply(403, r#"{"error":"Only administrators can do that"}"#) + } else if write && state.scope_too_narrow && request.path != "/users/1/profile.json" { + let mut refused = reply(403, ""); + refused + .headers + .push(("WWW-Authenticate", r#"Bearer error="insufficient_scope""#.to_string())); + refused } else { match (request.method.as_str(), request.path.as_str()) { ("GET", "/books.json") => json(json!([{ "id": 1, "title": "Handbook", "editable": true }])), @@ -315,6 +323,17 @@ fn a_server_error_on_a_change_shows_a_notice_and_keeps_the_list_as_it_was() { assert_eq!(state.invite, "abc"); } +#[test] +fn a_sign_in_without_the_admin_scope_says_to_sign_in_again() { + let (mut tui, state) = settings(true); + state.lock().unwrap().scope_too_narrow = true; + + tui.press(KeyCode::Down); + tui.press(KeyCode::Right); + let screen = tui.wait_for("this sign-in can't do that"); + assert!(row(&screen, "Kevin").ends_with("‹ member ›"), "{screen}"); +} + #[test] fn changes_only_the_name_without_asking_for_the_current_password() { let (mut tui, _) = settings(true); diff --git a/tests/read_only.rs b/tests/read_only.rs index c9cf212..6bfad7c 100644 --- a/tests/read_only.rs +++ b/tests/read_only.rs @@ -64,7 +64,8 @@ fn signs_in_with_full_access_unless_asked() { .find(|it| it.path == "/oauth/device_authorizations") .unwrap(); assert!( - authorization.body.contains("scope=read+write") || authorization.body.contains("scope=read%20write"), + authorization.body.contains("scope=read+write+admin") + || authorization.body.contains("scope=read%20write%20admin"), "{}", authorization.body ); From 464adfd856ba6e40bddcf25604f36800eae11c5d Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 16:26:17 +0100 Subject: [PATCH 09/21] Sign in to Writebooks from before the admin scope, and word a refusal by what the sign-in can do A Writebook without the admin scope refuses it as invalid_scope; the CLI then asks again for read write. An insufficient_scope 403 tells a read-only sign-in it's read-only, rather than to sign in as an administrator. --- src/api.rs | 52 +++++++++++++++++++++++++++++++++++----------- src/creds.rs | 26 ++++++++++++++++------- tests/read_only.rs | 29 ++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 20 deletions(-) diff --git a/src/api.rs b/src/api.rs index c2a16d2..8833fd7 100644 --- a/src/api.rs +++ b/src/api.rs @@ -79,14 +79,20 @@ impl std::error::Error for ApiError {} /// Writebook turned the request down because the sign-in's scope doesn't cover it. #[derive(Debug)] -pub struct ScopeTooNarrow; +pub struct ScopeTooNarrow { + read_only: bool, +} impl std::fmt::Display for ScopeTooNarrow { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "Writebook says this sign-in can't do that. To manage people and settings, sign in again as an administrator with `writebook instance add `" - ) + if self.read_only { + write!(f, "Writebook says this sign-in can't do that: it's read-only") + } else { + write!( + f, + "Writebook says this sign-in can't do that. To manage people and settings, sign in again as an administrator with `writebook instance add `" + ) + } } } @@ -220,7 +226,8 @@ impl Client { } fn request(&mut self, path: &str, request: Request) -> Result { - response_json(path, self.send_renewing(|client| client.send(path, &request))?) + let response = self.send_renewing(|client| client.send(path, &request))?; + response_json(path, response, self.read_only()) } fn multipart(&mut self, path: &str, method: MultipartMethod, parts: &[Part]) -> Result { @@ -228,10 +235,12 @@ impl Client { let body = multipart_body(&boundary, parts); let content_type = format!("multipart/form-data; boundary={boundary}"); - response_json( - path, - self.send_renewing(|client| client.send_multipart(path, method, &content_type, &body))?, - ) + let response = self.send_renewing(|client| client.send_multipart(path, method, &content_type, &body))?; + response_json(path, response, self.read_only()) + } + + fn read_only(&self) -> bool { + self.token.access == creds::Access::ReadOnly } fn send_renewing(&mut self, send: impl Fn(&Client) -> Result) -> Result { @@ -362,7 +371,7 @@ pub fn url_on(host: &str, path: &str) -> Result { } } -fn response_json(path: &str, mut response: Response) -> Result { +fn response_json(path: &str, mut response: Response, read_only: bool) -> Result { let status = response.status().as_u16(); let scope_too_narrow = response .headers() @@ -371,7 +380,7 @@ fn response_json(path: &str, mut response: Response) -> Result { .is_some_and(|it| it.contains("insufficient_scope")); if status == 403 && scope_too_narrow { - Err(ScopeTooNarrow.into()) + Err(ScopeTooNarrow { read_only }.into()) } else { answer_json(path, status, response.body_mut().read_to_string()) } @@ -437,3 +446,22 @@ fn multipart_boundary() -> String { .as_nanos(); format!("writebook-{nanos}-{}", std::process::id()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn says_what_a_sign_in_lacks() { + assert!( + ScopeTooNarrow { read_only: true } + .to_string() + .ends_with("it's read-only") + ); + assert!( + ScopeTooNarrow { read_only: false } + .to_string() + .contains("sign in again as an administrator") + ); + } +} diff --git a/src/creds.rs b/src/creds.rs index 338e200..b41d23e 100644 --- a/src/creds.rs +++ b/src/creds.rs @@ -483,21 +483,31 @@ fn access_from(body: &Value) -> Access { } fn request_device_authorization(host: &str, access: Access) -> Result { - let scope = match access { - Access::Full => "read write admin", - Access::ReadOnly => "read", + let (status, body) = match access { + Access::ReadOnly => post_device_authorization(host, "read")?, + // Writebooks from before the admin scope refuse it as an unknown scope. + Access::Full => match post_device_authorization(host, "read write admin")? { + (400, body) if body["error"] == "invalid_scope" => post_device_authorization(host, "read write")?, + answer => answer, + }, }; + if status == 200 { + Ok(body) + } else { + bail!("{host} does not support device sign-in — is it running a Writebook with the CLI API?") + } +} + +fn post_device_authorization(host: &str, scope: &str) -> Result<(u16, Value)> { let mut response = api::agent() .post(&format!("{host}/oauth/device_authorizations")) .send_form([("client_id", CLIENT_ID), ("scope", scope)]) .with_context(|| format!("could not reach {host}"))?; - if response.status() != 200 { - bail!("{host} does not support device sign-in — is it running a Writebook with the CLI API?"); - } - - Ok(response.body_mut().read_json()?) + let status = response.status().as_u16(); + let body = response.body_mut().read_json().unwrap_or(Value::Null); + Ok((status, body)) } fn post_token_request(host: &str, form: &[(&str, &str)]) -> Result<(u16, Value)> { diff --git a/tests/read_only.rs b/tests/read_only.rs index 6bfad7c..3d3d532 100644 --- a/tests/read_only.rs +++ b/tests/read_only.rs @@ -75,6 +75,35 @@ fn signs_in_with_full_access_unless_asked() { assert!(!stdout(&listed).contains("read-only"), "{}", stdout(&listed)); } +#[test] +fn signs_in_to_a_writebook_from_before_the_admin_scope_without_it() { + let server = Server::start(|request| match request.path.as_str() { + "/oauth/device_authorizations" if request.body.contains("admin") => reply(400, r#"{"error":"invalid_scope"}"#), + "/oauth/device_authorizations" => support::device_authorization(request), + "/oauth/tokens" => reply( + 200, + r#"{"access_token":"wb_at_1","token_type":"Bearer","expires_in":3600,"refresh_token":"wb_rt_1","scope":"read write"}"#, + ), + _ => reply(404, ""), + }); + let config = tempdir(); + let env = [("XDG_CONFIG_HOME", config.to_str().unwrap())]; + + let started = writebook(&["instance", "add", &server.url], &env); + assert!(started.status.success(), "{}", stderr(&started)); + let finished = writebook(&["instance", "add", &server.url, "--code", "WXYZ-2345"], &env); + assert!(finished.status.success(), "{}", stderr(&finished)); + + let asked: Vec = server + .requests() + .into_iter() + .filter(|it| it.path == "/oauth/device_authorizations") + .map(|it| it.body) + .collect(); + assert_eq!(asked.len(), 2, "{asked:?}"); + assert!(!asked[1].contains("admin"), "{asked:?}"); +} + #[test] fn turns_down_full_access_when_read_only_was_asked() { let server = fake_writebook(""); From 986ae17fa17a4a643364c6be4e40bd7455e26146 Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 16:44:48 +0100 Subject: [PATCH 10/21] Answer 401 for a token Writebook turns away, word refusals by the missing scope, and add --public-url A client renews its token when it gets a 401, so the server now checks each token with Writebook before handling the request, and remembers accepted ones for a minute. A refusal names what's missing: a read-only connection is told to reconnect and choose read and change books, and a sign-in without admin to tick Manage people and settings. --public-url names the server's address for proxies that don't pass the original Host. --- README.md | 6 +- src/api.rs | 77 ++++++++++++----- src/main.rs | 8 +- src/mcp.rs | 184 ++++++++++++++++++++++++++++++---------- src/tui/flows/people.rs | 9 +- tests/mcp.rs | 61 +++++++++---- 6 files changed, 259 insertions(+), 86 deletions(-) diff --git a/README.md b/README.md index cd7baad..5de1236 100644 --- a/README.md +++ b/README.md @@ -103,8 +103,10 @@ docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli mcp --instance https://bo ``` Agents that sign in with OAuth are sent to your Writebook to sign in. Put the -server behind https, with the proxy sending `X-Forwarded-Proto: https`. Run it -yourself, next to your Writebook: every request's token passes through it. +server behind https, with the proxy passing on the original `Host` and sending +`X-Forwarded-Proto: https`. If your proxy can't, pass the server's address with +`--public-url https://mcp.example.com`. Run it yourself, next to your +Writebook: every request's token passes through it. To browse your books in the terminal, and add, delete, move and publish pages, run: diff --git a/src/api.rs b/src/api.rs index 8833fd7..519077c 100644 --- a/src/api.rs +++ b/src/api.rs @@ -80,18 +80,38 @@ impl std::error::Error for ApiError {} /// Writebook turned the request down because the sign-in's scope doesn't cover it. #[derive(Debug)] pub struct ScopeTooNarrow { - read_only: bool, + pub missing: MissingScope, +} + +#[derive(Debug, PartialEq)] +pub enum MissingScope { + Write, + Admin, + Unnamed, +} + +impl MissingScope { + // Writebook names the scope a request needs (RFC 6750 §3); older ones + // don't, and only ever refuse a read-only sign-in's writes. + fn from_challenge(challenge: &str, read_only: bool) -> MissingScope { + match challenge.split("scope=\"").nth(1).and_then(|it| it.split('"').next()) { + Some(scope) if scope.split(' ').any(|it| it == "admin") => MissingScope::Admin, + Some(_) => MissingScope::Write, + None if read_only => MissingScope::Write, + None => MissingScope::Unnamed, + } + } } impl std::fmt::Display for ScopeTooNarrow { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - if self.read_only { - write!(f, "Writebook says this sign-in can't do that: it's read-only") - } else { - write!( + match self.missing { + MissingScope::Write => write!(f, "Writebook says this sign-in can only read, so it can't change books"), + MissingScope::Admin => write!( f, - "Writebook says this sign-in can't do that. To manage people and settings, sign in again as an administrator with `writebook instance add `" - ) + "Writebook says this sign-in can't manage people and settings. Sign in again with `writebook instance add ` and tick \"Manage people and settings\"" + ), + MissingScope::Unnamed => write!(f, "Writebook says this sign-in can't do that"), } } } @@ -373,14 +393,18 @@ pub fn url_on(host: &str, path: &str) -> Result { fn response_json(path: &str, mut response: Response, read_only: bool) -> Result { let status = response.status().as_u16(); - let scope_too_narrow = response + let challenge = response .headers() .get("www-authenticate") .and_then(|it| it.to_str().ok()) - .is_some_and(|it| it.contains("insufficient_scope")); + .filter(|it| it.contains("insufficient_scope")) + .map(str::to_string); - if status == 403 && scope_too_narrow { - Err(ScopeTooNarrow { read_only }.into()) + if let (403, Some(challenge)) = (status, challenge) { + Err(ScopeTooNarrow { + missing: MissingScope::from_challenge(&challenge, read_only), + } + .into()) } else { answer_json(path, status, response.body_mut().read_to_string()) } @@ -452,16 +476,31 @@ mod tests { use super::*; #[test] - fn says_what_a_sign_in_lacks() { - assert!( - ScopeTooNarrow { read_only: true } - .to_string() - .ends_with("it's read-only") + fn tells_which_scope_a_refusal_lacked() { + let challenge = |scope: &str| format!(r#"Bearer error="insufficient_scope", scope="{scope}""#); + + assert_eq!( + MissingScope::from_challenge(&challenge("read write admin"), false), + MissingScope::Admin + ); + assert_eq!( + MissingScope::from_challenge(&challenge("read write"), false), + MissingScope::Write + ); + assert_eq!( + MissingScope::from_challenge(r#"Bearer error="insufficient_scope""#, true), + MissingScope::Write + ); + assert_eq!( + MissingScope::from_challenge(r#"Bearer error="insufficient_scope""#, false), + MissingScope::Unnamed ); assert!( - ScopeTooNarrow { read_only: false } - .to_string() - .contains("sign in again as an administrator") + ScopeTooNarrow { + missing: MissingScope::Admin + } + .to_string() + .contains("tick \"Manage people and settings\"") ); } } diff --git a/src/main.rs b/src/main.rs index 0cc3174..c3dba24 100644 --- a/src/main.rs +++ b/src/main.rs @@ -168,6 +168,11 @@ enum Command { #[usage(help = "Serve over HTTP at this address, like 127.0.0.1:8080, instead of stdio")] #[usage(long)] serve: Option, + #[usage( + help = "With --serve, the address clients reach the server at, like https://mcp.example.com, when a proxy doesn't pass on the original Host" + )] + #[usage(long)] + public_url: Option, }, #[usage(help = "Browse your instances' books in the terminal, and arrange their pages")] Tui, @@ -448,7 +453,8 @@ fn run(cli: Cli) -> Result<()> { instance, read_only, serve, - } => mcp::run(instance.as_deref(), read_only, serve.as_deref()), + public_url, + } => mcp::run(instance.as_deref(), read_only, serve.as_deref(), public_url.as_deref()), Command::Tui => tui::run(), Command::Setup => setup::run(), Command::Skill { command } => match command { diff --git a/src/mcp.rs b/src/mcp.rs index f555cbf..d11f067 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -23,13 +23,16 @@ use rmcp::transport::streamable_http_server::{ StreamableHttpServerConfig, StreamableHttpService, session::never::NeverSessionManager, }; use rmcp::{ErrorData, RoleServer, ServerHandler, ServiceExt}; +use sha2::Digest; use std::time::Instant; use crate::inventory::{self, Inventory}; use crate::web::Web; use crate::{api, creds}; -pub fn run(instance: Option<&str>, read_only: bool, serve: Option<&str>) -> Result<()> { +const ACCEPTED_FOR: std::time::Duration = std::time::Duration::from_secs(60); + +pub fn run(instance: Option<&str>, read_only: bool, serve: Option<&str>, public_url: Option<&str>) -> Result<()> { let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build()?; log::start(); @@ -37,11 +40,13 @@ pub fn run(instance: Option<&str>, read_only: bool, serve: Option<&str>) -> Resu None if instance.is_some() => { bail!("--instance only goes with --serve: on stdio, every instance you added is served") } + None if public_url.is_some() => bail!("--public-url only goes with --serve"), None => runtime.block_on(serve_stdio(read_only)), Some(address) => { let host = inventory::host(instance)?; creds::ensure_private_connection(&host)?; - runtime.block_on(serve_http(host, read_only, address)) + let public_url = public_url.map(|it| it.trim_end_matches('/').to_string()); + runtime.block_on(serve_http(host, read_only, address, public_url)) } } } @@ -71,11 +76,15 @@ async fn serve_stdio(read_only: bool) -> Result<()> { Ok(()) } -async fn serve_http(host: String, read_only: bool, address: &str) -> Result<()> { +async fn serve_http(host: String, read_only: bool, address: &str, public_url: Option) -> Result<()> { let listener = tokio::net::TcpListener::bind(address) .await .with_context(|| format!("could not listen on {address}"))?; - let served = host.clone(); + let gate = Gate { + writebook: host.clone(), + public_url, + accepted: Default::default(), + }; let logged = host.clone(); let writebook = Writebook { origin: Origin::Served { host }, @@ -97,21 +106,22 @@ async fn serve_http(host: String, read_only: bool, address: &str) -> Result<()> .with_json_response(true); let service: StreamableHttpService = StreamableHttpService::new(move || Ok(writebook.clone()), Default::default(), config); - let root = served.clone(); + let root = gate.clone(); + let mcp = gate.clone(); let router = axum::Router::new() .route_service("/mcp", service) - .route_layer(middleware::from_fn(require_token)) + .route_layer(middleware::from_fn_with_state(gate, require_token)) .route( "/.well-known/oauth-protected-resource", axum::routing::get( - move |headers: axum::http::HeaderMap| async move { resource_metadata(&headers, "", &root) }, + move |headers: axum::http::HeaderMap| async move { root.resource_metadata(&headers, "") }, ), ) .route( "/.well-known/oauth-protected-resource/mcp", - axum::routing::get(move |headers: axum::http::HeaderMap| async move { - resource_metadata(&headers, "/mcp", &served) - }), + axum::routing::get( + move |headers: axum::http::HeaderMap| async move { mcp.resource_metadata(&headers, "/mcp") }, + ), ) .layer(middleware::from_fn(log_request)); @@ -134,53 +144,132 @@ async fn log_request(request: Request, next: Next) -> Response { response } -async fn require_token(request: Request, next: Next) -> Response { - if bearer(request.headers()).is_some() { - next.run(request).await - } else { - // https://www.rfc-editor.org/rfc/rfc9728#section-5.1 - let challenge = match public_url(request.headers()) { - Some(url) => format!(r#"Bearer resource_metadata="{url}/.well-known/oauth-protected-resource/mcp""#), - None => "Bearer".to_string(), +async fn require_token( + axum::extract::State(gate): axum::extract::State, + request: Request, + next: Next, +) -> Response { + match bearer(request.headers()) { + None => gate.challenge(request.headers(), None, "a Writebook token is required\n"), + Some(token) => { + if gate.rejects(token).await { + gate.challenge( + request.headers(), + Some("invalid_token"), + "Writebook did not accept this token\n", + ) + } else { + next.run(request).await + } + } + } +} + +#[derive(Clone)] +struct Gate { + writebook: String, + public_url: Option, + accepted: std::sync::Arc>>, +} + +impl Gate { + // A token Writebook turns away gets a 401 here, so the client renews it, + // rather than a tool error inside a 200. Tokens Writebook accepted are + // remembered by digest for a minute, so most requests aren't checked twice. + async fn rejects(&self, token: String) -> bool { + let digest: [u8; 32] = sha2::Sha256::digest(token.as_bytes()).into(); + + if self.recently_accepted(&digest) { + false + } else { + let writebook = self.writebook.clone(); + let answer = tokio::task::spawn_blocking(move || { + api::agent() + .get(&format!("{writebook}/books.json")) + .header("Authorization", &format!("Bearer {token}")) + .header("Accept", "application/json") + .call() + .map(|it| it.status().as_u16()) + }) + .await; + + match answer { + Ok(Ok(401)) => true, + Ok(Ok(status)) if (200..300).contains(&status) => { + self.remember(digest); + false + } + _ => false, + } + } + } + + fn recently_accepted(&self, digest: &[u8; 32]) -> bool { + match self.accepted.lock() { + Ok(accepted) => accepted.get(digest).is_some_and(|it| it.elapsed() < ACCEPTED_FOR), + Err(_) => false, + } + } + + fn remember(&self, digest: [u8; 32]) { + if let Ok(mut accepted) = self.accepted.lock() { + accepted.retain(|_, at| at.elapsed() < ACCEPTED_FOR); + accepted.insert(digest, Instant::now()); + } + } + + // https://www.rfc-editor.org/rfc/rfc9728#section-5.1 + fn challenge(&self, headers: &axum::http::HeaderMap, error: Option<&str>, message: &'static str) -> Response { + let error = error.map(|it| format!(r#"error="{it}", "#)).unwrap_or_default(); + let challenge = match self.public_url(headers) { + Some(url) => format!(r#"Bearer {error}resource_metadata="{url}/.well-known/oauth-protected-resource/mcp""#), + None => format!("Bearer {error}").trim_end_matches([',', ' ']).to_string(), }; ( StatusCode::UNAUTHORIZED, [(header::WWW_AUTHENTICATE, challenge)], - "a Writebook token is required\n", + message, ) .into_response() } -} -// The resource is the path the metadata was asked for under, so the bare -// well-known path describes the server's root. -// https://www.rfc-editor.org/rfc/rfc9728#section-3.3 -fn resource_metadata(headers: &axum::http::HeaderMap, path: &str, writebook: &str) -> Response { - match public_url(headers) { - Some(url) => { - let metadata = serde_json::json!({ - "resource": format!("{url}{path}"), - "resource_name": "Writebook", - "authorization_servers": [writebook], - "scopes_supported": ["read", "write"], - "bearer_methods_supported": ["header"], - }); - - ([(header::CONTENT_TYPE, "application/json")], metadata.to_string()).into_response() + // The resource is the path the metadata was asked for under, so the bare + // well-known path describes the server's root. + // https://www.rfc-editor.org/rfc/rfc9728#section-3.3 + fn resource_metadata(&self, headers: &axum::http::HeaderMap, path: &str) -> Response { + match self.public_url(headers) { + Some(url) => { + let metadata = serde_json::json!({ + "resource": format!("{url}{path}"), + "resource_name": "Writebook", + "authorization_servers": [self.writebook], + "scopes_supported": ["read", "write"], + "bearer_methods_supported": ["header"], + }); + + ([(header::CONTENT_TYPE, "application/json")], metadata.to_string()).into_response() + } + None => (StatusCode::BAD_REQUEST, "a Host header is required\n").into_response(), } - None => (StatusCode::BAD_REQUEST, "a Host header is required\n").into_response(), } -} - -fn public_url(headers: &axum::http::HeaderMap) -> Option { - let scheme = match headers.get("x-forwarded-proto").and_then(|it| it.to_str().ok()) { - Some("https") => "https", - _ => "http", - }; - let host = headers.get(header::HOST)?.to_str().ok()?; - Some(format!("{scheme}://{host}")) + // --public-url wins, for proxies like nginx that send their own name as Host. + fn public_url(&self, headers: &axum::http::HeaderMap) -> Option { + match &self.public_url { + Some(url) => Some(url.clone()), + None => { + let forwarded = headers.get("x-forwarded-proto").and_then(|it| it.to_str().ok()); + let scheme = match forwarded.and_then(|it| it.split(',').next()).map(str::trim) { + Some("https") => "https", + _ => "http", + }; + let host = headers.get(header::HOST)?.to_str().ok()?; + + Some(format!("{scheme}://{host}")) + } + } + } } fn bearer(headers: &axum::http::HeaderMap) -> Option { @@ -329,6 +418,11 @@ impl ServerHandler for Writebook { (Err(error), Origin::Served { host }) if error.downcast_ref::().is_some() => { failure(&format!("{host} did not accept your Writebook token")) } + (Err(error), Origin::Served { .. }) + if error.downcast_ref::().is_some_and(|it| it.missing == api::MissingScope::Write) => + { + failure("Writebook says this connection can only read. Reconnect the app and choose \"Read and change books\"") + } (Err(error), _) => failure(&format!("{error:#}")), } .into()) diff --git a/src/tui/flows/people.rs b/src/tui/flows/people.rs index e4a1462..e4cc71b 100644 --- a/src/tui/flows/people.rs +++ b/src/tui/flows/people.rs @@ -40,9 +40,10 @@ fn workplace(can_administer: bool) -> (Tui, Arc>) { reply(403, r#"{"error":"Only administrators can do that"}"#) } else if write && state.scope_too_narrow && request.path != "/users/1/profile.json" { let mut refused = reply(403, ""); - refused - .headers - .push(("WWW-Authenticate", r#"Bearer error="insufficient_scope""#.to_string())); + refused.headers.push(( + "WWW-Authenticate", + r#"Bearer error="insufficient_scope", scope="read write admin""#.to_string(), + )); refused } else { match (request.method.as_str(), request.path.as_str()) { @@ -330,7 +331,7 @@ fn a_sign_in_without_the_admin_scope_says_to_sign_in_again() { tui.press(KeyCode::Down); tui.press(KeyCode::Right); - let screen = tui.wait_for("this sign-in can't do that"); + let screen = tui.wait_for("can't manage people and settings"); assert!(row(&screen, "Kevin").ends_with("‹ member ›"), "{screen}"); } diff --git a/tests/mcp.rs b/tests/mcp.rs index 1bb8097..08dee67 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -182,7 +182,7 @@ fn needs_an_instance_on_stdio() { fn serves_each_http_caller_with_their_own_token() { let server = fake_writebook(); let config = tempdir(); - let (mut child, mut logs, endpoint) = serve(&server, &config); + let (mut child, mut logs, endpoint) = serve(&server, &config, &[]); let anonymous = post( &endpoint, @@ -216,12 +216,22 @@ fn serves_each_http_caller_with_their_own_token() { .unwrap(); assert_eq!(books.header("Authorization"), Some("Bearer wb_at_alice")); - let (_, revoked) = post( - &endpoint, - Some("wb_at_revoked"), - &json!({ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "list_books", "arguments": {} } }), + let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); + let revoked = agent + .post(&endpoint) + .header("Authorization", "Bearer wb_at_revoked") + .send_json(json!({ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "list_books", "arguments": {} } })) + .unwrap(); + assert_eq!( + revoked.status().as_u16(), + 401, + "a token Writebook turns away gets a 401, so the client renews it" + ); + let challenge = revoked.headers().get("www-authenticate").unwrap().to_str().unwrap(); + assert!( + challenge.starts_with(r#"Bearer error="invalid_token", resource_metadata=""#), + "{challenge}" ); - assert!(revoked.contains("did not accept your Writebook token"), "{revoked}"); child.kill().unwrap(); child.wait().unwrap(); @@ -240,13 +250,7 @@ fn serves_each_http_caller_with_their_own_token() { ) }) .collect(); - assert_eq!( - calls, - [ - ("list_books", "ok", None), - ("list_books", "error", Some("token_rejected")) - ] - ); + assert_eq!(calls, [("list_books", "ok", None)]); assert!( events .iter() @@ -411,7 +415,7 @@ fn initialize() -> Value { fn points_mcp_clients_at_the_writebook_to_sign_in_with() { let server = fake_writebook(); let config = tempdir(); - let (mut child, _logs, endpoint) = serve(&server, &config); + let (mut child, _logs, endpoint) = serve(&server, &config, &[]); let base = endpoint.trim_end_matches("/mcp"); let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); @@ -437,7 +441,7 @@ fn points_mcp_clients_at_the_writebook_to_sign_in_with() { let mut behind_https = agent .get(&format!("{base}/.well-known/oauth-protected-resource/mcp")) - .header("X-Forwarded-Proto", "https") + .header("X-Forwarded-Proto", "https, http") .call() .unwrap(); let metadata: Value = serde_json::from_str(&behind_https.body_mut().read_to_string().unwrap()).unwrap(); @@ -460,12 +464,39 @@ fn points_mcp_clients_at_the_writebook_to_sign_in_with() { child.wait().unwrap(); } +#[test] +fn names_the_public_url_a_proxy_hides() { + let server = fake_writebook(); + let config = tempdir(); + let (mut child, _logs, endpoint) = serve(&server, &config, &["--public-url", "https://mcp.example.com/"]); + let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); + + let anonymous = agent.post(&endpoint).send_json(initialize()).unwrap(); + assert_eq!( + anonymous.headers().get("www-authenticate").unwrap().to_str().unwrap(), + r#"Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp""# + ); + + let mut response = agent + .get(&endpoint.replace("/mcp", "/.well-known/oauth-protected-resource/mcp")) + .header("Host", "upstream") + .call() + .unwrap(); + let metadata: Value = serde_json::from_str(&response.body_mut().read_to_string().unwrap()).unwrap(); + assert_eq!(metadata["resource"], json!("https://mcp.example.com/mcp")); + + child.kill().unwrap(); + child.wait().unwrap(); +} + fn serve( server: &Server, config: &std::path::Path, + flags: &[&str], ) -> (std::process::Child, BufReader, String) { let mut child = Command::new(env!("CARGO_BIN_EXE_writebook")) .args(["mcp", "--instance", &server.url, "--serve", "127.0.0.1:0"]) + .args(flags) .env_remove("WRITEBOOK_TOKEN") .env("XDG_CONFIG_HOME", config) .env("WRITEBOOK_NO_KEYRING", "1") From ceb3fe08ec3abcb42211f4802a5c0175ff90dc6c Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 16:48:39 +0100 Subject: [PATCH 11/21] Answer health checks at /up, and show how to run the MCP server behind kamal-proxy, Caddy and Apache --- README.md | 29 +++++++++++++++++++++++++++++ src/mcp.rs | 1 + tests/mcp.rs | 7 +++++++ 3 files changed, 37 insertions(+) diff --git a/README.md b/README.md index 5de1236..225b937 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,35 @@ server behind https, with the proxy passing on the original `Host` and sending `--public-url https://mcp.example.com`. Run it yourself, next to your Writebook: every request's token passes through it. +Give the server a host of its own, like `mcp.example.com`, not a path on +another site: MCP clients look for its sign-in details at the root of the host. +`GET /up` answers 200 for health checks. + +With [kamal-proxy](https://github.com/basecamp/kamal-proxy), deploy it as is: +kamal-proxy passes on the `Host`, sends `X-Forwarded-Proto` and checks `/up`. + +With Caddy: + +``` +mcp.example.com { + reverse_proxy 127.0.0.1:8080 +} +``` + +With Apache, which doesn't pass on the `Host` or send `X-Forwarded-Proto` by +default: + +```apache + + ServerName mcp.example.com + # your TLS settings + ProxyPreserveHost On + RequestHeader set X-Forwarded-Proto "https" + ProxyPass / http://127.0.0.1:8080/ + ProxyPassReverse / http://127.0.0.1:8080/ + +``` + To browse your books in the terminal, and add, delete, move and publish pages, run: diff --git a/src/mcp.rs b/src/mcp.rs index d11f067..e236f64 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -111,6 +111,7 @@ async fn serve_http(host: String, read_only: bool, address: &str, public_url: Op let router = axum::Router::new() .route_service("/mcp", service) .route_layer(middleware::from_fn_with_state(gate, require_token)) + .route("/up", axum::routing::get(|| async { "ok\n" })) .route( "/.well-known/oauth-protected-resource", axum::routing::get( diff --git a/tests/mcp.rs b/tests/mcp.rs index 08dee67..4b0732e 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -447,6 +447,13 @@ fn points_mcp_clients_at_the_writebook_to_sign_in_with() { let metadata: Value = serde_json::from_str(&behind_https.body_mut().read_to_string().unwrap()).unwrap(); assert_eq!(metadata["resource"], json!(endpoint.replace("http://", "https://"))); + let up = agent.get(&format!("{base}/up")).call().unwrap(); + assert_eq!( + up.status().as_u16(), + 200, + "proxies like kamal-proxy check /up before sending traffic" + ); + let mut without_host = std::net::TcpStream::connect(base.trim_start_matches("http://")).unwrap(); std::io::Write::write_all( &mut without_host, From 46f3642e4543f6bd9a6f0b73789946f38eb3f14e Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 16:49:31 +0100 Subject: [PATCH 12/21] Move the proxy setup out of the README into doc/mcp-server.md --- README.md | 30 ++-------------------------- doc/mcp-server.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 28 deletions(-) create mode 100644 doc/mcp-server.md diff --git a/README.md b/README.md index 225b937..5d5d71a 100644 --- a/README.md +++ b/README.md @@ -108,34 +108,8 @@ server behind https, with the proxy passing on the original `Host` and sending `--public-url https://mcp.example.com`. Run it yourself, next to your Writebook: every request's token passes through it. -Give the server a host of its own, like `mcp.example.com`, not a path on -another site: MCP clients look for its sign-in details at the root of the host. -`GET /up` answers 200 for health checks. - -With [kamal-proxy](https://github.com/basecamp/kamal-proxy), deploy it as is: -kamal-proxy passes on the `Host`, sends `X-Forwarded-Proto` and checks `/up`. - -With Caddy: - -``` -mcp.example.com { - reverse_proxy 127.0.0.1:8080 -} -``` - -With Apache, which doesn't pass on the `Host` or send `X-Forwarded-Proto` by -default: - -```apache - - ServerName mcp.example.com - # your TLS settings - ProxyPreserveHost On - RequestHeader set X-Forwarded-Proto "https" - ProxyPass / http://127.0.0.1:8080/ - ProxyPassReverse / http://127.0.0.1:8080/ - -``` +[doc/mcp-server.md](doc/mcp-server.md) shows how to set it up behind +kamal-proxy, Caddy and Apache. To browse your books in the terminal, and add, delete, move and publish pages, run: diff --git a/doc/mcp-server.md b/doc/mcp-server.md new file mode 100644 index 0000000..a340515 --- /dev/null +++ b/doc/mcp-server.md @@ -0,0 +1,51 @@ +# Running the MCP server behind a proxy + +`writebook mcp --serve` speaks plain HTTP, so put it behind a proxy that ends +TLS. MCP clients sign in with OAuth: the server points them at your Writebook, +and builds the addresses it gives them from the request. So the proxy must: + +- pass on the original `Host` header, +- send `X-Forwarded-Proto: https`, +- pass on the `Authorization` header. + +If the proxy can't pass on the `Host`, give the server its address with +`--public-url https://mcp.example.com`. + +Give the server a host of its own, like `mcp.example.com`, not a path on +another site. MCP clients look for its sign-in details at +`/.well-known/oauth-protected-resource` at the root of the host. + +`GET /up` answers 200 without a token, for health checks. + +## kamal-proxy + +Deploy it as it is. kamal-proxy passes on the `Host`, sends +`X-Forwarded-Proto`, and waits for `/up` to answer before it sends traffic. +Don't deploy it under `--path-prefix`. + +## Caddy + +``` +mcp.example.com { + reverse_proxy 127.0.0.1:8080 +} +``` + +Caddy passes on the `Host` and sends `X-Forwarded-Proto` by default. + +## Apache + +Apache doesn't pass on the `Host` or send `X-Forwarded-Proto` by default. It +needs `mod_proxy`, `mod_proxy_http` and `mod_headers`: + +```apache + + ServerName mcp.example.com + # your TLS settings + + ProxyPreserveHost On + RequestHeader set X-Forwarded-Proto "https" + ProxyPass / http://127.0.0.1:8080/ + ProxyPassReverse / http://127.0.0.1:8080/ + +``` From 924862f7183680292a46e9f6ad20e5c116f03273 Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 16:54:07 +0100 Subject: [PATCH 13/21] Serve MCP on port 80 by default in the image, with settings from environment variables, so it runs under ONCE ONCE can only pass environment variables to a container. WRITEBOOK_MCP_INSTANCE, WRITEBOOK_MCP_READ_ONLY and WRITEBOOK_MCP_PUBLIC_URL set the mcp options, and the image runs mcp --serve 0.0.0.0:80 unless given another command. --- Dockerfile | 4 ++-- doc/mcp-server.md | 14 ++++++++++++++ src/main.rs | 6 +++--- tests/mcp.rs | 3 ++- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/Dockerfile b/Dockerfile index af8a348..f157805 100644 --- a/Dockerfile +++ b/Dockerfile @@ -39,6 +39,6 @@ COPY --from=build /usr/local/bin/writebook /usr/local/bin/writebook USER writebook ENV WRITEBOOK_NO_KEYRING=1 -EXPOSE 8080 +EXPOSE 80 ENTRYPOINT ["writebook"] -CMD ["--help"] +CMD ["mcp", "--serve", "0.0.0.0:80"] diff --git a/doc/mcp-server.md b/doc/mcp-server.md index a340515..04a5f4f 100644 --- a/doc/mcp-server.md +++ b/doc/mcp-server.md @@ -33,6 +33,20 @@ mcp.example.com { Caddy passes on the `Host` and sends `X-Forwarded-Proto` by default. +## ONCE + +ONCE can't pass arguments to a container, so the image serves MCP on port 80 +by default and reads its settings from environment variables: + +```sh +once deploy ghcr.io/basecamp/writebook-cli --host mcp.example.com \ + --env WRITEBOOK_MCP_INSTANCE=https://books.example.com +``` + +`WRITEBOOK_MCP_READ_ONLY=true` serves only the tools that read, and +`WRITEBOOK_MCP_PUBLIC_URL` sets `--public-url`. ONCE puts the server behind +kamal-proxy, which handles TLS and the headers. + ## Apache Apache doesn't pass on the `Host` or send `X-Forwarded-Proto` by default. It diff --git a/src/main.rs b/src/main.rs index c3dba24..ed3fabd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -160,10 +160,10 @@ enum Command { #[usage(help_heading = "Agent commands")] Mcp { #[usage(help = "With --serve, the instance alias or URL to serve (defaults to the default instance)")] - #[usage(long)] + #[usage(long, env = "WRITEBOOK_MCP_INSTANCE")] instance: Option, #[usage(help = "Serve only the tools that read")] - #[usage(long)] + #[usage(long, env = "WRITEBOOK_MCP_READ_ONLY")] read_only: bool, #[usage(help = "Serve over HTTP at this address, like 127.0.0.1:8080, instead of stdio")] #[usage(long)] @@ -171,7 +171,7 @@ enum Command { #[usage( help = "With --serve, the address clients reach the server at, like https://mcp.example.com, when a proxy doesn't pass on the original Host" )] - #[usage(long)] + #[usage(long, env = "WRITEBOOK_MCP_PUBLIC_URL")] public_url: Option, }, #[usage(help = "Browse your instances' books in the terminal, and arrange their pages")] diff --git a/tests/mcp.rs b/tests/mcp.rs index 4b0732e..1ef186e 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -502,8 +502,9 @@ fn serve( flags: &[&str], ) -> (std::process::Child, BufReader, String) { let mut child = Command::new(env!("CARGO_BIN_EXE_writebook")) - .args(["mcp", "--instance", &server.url, "--serve", "127.0.0.1:0"]) + .args(["mcp", "--serve", "127.0.0.1:0"]) .args(flags) + .env("WRITEBOOK_MCP_INSTANCE", &server.url) .env_remove("WRITEBOOK_TOKEN") .env("XDG_CONFIG_HOME", config) .env("WRITEBOOK_NO_KEYRING", "1") From 5ba8e365bdcd90927337086e7dcbb308914fd54d Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 17:00:22 +0100 Subject: [PATCH 14/21] Fix the review's findings: test scope refusals, the token check and the MCP environment variables through the CLI, check --public-url, drop narrating comments --- README.md | 5 +- src/api.rs | 53 +++---------------- src/mcp.rs | 24 +++++++-- tests/mcp.rs | 143 +++++++++++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 169 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 5d5d71a..ac84808 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,9 @@ Sign in to your Writebook. The CLI prints a link to approve in the browser: writebook instance add https://books.example.com ``` +To manage people and settings from `writebook tui`, an administrator ticks +"Manage people and settings" when approving. + Add `--read-only` if this device only needs to read books. To sign in without approving anything, use an API token from your Writebook profile instead. It can only read: @@ -109,7 +112,7 @@ server behind https, with the proxy passing on the original `Host` and sending Writebook: every request's token passes through it. [doc/mcp-server.md](doc/mcp-server.md) shows how to set it up behind -kamal-proxy, Caddy and Apache. +kamal-proxy, Caddy and Apache, and with ONCE. To browse your books in the terminal, and add, delete, move and publish pages, run: diff --git a/src/api.rs b/src/api.rs index 519077c..0c7bf92 100644 --- a/src/api.rs +++ b/src/api.rs @@ -77,7 +77,6 @@ impl std::fmt::Display for ApiError { impl std::error::Error for ApiError {} -/// Writebook turned the request down because the sign-in's scope doesn't cover it. #[derive(Debug)] pub struct ScopeTooNarrow { pub missing: MissingScope, @@ -91,13 +90,11 @@ pub enum MissingScope { } impl MissingScope { - // Writebook names the scope a request needs (RFC 6750 §3); older ones - // don't, and only ever refuse a read-only sign-in's writes. - fn from_challenge(challenge: &str, read_only: bool) -> MissingScope { + // https://www.rfc-editor.org/rfc/rfc6750#section-3 + fn from_challenge(challenge: &str) -> MissingScope { match challenge.split("scope=\"").nth(1).and_then(|it| it.split('"').next()) { Some(scope) if scope.split(' ').any(|it| it == "admin") => MissingScope::Admin, Some(_) => MissingScope::Write, - None if read_only => MissingScope::Write, None => MissingScope::Unnamed, } } @@ -247,7 +244,7 @@ impl Client { fn request(&mut self, path: &str, request: Request) -> Result { let response = self.send_renewing(|client| client.send(path, &request))?; - response_json(path, response, self.read_only()) + response_json(path, response) } fn multipart(&mut self, path: &str, method: MultipartMethod, parts: &[Part]) -> Result { @@ -256,11 +253,7 @@ impl Client { let content_type = format!("multipart/form-data; boundary={boundary}"); let response = self.send_renewing(|client| client.send_multipart(path, method, &content_type, &body))?; - response_json(path, response, self.read_only()) - } - - fn read_only(&self) -> bool { - self.token.access == creds::Access::ReadOnly + response_json(path, response) } fn send_renewing(&mut self, send: impl Fn(&Client) -> Result) -> Result { @@ -391,7 +384,7 @@ pub fn url_on(host: &str, path: &str) -> Result { } } -fn response_json(path: &str, mut response: Response, read_only: bool) -> Result { +fn response_json(path: &str, mut response: Response) -> Result { let status = response.status().as_u16(); let challenge = response .headers() @@ -402,7 +395,7 @@ fn response_json(path: &str, mut response: Response, read_only: bool) -> Result< if let (403, Some(challenge)) = (status, challenge) { Err(ScopeTooNarrow { - missing: MissingScope::from_challenge(&challenge, read_only), + missing: MissingScope::from_challenge(&challenge), } .into()) } else { @@ -470,37 +463,3 @@ fn multipart_boundary() -> String { .as_nanos(); format!("writebook-{nanos}-{}", std::process::id()) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn tells_which_scope_a_refusal_lacked() { - let challenge = |scope: &str| format!(r#"Bearer error="insufficient_scope", scope="{scope}""#); - - assert_eq!( - MissingScope::from_challenge(&challenge("read write admin"), false), - MissingScope::Admin - ); - assert_eq!( - MissingScope::from_challenge(&challenge("read write"), false), - MissingScope::Write - ); - assert_eq!( - MissingScope::from_challenge(r#"Bearer error="insufficient_scope""#, true), - MissingScope::Write - ); - assert_eq!( - MissingScope::from_challenge(r#"Bearer error="insufficient_scope""#, false), - MissingScope::Unnamed - ); - assert!( - ScopeTooNarrow { - missing: MissingScope::Admin - } - .to_string() - .contains("tick \"Manage people and settings\"") - ); - } -} diff --git a/src/mcp.rs b/src/mcp.rs index e236f64..08356c5 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -45,12 +45,30 @@ pub fn run(instance: Option<&str>, read_only: bool, serve: Option<&str>, public_ Some(address) => { let host = inventory::host(instance)?; creds::ensure_private_connection(&host)?; - let public_url = public_url.map(|it| it.trim_end_matches('/').to_string()); + let public_url = public_url.map(origin).transpose()?; runtime.block_on(serve_http(host, read_only, address, public_url)) } } } +fn origin(url: &str) -> Result { + let parsed = url::Url::parse(url).ok().filter(|it| { + matches!(it.scheme(), "http" | "https") + && it.host().is_some() + && it.path() == "/" + && it.query().is_none() + && it.fragment().is_none() + && it.username().is_empty() + }); + + match parsed { + Some(parsed) => Ok(parsed.origin().ascii_serialization()), + None => bail!( + "--public-url takes the address clients reach the server at, with no path, like https://mcp.example.com" + ), + } +} + async fn serve_stdio(read_only: bool) -> Result<()> { let writebook = tokio::task::spawn_blocking(move || -> Result { let inventory = Inventory::load()?; @@ -174,9 +192,6 @@ struct Gate { } impl Gate { - // A token Writebook turns away gets a 401 here, so the client renews it, - // rather than a tool error inside a 200. Tokens Writebook accepted are - // remembered by digest for a minute, so most requests aren't checked twice. async fn rejects(&self, token: String) -> bool { let digest: [u8; 32] = sha2::Sha256::digest(token.as_bytes()).into(); @@ -255,7 +270,6 @@ impl Gate { } } - // --public-url wins, for proxies like nginx that send their own name as Host. fn public_url(&self, headers: &axum::http::HeaderMap) -> Option { match &self.public_url { Some(url) => Some(url.clone()), diff --git a/tests/mcp.rs b/tests/mcp.rs index 1ef186e..6298a9e 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -166,6 +166,58 @@ fn a_change_writebook_answers_without_an_id_is_an_error() { assert!(failed.contains("had no id for the page"), "{failed}"); } +#[test] +fn says_what_a_refused_change_lacks() { + let server = fake_writebook(); + let change = json!({ "book_id": 4, "page_id": 12, "fingerprint": "g", "markdown": "Call" }); + + let mut reader = Mcp::start(&server, Some("wb_at_reader")); + let refused = reader.call_failing("update_page", change.clone()); + assert!(refused.contains("can only read, so it can't change books"), "{refused}"); + + let mut unnamed = Mcp::start(&server, Some("wb_at_unnamed")); + let refused = unnamed.call_failing("update_page", change); + assert!( + refused.ends_with("Writebook says this sign-in can't do that"), + "{refused}" + ); +} + +#[test] +fn takes_a_public_url_only_with_serve_and_only_as_an_origin() { + let without_serve = support::writebook(&["mcp", "--public-url", "https://mcp.example.com"], &[]); + assert!(!without_serve.status.success()); + assert!( + support::stderr(&without_serve).contains("--public-url only goes with --serve"), + "{}", + support::stderr(&without_serve) + ); + + for url in [ + "mcp.example.com", + "https://mcp.example.com/mcp", + "ftp://mcp.example.com", + ] { + let output = support::writebook( + &[ + "mcp", + "--instance", + "https://books.example.com", + "--serve", + "127.0.0.1:0", + "--public-url", + url, + ], + &[], + ); + assert!(!output.status.success(), "{url}"); + assert!( + support::stderr(&output).contains("with no path, like https://mcp.example.com"), + "{url}" + ); + } +} + #[test] fn needs_an_instance_on_stdio() { let output = support::writebook(&["mcp"], &[]); @@ -182,7 +234,7 @@ fn needs_an_instance_on_stdio() { fn serves_each_http_caller_with_their_own_token() { let server = fake_writebook(); let config = tempdir(); - let (mut child, mut logs, endpoint) = serve(&server, &config, &[]); + let (mut child, mut logs, endpoint) = serve(&server, &config, &[], &[]); let anonymous = post( &endpoint, @@ -266,6 +318,21 @@ fn serves_each_http_caller_with_their_own_token() { fn fake_writebook() -> Server { Server::start(|request| match (request.method.as_str(), request.path.as_str()) { _ if request.header("Authorization") == Some("Bearer wb_at_revoked") => reply(401, ""), + ("PATCH", _) if request.header("Authorization") == Some("Bearer wb_at_reader") => { + let mut refused = reply(403, ""); + refused.headers.push(( + "WWW-Authenticate", + r#"Bearer error="insufficient_scope", scope="read write""#.to_string(), + )); + refused + } + ("PATCH", _) if request.header("Authorization") == Some("Bearer wb_at_unnamed") => { + let mut refused = reply(403, ""); + refused + .headers + .push(("WWW-Authenticate", r#"Bearer error="insufficient_scope""#.to_string())); + refused + } ("GET", path) if path.starts_with("/search.json?q=page") => { let hits: Vec = (1..=60).map(|n| json!({ "title": format!("Page {n}"), "url": "http://books.test/4/handbook/12/page", "book": { "title": "Handbook" } })).collect(); @@ -415,7 +482,7 @@ fn initialize() -> Value { fn points_mcp_clients_at_the_writebook_to_sign_in_with() { let server = fake_writebook(); let config = tempdir(); - let (mut child, _logs, endpoint) = serve(&server, &config, &[]); + let (mut child, _logs, endpoint) = serve(&server, &config, &[], &[]); let base = endpoint.trim_end_matches("/mcp"); let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); @@ -471,11 +538,79 @@ fn points_mcp_clients_at_the_writebook_to_sign_in_with() { child.wait().unwrap(); } +#[test] +fn checks_a_token_with_writebook_once_a_minute() { + let server = fake_writebook(); + let config = tempdir(); + let (mut child, _logs, endpoint) = serve(&server, &config, &[], &[]); + + for id in 1..=3 { + post( + &endpoint, + Some("wb_at_bob"), + &json!({ "jsonrpc": "2.0", "id": id, "method": "tools/list" }), + ); + } + + let checks = server + .requests() + .into_iter() + .filter(|it| it.path == "/books.json" && it.header("Authorization") == Some("Bearer wb_at_bob")) + .count(); + assert_eq!(checks, 1); + + child.kill().unwrap(); + child.wait().unwrap(); +} + +#[test] +fn tells_a_read_only_connection_to_reconnect_to_change_books() { + let server = fake_writebook(); + let config = tempdir(); + let (mut child, _logs, endpoint) = serve(&server, &config, &[], &[]); + + let (_, answer) = post( + &endpoint, + Some("wb_at_reader"), + &json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "update_page", "arguments": { "book_id": 4, "page_id": 12, "fingerprint": "g", "markdown": "Call" } } }), + ); + assert!( + answer.contains(r#"Reconnect the app and choose \"Read and change books\""#), + "{answer}" + ); + + child.kill().unwrap(); + child.wait().unwrap(); +} + +#[test] +fn serves_only_the_tools_that_read_when_the_environment_says_so() { + let server = fake_writebook(); + let config = tempdir(); + let (mut child, _logs, endpoint) = serve(&server, &config, &[], &[("WRITEBOOK_MCP_READ_ONLY", "true")]); + + let (_, tools) = post( + &endpoint, + Some("wb_at_alice"), + &json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }), + ); + assert!(tools.contains(r#""name":"read_page""#), "{tools}"); + assert!(!tools.contains(r#""name":"update_page""#), "{tools}"); + + child.kill().unwrap(); + child.wait().unwrap(); +} + #[test] fn names_the_public_url_a_proxy_hides() { let server = fake_writebook(); let config = tempdir(); - let (mut child, _logs, endpoint) = serve(&server, &config, &["--public-url", "https://mcp.example.com/"]); + let (mut child, _logs, endpoint) = serve( + &server, + &config, + &[], + &[("WRITEBOOK_MCP_PUBLIC_URL", "https://mcp.example.com/")], + ); let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); let anonymous = agent.post(&endpoint).send_json(initialize()).unwrap(); @@ -500,10 +635,12 @@ fn serve( server: &Server, config: &std::path::Path, flags: &[&str], + envs: &[(&str, &str)], ) -> (std::process::Child, BufReader, String) { let mut child = Command::new(env!("CARGO_BIN_EXE_writebook")) .args(["mcp", "--serve", "127.0.0.1:0"]) .args(flags) + .envs(envs.iter().copied()) .env("WRITEBOOK_MCP_INSTANCE", &server.url) .env_remove("WRITEBOOK_TOKEN") .env("XDG_CONFIG_HOME", config) From 24437be9ee6997809bed63f6ff2c6451d2e8f75a Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 17:07:56 +0100 Subject: [PATCH 15/21] Move HTTP serving to mcp serve --bind, and fix the second review's findings writebook mcp serves stdio as before; writebook mcp serve serves one instance over HTTP, listening on 127.0.0.1:8080 unless --bind says otherwise. Its options belong to it, so the "only goes with --serve" checks are gone. The token check answers 502 when it can't reach Writebook, instead of letting the request through. Host is parsed before it goes into an address. Scope refusals name the profile's sign-in command and what to approve. The device sign-in reports an unreadable answer instead of a missing code. Tests no longer pick up WRITEBOOK_MCP_* from the environment, and cover the challenges sent without a Host. The skill says what the image runs and when to tick the admin box. --- Dockerfile | 4 +- README.md | 4 +- doc/mcp-server.md | 2 +- skills/writebook/SKILL.md | 10 ++-- src/api.rs | 25 +++++++--- src/creds.rs | 12 ++++- src/main.rs | 53 +++++++++++++------- src/mcp.rs | 100 ++++++++++++++++++++------------------ tests/mcp.rs | 61 +++++++++++++++++------ tests/support/mod.rs | 4 ++ 10 files changed, 176 insertions(+), 99 deletions(-) diff --git a/Dockerfile b/Dockerfile index f157805..c428ee8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ # The writebook CLI, mainly for serving a Writebook to MCP clients: # # docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli \ -# mcp --instance https://books.example.com --serve 0.0.0.0:8080 +# mcp serve --instance https://books.example.com --bind 0.0.0.0:8080 ARG RUST_VERSION=1.99 FROM docker.io/library/rust:${RUST_VERSION}-slim-trixie AS build @@ -41,4 +41,4 @@ USER writebook ENV WRITEBOOK_NO_KEYRING=1 EXPOSE 80 ENTRYPOINT ["writebook"] -CMD ["mcp", "--serve", "0.0.0.0:80"] +CMD ["mcp", "serve", "--bind", "0.0.0.0:80"] diff --git a/README.md b/README.md index ac84808..abb85e4 100644 --- a/README.md +++ b/README.md @@ -96,13 +96,13 @@ It can also be used as a server to give anyone's agent access to a Writebook instance using their own logins: ```sh -writebook mcp --instance https://books.example.com --serve 127.0.0.1:8080 +writebook mcp serve --instance https://books.example.com ``` Or run it with Docker: ```sh -docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli mcp --instance https://books.example.com --serve 0.0.0.0:8080 +docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli mcp serve --instance https://books.example.com --bind 0.0.0.0:8080 ``` Agents that sign in with OAuth are sent to your Writebook to sign in. Put the diff --git a/doc/mcp-server.md b/doc/mcp-server.md index 04a5f4f..a459eee 100644 --- a/doc/mcp-server.md +++ b/doc/mcp-server.md @@ -1,6 +1,6 @@ # Running the MCP server behind a proxy -`writebook mcp --serve` speaks plain HTTP, so put it behind a proxy that ends +`writebook mcp serve` speaks plain HTTP, so put it behind a proxy that ends TLS. MCP clients sign in with OAuth: the server points them at your Writebook, and builds the addresses it gives them from the request. So the proxy must: diff --git a/skills/writebook/SKILL.md b/skills/writebook/SKILL.md index 319a3d1..13c0cb6 100644 --- a/skills/writebook/SKILL.md +++ b/skills/writebook/SKILL.md @@ -102,7 +102,9 @@ the user. It fails, and the error message says which command to run. If you only need to read books, add `--read-only` in step 1. The sign-in can read books but can't change them, so `push` fails. The approval page tells -the user that the device will only be able to read. +the user that the device will only be able to read. To manage people and +settings in `writebook tui`, an administrator ticks "Manage people and +settings" when approving. In `writebook tui`, creating a book needs a sign-in that can write: a read-only one isn't offered "new book". @@ -284,13 +286,13 @@ claude mcp add writebook -- writebook mcp To give other people's agents access to one instance, run it as a server: ```sh -writebook mcp --instance https://books.example.com --serve 0.0.0.0:8080 +writebook mcp serve --instance https://books.example.com --bind 0.0.0.0:8080 ``` The server doesn't use the user's sign-in. Each request must send a Writebook token as a Bearer header. The server sends the token only to that instance. The server uses plain HTTP, so put it behind https unless it listens only on this -computer. The Docker image `ghcr.io/basecamp/writebook-cli` runs the same -command. +computer. The Docker image `ghcr.io/basecamp/writebook-cli` runs this +server on port 80 unless you give it another command. If you already use the CLI, you don't need the MCP server. diff --git a/src/api.rs b/src/api.rs index 0c7bf92..61447f4 100644 --- a/src/api.rs +++ b/src/api.rs @@ -5,7 +5,7 @@ use anyhow::{Context, Result, bail}; use serde_json::Value; use std::time::{SystemTime, UNIX_EPOCH}; -use crate::creds; +use crate::{creds, inventory}; const USER_AGENT: &str = concat!("writebook-cli/", env!("CARGO_PKG_VERSION")); const DOWNLOAD_LIMIT: u64 = 512 * 1024 * 1024; @@ -80,6 +80,7 @@ impl std::error::Error for ApiError {} #[derive(Debug)] pub struct ScopeTooNarrow { pub missing: MissingScope, + sign_in: String, } #[derive(Debug, PartialEq)] @@ -102,13 +103,21 @@ impl MissingScope { impl std::fmt::Display for ScopeTooNarrow { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let sign_in = &self.sign_in; + match self.missing { - MissingScope::Write => write!(f, "Writebook says this sign-in can only read, so it can't change books"), + MissingScope::Write => write!( + f, + "Writebook says this sign-in can only read, so it can't change books. To change books, sign in again with `{sign_in}` and approve reading and changing books" + ), MissingScope::Admin => write!( f, - "Writebook says this sign-in can't manage people and settings. Sign in again with `writebook instance add ` and tick \"Manage people and settings\"" + "Writebook says this sign-in can't manage people and settings. Sign in again with `{sign_in}` and tick \"Manage people and settings\"" + ), + MissingScope::Unnamed => write!( + f, + "Writebook says this sign-in wasn't given access to do that. Sign in again with `{sign_in}` and approve the access it needs" ), - MissingScope::Unnamed => write!(f, "Writebook says this sign-in can't do that"), } } } @@ -244,7 +253,7 @@ impl Client { fn request(&mut self, path: &str, request: Request) -> Result { let response = self.send_renewing(|client| client.send(path, &request))?; - response_json(path, response) + response_json(&self.host, path, response) } fn multipart(&mut self, path: &str, method: MultipartMethod, parts: &[Part]) -> Result { @@ -253,7 +262,7 @@ impl Client { let content_type = format!("multipart/form-data; boundary={boundary}"); let response = self.send_renewing(|client| client.send_multipart(path, method, &content_type, &body))?; - response_json(path, response) + response_json(&self.host, path, response) } fn send_renewing(&mut self, send: impl Fn(&Client) -> Result) -> Result { @@ -384,7 +393,7 @@ pub fn url_on(host: &str, path: &str) -> Result { } } -fn response_json(path: &str, mut response: Response) -> Result { +fn response_json(host: &str, path: &str, mut response: Response) -> Result { let status = response.status().as_u16(); let challenge = response .headers() @@ -394,8 +403,10 @@ fn response_json(path: &str, mut response: Response) -> Result { .map(str::to_string); if let (403, Some(challenge)) = (status, challenge) { + let profile = inventory::profile_for(host).unwrap_or_else(|_| "default".to_string()); Err(ScopeTooNarrow { missing: MissingScope::from_challenge(&challenge), + sign_in: inventory::sign_in_command(host, &profile), } .into()) } else { diff --git a/src/creds.rs b/src/creds.rs index b41d23e..c87d758 100644 --- a/src/creds.rs +++ b/src/creds.rs @@ -506,8 +506,16 @@ fn post_device_authorization(host: &str, scope: &str) -> Result<(u16, Value)> { .with_context(|| format!("could not reach {host}"))?; let status = response.status().as_u16(); - let body = response.body_mut().read_json().unwrap_or(Value::Null); - Ok((status, body)) + + if status == 200 { + let body = response + .body_mut() + .read_json() + .with_context(|| format!("{host} sent a device sign-in answer the CLI can't read"))?; + Ok((status, body)) + } else { + Ok((status, response.body_mut().read_json().unwrap_or(Value::Null))) + } } fn post_token_request(host: &str, form: &[(&str, &str)]) -> Result<(u16, Value)> { diff --git a/src/main.rs b/src/main.rs index ed3fabd..75a227c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -155,24 +155,15 @@ enum Command { #[usage(help_heading = "Setup commands")] Upgrade, #[usage( - help = "Let agents read and edit books on every instance you added, through MCP: `claude mcp add writebook -- writebook mcp`. With --serve it gives anyone's agent access to one instance over HTTP at /mcp, using their own login: every request has to include a Writebook token as a Bearer header. It serves plain HTTP, so put it behind https unless it only listens on this machine" + help = "Let agents read and edit books on every instance you added, through MCP: `claude mcp add writebook -- writebook mcp`" )] #[usage(help_heading = "Agent commands")] Mcp { - #[usage(help = "With --serve, the instance alias or URL to serve (defaults to the default instance)")] - #[usage(long, env = "WRITEBOOK_MCP_INSTANCE")] - instance: Option, #[usage(help = "Serve only the tools that read")] #[usage(long, env = "WRITEBOOK_MCP_READ_ONLY")] read_only: bool, - #[usage(help = "Serve over HTTP at this address, like 127.0.0.1:8080, instead of stdio")] - #[usage(long)] - serve: Option, - #[usage( - help = "With --serve, the address clients reach the server at, like https://mcp.example.com, when a proxy doesn't pass on the original Host" - )] - #[usage(long, env = "WRITEBOOK_MCP_PUBLIC_URL")] - public_url: Option, + #[usage(subcommand)] + command: Option, }, #[usage(help = "Browse your instances' books in the terminal, and arrange their pages")] Tui, @@ -184,6 +175,29 @@ enum Command { }, } +#[derive(Subcommands)] +enum McpCommand { + #[usage( + help = "Give anyone's agent access to one instance over HTTP at /mcp, using their own login: every request to /mcp has to include a Writebook token as a Bearer header, and agents that sign in with OAuth are sent to the instance. It serves plain HTTP, so put it behind https unless it only listens on this machine" + )] + Serve { + #[usage(help = "The instance alias or URL to serve (defaults to the default instance)")] + #[usage(long, env = "WRITEBOOK_MCP_INSTANCE")] + instance: Option, + #[usage(help = "Serve only the tools that read")] + #[usage(long, env = "WRITEBOOK_MCP_READ_ONLY")] + read_only: bool, + #[usage(help = "The address to listen on")] + #[usage(long, env = "WRITEBOOK_MCP_BIND", default = "127.0.0.1:8080")] + bind: String, + #[usage( + help = "The address clients reach the server at, like https://mcp.example.com, when a proxy doesn't pass on the original Host" + )] + #[usage(long, env = "WRITEBOOK_MCP_PUBLIC_URL")] + public_url: Option, + }, +} + #[derive(Subcommands)] enum SkillCommand { #[usage(help = "Print the embedded SKILL.md")] @@ -449,12 +463,15 @@ fn run(cli: Cli) -> Result<()> { instance.as_deref(), Format::from_flags(json, markdown, jq)?, ), - Command::Mcp { - instance, - read_only, - serve, - public_url, - } => mcp::run(instance.as_deref(), read_only, serve.as_deref(), public_url.as_deref()), + Command::Mcp { read_only, command } => match command { + None => mcp::run(read_only), + Some(McpCommand::Serve { + instance, + read_only, + bind, + public_url, + }) => mcp::serve(instance.as_deref(), read_only, &bind, public_url.as_deref()), + }, Command::Tui => tui::run(), Command::Setup => setup::run(), Command::Skill { command } => match command { diff --git a/src/mcp.rs b/src/mcp.rs index 08356c5..a74e444 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -1,7 +1,7 @@ //! `writebook mcp`: Writebook books as MCP tools. //! //! On stdio it serves every instance in the inventory, with the person's own -//! sign-ins, to an MCP client on the same machine. With --serve it serves one +//! sign-ins, to an MCP client on the same machine. `mcp serve` serves one //! instance over HTTP, and every request to /mcp has to include a Writebook //! token. The server sends that token only to that instance and uses no //! stored login, so a request without a token can't use anyone else's. @@ -32,41 +32,41 @@ use crate::{api, creds}; const ACCEPTED_FOR: std::time::Duration = std::time::Duration::from_secs(60); -pub fn run(instance: Option<&str>, read_only: bool, serve: Option<&str>, public_url: Option<&str>) -> Result<()> { +pub fn run(read_only: bool) -> Result<()> { let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build()?; log::start(); - match serve { - None if instance.is_some() => { - bail!("--instance only goes with --serve: on stdio, every instance you added is served") - } - None if public_url.is_some() => bail!("--public-url only goes with --serve"), - None => runtime.block_on(serve_stdio(read_only)), - Some(address) => { - let host = inventory::host(instance)?; - creds::ensure_private_connection(&host)?; - let public_url = public_url.map(origin).transpose()?; - runtime.block_on(serve_http(host, read_only, address, public_url)) - } - } + runtime.block_on(serve_stdio(read_only)) } -fn origin(url: &str) -> Result { - let parsed = url::Url::parse(url).ok().filter(|it| { - matches!(it.scheme(), "http" | "https") - && it.host().is_some() - && it.path() == "/" - && it.query().is_none() - && it.fragment().is_none() - && it.username().is_empty() - }); - - match parsed { - Some(parsed) => Ok(parsed.origin().ascii_serialization()), - None => bail!( - "--public-url takes the address clients reach the server at, with no path, like https://mcp.example.com" - ), - } +pub fn serve(instance: Option<&str>, read_only: bool, bind: &str, public_url: Option<&str>) -> Result<()> { + let host = inventory::host(instance)?; + creds::ensure_private_connection(&host)?; + let public_url = match public_url { + Some(url) => Some(origin(url).context( + "--public-url takes the address clients reach the server at, with no path, like https://mcp.example.com", + )?), + None => None, + }; + + let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build()?; + log::start(); + + runtime.block_on(serve_http(host, read_only, bind, public_url)) +} + +fn origin(url: &str) -> Option { + url::Url::parse(url) + .ok() + .filter(|it| { + matches!(it.scheme(), "http" | "https") + && it.host().is_some() + && it.path() == "/" + && it.query().is_none() + && it.fragment().is_none() + && it.username().is_empty() + }) + .map(|it| it.origin().ascii_serialization()) } async fn serve_stdio(read_only: bool) -> Result<()> { @@ -170,20 +170,24 @@ async fn require_token( ) -> Response { match bearer(request.headers()) { None => gate.challenge(request.headers(), None, "a Writebook token is required\n"), - Some(token) => { - if gate.rejects(token).await { - gate.challenge( - request.headers(), - Some("invalid_token"), - "Writebook did not accept this token\n", - ) - } else { - next.run(request).await - } - } + Some(token) => match gate.check(token).await { + Check::Accepted => next.run(request).await, + Check::Rejected => gate.challenge( + request.headers(), + Some("invalid_token"), + "Writebook did not accept this token\n", + ), + Check::Failed => (StatusCode::BAD_GATEWAY, "could not check the token with Writebook\n").into_response(), + }, } } +enum Check { + Accepted, + Rejected, + Failed, +} + #[derive(Clone)] struct Gate { writebook: String, @@ -192,11 +196,11 @@ struct Gate { } impl Gate { - async fn rejects(&self, token: String) -> bool { + async fn check(&self, token: String) -> Check { let digest: [u8; 32] = sha2::Sha256::digest(token.as_bytes()).into(); if self.recently_accepted(&digest) { - false + Check::Accepted } else { let writebook = self.writebook.clone(); let answer = tokio::task::spawn_blocking(move || { @@ -210,12 +214,12 @@ impl Gate { .await; match answer { - Ok(Ok(401)) => true, + Ok(Ok(401)) => Check::Rejected, Ok(Ok(status)) if (200..300).contains(&status) => { self.remember(digest); - false + Check::Accepted } - _ => false, + _ => Check::Failed, } } } @@ -281,7 +285,7 @@ impl Gate { }; let host = headers.get(header::HOST)?.to_str().ok()?; - Some(format!("{scheme}://{host}")) + origin(&format!("{scheme}://{host}")) } } } diff --git a/tests/mcp.rs b/tests/mcp.rs index 6298a9e..c814315 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -173,26 +173,25 @@ fn says_what_a_refused_change_lacks() { let mut reader = Mcp::start(&server, Some("wb_at_reader")); let refused = reader.call_failing("update_page", change.clone()); - assert!(refused.contains("can only read, so it can't change books"), "{refused}"); + assert!( + refused.contains( + "can only read, so it can't change books. To change books, sign in again with `writebook instance add" + ), + "{refused}" + ); let mut unnamed = Mcp::start(&server, Some("wb_at_unnamed")); let refused = unnamed.call_failing("update_page", change); assert!( - refused.ends_with("Writebook says this sign-in can't do that"), + refused.contains( + "Writebook says this sign-in wasn't given access to do that. Sign in again with `writebook instance add" + ), "{refused}" ); } #[test] -fn takes_a_public_url_only_with_serve_and_only_as_an_origin() { - let without_serve = support::writebook(&["mcp", "--public-url", "https://mcp.example.com"], &[]); - assert!(!without_serve.status.success()); - assert!( - support::stderr(&without_serve).contains("--public-url only goes with --serve"), - "{}", - support::stderr(&without_serve) - ); - +fn takes_a_public_url_only_as_an_origin() { for url in [ "mcp.example.com", "https://mcp.example.com/mcp", @@ -201,9 +200,10 @@ fn takes_a_public_url_only_with_serve_and_only_as_an_origin() { let output = support::writebook( &[ "mcp", + "serve", "--instance", "https://books.example.com", - "--serve", + "--bind", "127.0.0.1:0", "--public-url", url, @@ -393,6 +393,10 @@ impl Mcp { command .args(["mcp"]) .env_remove("WRITEBOOK_TOKEN") + .env_remove("WRITEBOOK_MCP_INSTANCE") + .env_remove("WRITEBOOK_MCP_READ_ONLY") + .env_remove("WRITEBOOK_MCP_BIND") + .env_remove("WRITEBOOK_MCP_PUBLIC_URL") .env("XDG_CONFIG_HOME", &config); if let Some(token) = token { @@ -534,6 +538,30 @@ fn points_mcp_clients_at_the_writebook_to_sign_in_with() { "a request with no Host gets no made-up address" ); + for (token, challenge) in [ + (None, "Bearer"), + (Some("wb_at_revoked"), r#"Bearer error="invalid_token""#), + ] { + let authorization = token + .map(|it| format!("Authorization: Bearer {it}\r\n")) + .unwrap_or_default(); + let mut without_host = std::net::TcpStream::connect(base.trim_start_matches("http://")).unwrap(); + std::io::Write::write_all( + &mut without_host, + format!("POST /mcp HTTP/1.0\r\n{authorization}Content-Length: 0\r\n\r\n").as_bytes(), + ) + .unwrap(); + let mut answer = String::new(); + std::io::Read::read_to_string(&mut without_host, &mut answer).unwrap(); + assert!(answer.starts_with("HTTP/1.0 401"), "{answer}"); + assert!( + answer + .to_lowercase() + .contains(&format!("www-authenticate: {}\r\n", challenge.to_lowercase())), + "{answer}" + ); + } + child.kill().unwrap(); child.wait().unwrap(); } @@ -638,11 +666,14 @@ fn serve( envs: &[(&str, &str)], ) -> (std::process::Child, BufReader, String) { let mut child = Command::new(env!("CARGO_BIN_EXE_writebook")) - .args(["mcp", "--serve", "127.0.0.1:0"]) + .args(["mcp", "serve", "--bind", "127.0.0.1:0"]) .args(flags) - .envs(envs.iter().copied()) - .env("WRITEBOOK_MCP_INSTANCE", &server.url) .env_remove("WRITEBOOK_TOKEN") + .env_remove("WRITEBOOK_MCP_READ_ONLY") + .env_remove("WRITEBOOK_MCP_BIND") + .env_remove("WRITEBOOK_MCP_PUBLIC_URL") + .env("WRITEBOOK_MCP_INSTANCE", &server.url) + .envs(envs.iter().copied()) .env("XDG_CONFIG_HOME", config) .env("WRITEBOOK_NO_KEYRING", "1") .stdin(Stdio::null()) diff --git a/tests/support/mod.rs b/tests/support/mod.rs index 600218a..0033c71 100644 --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -46,6 +46,10 @@ fn command_in(dir: &std::path::Path, args: &[&str], env: &[(&str, &str)]) -> (Co .env_remove("WRITEBOOK_TOKEN_HOST") .env_remove("WRITEBOOK_PROFILE") .env_remove("WRITEBOOK_NO_SIGN_IN") + .env_remove("WRITEBOOK_MCP_INSTANCE") + .env_remove("WRITEBOOK_MCP_READ_ONLY") + .env_remove("WRITEBOOK_MCP_BIND") + .env_remove("WRITEBOOK_MCP_PUBLIC_URL") .env_remove("CLAUDECODE") .env("XDG_CONFIG_HOME", &config) .env("WRITEBOOK_NO_KEYRING", "1") From 9881e15766ffb3566c0296d134ef06f1fd97799d Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 17:10:11 +0100 Subject: [PATCH 16/21] Tell an administrator whose sign-in can't manage people how to sign in again, and trim the README to the commands --- README.md | 13 ++----------- doc/mcp-server.md | 3 +++ src/tui/data/people.rs | 18 ++++++++++++++++-- src/tui/flows/people.rs | 41 ++++++++++++++++++++++++++++++++++++----- src/tui/settings.rs | 20 ++++++++++++++++++++ 5 files changed, 77 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index abb85e4..d8be321 100644 --- a/README.md +++ b/README.md @@ -26,9 +26,6 @@ Sign in to your Writebook. The CLI prints a link to approve in the browser: writebook instance add https://books.example.com ``` -To manage people and settings from `writebook tui`, an administrator ticks -"Manage people and settings" when approving. - Add `--read-only` if this device only needs to read books. To sign in without approving anything, use an API token from your Writebook profile instead. It can only read: @@ -105,14 +102,8 @@ Or run it with Docker: docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli mcp serve --instance https://books.example.com --bind 0.0.0.0:8080 ``` -Agents that sign in with OAuth are sent to your Writebook to sign in. Put the -server behind https, with the proxy passing on the original `Host` and sending -`X-Forwarded-Proto: https`. If your proxy can't, pass the server's address with -`--public-url https://mcp.example.com`. Run it yourself, next to your -Writebook: every request's token passes through it. - -[doc/mcp-server.md](doc/mcp-server.md) shows how to set it up behind -kamal-proxy, Caddy and Apache, and with ONCE. +To put it behind a proxy or run it with ONCE, see +[doc/mcp-server.md](doc/mcp-server.md). To browse your books in the terminal, and add, delete, move and publish pages, run: diff --git a/doc/mcp-server.md b/doc/mcp-server.md index a459eee..eb7a3d2 100644 --- a/doc/mcp-server.md +++ b/doc/mcp-server.md @@ -8,6 +8,9 @@ and builds the addresses it gives them from the request. So the proxy must: - send `X-Forwarded-Proto: https`, - pass on the `Authorization` header. +Run it yourself, next to your Writebook: every request's token passes +through it. + If the proxy can't pass on the `Host`, give the server its address with `--public-url https://mcp.example.com`. diff --git a/src/tui/data/people.rs b/src/tui/data/people.rs index ae2b192..348e003 100644 --- a/src/tui/data/people.rs +++ b/src/tui/data/people.rs @@ -3,12 +3,16 @@ use serde::Deserialize; use serde_json::json; use super::{client, text}; +use crate::inventory; /// The people with access to an instance, and the link that invites more. pub struct People { pub join_url: Option, pub can_administer: bool, pub people: Vec, + /// For an administrator whose sign-in can't manage people: the command + /// that signs in again so it can. + pub sign_in_to_administer: Option, } #[derive(Deserialize, Clone)] @@ -28,12 +32,22 @@ impl Person { pub fn people(host: &str) -> Result { let value = client(host)?.get("/users.json")?; - let people = serde_json::from_value(value["users"].clone()).context("could not understand the list of people")?; + let people: Vec = + serde_json::from_value(value["users"].clone()).context("could not understand the list of people")?; + let can_administer = value["can_administer"].as_bool().unwrap_or(false); + let administrator = people.iter().any(|it| it.current && it.administrator()); + let sign_in_to_administer = if administrator && !can_administer { + let profile = inventory::profile_for(host).unwrap_or_else(|_| "default".to_string()); + Some(inventory::sign_in_command(host, &profile)) + } else { + None + }; Ok(People { join_url: text(&value, "join_url"), - can_administer: value["can_administer"].as_bool().unwrap_or(false), + can_administer, people, + sign_in_to_administer, }) } diff --git a/src/tui/flows/people.rs b/src/tui/flows/people.rs index e4cc71b..41e94d6 100644 --- a/src/tui/flows/people.rs +++ b/src/tui/flows/people.rs @@ -11,6 +11,7 @@ struct Workplace { can_administer: bool, failing: bool, scope_too_narrow: bool, + without_admin_scope: bool, profile_email: String, wrong_password: bool, } @@ -18,7 +19,11 @@ struct Workplace { fn workplace(can_administer: bool) -> (Tui, Arc>) { let state = Arc::new(Mutex::new(Workplace { people: vec![ - (1, "Me", "administrator".to_string()), + ( + 1, + "Me", + if can_administer { "administrator" } else { "member" }.to_string(), + ), (2, "Kevin", "member".to_string()), (3, "Jason", "member".to_string()), ], @@ -26,6 +31,7 @@ fn workplace(can_administer: bool) -> (Tui, Arc>) { can_administer, failing: false, scope_too_narrow: false, + without_admin_scope: false, profile_email: "me@example.com".to_string(), wrong_password: false, })); @@ -54,9 +60,13 @@ fn workplace(can_administer: bool) -> (Tui, Arc>) { .iter() .map(|(id, name, role)| json!({ "id": id, "name": name, "role": role, "current": *id == 1 })) .collect(); - json( - json!({ "users": users, "join_url": format!("http://{host}/join/{}", state.invite), "can_administer": state.can_administer }), - ) + if state.without_admin_scope { + json(json!({ "users": users, "can_administer": false })) + } else { + json( + json!({ "users": users, "join_url": format!("http://{host}/join/{}", state.invite), "can_administer": state.can_administer }), + ) + } } ("PATCH", path) if path.starts_with("/users/") && path.ends_with("/profile.json") => { if state.wrong_password { @@ -325,7 +335,28 @@ fn a_server_error_on_a_change_shows_a_notice_and_keeps_the_list_as_it_was() { } #[test] -fn a_sign_in_without_the_admin_scope_says_to_sign_in_again() { +fn an_administrator_whose_sign_in_cant_manage_people_is_told_to_sign_in_again() { + let (mut tui, state) = workplace(true); + state.lock().unwrap().without_admin_scope = true; + tui.press(KeyCode::Enter); + tui.wait_for("Handbook"); + tui.press(KeyCode::Char('s')); + + let screen = tui.wait_for("This sign-in can't manage people"); + assert!(screen.contains("Manage people and settings"), "{screen}"); + assert!(!screen.contains("‹"), "{screen}"); + assert!(!screen.contains("remove"), "{screen}"); + + tui.press(KeyCode::Down); + tui.press(KeyCode::Right); + tui.press(KeyCode::Char('d')); + let screen = tui.screen(); + assert!(!screen.contains("Remove Kevin?"), "{screen}"); + assert_eq!(state.lock().unwrap().people[1].2, "member"); +} + +#[test] +fn a_sign_in_that_loses_the_admin_scope_says_to_sign_in_again() { let (mut tui, state) = settings(true); state.lock().unwrap().scope_too_narrow = true; diff --git a/src/tui/settings.rs b/src/tui/settings.rs index 2adda14..2255d5e 100644 --- a/src/tui/settings.rs +++ b/src/tui/settings.rs @@ -169,6 +169,7 @@ impl SettingsPage { ..area }; let invite_height = match (&people.join_url, self.showing_qr) { + (None, _) if people.sign_in_to_administer.is_some() => 6, (None, _) => 0, (Some(url), true) => 6 + views::qr_lines(url, &self.host).len() as u16, (Some(_), false) => 5, @@ -180,6 +181,25 @@ impl SettingsPage { ]) .areas(area); + if let Some(command) = &people.sign_in_to_administer { + let lines = vec![ + Line::from("This sign-in can't manage people").bold().centered(), + Line::default(), + Line::from(format!( + "Sign in again with `{command}` and tick \"Manage people and settings\"" + )), + ]; + let block = Block::bordered() + .border_type(BorderType::Rounded) + .border_style(Style::default().fg(Color::DarkGray)); + frame.render_widget( + Paragraph::new(lines) + .block(block) + .wrap(ratatui::widgets::Wrap { trim: true }), + invite, + ); + } + if let Some(url) = &people.join_url { let mut lines = vec![ Line::from("Share to invite more people").bold().centered(), From 8f32285990eb7dd3cde206670de949e5a020b18c Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 17:12:16 +0100 Subject: [PATCH 17/21] Document running the MCP server with ONCE first, and write the docs and help in plain sentences --- README.md | 4 +- doc/mcp-server.md | 81 ++++++++++++++++++++++----------------- skills/writebook/SKILL.md | 7 ++-- src/main.rs | 2 +- 4 files changed, 52 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index d8be321..0b55e2a 100644 --- a/README.md +++ b/README.md @@ -102,8 +102,8 @@ Or run it with Docker: docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli mcp serve --instance https://books.example.com --bind 0.0.0.0:8080 ``` -To put it behind a proxy or run it with ONCE, see -[doc/mcp-server.md](doc/mcp-server.md). +[doc/mcp-server.md](doc/mcp-server.md) explains how to run it with ONCE or +behind a proxy. To browse your books in the terminal, and add, delete, move and publish pages, run: diff --git a/doc/mcp-server.md b/doc/mcp-server.md index eb7a3d2..e8fb90e 100644 --- a/doc/mcp-server.md +++ b/doc/mcp-server.md @@ -1,32 +1,57 @@ -# Running the MCP server behind a proxy +# Running the MCP server -`writebook mcp serve` speaks plain HTTP, so put it behind a proxy that ends -TLS. MCP clients sign in with OAuth: the server points them at your Writebook, -and builds the addresses it gives them from the request. So the proxy must: +`writebook mcp serve` gives agents access to one Writebook instance over HTTP. +Each agent uses its own Writebook sign-in. Agents that sign in with OAuth are +sent to your Writebook to sign in. + +Every request's token passes through the server, so run it yourself, on a +machine you control. + +Give the server its own host name, like `mcp.example.com`. Don't put it under +a path on another site, because MCP clients look for its sign-in details at +`/.well-known/oauth-protected-resource` on the root of the host. + +## With ONCE + +ONCE is the easiest way to run the server. It handles TLS and sets the headers +the server needs. + +```sh +once deploy ghcr.io/basecamp/writebook-cli --host mcp.example.com \ + --env WRITEBOOK_MCP_INSTANCE=https://books.example.com +``` + +The Docker image runs the server on port 80 by default. The server reads its +settings from these environment variables: + +- `WRITEBOOK_MCP_INSTANCE`: the URL of your Writebook. Required. +- `WRITEBOOK_MCP_READ_ONLY=true`: serve only the tools that read. +- `WRITEBOOK_MCP_PUBLIC_URL`: the server's address, if the proxy in front of + it doesn't pass on the original `Host` header. ONCE doesn't need it. + +## Behind another proxy + +The server uses plain HTTP, so put it behind a proxy that handles TLS. The +proxy must: - pass on the original `Host` header, - send `X-Forwarded-Proto: https`, - pass on the `Authorization` header. -Run it yourself, next to your Writebook: every request's token passes -through it. - -If the proxy can't pass on the `Host`, give the server its address with +If the proxy can't pass on the `Host` header, start the server with `--public-url https://mcp.example.com`. -Give the server a host of its own, like `mcp.example.com`, not a path on -another site. MCP clients look for its sign-in details at -`/.well-known/oauth-protected-resource` at the root of the host. +`GET /up` returns 200 without a token. Use it for health checks. -`GET /up` answers 200 without a token, for health checks. +### kamal-proxy -## kamal-proxy +kamal-proxy passes on the `Host` header, sends `X-Forwarded-Proto`, and checks +`/up` before it sends traffic to the server. You don't need to change anything. +Don't deploy the server with `--path-prefix`. -Deploy it as it is. kamal-proxy passes on the `Host`, sends -`X-Forwarded-Proto`, and waits for `/up` to answer before it sends traffic. -Don't deploy it under `--path-prefix`. +### Caddy -## Caddy +Caddy passes on the `Host` header and sends `X-Forwarded-Proto` by default: ``` mcp.example.com { @@ -34,26 +59,10 @@ mcp.example.com { } ``` -Caddy passes on the `Host` and sends `X-Forwarded-Proto` by default. - -## ONCE - -ONCE can't pass arguments to a container, so the image serves MCP on port 80 -by default and reads its settings from environment variables: - -```sh -once deploy ghcr.io/basecamp/writebook-cli --host mcp.example.com \ - --env WRITEBOOK_MCP_INSTANCE=https://books.example.com -``` - -`WRITEBOOK_MCP_READ_ONLY=true` serves only the tools that read, and -`WRITEBOOK_MCP_PUBLIC_URL` sets `--public-url`. ONCE puts the server behind -kamal-proxy, which handles TLS and the headers. - -## Apache +### Apache -Apache doesn't pass on the `Host` or send `X-Forwarded-Proto` by default. It -needs `mod_proxy`, `mod_proxy_http` and `mod_headers`: +Apache doesn't pass on the `Host` header or send `X-Forwarded-Proto` by +default. Turn on `mod_proxy`, `mod_proxy_http` and `mod_headers`, and set both: ```apache diff --git a/skills/writebook/SKILL.md b/skills/writebook/SKILL.md index 13c0cb6..7b4306a 100644 --- a/skills/writebook/SKILL.md +++ b/skills/writebook/SKILL.md @@ -102,9 +102,10 @@ the user. It fails, and the error message says which command to run. If you only need to read books, add `--read-only` in step 1. The sign-in can read books but can't change them, so `push` fails. The approval page tells -the user that the device will only be able to read. To manage people and -settings in `writebook tui`, an administrator ticks "Manage people and -settings" when approving. +the user that the device will only be able to read. + +An administrator who wants to manage people and settings in `writebook tui` +must tick "Manage people and settings" on the approval page. In `writebook tui`, creating a book needs a sign-in that can write: a read-only one isn't offered "new book". diff --git a/src/main.rs b/src/main.rs index 75a227c..f6c4880 100644 --- a/src/main.rs +++ b/src/main.rs @@ -178,7 +178,7 @@ enum Command { #[derive(Subcommands)] enum McpCommand { #[usage( - help = "Give anyone's agent access to one instance over HTTP at /mcp, using their own login: every request to /mcp has to include a Writebook token as a Bearer header, and agents that sign in with OAuth are sent to the instance. It serves plain HTTP, so put it behind https unless it only listens on this machine" + help = "Serve one instance over HTTP at /mcp. Each request to /mcp must include the caller's Writebook token as a Bearer header. Agents that sign in with OAuth are sent to the instance to sign in. The server uses plain HTTP, so put it behind https unless it only listens on this computer" )] Serve { #[usage(help = "The instance alias or URL to serve (defaults to the default instance)")] From cac397827aa8e02a21882f05a0b888743c55141b Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 17:17:04 +0100 Subject: [PATCH 18/21] Fix the third review's findings --read-only is one flag for mcp and mcp serve, so mcp --read-only serve no longer drops it. A refusal for a WRITEBOOK_TOKEN says to use a token with the access, since signing in again wouldn't change it, and mcp serve words every scope refusal for a remote app. The server logs a warning when the instance uses http. New tests cover the 502, WRITEBOOK_MCP_BIND and each way to set read-only. The skill says only /mcp needs a token and mentions --public-url. --- skills/writebook/SKILL.md | 7 +++- src/api.rs | 33 ++++++++------- src/creds.rs | 13 +++++- src/main.rs | 6 +-- src/mcp.rs | 17 +++++--- src/mcp/log.rs | 8 ++++ src/tui/data/people.rs | 18 ++++---- src/tui/flows/people.rs | 5 ++- src/tui/settings.rs | 8 ++-- tests/mcp.rs | 86 +++++++++++++++++++++++++++++++++------ 10 files changed, 147 insertions(+), 54 deletions(-) diff --git a/skills/writebook/SKILL.md b/skills/writebook/SKILL.md index 7b4306a..38778d7 100644 --- a/skills/writebook/SKILL.md +++ b/skills/writebook/SKILL.md @@ -290,8 +290,11 @@ To give other people's agents access to one instance, run it as a server: writebook mcp serve --instance https://books.example.com --bind 0.0.0.0:8080 ``` -The server doesn't use the user's sign-in. Each request must send a Writebook -token as a Bearer header. The server sends the token only to that instance. The +The server doesn't use the user's sign-in. Each request to `/mcp` must send a +Writebook token as a Bearer header. Agents that sign in with OAuth are sent to +the instance to sign in. If the server is behind a proxy that doesn't pass on +the original `Host` header, start it with `--public-url` and the server's +https address. The server sends the token only to that instance. The server uses plain HTTP, so put it behind https unless it listens only on this computer. The Docker image `ghcr.io/basecamp/writebook-cli` runs this server on port 80 unless you give it another command. diff --git a/src/api.rs b/src/api.rs index 61447f4..28db607 100644 --- a/src/api.rs +++ b/src/api.rs @@ -5,7 +5,7 @@ use anyhow::{Context, Result, bail}; use serde_json::Value; use std::time::{SystemTime, UNIX_EPOCH}; -use crate::{creds, inventory}; +use crate::creds; const USER_AGENT: &str = concat!("writebook-cli/", env!("CARGO_PKG_VERSION")); const DOWNLOAD_LIMIT: u64 = 512 * 1024 * 1024; @@ -80,7 +80,7 @@ impl std::error::Error for ApiError {} #[derive(Debug)] pub struct ScopeTooNarrow { pub missing: MissingScope, - sign_in: String, + sign_in: Option, } #[derive(Debug, PartialEq)] @@ -103,20 +103,26 @@ impl MissingScope { impl std::fmt::Display for ScopeTooNarrow { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let sign_in = &self.sign_in; - - match self.missing { - MissingScope::Write => write!( - f, - "Writebook says this sign-in can only read, so it can't change books. To change books, sign in again with `{sign_in}` and approve reading and changing books" + let (refusal, approval) = match self.missing { + MissingScope::Write => ( + "can only read, so it can't change books", + "approve reading and changing books", + ), + MissingScope::Admin => ( + "can't manage people and settings", + "tick \"Manage people and settings\"", ), - MissingScope::Admin => write!( + MissingScope::Unnamed => ("wasn't given access to do that", "approve the access it needs"), + }; + + match &self.sign_in { + Some(sign_in) => write!( f, - "Writebook says this sign-in can't manage people and settings. Sign in again with `{sign_in}` and tick \"Manage people and settings\"" + "Writebook says this sign-in {refusal}. Sign in again with `{sign_in}` and {approval}" ), - MissingScope::Unnamed => write!( + None => write!( f, - "Writebook says this sign-in wasn't given access to do that. Sign in again with `{sign_in}` and approve the access it needs" + "Writebook says the token in WRITEBOOK_TOKEN {refusal}. Use a token that has the access it needs" ), } } @@ -403,10 +409,9 @@ fn response_json(host: &str, path: &str, mut response: Response) -> Result Option { + if GIVEN_TOKEN.get().is_some() { + None + } else { + inventory::profile_for(host) + .ok() + .map(|profile| inventory::sign_in_command(host, &profile)) + } +} + pub fn rejected_token_advice(host: &str) -> String { if GIVEN_TOKEN.get().is_some() { "Check WRITEBOOK_TOKEN".to_string() @@ -485,7 +497,6 @@ fn access_from(body: &Value) -> Access { fn request_device_authorization(host: &str, access: Access) -> Result { let (status, body) = match access { Access::ReadOnly => post_device_authorization(host, "read")?, - // Writebooks from before the admin scope refuse it as an unknown scope. Access::Full => match post_device_authorization(host, "read write admin")? { (400, body) if body["error"] == "invalid_scope" => post_device_authorization(host, "read write")?, answer => answer, diff --git a/src/main.rs b/src/main.rs index f6c4880..18ee96f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -160,7 +160,7 @@ enum Command { #[usage(help_heading = "Agent commands")] Mcp { #[usage(help = "Serve only the tools that read")] - #[usage(long, env = "WRITEBOOK_MCP_READ_ONLY")] + #[usage(long, global, env = "WRITEBOOK_MCP_READ_ONLY")] read_only: bool, #[usage(subcommand)] command: Option, @@ -184,9 +184,6 @@ enum McpCommand { #[usage(help = "The instance alias or URL to serve (defaults to the default instance)")] #[usage(long, env = "WRITEBOOK_MCP_INSTANCE")] instance: Option, - #[usage(help = "Serve only the tools that read")] - #[usage(long, env = "WRITEBOOK_MCP_READ_ONLY")] - read_only: bool, #[usage(help = "The address to listen on")] #[usage(long, env = "WRITEBOOK_MCP_BIND", default = "127.0.0.1:8080")] bind: String, @@ -467,7 +464,6 @@ fn run(cli: Cli) -> Result<()> { None => mcp::run(read_only), Some(McpCommand::Serve { instance, - read_only, bind, public_url, }) => mcp::serve(instance.as_deref(), read_only, &bind, public_url.as_deref()), diff --git a/src/mcp.rs b/src/mcp.rs index a74e444..b606faa 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -115,6 +115,9 @@ async fn serve_http(host: String, read_only: bool, address: &str, public_url: Op Some(format!("http://{}/mcp", listener.local_addr()?)), read_only, ); + if logged.starts_with("http://") { + log::unencrypted_instance(); + } // Allow any Host header. Host checks stop a web page from using a local // server's stored login, and this server doesn't store one. @@ -437,11 +440,15 @@ impl ServerHandler for Writebook { (Err(error), Origin::Served { host }) if error.downcast_ref::().is_some() => { failure(&format!("{host} did not accept your Writebook token")) } - (Err(error), Origin::Served { .. }) - if error.downcast_ref::().is_some_and(|it| it.missing == api::MissingScope::Write) => - { - failure("Writebook says this connection can only read. Reconnect the app and choose \"Read and change books\"") - } + (Err(error), Origin::Served { .. }) => match error.downcast_ref::() { + Some(refusal) if refusal.missing == api::MissingScope::Write => failure( + "Writebook says this connection can only read. Reconnect the app and choose \"Read and change books\"", + ), + Some(_) => failure( + "Writebook says this connection doesn't have the access to do that. Reconnect the app and approve the access it needs", + ), + None => failure(&format!("{error:#}")), + }, (Err(error), _) => failure(&format!("{error:#}")), } .into()) diff --git a/src/mcp/log.rs b/src/mcp/log.rs index 2a202be..0c32e4a 100644 --- a/src/mcp/log.rs +++ b/src/mcp/log.rs @@ -34,6 +34,14 @@ pub fn serving(instance: &str, transport: &str, address: Option, read_on info!(target: TARGET, event = "serving", instance, transport, address, read_only); } +pub fn unencrypted_instance() { + warn!( + target: TARGET, + event = "unencrypted_instance", + message = "the instance uses http, so agents' tokens are sent to it unencrypted" + ); +} + pub fn http_request(method: &Method, status: u16, duration: Duration) { info!(target: TARGET, event = "http_request", method = method.as_str(), status, duration_ms = duration.as_millis() as u64); } diff --git a/src/tui/data/people.rs b/src/tui/data/people.rs index 348e003..5560d07 100644 --- a/src/tui/data/people.rs +++ b/src/tui/data/people.rs @@ -3,16 +3,16 @@ use serde::Deserialize; use serde_json::json; use super::{client, text}; -use crate::inventory; +use crate::creds; /// The people with access to an instance, and the link that invites more. pub struct People { pub join_url: Option, pub can_administer: bool, pub people: Vec, - /// For an administrator whose sign-in can't manage people: the command - /// that signs in again so it can. - pub sign_in_to_administer: Option, + /// For an administrator whose sign-in can't manage people: what to do + /// so it can. + pub to_administer: Option, } #[derive(Deserialize, Clone)] @@ -36,9 +36,11 @@ pub fn people(host: &str) -> Result { serde_json::from_value(value["users"].clone()).context("could not understand the list of people")?; let can_administer = value["can_administer"].as_bool().unwrap_or(false); let administrator = people.iter().any(|it| it.current && it.administrator()); - let sign_in_to_administer = if administrator && !can_administer { - let profile = inventory::profile_for(host).unwrap_or_else(|_| "default".to_string()); - Some(inventory::sign_in_command(host, &profile)) + let to_administer = if administrator && !can_administer { + Some(match creds::sign_in_again_command(host) { + Some(command) => format!("Sign in again with `{command}` and tick \"Manage people and settings\""), + None => "Use a WRITEBOOK_TOKEN that can manage people and settings".to_string(), + }) } else { None }; @@ -47,7 +49,7 @@ pub fn people(host: &str) -> Result { join_url: text(&value, "join_url"), can_administer, people, - sign_in_to_administer, + to_administer, }) } diff --git a/src/tui/flows/people.rs b/src/tui/flows/people.rs index 41e94d6..9fad3d8 100644 --- a/src/tui/flows/people.rs +++ b/src/tui/flows/people.rs @@ -343,7 +343,10 @@ fn an_administrator_whose_sign_in_cant_manage_people_is_told_to_sign_in_again() tui.press(KeyCode::Char('s')); let screen = tui.wait_for("This sign-in can't manage people"); - assert!(screen.contains("Manage people and settings"), "{screen}"); + assert!( + screen.contains("Use a WRITEBOOK_TOKEN that can manage people and settings"), + "{screen}" + ); assert!(!screen.contains("‹"), "{screen}"); assert!(!screen.contains("remove"), "{screen}"); diff --git a/src/tui/settings.rs b/src/tui/settings.rs index 2255d5e..06a398f 100644 --- a/src/tui/settings.rs +++ b/src/tui/settings.rs @@ -169,7 +169,7 @@ impl SettingsPage { ..area }; let invite_height = match (&people.join_url, self.showing_qr) { - (None, _) if people.sign_in_to_administer.is_some() => 6, + (None, _) if people.to_administer.is_some() => 6, (None, _) => 0, (Some(url), true) => 6 + views::qr_lines(url, &self.host).len() as u16, (Some(_), false) => 5, @@ -181,13 +181,11 @@ impl SettingsPage { ]) .areas(area); - if let Some(command) = &people.sign_in_to_administer { + if let Some(advice) = &people.to_administer { let lines = vec![ Line::from("This sign-in can't manage people").bold().centered(), Line::default(), - Line::from(format!( - "Sign in again with `{command}` and tick \"Manage people and settings\"" - )), + Line::from(advice.clone()), ]; let block = Block::bordered() .border_type(BorderType::Rounded) diff --git a/tests/mcp.rs b/tests/mcp.rs index c814315..f3778ae 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -175,7 +175,7 @@ fn says_what_a_refused_change_lacks() { let refused = reader.call_failing("update_page", change.clone()); assert!( refused.contains( - "can only read, so it can't change books. To change books, sign in again with `writebook instance add" + "Writebook says the token in WRITEBOOK_TOKEN can only read, so it can't change books. Use a token that has the access it needs" ), "{refused}" ); @@ -183,9 +183,7 @@ fn says_what_a_refused_change_lacks() { let mut unnamed = Mcp::start(&server, Some("wb_at_unnamed")); let refused = unnamed.call_failing("update_page", change); assert!( - refused.contains( - "Writebook says this sign-in wasn't given access to do that. Sign in again with `writebook instance add" - ), + refused.contains("Writebook says the token in WRITEBOOK_TOKEN wasn't given access to do that"), "{refused}" ); } @@ -612,18 +610,68 @@ fn tells_a_read_only_connection_to_reconnect_to_change_books() { } #[test] -fn serves_only_the_tools_that_read_when_the_environment_says_so() { +fn serves_only_the_tools_that_read_however_read_only_is_set() { let server = fake_writebook(); let config = tempdir(); - let (mut child, _logs, endpoint) = serve(&server, &config, &[], &[("WRITEBOOK_MCP_READ_ONLY", "true")]); + let ways: [(&[&str], &[(&str, &str)]); 3] = [ + ( + &["mcp", "serve", "--bind", "127.0.0.1:0"], + &[("WRITEBOOK_MCP_READ_ONLY", "true")], + ), + (&["mcp", "--read-only", "serve", "--bind", "127.0.0.1:0"], &[]), + (&["mcp", "serve", "--bind", "127.0.0.1:0", "--read-only"], &[]), + ]; - let (_, tools) = post( + for (args, envs) in ways { + let (mut child, _logs, endpoint) = serve_with(&server.url, &config, args, envs); + let (_, tools) = post( + &endpoint, + Some("wb_at_alice"), + &json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }), + ); + assert!(tools.contains(r#""name":"read_page""#), "{args:?} {tools}"); + assert!(!tools.contains(r#""name":"update_page""#), "{args:?} {tools}"); + + child.kill().unwrap(); + child.wait().unwrap(); + } +} + +#[test] +fn listens_where_the_environment_says() { + let server = fake_writebook(); + let config = tempdir(); + let (mut child, _logs, endpoint) = serve_with( + &server.url, + &config, + &["mcp", "serve"], + &[("WRITEBOOK_MCP_BIND", "127.0.0.1:0")], + ); + + assert!(endpoint.starts_with("http://127.0.0.1:"), "{endpoint}"); + assert!(!endpoint.contains(":8080/"), "{endpoint}"); + let up = ureq::get(&endpoint.replace("/mcp", "/up")).call().unwrap(); + assert_eq!(up.status().as_u16(), 200); + + child.kill().unwrap(); + child.wait().unwrap(); +} + +#[test] +fn answers_502_when_it_cant_check_a_token_with_writebook() { + let unreachable = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let instance = format!("http://{}", unreachable.local_addr().unwrap()); + drop(unreachable); + let config = tempdir(); + let (mut child, _logs, endpoint) = serve_with(&instance, &config, &["mcp", "serve", "--bind", "127.0.0.1:0"], &[]); + + let (status, answer) = post( &endpoint, Some("wb_at_alice"), &json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }), ); - assert!(tools.contains(r#""name":"read_page""#), "{tools}"); - assert!(!tools.contains(r#""name":"update_page""#), "{tools}"); + assert_eq!(status, 502, "{answer}"); + assert!(!answer.contains("read_page"), "{answer}"); child.kill().unwrap(); child.wait().unwrap(); @@ -664,15 +712,27 @@ fn serve( config: &std::path::Path, flags: &[&str], envs: &[(&str, &str)], +) -> (std::process::Child, BufReader, String) { + let args: Vec<&str> = ["mcp", "serve", "--bind", "127.0.0.1:0"] + .into_iter() + .chain(flags.iter().copied()) + .collect(); + serve_with(&server.url, config, &args, envs) +} + +fn serve_with( + instance: &str, + config: &std::path::Path, + args: &[&str], + envs: &[(&str, &str)], ) -> (std::process::Child, BufReader, String) { let mut child = Command::new(env!("CARGO_BIN_EXE_writebook")) - .args(["mcp", "serve", "--bind", "127.0.0.1:0"]) - .args(flags) + .args(args) .env_remove("WRITEBOOK_TOKEN") .env_remove("WRITEBOOK_MCP_READ_ONLY") .env_remove("WRITEBOOK_MCP_BIND") .env_remove("WRITEBOOK_MCP_PUBLIC_URL") - .env("WRITEBOOK_MCP_INSTANCE", &server.url) + .env("WRITEBOOK_MCP_INSTANCE", instance) .envs(envs.iter().copied()) .env("XDG_CONFIG_HOME", config) .env("WRITEBOOK_NO_KEYRING", "1") @@ -687,7 +747,7 @@ fn serve( let serving: Value = serde_json::from_str(&serving).unwrap(); assert_eq!( (&serving["event"], &serving["instance"], &serving["transport"]), - (&json!("serving"), &json!(server.url), &json!("http")) + (&json!("serving"), &json!(instance), &json!("http")) ); let endpoint = serving["address"].as_str().unwrap().to_string(); From 9fffdfcd0fb389f6b50da092053c12e14e79a810 Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 17:29:54 +0100 Subject: [PATCH 19/21] Exchange agents' tokens with Writebook instead of passing them through Writebook now issues MCP clients tokens bound to this server (RFC 8707) and refuses them anywhere else. mcp serve exchanges each one for a short-lived Writebook token (RFC 8693), authenticating with WRITEBOOK_MCP_SECRET, and gives that to the tools. Exchanged and refused tokens are remembered, so a client's token is exchanged once per short-lived token and junk tokens don't reach Writebook again for a minute. --public-url is now required, since the bound address has to match exactly, so the server no longer builds addresses from Host or X-Forwarded-Proto, and the root resource metadata path is gone. The server checks its secret with Writebook when it starts. --- Dockerfile | 7 +- README.md | 11 +- doc/mcp-server.md | 85 ++++++++------- skills/writebook/SKILL.md | 15 ++- src/main.rs | 8 +- src/mcp.rs | 178 ++++++++++--------------------- src/mcp/exchange.rs | 152 +++++++++++++++++++++++++++ tests/mcp.rs | 213 ++++++++++++++++++++------------------ 8 files changed, 384 insertions(+), 285 deletions(-) create mode 100644 src/mcp/exchange.rs diff --git a/Dockerfile b/Dockerfile index c428ee8..95693b8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,8 +3,11 @@ # The writebook CLI, mainly for serving a Writebook to MCP clients: # -# docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli \ -# mcp serve --instance https://books.example.com --bind 0.0.0.0:8080 +# docker run -p 8080:80 \ +# -e WRITEBOOK_MCP_INSTANCE=https://books.example.com \ +# -e WRITEBOOK_MCP_PUBLIC_URL=https://mcp.example.com \ +# -e WRITEBOOK_MCP_SECRET= \ +# ghcr.io/basecamp/writebook-cli ARG RUST_VERSION=1.99 FROM docker.io/library/rust:${RUST_VERSION}-slim-trixie AS build diff --git a/README.md b/README.md index 0b55e2a..2d073a8 100644 --- a/README.md +++ b/README.md @@ -93,16 +93,11 @@ It can also be used as a server to give anyone's agent access to a Writebook instance using their own logins: ```sh -writebook mcp serve --instance https://books.example.com +WRITEBOOK_MCP_SECRET= writebook mcp serve \ + --instance https://books.example.com --public-url https://mcp.example.com ``` -Or run it with Docker: - -```sh -docker run -p 8080:8080 ghcr.io/basecamp/writebook-cli mcp serve --instance https://books.example.com --bind 0.0.0.0:8080 -``` - -[doc/mcp-server.md](doc/mcp-server.md) explains how to run it with ONCE or +[doc/mcp-server.md](doc/mcp-server.md) explains how to set it up, with ONCE or behind a proxy. To browse your books in the terminal, and add, delete, move and publish diff --git a/doc/mcp-server.md b/doc/mcp-server.md index e8fb90e..beeee4f 100644 --- a/doc/mcp-server.md +++ b/doc/mcp-server.md @@ -1,57 +1,73 @@ # Running the MCP server `writebook mcp serve` gives agents access to one Writebook instance over HTTP. -Each agent uses its own Writebook sign-in. Agents that sign in with OAuth are -sent to your Writebook to sign in. +Each agent signs in to your Writebook with OAuth, and Writebook issues it a +token that only this MCP server accepts. The server exchanges that token with +Writebook for a short-lived one, and uses that to read and change books. -Every request's token passes through the server, so run it yourself, on a -machine you control. +Give the server its own host name, like `mcp.example.com`. MCP clients look +for its sign-in details at `/.well-known/oauth-protected-resource/mcp` on that +host. -Give the server its own host name, like `mcp.example.com`. Don't put it under -a path on another site, because MCP clients look for its sign-in details at -`/.well-known/oauth-protected-resource` on the root of the host. +The server and your Writebook share a secret of at least 32 characters. Make +one with: + +```sh +openssl rand -hex 32 +``` ## With ONCE -ONCE is the easiest way to run the server. It handles TLS and sets the headers -the server needs. +ONCE is the easiest way to run the server. It handles TLS for you. + +Tell your Writebook about the server. `--env` replaces the app's environment +variables, so include any you already set: + +```sh +once update books.example.com \ + --env MCP_SERVER_URL=https://mcp.example.com/mcp \ + --env MCP_SERVER_SECRET= +``` + +Then deploy the server: ```sh once deploy ghcr.io/basecamp/writebook-cli --host mcp.example.com \ - --env WRITEBOOK_MCP_INSTANCE=https://books.example.com + --env WRITEBOOK_MCP_INSTANCE=https://books.example.com \ + --env WRITEBOOK_MCP_PUBLIC_URL=https://mcp.example.com \ + --env WRITEBOOK_MCP_SECRET= ``` -The Docker image runs the server on port 80 by default. The server reads its -settings from these environment variables: +The Docker image runs the server on port 80 by default. It reads its settings +from these environment variables: -- `WRITEBOOK_MCP_INSTANCE`: the URL of your Writebook. Required. +- `WRITEBOOK_MCP_INSTANCE`: the URL of your Writebook. +- `WRITEBOOK_MCP_PUBLIC_URL`: the server's https address. Your Writebook's + `MCP_SERVER_URL` is this address followed by `/mcp`. +- `WRITEBOOK_MCP_SECRET`: the secret, the same as your Writebook's + `MCP_SERVER_SECRET`. - `WRITEBOOK_MCP_READ_ONLY=true`: serve only the tools that read. -- `WRITEBOOK_MCP_PUBLIC_URL`: the server's address, if the proxy in front of - it doesn't pass on the original `Host` header. ONCE doesn't need it. + +The server checks the secret with your Writebook when it starts, and stops if +Writebook doesn't accept it. ## Behind another proxy -The server uses plain HTTP, so put it behind a proxy that handles TLS. The -proxy must: +Set `MCP_SERVER_URL` and `MCP_SERVER_SECRET` on your Writebook as above, then +start the server with the same settings, as flags or environment variables: -- pass on the original `Host` header, -- send `X-Forwarded-Proto: https`, -- pass on the `Authorization` header. +```sh +WRITEBOOK_MCP_SECRET= writebook mcp serve \ + --instance https://books.example.com --public-url https://mcp.example.com +``` -If the proxy can't pass on the `Host` header, start the server with -`--public-url https://mcp.example.com`. +The secret can only be set with the environment variable. +The server uses plain HTTP and listens on `127.0.0.1:8080`, so put it behind a +proxy that handles TLS. The proxy must pass on the `Authorization` header. `GET /up` returns 200 without a token. Use it for health checks. -### kamal-proxy - -kamal-proxy passes on the `Host` header, sends `X-Forwarded-Proto`, and checks -`/up` before it sends traffic to the server. You don't need to change anything. -Don't deploy the server with `--path-prefix`. - -### Caddy - -Caddy passes on the `Host` header and sends `X-Forwarded-Proto` by default: +With kamal-proxy, deploy it as it is, without `--path-prefix`. With Caddy: ``` mcp.example.com { @@ -59,18 +75,13 @@ mcp.example.com { } ``` -### Apache - -Apache doesn't pass on the `Host` header or send `X-Forwarded-Proto` by -default. Turn on `mod_proxy`, `mod_proxy_http` and `mod_headers`, and set both: +With Apache, turn on `mod_proxy` and `mod_proxy_http`: ```apache ServerName mcp.example.com # your TLS settings - ProxyPreserveHost On - RequestHeader set X-Forwarded-Proto "https" ProxyPass / http://127.0.0.1:8080/ ProxyPassReverse / http://127.0.0.1:8080/ diff --git a/skills/writebook/SKILL.md b/skills/writebook/SKILL.md index 38778d7..121327c 100644 --- a/skills/writebook/SKILL.md +++ b/skills/writebook/SKILL.md @@ -287,16 +287,15 @@ claude mcp add writebook -- writebook mcp To give other people's agents access to one instance, run it as a server: ```sh -writebook mcp serve --instance https://books.example.com --bind 0.0.0.0:8080 +WRITEBOOK_MCP_SECRET= writebook mcp serve \ + --instance https://books.example.com --public-url https://mcp.example.com ``` -The server doesn't use the user's sign-in. Each request to `/mcp` must send a -Writebook token as a Bearer header. Agents that sign in with OAuth are sent to -the instance to sign in. If the server is behind a proxy that doesn't pass on -the original `Host` header, start it with `--public-url` and the server's -https address. The server sends the token only to that instance. The -server uses plain HTTP, so put it behind https unless it listens only on this -computer. The Docker image `ghcr.io/basecamp/writebook-cli` runs this +The server doesn't use the user's sign-in. Agents sign in to the instance with +OAuth, and the instance issues them tokens that only this server accepts. The +instance needs `MCP_SERVER_URL` set to the public URL followed by `/mcp`, and +`MCP_SERVER_SECRET` set to the same secret. The server uses plain HTTP, so put +it behind https. The Docker image `ghcr.io/basecamp/writebook-cli` runs this server on port 80 unless you give it another command. If you already use the CLI, you don't need the MCP server. diff --git a/src/main.rs b/src/main.rs index 18ee96f..b8ce3d5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -178,7 +178,7 @@ enum Command { #[derive(Subcommands)] enum McpCommand { #[usage( - help = "Serve one instance over HTTP at /mcp. Each request to /mcp must include the caller's Writebook token as a Bearer header. Agents that sign in with OAuth are sent to the instance to sign in. The server uses plain HTTP, so put it behind https unless it only listens on this computer" + help = "Serve one instance over HTTP at /mcp. Agents sign in to the instance with OAuth, and the server exchanges their tokens with the instance using the secret in WRITEBOOK_MCP_SECRET, which must match the instance's MCP_SERVER_SECRET. The server uses plain HTTP, so put it behind https" )] Serve { #[usage(help = "The instance alias or URL to serve (defaults to the default instance)")] @@ -188,10 +188,10 @@ enum McpCommand { #[usage(long, env = "WRITEBOOK_MCP_BIND", default = "127.0.0.1:8080")] bind: String, #[usage( - help = "The address clients reach the server at, like https://mcp.example.com, when a proxy doesn't pass on the original Host" + help = "The https address clients reach the server at, like https://mcp.example.com. Your Writebook's MCP_SERVER_URL is this address followed by /mcp" )] #[usage(long, env = "WRITEBOOK_MCP_PUBLIC_URL")] - public_url: Option, + public_url: String, }, } @@ -466,7 +466,7 @@ fn run(cli: Cli) -> Result<()> { instance, bind, public_url, - }) => mcp::serve(instance.as_deref(), read_only, &bind, public_url.as_deref()), + }) => mcp::serve(instance.as_deref(), read_only, &bind, &public_url), }, Command::Tui => tui::run(), Command::Setup => setup::run(), diff --git a/src/mcp.rs b/src/mcp.rs index b606faa..0b7c075 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -6,6 +6,7 @@ //! token. The server sends that token only to that instance and uses no //! stored login, so a request without a token can't use anyone else's. +mod exchange; mod log; mod tools; @@ -23,14 +24,14 @@ use rmcp::transport::streamable_http_server::{ StreamableHttpServerConfig, StreamableHttpService, session::never::NeverSessionManager, }; use rmcp::{ErrorData, RoleServer, ServerHandler, ServiceExt}; -use sha2::Digest; use std::time::Instant; use crate::inventory::{self, Inventory}; use crate::web::Web; use crate::{api, creds}; +use exchange::{Exchange, Exchanged}; -const ACCEPTED_FOR: std::time::Duration = std::time::Duration::from_secs(60); +const SECRET_VARIABLE: &str = "WRITEBOOK_MCP_SECRET"; pub fn run(read_only: bool) -> Result<()> { let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build()?; @@ -39,20 +40,23 @@ pub fn run(read_only: bool) -> Result<()> { runtime.block_on(serve_stdio(read_only)) } -pub fn serve(instance: Option<&str>, read_only: bool, bind: &str, public_url: Option<&str>) -> Result<()> { +pub fn serve(instance: Option<&str>, read_only: bool, bind: &str, public_url: &str) -> Result<()> { let host = inventory::host(instance)?; creds::ensure_private_connection(&host)?; - let public_url = match public_url { - Some(url) => Some(origin(url).context( - "--public-url takes the address clients reach the server at, with no path, like https://mcp.example.com", - )?), - None => None, - }; + let public_url = origin(public_url).context( + "--public-url takes the https address clients reach the server at, with no path, like https://mcp.example.com", + )?; + let secret = std::env::var(SECRET_VARIABLE) + .ok() + .filter(|it| !it.is_empty()) + .with_context(|| format!("set {SECRET_VARIABLE} to the MCP_SERVER_SECRET your Writebook has"))?; + let exchange = Exchange::new(host.clone(), secret); + exchange.check_secret()?; let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build()?; log::start(); - runtime.block_on(serve_http(host, read_only, bind, public_url)) + runtime.block_on(serve_http(host, read_only, bind, public_url, exchange)) } fn origin(url: &str) -> Option { @@ -94,14 +98,20 @@ async fn serve_stdio(read_only: bool) -> Result<()> { Ok(()) } -async fn serve_http(host: String, read_only: bool, address: &str, public_url: Option) -> Result<()> { +async fn serve_http( + host: String, + read_only: bool, + address: &str, + public_url: String, + exchange: Exchange, +) -> Result<()> { let listener = tokio::net::TcpListener::bind(address) .await .with_context(|| format!("could not listen on {address}"))?; let gate = Gate { - writebook: host.clone(), + exchange, public_url, - accepted: Default::default(), + writebook: host.clone(), }; let logged = host.clone(); let writebook = Writebook { @@ -127,23 +137,14 @@ async fn serve_http(host: String, read_only: bool, address: &str, public_url: Op .with_json_response(true); let service: StreamableHttpService = StreamableHttpService::new(move || Ok(writebook.clone()), Default::default(), config); - let root = gate.clone(); - let mcp = gate.clone(); + let metadata = gate.clone(); let router = axum::Router::new() .route_service("/mcp", service) .route_layer(middleware::from_fn_with_state(gate, require_token)) .route("/up", axum::routing::get(|| async { "ok\n" })) - .route( - "/.well-known/oauth-protected-resource", - axum::routing::get( - move |headers: axum::http::HeaderMap| async move { root.resource_metadata(&headers, "") }, - ), - ) .route( "/.well-known/oauth-protected-resource/mcp", - axum::routing::get( - move |headers: axum::http::HeaderMap| async move { mcp.resource_metadata(&headers, "/mcp") }, - ), + axum::routing::get(move || async move { metadata.resource_metadata() }), ) .layer(middleware::from_fn(log_request)); @@ -168,86 +169,39 @@ async fn log_request(request: Request, next: Next) -> Response { async fn require_token( axum::extract::State(gate): axum::extract::State, - request: Request, + mut request: Request, next: Next, ) -> Response { match bearer(request.headers()) { - None => gate.challenge(request.headers(), None, "a Writebook token is required\n"), - Some(token) => match gate.check(token).await { - Check::Accepted => next.run(request).await, - Check::Rejected => gate.challenge( - request.headers(), - Some("invalid_token"), - "Writebook did not accept this token\n", - ), - Check::Failed => (StatusCode::BAD_GATEWAY, "could not check the token with Writebook\n").into_response(), + None => gate.challenge(None, "a Writebook token is required\n"), + Some(token) => match gate.exchange.for_api(token).await { + Exchanged::Token(token) => { + request.extensions_mut().insert(token); + next.run(request).await + } + Exchanged::Refused => gate.challenge(Some("invalid_token"), "Writebook did not accept this token\n"), + Exchanged::Failed => { + (StatusCode::BAD_GATEWAY, "could not check the token with Writebook\n").into_response() + } }, } } -enum Check { - Accepted, - Rejected, - Failed, -} - #[derive(Clone)] struct Gate { + exchange: Exchange, + public_url: String, writebook: String, - public_url: Option, - accepted: std::sync::Arc>>, } impl Gate { - async fn check(&self, token: String) -> Check { - let digest: [u8; 32] = sha2::Sha256::digest(token.as_bytes()).into(); - - if self.recently_accepted(&digest) { - Check::Accepted - } else { - let writebook = self.writebook.clone(); - let answer = tokio::task::spawn_blocking(move || { - api::agent() - .get(&format!("{writebook}/books.json")) - .header("Authorization", &format!("Bearer {token}")) - .header("Accept", "application/json") - .call() - .map(|it| it.status().as_u16()) - }) - .await; - - match answer { - Ok(Ok(401)) => Check::Rejected, - Ok(Ok(status)) if (200..300).contains(&status) => { - self.remember(digest); - Check::Accepted - } - _ => Check::Failed, - } - } - } - - fn recently_accepted(&self, digest: &[u8; 32]) -> bool { - match self.accepted.lock() { - Ok(accepted) => accepted.get(digest).is_some_and(|it| it.elapsed() < ACCEPTED_FOR), - Err(_) => false, - } - } - - fn remember(&self, digest: [u8; 32]) { - if let Ok(mut accepted) = self.accepted.lock() { - accepted.retain(|_, at| at.elapsed() < ACCEPTED_FOR); - accepted.insert(digest, Instant::now()); - } - } - // https://www.rfc-editor.org/rfc/rfc9728#section-5.1 - fn challenge(&self, headers: &axum::http::HeaderMap, error: Option<&str>, message: &'static str) -> Response { + fn challenge(&self, error: Option<&str>, message: &'static str) -> Response { let error = error.map(|it| format!(r#"error="{it}", "#)).unwrap_or_default(); - let challenge = match self.public_url(headers) { - Some(url) => format!(r#"Bearer {error}resource_metadata="{url}/.well-known/oauth-protected-resource/mcp""#), - None => format!("Bearer {error}").trim_end_matches([',', ' ']).to_string(), - }; + let challenge = format!( + r#"Bearer {error}resource_metadata="{}/.well-known/oauth-protected-resource/mcp""#, + self.public_url + ); ( StatusCode::UNAUTHORIZED, @@ -257,40 +211,16 @@ impl Gate { .into_response() } - // The resource is the path the metadata was asked for under, so the bare - // well-known path describes the server's root. - // https://www.rfc-editor.org/rfc/rfc9728#section-3.3 - fn resource_metadata(&self, headers: &axum::http::HeaderMap, path: &str) -> Response { - match self.public_url(headers) { - Some(url) => { - let metadata = serde_json::json!({ - "resource": format!("{url}{path}"), - "resource_name": "Writebook", - "authorization_servers": [self.writebook], - "scopes_supported": ["read", "write"], - "bearer_methods_supported": ["header"], - }); - - ([(header::CONTENT_TYPE, "application/json")], metadata.to_string()).into_response() - } - None => (StatusCode::BAD_REQUEST, "a Host header is required\n").into_response(), - } - } + fn resource_metadata(&self) -> Response { + let metadata = serde_json::json!({ + "resource": format!("{}/mcp", self.public_url), + "resource_name": "Writebook", + "authorization_servers": [self.writebook], + "scopes_supported": ["read", "write"], + "bearer_methods_supported": ["header"], + }); - fn public_url(&self, headers: &axum::http::HeaderMap) -> Option { - match &self.public_url { - Some(url) => Some(url.clone()), - None => { - let forwarded = headers.get("x-forwarded-proto").and_then(|it| it.to_str().ok()); - let scheme = match forwarded.and_then(|it| it.split(',').next()).map(str::trim) { - Some("https") => "https", - _ => "http", - }; - let host = headers.get(header::HOST)?.to_str().ok()?; - - origin(&format!("{scheme}://{host}")) - } - } + ([(header::CONTENT_TYPE, "application/json")], metadata.to_string()).into_response() } } @@ -408,11 +338,11 @@ impl ServerHandler for Writebook { Origin::Served { host } => match context .extensions .get::() - .and_then(|parts| bearer(&parts.headers)) + .and_then(|parts| parts.extensions.get::()) { Some(token) => Some(Connection { host: host.clone(), - caller_token: Some(token), + caller_token: Some(token.0.clone()), }), None => return Ok(failure("a Writebook token is required").into()), }, diff --git a/src/mcp/exchange.rs b/src/mcp/exchange.rs new file mode 100644 index 0000000..1f6dc71 --- /dev/null +++ b/src/mcp/exchange.rs @@ -0,0 +1,152 @@ +//! Swaps the tokens MCP clients send, which Writebook issues for this server +//! only, for short-lived Writebook API tokens (RFC 8693). The server never +//! passes a client's own token on to Writebook. + +use anyhow::{Result, bail}; +use serde_json::Value; +use sha2::Digest; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use crate::api; + +const CLIENT_ID: &str = "writebook-mcp-server"; +const GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:token-exchange"; +const ACCESS_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token"; +const REFUSED_FOR: Duration = Duration::from_secs(60); +const RENEW_BEFORE: Duration = Duration::from_secs(15); +const REMEMBERED: usize = 10_000; + +type TokenDigest = [u8; 32]; + +/// A Writebook API token the exchange handed out for one request's caller. +#[derive(Clone)] +pub struct ApiToken(pub String); + +pub enum Exchanged { + Token(ApiToken), + Refused, + Failed, +} + +#[derive(Clone)] +pub struct Exchange { + writebook: String, + secret: Arc, + issued: Arc>>, + refused: Arc>>, +} + +impl Exchange { + pub fn new(writebook: String, secret: String) -> Exchange { + Exchange { + writebook, + secret: Arc::new(secret), + issued: Default::default(), + refused: Default::default(), + } + } + + /// Writebook answers a made-up token with invalid_grant only once the + /// secret checks out, so a wrong secret stops the server before it starts. + pub fn check_secret(&self) -> Result<()> { + let (status, body) = self.post("wb_at_checking_the_secret")?; + + match (status, body["error"].as_str()) { + (400, Some("invalid_grant")) => Ok(()), + (401, _) => bail!( + "{} didn't accept WRITEBOOK_MCP_SECRET. Set it to the MCP_SERVER_SECRET your Writebook has", + self.writebook + ), + (_, Some("unsupported_grant_type")) => bail!( + "{} can't exchange tokens for an MCP server. Update it to a Writebook that can", + self.writebook + ), + _ => bail!( + "{} answered {status} when the MCP server checked its secret", + self.writebook + ), + } + } + + pub async fn for_api(&self, token: String) -> Exchanged { + let digest: TokenDigest = sha2::Sha256::digest(token.as_bytes()).into(); + + if let Some(issued) = self.issued_for(&digest) { + Exchanged::Token(issued) + } else if self.recently_refused(&digest) { + Exchanged::Refused + } else { + let exchange = self.clone(); + let answer = tokio::task::spawn_blocking(move || exchange.post(&token)).await; + + match answer { + Ok(Ok((200, body))) => match (body["access_token"].as_str(), body["expires_in"].as_u64()) { + (Some(issued), Some(expires_in)) => { + let issued = ApiToken(issued.to_string()); + self.remember_issued(digest, issued.clone(), Duration::from_secs(expires_in)); + Exchanged::Token(issued) + } + _ => Exchanged::Failed, + }, + Ok(Ok((400, body))) if body["error"] == "invalid_grant" => { + self.remember_refused(digest); + Exchanged::Refused + } + _ => Exchanged::Failed, + } + } + } + + fn post(&self, subject: &str) -> Result<(u16, Value)> { + let mut response = api::agent() + .post(&format!("{}/oauth/tokens", self.writebook)) + .send_form([ + ("grant_type", GRANT_TYPE), + ("client_id", CLIENT_ID), + ("client_secret", self.secret.as_str()), + ("subject_token", subject), + ("subject_token_type", ACCESS_TOKEN_TYPE), + ])?; + + let status = response.status().as_u16(); + let body = response.body_mut().read_json().unwrap_or(Value::Null); + Ok((status, body)) + } + + fn issued_for(&self, digest: &TokenDigest) -> Option { + let issued = self.issued.lock().unwrap_or_else(PoisonError::into_inner); + let (token, until) = issued.get(digest)?; + + if Instant::now() + RENEW_BEFORE < *until { + Some(token.clone()) + } else { + None + } + } + + fn remember_issued(&self, digest: TokenDigest, token: ApiToken, lasts: Duration) { + let mut issued = self.issued.lock().unwrap_or_else(PoisonError::into_inner); + let now = Instant::now(); + issued.retain(|_, (_, until)| *until > now); + if issued.len() >= REMEMBERED { + issued.clear(); + } + issued.insert(digest, (token, now + lasts)); + } + + fn recently_refused(&self, digest: &TokenDigest) -> bool { + let refused = self.refused.lock().unwrap_or_else(PoisonError::into_inner); + refused.get(digest).is_some_and(|it| it.elapsed() < REFUSED_FOR) + } + + fn remember_refused(&self, digest: TokenDigest) { + let mut refused = self.refused.lock().unwrap_or_else(PoisonError::into_inner); + refused.retain(|_, at| at.elapsed() < REFUSED_FOR); + if refused.len() >= REMEMBERED { + refused.clear(); + } + refused.insert(digest, Instant::now()); + } +} diff --git a/tests/mcp.rs b/tests/mcp.rs index f3778ae..e26da1c 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -7,10 +7,13 @@ mod support; use serde_json::{Value, json}; +use std::collections::HashMap; use std::io::{BufRead, BufReader, Write}; use std::process::{Child, ChildStdout, Command, Stdio}; use support::{Server, reply, tempdir}; +const SECRET: &str = "the secret the MCP server and Writebook share"; + #[test] fn reads_and_changes_pages_on_stdio() { let server = fake_writebook(); @@ -264,7 +267,11 @@ fn serves_each_http_caller_with_their_own_token() { .into_iter() .find(|it| it.path == "/books.json") .unwrap(); - assert_eq!(books.header("Authorization"), Some("Bearer wb_at_alice")); + assert_eq!( + books.header("Authorization"), + Some("Bearer wb_at_alice_exchanged"), + "tools use the exchanged token, never the client's own" + ); let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); let revoked = agent @@ -315,8 +322,13 @@ fn serves_each_http_caller_with_their_own_token() { fn fake_writebook() -> Server { Server::start(|request| match (request.method.as_str(), request.path.as_str()) { + ("POST", "/oauth/tokens") => exchange(&request.body), _ if request.header("Authorization") == Some("Bearer wb_at_revoked") => reply(401, ""), - ("PATCH", _) if request.header("Authorization") == Some("Bearer wb_at_reader") => { + ("PATCH", _) + if request + .header("Authorization") + .is_some_and(|it| it.starts_with("Bearer wb_at_reader")) => + { let mut refused = reply(403, ""); refused.headers.push(( "WWW-Authenticate", @@ -324,7 +336,11 @@ fn fake_writebook() -> Server { )); refused } - ("PATCH", _) if request.header("Authorization") == Some("Bearer wb_at_unnamed") => { + ("PATCH", _) + if request + .header("Authorization") + .is_some_and(|it| it.starts_with("Bearer wb_at_unnamed")) => + { let mut refused = reply(403, ""); refused .headers @@ -467,6 +483,28 @@ impl Drop for Mcp { } } +fn exchange(body: &str) -> support::Reply { + let form: HashMap = url::form_urlencoded::parse(body.as_bytes()).into_owned().collect(); + let subject = form["subject_token"].as_str(); + + if form["grant_type"] != "urn:ietf:params:oauth:grant-type:token-exchange" + || form["client_id"] != "writebook-mcp-server" + { + reply(400, r#"{"error":"unsupported_grant_type"}"#) + } else if form["client_secret"] != SECRET { + reply(401, r#"{"error":"invalid_client"}"#) + } else if subject == "wb_at_broken" { + reply(500, "") + } else if subject == "wb_at_revoked" || subject == "wb_at_checking_the_secret" { + reply(400, r#"{"error":"invalid_grant"}"#) + } else { + reply( + 200, + &json!({ "access_token": format!("{subject}_exchanged"), "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", "token_type": "Bearer", "expires_in": 300, "scope": "read write" }).to_string(), + ) + } +} + fn instance(alias: &str, url: &str) -> String { format!("[instances.{alias}]\nurl = \"{url}\"\ndefault_profile = \"default\"\nprofiles = [\"default\"]\n") } @@ -492,29 +530,26 @@ fn points_mcp_clients_at_the_writebook_to_sign_in_with() { assert_eq!(anonymous.status().as_u16(), 401); assert_eq!( anonymous.headers().get("www-authenticate").unwrap().to_str().unwrap(), - format!(r#"Bearer resource_metadata="{base}/.well-known/oauth-protected-resource/mcp""#) + r#"Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp""# ); - for (path, resource) in [ - ("/.well-known/oauth-protected-resource/mcp", endpoint.as_str()), - ("/.well-known/oauth-protected-resource", base), - ] { - let mut response = agent.get(&format!("{base}{path}")).call().unwrap(); - assert_eq!(response.status().as_u16(), 200, "{path}"); - let metadata: Value = serde_json::from_str(&response.body_mut().read_to_string().unwrap()).unwrap(); - assert_eq!(metadata["resource"], json!(resource), "{path}"); - assert_eq!(metadata["authorization_servers"], json!([server.url])); - assert_eq!(metadata["scopes_supported"], json!(["read", "write"]), "{path}"); - assert_eq!(metadata["bearer_methods_supported"], json!(["header"]), "{path}"); - } - - let mut behind_https = agent + let mut response = agent .get(&format!("{base}/.well-known/oauth-protected-resource/mcp")) - .header("X-Forwarded-Proto", "https, http") + .header("Host", "upstream") .call() .unwrap(); - let metadata: Value = serde_json::from_str(&behind_https.body_mut().read_to_string().unwrap()).unwrap(); - assert_eq!(metadata["resource"], json!(endpoint.replace("http://", "https://"))); + assert_eq!(response.status().as_u16(), 200); + let metadata: Value = serde_json::from_str(&response.body_mut().read_to_string().unwrap()).unwrap(); + assert_eq!(metadata["resource"], json!("https://mcp.example.com/mcp")); + assert_eq!(metadata["authorization_servers"], json!([server.url])); + assert_eq!(metadata["scopes_supported"], json!(["read", "write"])); + assert_eq!(metadata["bearer_methods_supported"], json!(["header"])); + + let root = agent + .get(&format!("{base}/.well-known/oauth-protected-resource")) + .call() + .unwrap(); + assert_eq!(root.status().as_u16(), 404, "only /mcp is a resource"); let up = agent.get(&format!("{base}/up")).call().unwrap(); assert_eq!( @@ -523,67 +558,47 @@ fn points_mcp_clients_at_the_writebook_to_sign_in_with() { "proxies like kamal-proxy check /up before sending traffic" ); - let mut without_host = std::net::TcpStream::connect(base.trim_start_matches("http://")).unwrap(); - std::io::Write::write_all( - &mut without_host, - b"GET /.well-known/oauth-protected-resource/mcp HTTP/1.0\r\n\r\n", - ) - .unwrap(); - let mut answer = String::new(); - std::io::Read::read_to_string(&mut without_host, &mut answer).unwrap(); - assert!( - answer.starts_with("HTTP/1.0 400"), - "a request with no Host gets no made-up address" - ); - - for (token, challenge) in [ - (None, "Bearer"), - (Some("wb_at_revoked"), r#"Bearer error="invalid_token""#), - ] { - let authorization = token - .map(|it| format!("Authorization: Bearer {it}\r\n")) - .unwrap_or_default(); - let mut without_host = std::net::TcpStream::connect(base.trim_start_matches("http://")).unwrap(); - std::io::Write::write_all( - &mut without_host, - format!("POST /mcp HTTP/1.0\r\n{authorization}Content-Length: 0\r\n\r\n").as_bytes(), - ) + let revoked = agent + .post(&endpoint) + .header("Authorization", "Bearer wb_at_revoked") + .send_json(initialize()) .unwrap(); - let mut answer = String::new(); - std::io::Read::read_to_string(&mut without_host, &mut answer).unwrap(); - assert!(answer.starts_with("HTTP/1.0 401"), "{answer}"); - assert!( - answer - .to_lowercase() - .contains(&format!("www-authenticate: {}\r\n", challenge.to_lowercase())), - "{answer}" - ); - } + assert_eq!(revoked.status().as_u16(), 401); + assert_eq!( + revoked.headers().get("www-authenticate").unwrap().to_str().unwrap(), + r#"Bearer error="invalid_token", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp""# + ); child.kill().unwrap(); child.wait().unwrap(); } #[test] -fn checks_a_token_with_writebook_once_a_minute() { +fn exchanges_a_token_once_until_the_exchanged_one_runs_out() { let server = fake_writebook(); let config = tempdir(); let (mut child, _logs, endpoint) = serve(&server, &config, &[], &[]); - for id in 1..=3 { + for token in ["wb_at_bob", "wb_at_bob", "wb_at_bob", "wb_at_revoked", "wb_at_revoked"] { post( &endpoint, - Some("wb_at_bob"), - &json!({ "jsonrpc": "2.0", "id": id, "method": "tools/list" }), + Some(token), + &json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }), ); } - let checks = server + let exchanges: Vec = server .requests() .into_iter() - .filter(|it| it.path == "/books.json" && it.header("Authorization") == Some("Bearer wb_at_bob")) - .count(); - assert_eq!(checks, 1); + .filter(|it| it.path == "/oauth/tokens" && !it.body.contains("checking_the_secret")) + .map(|it| it.body) + .collect(); + assert_eq!(exchanges.len(), 2, "{exchanges:?}"); + assert!(exchanges[0].contains("subject_token=wb_at_bob"), "{exchanges:?}"); + assert!( + exchanges[1].contains("subject_token=wb_at_revoked"), + "a refused token is remembered too" + ); child.kill().unwrap(); child.wait().unwrap(); @@ -613,17 +628,17 @@ fn tells_a_read_only_connection_to_reconnect_to_change_books() { fn serves_only_the_tools_that_read_however_read_only_is_set() { let server = fake_writebook(); let config = tempdir(); - let ways: [(&[&str], &[(&str, &str)]); 3] = [ + let ways = [ ( - &["mcp", "serve", "--bind", "127.0.0.1:0"], - &[("WRITEBOOK_MCP_READ_ONLY", "true")], + vec!["mcp", "serve", "--bind", "127.0.0.1:0"], + vec![("WRITEBOOK_MCP_READ_ONLY", "true")], ), - (&["mcp", "--read-only", "serve", "--bind", "127.0.0.1:0"], &[]), - (&["mcp", "serve", "--bind", "127.0.0.1:0", "--read-only"], &[]), + (vec!["mcp", "--read-only", "serve", "--bind", "127.0.0.1:0"], vec![]), + (vec!["mcp", "serve", "--bind", "127.0.0.1:0", "--read-only"], vec![]), ]; for (args, envs) in ways { - let (mut child, _logs, endpoint) = serve_with(&server.url, &config, args, envs); + let (mut child, _logs, endpoint) = serve_with(&server.url, &config, &args, &envs); let (_, tools) = post( &endpoint, Some("wb_at_alice"), @@ -658,16 +673,14 @@ fn listens_where_the_environment_says() { } #[test] -fn answers_502_when_it_cant_check_a_token_with_writebook() { - let unreachable = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let instance = format!("http://{}", unreachable.local_addr().unwrap()); - drop(unreachable); +fn answers_502_when_writebook_fails_to_exchange_a_token() { + let server = fake_writebook(); let config = tempdir(); - let (mut child, _logs, endpoint) = serve_with(&instance, &config, &["mcp", "serve", "--bind", "127.0.0.1:0"], &[]); + let (mut child, _logs, endpoint) = serve(&server, &config, &[], &[]); let (status, answer) = post( &endpoint, - Some("wb_at_alice"), + Some("wb_at_broken"), &json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }), ); assert_eq!(status, 502, "{answer}"); @@ -678,33 +691,27 @@ fn answers_502_when_it_cant_check_a_token_with_writebook() { } #[test] -fn names_the_public_url_a_proxy_hides() { +fn wont_start_without_a_secret_writebook_accepts() { let server = fake_writebook(); - let config = tempdir(); - let (mut child, _logs, endpoint) = serve( - &server, - &config, - &[], - &[("WRITEBOOK_MCP_PUBLIC_URL", "https://mcp.example.com/")], - ); - let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); - - let anonymous = agent.post(&endpoint).send_json(initialize()).unwrap(); - assert_eq!( - anonymous.headers().get("www-authenticate").unwrap().to_str().unwrap(), - r#"Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp""# - ); - - let mut response = agent - .get(&endpoint.replace("/mcp", "/.well-known/oauth-protected-resource/mcp")) - .header("Host", "upstream") - .call() - .unwrap(); - let metadata: Value = serde_json::from_str(&response.body_mut().read_to_string().unwrap()).unwrap(); - assert_eq!(metadata["resource"], json!("https://mcp.example.com/mcp")); - - child.kill().unwrap(); - child.wait().unwrap(); + let serve = |envs: &[(&str, &str)]| { + let mut command = Command::new(env!("CARGO_BIN_EXE_writebook")); + command + .args(["mcp", "serve", "--bind", "127.0.0.1:0", "--instance", &server.url]) + .args(["--public-url", "https://mcp.example.com"]) + .env_remove("WRITEBOOK_MCP_SECRET") + .envs(envs.iter().copied()) + .env("XDG_CONFIG_HOME", tempdir()) + .env("WRITEBOOK_NO_KEYRING", "1"); + command.output().unwrap() + }; + + let without = serve(&[]); + assert!(!without.status.success()); + assert!(String::from_utf8_lossy(&without.stderr).contains("set WRITEBOOK_MCP_SECRET")); + + let wrong = serve(&[("WRITEBOOK_MCP_SECRET", "not the secret")]); + assert!(!wrong.status.success()); + assert!(String::from_utf8_lossy(&wrong.stderr).contains("didn't accept WRITEBOOK_MCP_SECRET")); } fn serve( @@ -733,6 +740,8 @@ fn serve_with( .env_remove("WRITEBOOK_MCP_BIND") .env_remove("WRITEBOOK_MCP_PUBLIC_URL") .env("WRITEBOOK_MCP_INSTANCE", instance) + .env("WRITEBOOK_MCP_PUBLIC_URL", "https://mcp.example.com") + .env("WRITEBOOK_MCP_SECRET", SECRET) .envs(envs.iter().copied()) .env("XDG_CONFIG_HOME", config) .env("WRITEBOOK_NO_KEYRING", "1") From d7ffceaae797b23def7c21f47a0e07f382a50e1b Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 17:49:49 +0100 Subject: [PATCH 20/21] Fix the review's findings on the token exchange --public-url must be https unless it's this machine. An expiry Writebook can't mean is a failed exchange instead of a crash. The startup check says which host it couldn't reach, and a 401 names every cause Writebook has for it. An unreadable inventory no longer reads as a WRITEBOOK_TOKEN sign-in. New tests cover the http warning, exchanging a token again before it runs out, and the sign-in command a refusal names for a stored profile. --- src/creds.rs | 9 +++++---- src/mcp.rs | 8 +++++--- src/mcp/exchange.rs | 32 ++++++++++++++--------------- tests/mcp.rs | 27 ++++++++++++++++++++++--- tests/read_only.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 99 insertions(+), 26 deletions(-) diff --git a/src/creds.rs b/src/creds.rs index 16ded88..a30d2e5 100644 --- a/src/creds.rs +++ b/src/creds.rs @@ -188,7 +188,7 @@ pub fn normalize_host(host: &str) -> String { host.trim().trim_end_matches('/').to_lowercase() } -fn is_local(host: &str) -> bool { +pub fn is_local(host: &str) -> bool { let name = host.trim_start_matches("http://").split(':').next().unwrap_or_default(); matches!(name, "localhost" | "127.0.0.1") || host.trim_start_matches("http://").starts_with("[::1]") } @@ -310,9 +310,10 @@ pub fn sign_in_again_command(host: &str) -> Option { if GIVEN_TOKEN.get().is_some() { None } else { - inventory::profile_for(host) - .ok() - .map(|profile| inventory::sign_in_command(host, &profile)) + match inventory::profile_for(host) { + Ok(profile) => Some(inventory::sign_in_command(host, &profile)), + Err(_) => Some(format!("writebook instance add {host}")), + } } } diff --git a/src/mcp.rs b/src/mcp.rs index 0b7c075..6ab9f66 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -43,9 +43,11 @@ pub fn run(read_only: bool) -> Result<()> { pub fn serve(instance: Option<&str>, read_only: bool, bind: &str, public_url: &str) -> Result<()> { let host = inventory::host(instance)?; creds::ensure_private_connection(&host)?; - let public_url = origin(public_url).context( - "--public-url takes the https address clients reach the server at, with no path, like https://mcp.example.com", - )?; + let public_url = origin(public_url) + .filter(|it| it.starts_with("https://") || creds::is_local(it)) + .context( + "--public-url takes the https address clients reach the server at, with no path, like https://mcp.example.com", + )?; let secret = std::env::var(SECRET_VARIABLE) .ok() .filter(|it| !it.is_empty()) diff --git a/src/mcp/exchange.rs b/src/mcp/exchange.rs index 1f6dc71..9355662 100644 --- a/src/mcp/exchange.rs +++ b/src/mcp/exchange.rs @@ -1,8 +1,4 @@ -//! Swaps the tokens MCP clients send, which Writebook issues for this server -//! only, for short-lived Writebook API tokens (RFC 8693). The server never -//! passes a client's own token on to Writebook. - -use anyhow::{Result, bail}; +use anyhow::{Context, Result, bail}; use serde_json::Value; use sha2::Digest; use std::collections::HashMap; @@ -56,11 +52,7 @@ impl Exchange { match (status, body["error"].as_str()) { (400, Some("invalid_grant")) => Ok(()), (401, _) => bail!( - "{} didn't accept WRITEBOOK_MCP_SECRET. Set it to the MCP_SERVER_SECRET your Writebook has", - self.writebook - ), - (_, Some("unsupported_grant_type")) => bail!( - "{} can't exchange tokens for an MCP server. Update it to a Writebook that can", + "{} didn't accept WRITEBOOK_MCP_SECRET. Check that your Writebook is up to date, that its MCP_SERVER_URL is set, and that its MCP_SERVER_SECRET is at least 32 characters and the same as WRITEBOOK_MCP_SECRET", self.writebook ), _ => bail!( @@ -70,6 +62,8 @@ impl Exchange { } } + /// A Writebook API token for the caller (RFC 8693). The caller's own token + /// only goes to the instance's /oauth/tokens. pub async fn for_api(&self, token: String) -> Exchanged { let digest: TokenDigest = sha2::Sha256::digest(token.as_bytes()).into(); @@ -84,9 +78,14 @@ impl Exchange { match answer { Ok(Ok((200, body))) => match (body["access_token"].as_str(), body["expires_in"].as_u64()) { (Some(issued), Some(expires_in)) => { - let issued = ApiToken(issued.to_string()); - self.remember_issued(digest, issued.clone(), Duration::from_secs(expires_in)); - Exchanged::Token(issued) + match Instant::now().checked_add(Duration::from_secs(expires_in)) { + Some(until) => { + let issued = ApiToken(issued.to_string()); + self.remember_issued(digest, issued.clone(), until); + Exchanged::Token(issued) + } + None => Exchanged::Failed, + } } _ => Exchanged::Failed, }, @@ -108,7 +107,8 @@ impl Exchange { ("client_secret", self.secret.as_str()), ("subject_token", subject), ("subject_token_type", ACCESS_TOKEN_TYPE), - ])?; + ]) + .with_context(|| format!("could not reach {}", self.writebook))?; let status = response.status().as_u16(); let body = response.body_mut().read_json().unwrap_or(Value::Null); @@ -126,14 +126,14 @@ impl Exchange { } } - fn remember_issued(&self, digest: TokenDigest, token: ApiToken, lasts: Duration) { + fn remember_issued(&self, digest: TokenDigest, token: ApiToken, until: Instant) { let mut issued = self.issued.lock().unwrap_or_else(PoisonError::into_inner); let now = Instant::now(); issued.retain(|_, (_, until)| *until > now); if issued.len() >= REMEMBERED { issued.clear(); } - issued.insert(digest, (token, now + lasts)); + issued.insert(digest, (token, until)); } fn recently_refused(&self, digest: &TokenDigest) -> bool { diff --git a/tests/mcp.rs b/tests/mcp.rs index e26da1c..b394d2c 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -197,6 +197,7 @@ fn takes_a_public_url_only_as_an_origin() { "mcp.example.com", "https://mcp.example.com/mcp", "ftp://mcp.example.com", + "http://mcp.example.com", ] { let output = support::writebook( &[ @@ -315,6 +316,13 @@ fn serves_each_http_caller_with_their_own_token() { "{rest}" ); + assert!( + events + .iter() + .any(|it| it["event"] == "unencrypted_instance" && it["level"] == "WARN"), + "an instance on plain http gets a warning: {rest}" + ); + for word in ["wb_at_alice", "wb_at_revoked", "127.0.0.1", "Handbook"] { assert!(!rest.contains(word), "the logs mention a token, an address or a title"); } @@ -498,9 +506,10 @@ fn exchange(body: &str) -> support::Reply { } else if subject == "wb_at_revoked" || subject == "wb_at_checking_the_secret" { reply(400, r#"{"error":"invalid_grant"}"#) } else { + let expires_in = if subject == "wb_at_brief" { 10 } else { 300 }; reply( 200, - &json!({ "access_token": format!("{subject}_exchanged"), "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", "token_type": "Bearer", "expires_in": 300, "scope": "read write" }).to_string(), + &json!({ "access_token": format!("{subject}_exchanged"), "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", "token_type": "Bearer", "expires_in": expires_in, "scope": "read write" }).to_string(), ) } } @@ -579,7 +588,15 @@ fn exchanges_a_token_once_until_the_exchanged_one_runs_out() { let config = tempdir(); let (mut child, _logs, endpoint) = serve(&server, &config, &[], &[]); - for token in ["wb_at_bob", "wb_at_bob", "wb_at_bob", "wb_at_revoked", "wb_at_revoked"] { + for token in [ + "wb_at_bob", + "wb_at_bob", + "wb_at_bob", + "wb_at_revoked", + "wb_at_revoked", + "wb_at_brief", + "wb_at_brief", + ] { post( &endpoint, Some(token), @@ -593,12 +610,16 @@ fn exchanges_a_token_once_until_the_exchanged_one_runs_out() { .filter(|it| it.path == "/oauth/tokens" && !it.body.contains("checking_the_secret")) .map(|it| it.body) .collect(); - assert_eq!(exchanges.len(), 2, "{exchanges:?}"); + assert_eq!(exchanges.len(), 4, "{exchanges:?}"); assert!(exchanges[0].contains("subject_token=wb_at_bob"), "{exchanges:?}"); assert!( exchanges[1].contains("subject_token=wb_at_revoked"), "a refused token is remembered too" ); + assert!( + exchanges[2..].iter().all(|it| it.contains("subject_token=wb_at_brief")), + "a token about to run out is exchanged again: {exchanges:?}" + ); child.kill().unwrap(); child.wait().unwrap(); diff --git a/tests/read_only.rs b/tests/read_only.rs index 3d3d532..0b194b0 100644 --- a/tests/read_only.rs +++ b/tests/read_only.rs @@ -315,6 +315,55 @@ fn a_supplied_token_pushes_whatever_profile_is_picked() { assert!(stderr(&pushed).contains("index.md"), "{}", stderr(&pushed)); } +#[test] +fn a_refusal_names_the_command_that_signs_the_profile_in_again() { + let server = Server::start(|request| match request.path.as_str() { + "/oauth/device_authorizations" => support::device_authorization(request), + "/oauth/tokens" => reply( + 200, + r#"{"access_token":"wb_at_1","token_type":"Bearer","expires_in":3600,"refresh_token":"wb_rt_1","scope":"read write"}"#, + ), + "/books/4/manifest.json" => { + let mut refused = reply(403, ""); + refused.headers.push(( + "WWW-Authenticate", + r#"Bearer error="insufficient_scope", scope="read write""#.to_string(), + )); + refused + } + _ => reply(404, ""), + }); + let config = tempdir(); + let env = [("XDG_CONFIG_HOME", config.to_str().unwrap())]; + + writebook(&["instance", "add", &server.url], &env); + writebook(&["instance", "add", &server.url, "--code", "WXYZ-2345"], &env); + writebook(&["profile", "add", "editor"], &env); + let added = writebook(&["profile", "add", "editor", "--code", "WXYZ-2345"], &env); + assert!(added.status.success(), "{}", stderr(&added)); + + let checkout = tempdir().join("checkout"); + let cloned = writebook( + &[ + "--profile", + "editor", + "clone", + &format!("{}/4/handbook", server.url), + checkout.to_str().unwrap(), + ], + &env, + ); + assert!(!cloned.status.success()); + assert!( + stderr(&cloned).contains(&format!( + "Writebook says this sign-in can only read, so it can't change books. Sign in again with `writebook instance add {} --profile editor` and approve reading and changing books", + server.url.trim_start_matches("http://") + )), + "{}", + stderr(&cloned) + ); +} + fn fake_writebook(scope: &'static str) -> Server { fake_writebook_renewing(scope, scope) } From 5c547bb1400ca52866179b7fa679afc5dfbc9bfc Mon Sep 17 00:00:00 2001 From: "Stanko K.R." Date: Mon, 30 Nov 2026 17:59:24 +0100 Subject: [PATCH 21/21] Forget an exchanged token Writebook rejects, so the next request gets a 401 Revoking an app's token revokes what the server exchanged it for, but the server kept reusing its copy, so tools failed inside 200 answers for up to five minutes and clients never renewed. Found by revoking a token against a real Writebook. --- src/mcp.rs | 38 ++++++++++++++++++++------------------ src/mcp/exchange.rs | 9 ++++++++- tests/mcp.rs | 30 +++++++++++++++++++++++++++++- 3 files changed, 57 insertions(+), 20 deletions(-) diff --git a/src/mcp.rs b/src/mcp.rs index 6ab9f66..6181e89 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -111,13 +111,13 @@ async fn serve_http( .await .with_context(|| format!("could not listen on {address}"))?; let gate = Gate { - exchange, + exchange: exchange.clone(), public_url, writebook: host.clone(), }; let logged = host.clone(); let writebook = Writebook { - origin: Origin::Served { host }, + origin: Origin::Served { host, exchange }, read_only, }; @@ -244,7 +244,7 @@ struct Writebook { #[derive(Clone)] enum Origin { Inventory, - Served { host: String }, + Served { host: String, exchange: Exchange }, } /// What a tool needs to talk to an instance as the caller. @@ -302,7 +302,7 @@ impl ServerHandler for Writebook { Origin::Inventory => "Books on your Writebook instances. list_instances lists them, and every other tool \ takes one as instance, or uses the default one." .to_string(), - Origin::Served { host } => format!("Books on the Writebook at {host}."), + Origin::Served { host, .. } => format!("Books on the Writebook at {host}."), }; let changes = if self.read_only { "Nothing here can change a book." @@ -335,19 +335,18 @@ impl ServerHandler for Writebook { request: CallToolRequestParams, context: RequestContext, ) -> Result { - let served = match &self.origin { - Origin::Inventory => None, - Origin::Served { host } => match context - .extensions - .get::() - .and_then(|parts| parts.extensions.get::()) - { - Some(token) => Some(Connection { - host: host.clone(), - caller_token: Some(token.0.clone()), - }), - None => return Ok(failure("a Writebook token is required").into()), - }, + let api_token = context + .extensions + .get::() + .and_then(|parts| parts.extensions.get::()) + .cloned(); + let served = match (&self.origin, &api_token) { + (Origin::Inventory, _) => None, + (Origin::Served { host, .. }, Some(token)) => Some(Connection { + host: host.clone(), + caller_token: Some(token.0.clone()), + }), + (Origin::Served { .. }, None) => return Ok(failure("a Writebook token is required").into()), }; let read_only = self.read_only; @@ -369,7 +368,10 @@ impl ServerHandler for Writebook { )]), // The CLI's message for a rejected token tells you to sign in // again, which doesn't apply to a token sent over HTTP. - (Err(error), Origin::Served { host }) if error.downcast_ref::().is_some() => { + (Err(error), Origin::Served { host, exchange }) if error.downcast_ref::().is_some() => { + if let Some(token) = &api_token { + exchange.forget(token); + } failure(&format!("{host} did not accept your Writebook token")) } (Err(error), Origin::Served { .. }) => match error.downcast_ref::() { diff --git a/src/mcp/exchange.rs b/src/mcp/exchange.rs index 9355662..6656314 100644 --- a/src/mcp/exchange.rs +++ b/src/mcp/exchange.rs @@ -17,7 +17,7 @@ const REMEMBERED: usize = 10_000; type TokenDigest = [u8; 32]; /// A Writebook API token the exchange handed out for one request's caller. -#[derive(Clone)] +#[derive(Clone, PartialEq)] pub struct ApiToken(pub String); pub enum Exchanged { @@ -98,6 +98,13 @@ impl Exchange { } } + /// Writebook turned the token away, so the caller's next request is + /// exchanged again, and gets a 401 if Writebook refuses that too. + pub fn forget(&self, token: &ApiToken) { + let mut issued = self.issued.lock().unwrap_or_else(PoisonError::into_inner); + issued.retain(|_, (issued, _)| issued != token); + } + fn post(&self, subject: &str) -> Result<(u16, Value)> { let mut response = api::agent() .post(&format!("{}/oauth/tokens", self.writebook)) diff --git a/tests/mcp.rs b/tests/mcp.rs index b394d2c..7a22033 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -14,6 +14,8 @@ use support::{Server, reply, tempdir}; const SECRET: &str = "the secret the MCP server and Writebook share"; +static DISCONNECTED_ONCE_EXCHANGED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + #[test] fn reads_and_changes_pages_on_stdio() { let server = fake_writebook(); @@ -332,6 +334,7 @@ fn fake_writebook() -> Server { Server::start(|request| match (request.method.as_str(), request.path.as_str()) { ("POST", "/oauth/tokens") => exchange(&request.body), _ if request.header("Authorization") == Some("Bearer wb_at_revoked") => reply(401, ""), + _ if request.header("Authorization") == Some("Bearer wb_at_disconnected_exchanged") => reply(401, ""), ("PATCH", _) if request .header("Authorization") @@ -503,7 +506,11 @@ fn exchange(body: &str) -> support::Reply { reply(401, r#"{"error":"invalid_client"}"#) } else if subject == "wb_at_broken" { reply(500, "") - } else if subject == "wb_at_revoked" || subject == "wb_at_checking_the_secret" { + } else if subject == "wb_at_revoked" + || subject == "wb_at_checking_the_secret" + || (subject == "wb_at_disconnected" + && DISCONNECTED_ONCE_EXCHANGED.swap(true, std::sync::atomic::Ordering::SeqCst)) + { reply(400, r#"{"error":"invalid_grant"}"#) } else { let expires_in = if subject == "wb_at_brief" { 10 } else { 300 }; @@ -693,6 +700,27 @@ fn listens_where_the_environment_says() { child.wait().unwrap(); } +#[test] +fn a_token_writebook_stops_accepting_gets_a_401_on_the_next_request() { + let server = fake_writebook(); + let config = tempdir(); + let (mut child, _logs, endpoint) = serve(&server, &config, &[], &[]); + let list_books = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "list_books", "arguments": {} } }); + + let (status, answer) = post(&endpoint, Some("wb_at_disconnected"), &list_books); + assert_eq!(status, 200, "{answer}"); + assert!(answer.contains("did not accept your Writebook token"), "{answer}"); + + let (status, _) = post(&endpoint, Some("wb_at_disconnected"), &list_books); + assert_eq!( + status, 401, + "the exchanged token is forgotten, so the client is told to renew" + ); + + child.kill().unwrap(); + child.wait().unwrap(); +} + #[test] fn answers_502_when_writebook_fails_to_exchange_a_token() { let server = fake_writebook();