diff --git a/Dockerfile b/Dockerfile index af8a348..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 --instance https://books.example.com --serve 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 @@ -39,6 +42,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", "--bind", "0.0.0.0:80"] diff --git a/README.md b/README.md index cb4ddf9..2d073a8 100644 --- a/README.md +++ b/README.md @@ -93,14 +93,12 @@ 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_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 --instance https://books.example.com --serve 0.0.0.0:8080 -``` +[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 pages, run: diff --git a/doc/mcp-server.md b/doc/mcp-server.md new file mode 100644 index 0000000..beeee4f --- /dev/null +++ b/doc/mcp-server.md @@ -0,0 +1,88 @@ +# Running the MCP server + +`writebook mcp serve` gives agents access to one Writebook instance over HTTP. +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. + +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. + +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 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_PUBLIC_URL=https://mcp.example.com \ + --env WRITEBOOK_MCP_SECRET= +``` + +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. +- `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. + +The server checks the secret with your Writebook when it starts, and stops if +Writebook doesn't accept it. + +## Behind another proxy + +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: + +```sh +WRITEBOOK_MCP_SECRET= writebook mcp serve \ + --instance https://books.example.com --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. + +With kamal-proxy, deploy it as it is, without `--path-prefix`. With Caddy: + +``` +mcp.example.com { + reverse_proxy 127.0.0.1:8080 +} +``` + +With Apache, turn on `mod_proxy` and `mod_proxy_http`: + +```apache + + ServerName mcp.example.com + # your TLS settings + + 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 319a3d1..121327c 100644 --- a/skills/writebook/SKILL.md +++ b/skills/writebook/SKILL.md @@ -103,6 +103,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. + +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". @@ -284,13 +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 --instance https://books.example.com --serve 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 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. +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/api.rs b/src/api.rs index 19fa6f5..28db607 100644 --- a/src/api.rs +++ b/src/api.rs @@ -77,6 +77,59 @@ impl std::fmt::Display for ApiError { impl std::error::Error for ApiError {} +#[derive(Debug)] +pub struct ScopeTooNarrow { + pub missing: MissingScope, + sign_in: Option, +} + +#[derive(Debug, PartialEq)] +pub enum MissingScope { + Write, + Admin, + Unnamed, +} + +impl 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 => MissingScope::Unnamed, + } + } +} + +impl std::fmt::Display for ScopeTooNarrow { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + 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::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 {refusal}. Sign in again with `{sign_in}` and {approval}" + ), + None => write!( + f, + "Writebook says the token in WRITEBOOK_TOKEN {refusal}. Use a token that has the access it needs" + ), + } + } +} + +impl std::error::Error for ScopeTooNarrow {} + /// The site turned the token away. #[derive(Debug)] pub struct TokenRejected { @@ -205,7 +258,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(&self.host, path, response) } fn multipart(&mut self, path: &str, method: MultipartMethod, parts: &[Part]) -> Result { @@ -213,10 +267,8 @@ 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(&self.host, path, response) } fn send_renewing(&mut self, send: impl Fn(&Client) -> Result) -> Result { @@ -347,10 +399,27 @@ 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 text = response.body_mut().read_to_string(); + let challenge = response + .headers() + .get("www-authenticate") + .and_then(|it| it.to_str().ok()) + .filter(|it| it.contains("insufficient_scope")) + .map(str::to_string); + + if let (403, Some(challenge)) = (status, challenge) { + Err(ScopeTooNarrow { + missing: MissingScope::from_challenge(&challenge), + sign_in: creds::sign_in_again_command(host), + } + .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..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]") } @@ -304,6 +304,19 @@ impl std::fmt::Display for RenewalFailed { impl std::error::Error for RenewalFailed {} +/// The command that signs the current profile in again, unless the token +/// came from WRITEBOOK_TOKEN, which signing in again wouldn't change. +pub fn sign_in_again_command(host: &str) -> Option { + if GIVEN_TOKEN.get().is_some() { + None + } else { + match inventory::profile_for(host) { + Ok(profile) => Some(inventory::sign_in_command(host, &profile)), + Err(_) => Some(format!("writebook instance add {host}")), + } + } +} + pub fn rejected_token_advice(host: &str) -> String { if GIVEN_TOKEN.get().is_some() { "Check WRITEBOOK_TOKEN".to_string() @@ -483,21 +496,38 @@ fn access_from(body: &Value) -> Access { } fn request_device_authorization(host: &str, access: Access) -> Result { - let scope = match access { - Access::Full => "read write", - Access::ReadOnly => "read", + let (status, body) = match access { + Access::ReadOnly => post_device_authorization(host, "read")?, + 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?"); - } + let status = response.status().as_u16(); - Ok(response.body_mut().read_json()?) + 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 0cc3174..b8ce3d5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -155,19 +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)] - instance: Option, #[usage(help = "Serve only the tools that read")] - #[usage(long)] + #[usage(long, global, 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(subcommand)] + command: Option, }, #[usage(help = "Browse your instances' books in the terminal, and arrange their pages")] Tui, @@ -179,6 +175,26 @@ enum Command { }, } +#[derive(Subcommands)] +enum McpCommand { + #[usage( + 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)")] + #[usage(long, env = "WRITEBOOK_MCP_INSTANCE")] + instance: Option, + #[usage(help = "The address to listen on")] + #[usage(long, env = "WRITEBOOK_MCP_BIND", default = "127.0.0.1:8080")] + bind: String, + #[usage( + 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: String, + }, +} + #[derive(Subcommands)] enum SkillCommand { #[usage(help = "Print the embedded SKILL.md")] @@ -444,11 +460,14 @@ fn run(cli: Cli) -> Result<()> { instance.as_deref(), Format::from_flags(json, markdown, jq)?, ), - Command::Mcp { - instance, - read_only, - serve, - } => mcp::run(instance.as_deref(), read_only, serve.as_deref()), + Command::Mcp { read_only, command } => match command { + None => mcp::run(read_only), + Some(McpCommand::Serve { + instance, + bind, + public_url, + }) => mcp::serve(instance.as_deref(), read_only, &bind, &public_url), + }, Command::Tui => tui::run(), Command::Setup => setup::run(), Command::Skill { command } => match command { diff --git a/src/mcp.rs b/src/mcp.rs index 7365993..6181e89 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -1,11 +1,12 @@ //! `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 -//! 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. +//! 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. +mod exchange; mod log; mod tools; @@ -28,22 +29,50 @@ use std::time::Instant; use crate::inventory::{self, Inventory}; use crate::web::Web; use crate::{api, creds}; +use exchange::{Exchange, Exchanged}; -pub fn run(instance: Option<&str>, read_only: bool, serve: Option<&str>) -> Result<()> { +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()?; log::start(); - match serve { - None if instance.is_some() => { - bail!("--instance only goes with --serve: on stdio, every instance you added is served") - } - 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)) - } - } + runtime.block_on(serve_stdio(read_only)) +} + +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) + .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()) + .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, exchange)) +} + +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<()> { @@ -71,22 +100,36 @@ 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: String, + exchange: Exchange, +) -> Result<()> { let listener = tokio::net::TcpListener::bind(address) .await .with_context(|| format!("could not listen on {address}"))?; - let served = host.clone(); + let gate = Gate { + 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, }; log::serving( - &served, + &logged, "http", 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. @@ -96,9 +139,15 @@ 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 = gate.clone(); let router = axum::Router::new() .route_service("/mcp", service) - .layer(middleware::from_fn(require_token)) + .route_layer(middleware::from_fn_with_state(gate, require_token)) + .route("/up", axum::routing::get(|| async { "ok\n" })) + .route( + "/.well-known/oauth-protected-resource/mcp", + axum::routing::get(move || async move { metadata.resource_metadata() }), + ) .layer(middleware::from_fn(log_request)); axum::serve(listener, router) @@ -120,17 +169,61 @@ 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 { +async fn require_token( + axum::extract::State(gate): axum::extract::State, + mut request: Request, + next: Next, +) -> Response { + match bearer(request.headers()) { + 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() + } + }, + } +} + +#[derive(Clone)] +struct Gate { + exchange: Exchange, + public_url: String, + writebook: String, +} + +impl Gate { + // https://www.rfc-editor.org/rfc/rfc9728#section-5.1 + fn challenge(&self, error: Option<&str>, message: &'static str) -> Response { + let error = error.map(|it| format!(r#"error="{it}", "#)).unwrap_or_default(); + let challenge = format!( + r#"Bearer {error}resource_metadata="{}/.well-known/oauth-protected-resource/mcp""#, + self.public_url + ); + ( StatusCode::UNAUTHORIZED, - [(header::WWW_AUTHENTICATE, "Bearer")], - "a Writebook token is required\n", + [(header::WWW_AUTHENTICATE, challenge)], + message, ) .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"], + }); + + ([(header::CONTENT_TYPE, "application/json")], metadata.to_string()).into_response() + } } fn bearer(headers: &axum::http::HeaderMap) -> Option { @@ -151,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. @@ -209,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." @@ -242,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| bearer(&parts.headers)) - { - Some(token) => Some(Connection { - host: host.clone(), - caller_token: Some(token), - }), - 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; @@ -276,9 +368,21 @@ 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::() { + 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/exchange.rs b/src/mcp/exchange.rs new file mode 100644 index 0000000..6656314 --- /dev/null +++ b/src/mcp/exchange.rs @@ -0,0 +1,159 @@ +use anyhow::{Context, 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, PartialEq)] +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. 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!( + "{} answered {status} when the MCP server checked its secret", + self.writebook + ), + } + } + + /// 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(); + + 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)) => { + 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, + }, + Ok(Ok((400, body))) if body["error"] == "invalid_grant" => { + self.remember_refused(digest); + Exchanged::Refused + } + _ => Exchanged::Failed, + } + } + } + + /// 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)) + .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), + ]) + .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); + 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, 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, until)); + } + + 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/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 ae2b192..5560d07 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::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: what to do + /// so it can. + pub to_administer: Option, } #[derive(Deserialize, Clone)] @@ -28,12 +32,24 @@ 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 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 + }; Ok(People { join_url: text(&value, "join_url"), - can_administer: value["can_administer"].as_bool().unwrap_or(false), + can_administer, people, + to_administer, }) } diff --git a/src/tui/flows/people.rs b/src/tui/flows/people.rs index 81cd41d..9fad3d8 100644 --- a/src/tui/flows/people.rs +++ b/src/tui/flows/people.rs @@ -10,6 +10,8 @@ struct Workplace { invite: &'static str, can_administer: bool, failing: bool, + scope_too_narrow: bool, + without_admin_scope: bool, profile_email: String, wrong_password: bool, } @@ -17,13 +19,19 @@ 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()), ], invite: "abc", can_administer, failing: false, + scope_too_narrow: false, + without_admin_scope: false, profile_email: "me@example.com".to_string(), wrong_password: false, })); @@ -36,6 +44,13 @@ 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", scope="read write admin""#.to_string(), + )); + refused } else { match (request.method.as_str(), request.path.as_str()) { ("GET", "/books.json") => json(json!([{ "id": 1, "title": "Handbook", "editable": true }])), @@ -45,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 { @@ -315,6 +334,41 @@ fn a_server_error_on_a_change_shows_a_notice_and_keeps_the_list_as_it_was() { assert_eq!(state.invite, "abc"); } +#[test] +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("Use a WRITEBOOK_TOKEN that can 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; + + tui.press(KeyCode::Down); + tui.press(KeyCode::Right); + let screen = tui.wait_for("can't manage people and settings"); + 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/src/tui/settings.rs b/src/tui/settings.rs index 2adda14..06a398f 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.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,23 @@ impl SettingsPage { ]) .areas(area); + 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(advice.clone()), + ]; + 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(), diff --git a/tests/mcp.rs b/tests/mcp.rs index adc76df..7a22033 100644 --- a/tests/mcp.rs +++ b/tests/mcp.rs @@ -7,10 +7,15 @@ 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"; + +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(); @@ -166,6 +171,57 @@ 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( + "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}" + ); + + let mut unnamed = Mcp::start(&server, Some("wb_at_unnamed")); + let refused = unnamed.call_failing("update_page", change); + assert!( + refused.contains("Writebook says the token in WRITEBOOK_TOKEN wasn't given access to do that"), + "{refused}" + ); +} + +#[test] +fn takes_a_public_url_only_as_an_origin() { + for url in [ + "mcp.example.com", + "https://mcp.example.com/mcp", + "ftp://mcp.example.com", + "http://mcp.example.com", + ] { + let output = support::writebook( + &[ + "mcp", + "serve", + "--instance", + "https://books.example.com", + "--bind", + "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,25 +238,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, @@ -232,14 +270,28 @@ 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 (_, 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(); @@ -258,13 +310,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() @@ -272,6 +318,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"); } @@ -279,7 +332,32 @@ 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, ""), + _ if request.header("Authorization") == Some("Bearer wb_at_disconnected_exchanged") => reply(401, ""), + ("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", + r#"Bearer error="insufficient_scope", scope="read write""#.to_string(), + )); + refused + } + ("PATCH", _) + if request + .header("Authorization") + .is_some_and(|it| it.starts_with("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(); @@ -340,6 +418,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 { @@ -412,6 +494,33 @@ 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" + || (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 }; + reply( + 200, + &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(), + ) + } +} + fn instance(alias: &str, url: &str) -> String { format!("[instances.{alias}]\nurl = \"{url}\"\ndefault_profile = \"default\"\nprofiles = [\"default\"]\n") } @@ -425,6 +534,284 @@ 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(), + r#"Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp""# + ); + + let mut response = agent + .get(&format!("{base}/.well-known/oauth-protected-resource/mcp")) + .header("Host", "upstream") + .call() + .unwrap(); + 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!( + up.status().as_u16(), + 200, + "proxies like kamal-proxy check /up before sending traffic" + ); + + let revoked = agent + .post(&endpoint) + .header("Authorization", "Bearer wb_at_revoked") + .send_json(initialize()) + .unwrap(); + 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 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 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), + &json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }), + ); + } + + let exchanges: Vec = server + .requests() + .into_iter() + .filter(|it| it.path == "/oauth/tokens" && !it.body.contains("checking_the_secret")) + .map(|it| it.body) + .collect(); + 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(); +} + +#[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_however_read_only_is_set() { + let server = fake_writebook(); + let config = tempdir(); + let ways = [ + ( + vec!["mcp", "serve", "--bind", "127.0.0.1:0"], + vec![("WRITEBOOK_MCP_READ_ONLY", "true")], + ), + (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 (_, 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 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(); + let config = tempdir(); + let (mut child, _logs, endpoint) = serve(&server, &config, &[], &[]); + + let (status, answer) = post( + &endpoint, + Some("wb_at_broken"), + &json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" }), + ); + assert_eq!(status, 502, "{answer}"); + assert!(!answer.contains("read_page"), "{answer}"); + + child.kill().unwrap(); + child.wait().unwrap(); +} + +#[test] +fn wont_start_without_a_secret_writebook_accepts() { + let server = fake_writebook(); + 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( + server: &Server, + 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(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", 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") + .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!(instance), &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 diff --git a/tests/read_only.rs b/tests/read_only.rs index c9cf212..0b194b0 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 ); @@ -74,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(""); @@ -285,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) } 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")