From 8433867537d5a8138fe16beeb49e507361635caa Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Thu, 19 Nov 2026 16:37:19 -0500 Subject: [PATCH 01/24] refactor(admin): extract the settings write into one transport-free function --- .../controllers/admin_json_body_middleware.rs | 23 ++-- .../src/controllers/patch_settings.rs | 122 ++++++++++++------ 2 files changed, 97 insertions(+), 48 deletions(-) diff --git a/crates/nostream-admin/src/controllers/admin_json_body_middleware.rs b/crates/nostream-admin/src/controllers/admin_json_body_middleware.rs index 098d0da66..e21822ce8 100644 --- a/crates/nostream-admin/src/controllers/admin_json_body_middleware.rs +++ b/crates/nostream-admin/src/controllers/admin_json_body_middleware.rs @@ -12,10 +12,10 @@ use std::sync::Arc; use axum::body::Bytes; use axum::extract::{FromRequest, Request}; use axum::http::{StatusCode, header}; -use axum::response::{IntoResponse, Response}; +use axum::response::Response; use serde_json::{Map, Value, json}; -use crate::controllers::with_admin_controller_request_handler::error_message; +use crate::controllers::with_admin_controller_request_handler::{error_message, json_response}; use crate::state::AdminState; /// The body cap the capture mounts (`json({ limit: '1mb' })`). @@ -28,7 +28,12 @@ pub fn unsupported_media_type() -> Response { /// `400 {"error":"Invalid request"}`. pub fn invalid_request() -> Response { - error_message(StatusCode::BAD_REQUEST, "Invalid request") + json_response(StatusCode::BAD_REQUEST, &invalid_request_body()) +} + +/// The body [`invalid_request`] answers, for a caller that has no response to build. +pub fn invalid_request_body() -> Value { + json!({ "error": "Invalid request" }) } fn payload_too_large() -> Response { @@ -449,16 +454,16 @@ fn kind_rule_list(value: &Value) -> Option> { /// `400 {"error":"Validation failed","issues":[…]}`, the settings and notifications patch /// failure body. pub fn validation_failed(issues: &[nostream_config::Issue]) -> Response { + json_response(StatusCode::BAD_REQUEST, &validation_failed_body(issues)) +} + +/// The body [`validation_failed`] answers, for a caller that has no response to build. +pub fn validation_failed_body(issues: &[nostream_config::Issue]) -> Value { let issues: Vec = issues .iter() .map(|issue| json!({ "path": issue.path, "message": issue.message })) .collect(); - ( - StatusCode::BAD_REQUEST, - [(header::CONTENT_TYPE, "application/json")], - json!({ "error": "Validation failed", "issues": issues }).to_string(), - ) - .into_response() + json!({ "error": "Validation failed", "issues": issues }) } #[cfg(test)] diff --git a/crates/nostream-admin/src/controllers/patch_settings.rs b/crates/nostream-admin/src/controllers/patch_settings.rs index b489adba6..4d879b5ad 100644 --- a/crates/nostream-admin/src/controllers/patch_settings.rs +++ b/crates/nostream-admin/src/controllers/patch_settings.rs @@ -1,22 +1,36 @@ //! `PATCH /admin/settings`: validate each path, merge the changes into the user //! document, validate the merged result, write it with a backup, audit it, and enqueue the //! `settings.changed` row. Mirrors `src/controllers/admin/patch-settings-controller.ts`. +//! +//! The sequence is [`apply`] — transport-free, over the admin state and the body's JSON object — +//! because the MCP server's `settings_set` tool performs the same write (R13). [`handle`] is the +//! HTTP edge: the extractors, then that call, then the response. use std::sync::Arc; use axum::extract::State; use axum::http::StatusCode; -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; use crate::controllers::admin_auth_middleware::Session; use crate::controllers::admin_json_body_middleware::{ - JsonBody, SettingsChange, SettingsPatch, invalid_request, settings_patch, validation_failed, + JsonBody, SettingsChange, SettingsPatch, invalid_request_body, settings_patch, + validation_failed_body, }; use crate::controllers::admin_rate_limit_middleware::AdminRateLimited; use crate::controllers::request_context::ClientInfo; use crate::controllers::with_admin_controller_request_handler::{HandlerResult, json_response}; use crate::state::AdminState; +/// What one settings write produced: the controller's body, or its refusal with its status. +#[derive(Debug, Clone, PartialEq)] +pub enum SettingsWrite { + /// The controller's `200` body, verbatim. + Written(Value), + /// The controller's `400` body, and the status every refusal carries. + Refused { status: StatusCode, body: Value }, +} + /// `getSettingsReloadBehavior`: `restart-required` for `workers.`, `payments` and `network.`, /// else `hot-reload` (Value 15 — `payments` is compared without a dot, as written). pub fn reload_behavior(path: &str) -> &'static str { @@ -66,15 +80,20 @@ fn apply_changes( Ok((next_user, next_merged)) } -pub async fn handle( - State(state): State>, - _limited: AdminRateLimited, - _session: Session, - client: ClientInfo, - JsonBody(body): JsonBody, -) -> HandlerResult { - let Some(SettingsPatch { changes, list_form }) = settings_patch(&body) else { - return Ok(invalid_request()); +/// The read → guard → merge → validate → save → audit → outbox sequence, transport-free. +/// +/// `remote_address` is the HTTP caller's address, and the empty string for a caller that has +/// none: the audit's `remoteAddress` is then omitted rather than written blank. +pub async fn apply( + state: &AdminState, + body: &Map, + remote_address: &str, +) -> Result { + let Some(SettingsPatch { changes, list_form }) = settings_patch(body) else { + return Ok(SettingsWrite::Refused { + status: StatusCode::BAD_REQUEST, + body: invalid_request_body(), + }); }; // The whole read → change → validate → write sequence runs under the settings write @@ -102,17 +121,26 @@ pub async fn handle( } } if !issues.is_empty() { - return Ok(validation_failed(&issues)); + return Ok(SettingsWrite::Refused { + status: StatusCode::BAD_REQUEST, + body: validation_failed_body(&issues), + }); } let user = state.user_document()?; let Ok((next_user, next_merged)) = apply_changes(&user, &merged, &changes) else { - return Ok(invalid_request()); + return Ok(SettingsWrite::Refused { + status: StatusCode::BAD_REQUEST, + body: invalid_request_body(), + }); }; let validation = nostream_config::validate_document(&next_merged, &defaults); if !validation.is_empty() { - return Ok(validation_failed(&validation)); + return Ok(SettingsWrite::Refused { + status: StatusCode::BAD_REQUEST, + body: validation_failed_body(&validation), + }); } state.save_user_settings(&next_user)?; @@ -132,34 +160,50 @@ pub async fn handle( .iter() .map(|change| json!({ "path": change["path"], "reload": change["reload"] })) .collect(); - let _ = state.append_settings_audit(json!({ + let mut settings_audit = json!({ "timestamp": crate::state::iso8601(state.clock().now_ms()), "action": "settings.updated", "changes": audit_changes, - "remoteAddress": client.address, - })); - crate::controllers::post_login::record_audit(&state, "settings.updated", &client.address, None); - state - .enqueue_settings_changed(json!({ - "changes": updated, - "remoteAddress": client.address, - })) - .await; - - match updated.as_slice() { - [only] if !list_form => Ok(json_response( - StatusCode::OK, - &json!({ - "ok": true, - "path": only["path"], - "value": only["value"], - "reload": only["reload"], - }), - )), - _ => Ok(json_response( - StatusCode::OK, - &json!({ "ok": true, "changes": updated }), - )), + }); + let mut outbox_payload = json!({ "changes": updated }); + with_remote_address(&mut settings_audit, remote_address); + with_remote_address(&mut outbox_payload, remote_address); + let _ = state.append_settings_audit(settings_audit); + crate::controllers::post_login::record_audit(state, "settings.updated", remote_address, None); + state.enqueue_settings_changed(outbox_payload).await; + + let body = match updated.as_slice() { + [only] if !list_form => json!({ + "ok": true, + "path": only["path"], + "value": only["value"], + "reload": only["reload"], + }), + _ => json!({ "ok": true, "changes": updated }), + }; + Ok(SettingsWrite::Written(body)) +} + +/// Adds `remoteAddress` to a record, and leaves the key out when there is none — the same +/// convention [`record_audit`](crate::controllers::post_login::record_audit) uses, so a write +/// from a caller with no address (the MCP server's stdio client) records no address rather +/// than a blank one. +fn with_remote_address(document: &mut Value, remote_address: &str) { + if !remote_address.is_empty() { + document["remoteAddress"] = json!(remote_address); + } +} + +pub async fn handle( + State(state): State>, + _limited: AdminRateLimited, + _session: Session, + client: ClientInfo, + JsonBody(body): JsonBody, +) -> HandlerResult { + match apply(&state, &body, &client.address).await? { + SettingsWrite::Written(body) => Ok(json_response(StatusCode::OK, &body)), + SettingsWrite::Refused { status, body } => Ok(json_response(status, &body)), } } From 7a1cde0ec037d43fa739edd657506cdc649f9fc0 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Thu, 19 Nov 2026 16:37:19 -0500 Subject: [PATCH 02/24] feat(admin): serve the admin MCP server on stdio (#1183) --- .changeset/admin-mcp-server.md | 12 + Cargo.lock | 196 +++++++++ Cargo.toml | 2 + crates/nostream-admin/src/lib.rs | 3 +- crates/nostream-mcp/Cargo.toml | 29 ++ crates/nostream-mcp/src/error.rs | 31 ++ crates/nostream-mcp/src/lib.rs | 27 ++ crates/nostream-mcp/src/server.rs | 329 +++++++++++++++ crates/nostream-mcp/tests/audit.rs | 112 +++++ crates/nostream-mcp/tests/auth.rs | 103 +++++ crates/nostream-mcp/tests/common/mod.rs | 385 ++++++++++++++++++ .../tests/fixtures/tools_list.json | 105 +++++ crates/nostream-mcp/tests/tool_payloads.rs | 349 ++++++++++++++++ crates/nostream-mcp/tests/tools_list.rs | 170 ++++++++ crates/nostreamd/Cargo.toml | 2 + crates/nostreamd/src/lib.rs | 7 +- crates/nostreamd/src/main.rs | 23 +- crates/nostreamd/src/mcp_stdio.rs | 72 ++++ crates/nostreamd/src/settings_gate.rs | 5 +- crates/nostreamd/src/telemetry.rs | 36 +- crates/nostreamd/tests/mcp_stdio.rs | 321 +++++++++++++++ .../decisions/0014-admin-http-surface.md | 34 ++ 22 files changed, 2338 insertions(+), 15 deletions(-) create mode 100644 .changeset/admin-mcp-server.md create mode 100644 crates/nostream-mcp/Cargo.toml create mode 100644 crates/nostream-mcp/src/error.rs create mode 100644 crates/nostream-mcp/src/lib.rs create mode 100644 crates/nostream-mcp/src/server.rs create mode 100644 crates/nostream-mcp/tests/audit.rs create mode 100644 crates/nostream-mcp/tests/auth.rs create mode 100644 crates/nostream-mcp/tests/common/mod.rs create mode 100644 crates/nostream-mcp/tests/fixtures/tools_list.json create mode 100644 crates/nostream-mcp/tests/tool_payloads.rs create mode 100644 crates/nostream-mcp/tests/tools_list.rs create mode 100644 crates/nostreamd/src/mcp_stdio.rs create mode 100644 crates/nostreamd/tests/mcp_stdio.rs diff --git a/.changeset/admin-mcp-server.md b/.changeset/admin-mcp-server.md new file mode 100644 index 000000000..9fda19ba7 --- /dev/null +++ b/.changeset/admin-mcp-server.md @@ -0,0 +1,12 @@ +--- +--- + +feat(admin): the admin MCP server, slice 1 — four tools over stdio + +A new Rust crate serves `settings_get`, `settings_set`, `list_events` and +`get_event` on stdin/stdout through `rmcp`, inside the daemon's own process +(`--mcp-stdio`). Every call is gated by the console's own session token and +audited to `admin-audit.jsonl` under one `mcp.` action; the four names are +recorded as ADR 0014 D18. + +Rust only: no published package changes, so this changeset is deliberately empty. diff --git a/Cargo.lock b/Cargo.lock index 9cab4b723..d0c927155 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -474,6 +474,40 @@ dependencies = [ "cmov", ] +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.9", +] + [[package]] name = "data-encoding" version = "2.11.1" @@ -529,6 +563,12 @@ dependencies = [ "phf", ] +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "either" version = "1.19.0" @@ -618,6 +658,21 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -691,6 +746,7 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ + "futures-channel", "futures-core", "futures-io", "futures-macro", @@ -1108,6 +1164,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -1137,6 +1199,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", + "serde", + "serde_core", ] [[package]] @@ -1401,6 +1465,25 @@ dependencies = [ "url", ] +[[package]] +name = "nostream-mcp" +version = "0.1.0" +dependencies = [ + "nostream-admin", + "nostream-config", + "nostream-core", + "nostream-services", + "nostream-storage", + "rmcp", + "serde", + "serde_json", + "serde_yaml", + "tempfile", + "thiserror", + "tokio", + "tracing", +] + [[package]] name = "nostream-relay" version = "0.1.0" @@ -1481,11 +1564,13 @@ dependencies = [ "nostream-admin", "nostream-config", "nostream-core", + "nostream-mcp", "nostream-relay", "nostream-services", "nostream-storage", "opentelemetry", "opentelemetry-otlp", + "rmcp", "serde_json", "tempfile", "thiserror", @@ -1636,6 +1721,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pbkdf2" version = "0.12.2" @@ -1950,6 +2041,26 @@ dependencies = [ "bitflags", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "regex-automata" version = "0.4.18" @@ -2019,6 +2130,48 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rmcp" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "391f153431ab68664d946513ea0cb3edbca78eaf99c5a983036cacab6220d85b" +dependencies = [ + "base64 0.23.1", + "chrono", + "futures", + "indexmap", + "libc", + "pastey", + "percent-encoding", + "pin-project-lite", + "rmcp-macros", + "schemars", + "serde", + "serde_json", + "sha2 0.11.1", + "thiserror", + "tokio", + "tokio-stream", + "tokio-util", + "tracing", + "unicode-general-category", + "unicode-normalization", + "uuid", +] + +[[package]] +name = "rmcp-macros" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3598e3f36f4af2b5219b133baf7d97a2197039225adc3d4acf3dd8805b5a2aef" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "serde_json", + "syn 3.0.9", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -2094,6 +2247,32 @@ dependencies = [ "cipher 0.4.4", ] +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "chrono", + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.9", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -2161,6 +2340,17 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "serde_json" version = "1.0.154" @@ -2912,6 +3102,12 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + [[package]] name = "unicode-ident" version = "1.0.27" diff --git a/Cargo.toml b/Cargo.toml index a3ec61dfa..807a8f890 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ nostream-admin = { path = "crates/nostream-admin" } nostream-cli = { path = "crates/nostream-cli" } nostream-config = { path = "crates/nostream-config" } nostream-core = { path = "crates/nostream-core" } +nostream-mcp = { path = "crates/nostream-mcp" } nostream-relay = { path = "crates/nostream-relay" } nostream-services = { path = "crates/nostream-services" } nostream-storage = { path = "crates/nostream-storage" } @@ -40,6 +41,7 @@ opentelemetry = "0.33.1" opentelemetry-otlp = { version = "0.33.1", default-features = false, features = ["trace", "grpc-tonic"] } opentelemetry_sdk = { version = "0.33.1", default-features = false, features = ["trace", "rt-tokio"] } reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] } +rmcp = { version = "3.11", features = ["server", "transport-io", "transport-async-rw"] } scrypt = "0.11" secp256k1 = "0.33.1" serde = { version = "1", features = ["derive"] } diff --git a/crates/nostream-admin/src/lib.rs b/crates/nostream-admin/src/lib.rs index 7ff06b1fc..ff9c73252 100644 --- a/crates/nostream-admin/src/lib.rs +++ b/crates/nostream-admin/src/lib.rs @@ -32,7 +32,8 @@ //! - the event store, the repositories and the notification channels — `nostream-storage` and //! `nostream-services`; //! - NIP-98 authentication and its replay claim — a later job (D6); -//! - the MCP server and the CLI — separate issues, with no module here; +//! - the MCP server — `crates/nostream-mcp`, a separate crate that reuses this one's state, +//! session credential and audit path — and the CLI, a separate issue; //! - the app-level connection rate limiter — deliberately not applied to HTTP (D1). // An axum rejection *is* an `http::Response`, so every extractor's error type is one; the diff --git a/crates/nostream-mcp/Cargo.toml b/crates/nostream-mcp/Cargo.toml new file mode 100644 index 000000000..e2c3fcc66 --- /dev/null +++ b/crates/nostream-mcp/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "nostream-mcp" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "The admin MCP server: the tool router, the credential gate and the audit sink" + +[dependencies] +nostream-admin.workspace = true +nostream-config.workspace = true +nostream-core.workspace = true +nostream-storage.workspace = true +rmcp.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +tracing.workspace = true + +[dev-dependencies] +nostream-services.workspace = true +rmcp = { workspace = true, features = ["client"] } +serde_yaml.workspace = true +tempfile.workspace = true +tokio.workspace = true + +[lints] +workspace = true diff --git a/crates/nostream-mcp/src/error.rs b/crates/nostream-mcp/src/error.rs new file mode 100644 index 000000000..0e7a58915 --- /dev/null +++ b/crates/nostream-mcp/src/error.rs @@ -0,0 +1,31 @@ +//! The MCP server's error type. +//! +//! A tool answers its failures as `isError: true` results, so these variants exist to be +//! rendered into a caller-visible text rather than matched by a status code: a pipe carries no +//! status, and a caller that reads `Tool result missing due to internal error` learns nothing. +//! `Display` is therefore the operator-facing message, and the store's own message is passed +//! through unchanged (R19). + +use nostream_admin::AdminError; +use nostream_storage::StorageError; +use thiserror::Error; + +/// Errors raised by `nostream-mcp`. +#[derive(Debug, Error)] +pub enum McpError { + /// The admin state could not be read: the settings files, the audit file or the write path. + #[error(transparent)] + Admin(#[from] AdminError), + + /// A repository call failed. Its message is the backend's own, verbatim (R19). + #[error(transparent)] + Storage(#[from] StorageError), + + /// A tool's arguments are not the shape its `inputSchema` states. + #[error("the tool's arguments could not be read: {0}")] + Arguments(String), + + /// A payload the tool built could not be serialised. + #[error("the payload could not be serialised: {0}")] + Serialise(#[from] serde_json::Error), +} diff --git a/crates/nostream-mcp/src/lib.rs b/crates/nostream-mcp/src/lib.rs new file mode 100644 index 000000000..78a1d787e --- /dev/null +++ b/crates/nostream-mcp/src/lib.rs @@ -0,0 +1,27 @@ +//! `nostream-mcp` owns the admin MCP server: the tool router, the four slice-1 tools, the +//! credential gate and the audit sink. +//! +//! It owns no transport and no socket. `nostreamd --mcp-stdio` serves this server on +//! stdin/stdout through `rmcp`'s `transport-io`, in the daemon's own process, so the tools read +//! the same [`AdminState`](nostream_admin::AdminState) the HTTP console does: the same session +//! credential, the same `/admin-audit.jsonl` and the same repository bundle (D9, D13). +//! +//! **Deliberately not owned here** — a reader should be able to tell an omission from a gap: +//! +//! - the runtime, the signals, the socket and the stdio mode — `nostreamd`; +//! - the admin state, the session token, the audit file and the settings write path — +//! `nostream-admin` (used here, not re-implemented); +//! - the settings merge, validation, redaction and the guided catalogue — `nostream-config`; +//! - the event store and the repositories — `nostream-storage`; +//! - every tool family outside slice 1: `relay_status`, `delete_event`, `user_admin`, +//! `invoices_*`, `reports_*` and `maintenance_*` are later slices of #1183. + +mod error; +mod server; + +pub use error::McpError; +pub use server::{ + AdminMcp, GetEventArgs, INTERNAL_SERVER_ERROR, ListEventsArgs, MCP_SERVER_NAME, NOT_FOUND, + SettingsSetArgs, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, + UNAUTHORIZED, audit_action, +}; diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs new file mode 100644 index 000000000..681d2ec63 --- /dev/null +++ b/crates/nostream-mcp/src/server.rs @@ -0,0 +1,329 @@ +//! The MCP server: the four tools, the credential gate and the audit sink. +//! +//! Every tool is a thin handler over a seam that already exists — `AdminState` for the settings, +//! `EventRepository` for the events — and nothing here knows what an HTTP status is (R3). The +//! gate and the audit line live in [`ServerHandler::call_tool`], at dispatch: a call the gate +//! refuses reaches no tool and writes nothing (R8), and a call that reaches a tool has its +//! `mcp.` line written before the tool's own work, so the file's order is the dispatch +//! order (R9). + +use std::sync::Arc; + +use nostream_admin::AdminState; +use nostream_admin::controllers::admin_json_body_middleware::settings_patch; +use nostream_admin::controllers::patch_settings::{self, SettingsWrite}; +use nostream_admin::utils::session; +use nostream_core::{Filter, Kind}; +use nostream_storage::repositories::{EventRecord, collect_records}; +use rmcp::handler::server::router::tool::ToolRouter; +use rmcp::handler::server::tool::ToolCallContext; +use rmcp::handler::server::wrapper::Parameters; +use rmcp::model::{ + CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Implementation, + ServerCapabilities, ServerConfig, +}; +use rmcp::schemars::{self, JsonSchema}; +use rmcp::service::RequestContext; +use rmcp::{RoleServer, ServerHandler, tool, tool_handler, tool_router}; +use serde::Deserialize; +use serde_json::{Map, Value, json}; + +use crate::error::McpError; + +/// The server name `initialize` reports: the server, not the SDK, which would name `rmcp` (R6). +pub const MCP_SERVER_NAME: &str = "nostream"; + +/// The tool names slice 1 registers (R5). Each is also its audit action's suffix (R9). +pub const TOOL_SETTINGS_GET: &str = "settings_get"; +pub const TOOL_SETTINGS_SET: &str = "settings_set"; +pub const TOOL_LIST_EVENTS: &str = "list_events"; +pub const TOOL_GET_EVENT: &str = "get_event"; + +/// The refusal for a token that is absent, malformed or expired — the HTTP gate's `401`. +pub const UNAUTHORIZED: &str = "Unauthorized"; + +/// The refusal for a surface whose `SECRET` is absent — the HTTP gate's `500`. +pub const INTERNAL_SERVER_ERROR: &str = "Internal Server Error"; + +/// The refusal for a surface `admin.enabled` does not turn on — the console's `404`. +pub const NOT_FOUND: &str = "Not Found"; + +/// The audit action one dispatched call records: `mcp.` (R9). +pub fn audit_action(tool: &str) -> String { + format!("mcp.{tool}") +} + +/// The `list_events` criteria: each maps to one [`Filter`] field (R15). +#[derive(Debug, Clone, Default, Deserialize, JsonSchema)] +pub struct ListEventsArgs { + /// Kinds to select; absent selects every kind. + pub kinds: Option>, + /// Author pubkey hex prefixes. + pub authors: Option>, + /// Event id hex prefixes. + pub ids: Option>, + /// Events created at or after this unix second. + pub since: Option, + /// Events created at or before this unix second. + pub until: Option, + /// Page size; absent leaves the store's own default in charge. + pub limit: Option, +} + +/// The `get_event` arguments. +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub struct GetEventArgs { + /// The event's 64-character lowercase hex id. + pub id: String, +} + +/// The `settings_set` arguments: the same JSON object the console's HTTP body carries (R12). +/// +/// Kept as a raw map rather than a typed struct because the schema's rule is that an explicit +/// `null` is a value and not an absent key: a typed `Option` would collapse the two and +/// turn the validator's `Expected string, got null` into `Invalid request`. +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub struct SettingsSetArgs { + /// `{path, value}` or `{changes: [{path, value}, …]}`. + #[serde(flatten)] + pub body: Map, +} + +/// The server: the shared admin state, the resolved token and the composition's identity. +#[derive(Debug, Clone)] +pub struct AdminMcp { + state: Arc, + /// `NOSTREAM_ADMIN_TOKEN` as a value, read once by the composition root (R7). Never the + /// environment: a gate that read it per call could not be tested without racing. + token: Option, + implementation: Implementation, + tool_router: ToolRouter, +} + +#[tool_router] +impl AdminMcp { + /// Builds the server. `implementation` is the composition root's, so `serverInfo` carries + /// the daemon's version and not this crate's (R6). + pub fn new( + state: Arc, + token: Option, + implementation: Implementation, + ) -> Self { + Self { + state, + token, + implementation, + tool_router: Self::tool_router(), + } + } + + /// `GET /admin/settings`: the merged document narrowed to the defaults' keys and + /// redacted, by the same two functions in the same order the controller uses (R11). + #[tool( + description = "Read the merged settings document, narrowed to the defaults' keys and redacted" + )] + async fn settings_get(&self) -> CallToolResult { + match self.settings_document() { + Ok(document) => CallToolResult::structured(json!({ "settings": document })), + Err(error) => tool_error(&error), + } + } + + /// `PATCH /admin/settings`, through the controller's own write function (R13). + #[tool( + description = "Write settings: one path as {\"path\": \"wot.enabled\", \"value\": false}, or several as {\"changes\": [{\"path\": …, \"value\": …}, …]}" + )] + async fn settings_set( + &self, + Parameters(arguments): Parameters, + ) -> CallToolResult { + match patch_settings::apply(&self.state, &arguments.body, "").await { + Ok(SettingsWrite::Written(body)) => CallToolResult::structured(body), + Ok(SettingsWrite::Refused { body, .. }) => tool_error_body(&body), + Err(error) => tool_error(&McpError::from(error)), + } + } + + /// One `EventRepository` read over one [`Filter`], through `collect_records` so a vanished + /// slot never reaches the payload (R15). + #[tool( + description = "List stored events matching the given kinds, authors, ids, since and until, up to limit" + )] + async fn list_events( + &self, + Parameters(criteria): Parameters, + ) -> CallToolResult { + match self.events(criteria).await { + Ok(records) => CallToolResult::structured(json!({ "events": records })), + Err(error) => tool_error(&error), + } + } + + /// One exact-id read: the filter selects prefixes, so the row's id is compared for equality + /// before it is returned (R16). + #[tool( + description = "Read one stored event by its exact 64-character hex id; null when no such id is stored" + )] + async fn get_event(&self, Parameters(arguments): Parameters) -> CallToolResult { + match self.event(&arguments.id).await { + Ok(Some(record)) => CallToolResult::structured(json!({ "event": record })), + Ok(None) => CallToolResult::structured(json!({ "event": null })), + Err(error) => tool_error(&error), + } + } + + fn settings_document(&self) -> Result { + let (merged, defaults) = self.state.merged_document()?; + let filtered = nostream_config::store::filter_against_defaults(&merged, &defaults); + let redacted = nostream_config::redaction::redact_settings_secrets(&filtered); + Ok(serde_json::to_value(redacted)?) + } + + async fn events(&self, criteria: ListEventsArgs) -> Result, McpError> { + // No default limit: an absent `limit` leaves the store's `DEFAULT_FILTER_LIMIT` in + // charge, which is what a caller who passed none is entitled to (R15). + let filter = Filter { + kinds: criteria + .kinds + .map(|kinds| kinds.into_iter().map(Kind).collect()), + authors: criteria.authors, + ids: criteria.ids, + since: criteria.since, + until: criteria.until, + limit: criteria.limit, + ..Filter::default() + }; + let filters = [filter]; + let stream = self.state.stores().events.find_by_filters(&filters).await?; + Ok(collect_records(stream).await?) + } + + async fn event(&self, id: &str) -> Result, McpError> { + let filters = [Filter { + ids: Some(vec![id.to_owned()]), + limit: Some(1), + ..Filter::default() + }]; + let stream = self.state.stores().events.find_by_filters(&filters).await?; + let records = collect_records(stream).await?; + // `Filter::ids` members are hex prefixes and the store widens a short one to a + // whole-field range, so only an equal id is the event that was asked for (R16). + Ok(records + .into_iter() + .find(|record| record.event.id.to_string() == id)) + } + + /// The gate's refusal, if the call cannot run (R7): the console's enabled predicate first, + /// then its `SECRET`, then its session token — the three checks its own layers make, in the + /// order its router makes them. + fn refusal(&self) -> Option<&'static str> { + if !self.surface_enabled() { + return Some(NOT_FOUND); + } + let Some(secret) = self.state.secret() else { + return Some(INTERNAL_SERVER_ERROR); + }; + let key = session::session_key(secret); + match &self.token { + Some(token) if session::is_valid_token(&key, token, self.state.clock().now_secs()) => { + None + } + _ => Some(UNAUTHORIZED), + } + } + + /// `admin.enabled`, the predicate `admin_enabled_middleware` gates the console with. + fn surface_enabled(&self) -> bool { + self.state + .settings() + .ok() + .and_then(|settings| settings.admin.map(|admin| admin.enabled)) + .unwrap_or(false) + } + + /// R9's line, appended at dispatch: the tool name and the requested paths are the + /// arguments, so nothing recorded depends on what the handler then does. + fn record_dispatch(&self, tool: &str, arguments: Option<&Map>) { + let detail = dispatch_detail(tool, arguments); + if let Err(error) = self + .state + .append_audit(&audit_action(tool), None, Some(detail)) + { + tracing::warn!(%error, tool, "the MCP audit entry was not recorded"); + } + } +} + +/// Whether a call's arguments are the shape its `inputSchema` states. +/// +/// The router answers a deserialisation failure with its own `isError` result, and R9 puts that +/// failure on the same footing as a refused credential: nothing is written. So the audit line is +/// emitted only for a call that will reach a tool, which needs the arguments checked before +/// dispatch — against the same types the tools take, so the two cannot drift. +fn arguments_parse(tool: &str, arguments: Option<&Map>) -> bool { + let arguments = Value::Object(arguments.cloned().unwrap_or_default()); + match tool { + // No parameters: the router deserialises nothing, so anything is accepted. + TOOL_SETTINGS_GET => true, + TOOL_SETTINGS_SET => serde_json::from_value::(arguments).is_ok(), + TOOL_LIST_EVENTS => serde_json::from_value::(arguments).is_ok(), + TOOL_GET_EVENT => serde_json::from_value::(arguments).is_ok(), + // An unknown tool is not dispatched at all: the router answers `-32602` and nothing runs. + _ => false, + } +} + +#[tool_handler(router = self.tool_router)] +impl ServerHandler for AdminMcp { + fn get_info(&self) -> ServerConfig { + ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) + .with_server_info(self.implementation.clone()) + } + + /// The gate and the audit sink, in front of the router's dispatch. + /// + /// `tools/list` is not gated (R8): a client discovers the surface before it presents a + /// credential, and the refusal is at the call. + async fn call_tool( + &self, + request: CallToolRequestParams, + context: RequestContext, + ) -> Result { + if let Some(refusal) = self.refusal() { + tracing::warn!(tool = %request.name, refusal, "the MCP call was refused"); + return Ok(CallToolResult::error(vec![ContentBlock::text(refusal)]).into()); + } + if arguments_parse(&request.name, request.arguments.as_ref()) { + self.record_dispatch(&request.name, request.arguments.as_ref()); + } + let call = ToolCallContext::new(self, request, context); + self.tool_router.call(call).await + } +} + +/// The detail an `mcp.` line carries: the tool, plus the requested paths for +/// `settings_set` — never a value (R9). +fn dispatch_detail(tool: &str, arguments: Option<&Map>) -> Value { + if tool == TOOL_SETTINGS_SET + && let Some(patch) = arguments.and_then(settings_patch) + { + let paths: Vec<&str> = patch + .changes + .iter() + .map(|change| change.path.as_str()) + .collect(); + return json!({ "tool": tool, "paths": paths }); + } + json!({ "tool": tool }) +} + +/// A failure as an `isError: true` result, carrying the error's own message so the caller can +/// read it: a JSON-RPC error would reach them as an opaque internal failure. +fn tool_error(error: &McpError) -> CallToolResult { + CallToolResult::error(vec![ContentBlock::text(error.to_string())]) +} + +/// A refusal body as an `isError: true` result — the controller's own JSON, rendered (R13). +fn tool_error_body(body: &Value) -> CallToolResult { + CallToolResult::error(vec![ContentBlock::text(body.to_string())]) +} diff --git a/crates/nostream-mcp/tests/audit.rs b/crates/nostream-mcp/tests/audit.rs new file mode 100644 index 000000000..c0b2e1741 --- /dev/null +++ b/crates/nostream-mcp/tests/audit.rs @@ -0,0 +1,112 @@ +//! AC22 — one audit line per executed call, and none for a refused one. +//! +//! | case | what it proves | +//! |---|---| +//! | `each_call_appends_one_line` | four calls append five lines in call order — the four `mcp.*` lines, then `settings_set`'s own `settings.updated` | +//! | `a_refused_call_appends_nothing` | a call with bad arguments and a call with no token each leave the file untouched | +//! +//! R9 appends the `mcp.*` line at dispatch, before the handler's work, so the order in the file +//! is the order of the calls and a domain line always follows its own dispatch line. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::{Fixture, TestMcp, Token, event, id_of, text}; +use nostream_mcp::{ + TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, audit_action, +}; +use serde_json::json; + +#[tokio::test] +async fn each_call_appends_one_line() { + let fixture = TestMcp::start().await; + let record = event(21, 1, 1_699_999_960); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + client.call(TOOL_SETTINGS_GET, json!({})).await; + client.call(TOOL_LIST_EVENTS, json!({})).await; + client.call(TOOL_GET_EVENT, json!({ "id": id })).await; + let written = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": false }), + ) + .await; + assert_eq!(written.is_error, Some(false), "{}", text(&written)); + + let entries = fixture.audit_entries(); + let actions: Vec<&str> = entries + .iter() + .map(|entry| entry["action"].as_str().unwrap()) + .collect(); + assert_eq!( + actions, + vec![ + "mcp.settings_get", + "mcp.list_events", + "mcp.get_event", + "mcp.settings_set", + "settings.updated", + ], + "call order, with the write path's own line from its own call: {entries:?}" + ); + + for (entry, tool) in entries.iter().zip([ + TOOL_SETTINGS_GET, + TOOL_LIST_EVENTS, + TOOL_GET_EVENT, + TOOL_SETTINGS_SET, + ]) { + assert_eq!(entry["action"], audit_action(tool)); + assert!( + entry.get("remoteAddress").is_none(), + "a stdio caller has no address: {entry}" + ); + assert_eq!(entry["detail"]["tool"], tool); + assert!(entry["id"].as_str().is_some_and(|id| !id.is_empty())); + assert!(entry["at"].as_str().is_some()); + } + + assert_eq!( + entries[3]["detail"]["paths"], + json!(["wot.enabled"]), + "the settings write names the paths it asked for, never the values" + ); + assert!( + entries[3]["detail"].get("value").is_none(), + "no value is recorded: {}", + entries[3] + ); +} + +#[tokio::test] +async fn a_refused_call_appends_nothing() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + let error = client + .try_call(TOOL_GET_EVENT, json!({ "id": 7 })) + .await + .expect("a tool result"); + assert_eq!(error.is_error, Some(true)); + assert!( + fixture.audit_entries().is_empty(), + "an argument the schema refuses is refused before dispatch" + ); + + // A second server, built with no token, over its own config dir. + let untokened = TestMcp::start_with(Fixture { + token: Token::Absent, + ..Fixture::default() + }) + .await; + let unauthenticated = untokened.client().await; + let refused = unauthenticated.call(TOOL_SETTINGS_GET, json!({})).await; + assert_eq!(refused.is_error, Some(true)); + assert!( + untokened.audit_entries().is_empty(), + "a refused credential writes nothing" + ); +} diff --git a/crates/nostream-mcp/tests/auth.rs b/crates/nostream-mcp/tests/auth.rs new file mode 100644 index 000000000..ca8bed9b8 --- /dev/null +++ b/crates/nostream-mcp/tests/auth.rs @@ -0,0 +1,103 @@ +//! AC21 — unauthenticated calls are refused, four ways, without touching the environment. +//! +//! | case | what it proves | +//! |---|---| +//! | `no_token_refuses_every_tool` | a server built with no token refuses all four tools with `Unauthorized`, and still lists them | +//! | `an_expired_token_is_refused` | a token that expired one second ago is `Unauthorized` | +//! | `a_disabled_surface_is_refused` | `admin.enabled: false` answers `Not Found`, as the console does | +//! | `a_missing_secret_is_refused` | no `SECRET` answers `Internal Server Error` | +//! +//! Each case builds its own server with the token as a **value**, and none sets an environment +//! variable: four cases in one binary run in parallel, so an environment-based gate would race. +//! The three texts are distinct on purpose — a gate that collapsed them could pass a case +//! written against the wrong arm. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::{Fixture, TestMcp, Token, text}; +use nostream_mcp::{INTERNAL_SERVER_ERROR, NOT_FOUND, TOOL_GET_EVENT, UNAUTHORIZED}; +use serde_json::json; + +/// The four tools, each with arguments its schema accepts, so the refusal cannot be a +/// deserialisation failure in disguise. +fn calls() -> [(&'static str, serde_json::Value); 4] { + [ + (nostream_mcp::TOOL_SETTINGS_GET, json!({})), + ( + nostream_mcp::TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": true }), + ), + (nostream_mcp::TOOL_LIST_EVENTS, json!({ "kinds": [1] })), + (TOOL_GET_EVENT, json!({ "id": "00".repeat(32) })), + ] +} + +#[tokio::test] +async fn no_token_refuses_every_tool() { + let fixture = TestMcp::start_with(Fixture { + token: Token::Absent, + ..Fixture::default() + }) + .await; + let client = fixture.client().await; + + assert_eq!(client.tools().await.len(), 4, "tools/list is not gated"); + for (tool, arguments) in calls() { + let result = client.call(tool, arguments).await; + assert_eq!(result.is_error, Some(true), "{tool}"); + assert_eq!(text(&result), UNAUTHORIZED, "{tool}"); + } + assert!( + fixture.audit_entries().is_empty(), + "a refusal writes nothing" + ); +} + +#[tokio::test] +async fn an_expired_token_is_refused() { + let fixture = TestMcp::start_with(Fixture { + token: Token::Expired, + ..Fixture::default() + }) + .await; + let client = fixture.client().await; + + let result = client + .call(nostream_mcp::TOOL_SETTINGS_GET, json!({})) + .await; + assert_eq!(result.is_error, Some(true)); + assert_eq!(text(&result), UNAUTHORIZED); + assert!(fixture.audit_entries().is_empty()); +} + +#[tokio::test] +async fn a_disabled_surface_is_refused() { + let fixture = TestMcp::start_with(Fixture::default().with("admin.enabled", json!(false))).await; + let client = fixture.client().await; + + let result = client + .call(nostream_mcp::TOOL_SETTINGS_GET, json!({})) + .await; + assert_eq!(result.is_error, Some(true)); + assert_eq!(text(&result), NOT_FOUND); + assert!(fixture.audit_entries().is_empty()); +} + +#[tokio::test] +async fn a_missing_secret_is_refused() { + let fixture = TestMcp::start_with(Fixture { + secret: None, + ..Fixture::default() + }) + .await; + let client = fixture.client().await; + + let result = client + .call(nostream_mcp::TOOL_SETTINGS_GET, json!({})) + .await; + assert_eq!(result.is_error, Some(true)); + assert_eq!(text(&result), INTERNAL_SERVER_ERROR); + assert!(fixture.audit_entries().is_empty()); +} diff --git a/crates/nostream-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs new file mode 100644 index 000000000..abadabc98 --- /dev/null +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -0,0 +1,385 @@ +//! The MCP test harness: `AdminState` over a temporary config dir and an LMDB store, and an +//! in-process duplex client — no child process and no port. +//! +//! The state is composed the way `crates/nostream-admin/tests/common/mod.rs:153-232` composes it, +//! minus the HTTP server: the same fixture values (`SECRET`, `PASSWORD_HASH`, `NOW_MS`), the same +//! seeding pattern (`crates/nostream-storage/tests/parity_lmdb.rs:84-92`) and the console's real +//! `resources/` tree as the schema source. The client is `rmcp`'s over `tokio::io::duplex`, which +//! is the only way to call a tool without a transport (`Peer::new` is `pub(crate)` in the SDK). + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, dead_code)] + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use nostream_admin::state::AdminStateConfig; +use nostream_admin::utils::session; +use nostream_admin::{AdminState, GrafanaSettings}; +use nostream_config::SettingsPaths; +use nostream_core::clock::TestClock; +use nostream_core::nip05::Nip05Fetch; +use nostream_core::random::SystemRandom; +use nostream_core::{Event, EventId, Kind, Pubkey, Signature}; +use nostream_mcp::{AdminMcp, MCP_SERVER_NAME}; +use nostream_services::{HttpClient, ReqwestClient, ServiceStores}; +use nostream_storage::lmdb::LmdbBackend; +use nostream_storage::repositories::{EventRecord, EventRepository}; +use rmcp::model::{ + CallToolRequestParams, CallToolResult, ClientCapabilities, ClientConfig, Implementation, + ProtocolVersion, Tool, +}; +use rmcp::service::RunningService; +use rmcp::{RoleClient, ServiceError, ServiceExt}; +use serde_json::{Map, Value}; +use tokio::task::JoinHandle; + +/// The repository root, from the crate's manifest directory. +pub fn repo_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +/// The resources root the settings schema is read from. +pub fn resources_root() -> PathBuf { + repo_root().join("resources") +} + +/// The fixture password hash `hashAdminPassword` writes for `hunter2`. +pub const PASSWORD_HASH: &str = "scrypt:BwcHBwcHBwcHBwcHBwcHBw==:r5daXU05UJ9EUDu45YoHMWUoQCmkVbwINYNntY1/dwrJPOt3fTi/1IWw1wp9+YXRj1Vm6IpFi+gSU0JdqZvWIw=="; + +/// The literal `SECRET` the fixture signs sessions with. +pub const SECRET: &[u8] = b"a-test-secret"; + +/// The clock the fixture starts at. +pub const NOW_MS: u64 = 1_700_000_000_000; + +/// The console's happy-path settings: the surface on and the fixture hash. +pub fn base_settings() -> serde_yaml::Value { + serde_yaml::from_str(&format!( + "info:\n name: Example\n relay_url: wss://relay.example\nadmin:\n enabled: true\n passwordHash: \"{PASSWORD_HASH}\"\n" + )) + .unwrap() +} + +/// The token a case presents. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Token { + /// A valid session token minted from the fixture's `SECRET`. + Valid, + /// No token at all. + Absent, + /// A token that expired one second before the fixture's clock. + Expired, +} + +/// What a test wants built. +pub struct Fixture { + /// The user settings document written to `/settings.yaml`. + pub settings: serde_yaml::Value, + /// `SECRET` as a value; `None` is the missing-secret case. + pub secret: Option>, + /// The token the server is built with. + pub token: Token, + /// The starting clock reading. + pub now_ms: u64, +} + +impl Default for Fixture { + fn default() -> Self { + Self { + settings: base_settings(), + secret: Some(SECRET.to_vec()), + token: Token::Valid, + now_ms: NOW_MS, + } + } +} + +impl Fixture { + /// The base settings with one path replaced. + pub fn with(mut self, path: &str, value: Value) -> Self { + let value: serde_yaml::Value = serde_yaml::from_str(&value.to_string()).unwrap(); + self.settings = nostream_config::path::set_by_path(&self.settings, path, value).unwrap(); + self + } +} + +/// One composed server over a temporary config dir, and what it was composed with. +pub struct TestMcp { + pub state: Arc, + pub clock: Arc, + pub config_dir: PathBuf, + pub backend: Arc, + token: Option, + _temp: tempfile::TempDir, +} + +impl TestMcp { + /// Builds the fixture's default composition. + pub async fn start() -> Self { + Self::start_with(Fixture::default()).await + } + + /// Builds a case's composition. + pub async fn start_with(fixture: Fixture) -> Self { + let temp = tempfile::tempdir().unwrap(); + let config_dir = temp.path().join("config"); + std::fs::create_dir_all(&config_dir).unwrap(); + write_settings(&config_dir, &fixture.settings); + + // `is_valid_token` refuses `expires_at <= now`, so a token minted for the second before + // the clock is a token that has just expired. + let token = match (fixture.token, fixture.secret.as_deref()) { + (Token::Absent, _) | (_, None) => None, + (Token::Valid, Some(secret)) => Some(mint(secret, now_seconds(fixture.now_ms) + 3_600)), + (Token::Expired, Some(secret)) => Some(mint(secret, now_seconds(fixture.now_ms) - 1)), + }; + + let backend = LmdbBackend::open(temp.path().join("store")).await.unwrap(); + let backend = Arc::new(backend); + let stores = Arc::new(ServiceStores { + events: Arc::clone(&backend) as Arc, + users: Arc::clone(&backend) as Arc, + invoices: Arc::clone(&backend) + as Arc, + nip05: Arc::clone(&backend) + as Arc, + dvm_jobs: Arc::clone(&backend) + as Arc, + notification_outbox: Arc::clone(&backend) + as Arc, + notification_delivery_log: Arc::clone(&backend) + as Arc, + }); + + let client = Arc::new(ReqwestClient::new().unwrap()); + let http: Arc = client.clone(); + let fetch: Arc = client; + + let clock = Arc::new(TestClock::new(fixture.now_ms)); + let state = Arc::new(AdminState::with_random( + AdminStateConfig { + paths: SettingsPaths::from_config_dir(&repo_root(), &config_dir), + resources_root: resources_root(), + secret: fixture.secret, + stores, + http, + fetch, + clock: clock.clone(), + grafana: GrafanaSettings::default(), + metrics_interval: std::time::Duration::from_millis(1_000), + worker_type: "primary".to_owned(), + worker_index: None, + worker_count_override: Some(1), + password_override: None, + }, + Arc::new(SystemRandom), + )); + + Self { + state, + clock, + config_dir, + backend, + token, + _temp: temp, + } + } + + /// A client over an in-process duplex, served by a server on the fixture's state. + pub async fn client(&self) -> Mcp { + self.client_with_version(env!("CARGO_PKG_VERSION")).await + } + + /// The same, with the `serverInfo` version the composition would supply (R6). + pub async fn client_with_version(&self, version: &str) -> Mcp { + let server = AdminMcp::new( + Arc::clone(&self.state), + self.token.clone(), + Implementation::new(MCP_SERVER_NAME, version), + ); + let (server_io, client_io) = tokio::io::duplex(64 * 1024); + let handle = tokio::spawn(async move { + let service = server.serve(server_io).await.unwrap(); + service.waiting().await.unwrap(); + }); + // Pinned to a version with the `initialize` handshake, so the dialogue is the session + // model the console's credential belongs to. + let config = ClientConfig::new( + ClientCapabilities::default(), + Implementation::new("nostream-mcp-tests", "0.1.0"), + ) + .with_protocol_version(ProtocolVersion::V_2025_06_18); + let client = config.serve(client_io).await.unwrap(); + Mcp { + client, + _server: handle, + } + } + + /// Seeds events through the store's own insert path. + pub async fn seed(&self, records: &[EventRecord]) { + self.backend.upsert_many(records).await.unwrap(); + } + + /// Writes the user settings document, for a case whose fixture is a file edit. + pub fn write_settings(&self, document: &serde_yaml::Value) { + write_settings(&self.config_dir, document); + } + + /// The user settings document as it stands on disk. + pub fn settings_file(&self) -> serde_yaml::Value { + serde_yaml::from_str( + &std::fs::read_to_string(self.config_dir.join("settings.yaml")).unwrap(), + ) + .unwrap() + } + + /// The `admin-audit.jsonl` entries, in file order. + pub fn audit_entries(&self) -> Vec { + lines(&self.config_dir.join("admin-audit.jsonl")) + } + + /// The `settings-audit.jsonl` entries, in file order. + pub fn settings_audit_entries(&self) -> Vec { + lines(&self.config_dir.join("settings-audit.jsonl")) + } + + /// The backup files `save_with_backup` left. + pub fn backups(&self) -> Vec { + let Ok(entries) = std::fs::read_dir(self.config_dir.join("backups")) else { + return Vec::new(); + }; + let mut names: Vec = entries + .filter_map(|entry| entry.ok()) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names + } + + /// The outbox rows a write enqueued, claimed the way the delivery worker claims them. + pub async fn outbox(&self) -> Vec { + self.state + .stores() + .notification_outbox + .claim_batch(50) + .await + .expect("the outbox") + } +} + +/// One connected client, and the server task behind it. +pub struct Mcp { + pub client: RunningService, + _server: JoinHandle<()>, +} + +impl Mcp { + /// The `tools/list` document's tools, in the order the server returns them. + pub async fn tools(&self) -> Vec { + self.client.list_tools(None).await.unwrap().tools + } + + /// One `tools/call`, unwrapping the protocol layer. + pub async fn call(&self, name: &str, arguments: Value) -> CallToolResult { + self.try_call(name, arguments).await.unwrap() + } + + /// One `tools/call` carrying no arguments at all. + pub async fn call_without_arguments(&self, name: &str) -> CallToolResult { + self.client + .call_tool(CallToolRequestParams::new(name.to_owned())) + .await + .unwrap() + } + + /// One `tools/call`, keeping a JSON-RPC error as an error. + pub async fn try_call( + &self, + name: &str, + arguments: Value, + ) -> Result { + self.client + .call_tool( + CallToolRequestParams::new(name.to_owned()).with_arguments(object(arguments)), + ) + .await + } +} + +/// The structured payload a tool answered, which every payload assertion reads. +pub fn payload(result: &CallToolResult) -> Value { + result + .structured_content + .clone() + .expect("a tool that succeeds answers structured content") +} + +/// The text a tool answered — an error result's whole message. +pub fn text(result: &CallToolResult) -> String { + result + .content + .iter() + .filter_map(|block| block.as_text()) + .map(|text| text.text.clone()) + .collect::>() + .join("") +} + +/// A JSON object as the arguments type the protocol carries. +pub fn object(value: Value) -> Map { + match value { + Value::Object(object) => object, + _ => panic!("arguments must be a JSON object"), + } +} + +/// A signed event of the given kind and creation time, by the key `secret`. +/// +/// The store's fixture (`crates/nostream-storage/tests/parity_lmdb.rs:92-105`): the same +/// arguments twice are one event and one id, so a case that wants two rows of one kind passes +/// two different secrets. +pub fn event(secret: u8, kind: u64, created_at: i64) -> EventRecord { + let mut event = Event { + id: EventId::from_byte_array([0; 32]), + pubkey: Pubkey::from_byte_array([0; 32]), + created_at, + kind: Kind(kind), + tags: Vec::new(), + content: format!("{secret}-{created_at}"), + sig: Signature::from_byte_array([0; 64]), + }; + nostream_core::crypto::sign_event(&[secret; 32], &mut event).expect("the event signs"); + EventRecord::from_event(&event) +} + +/// The hex id a seeded record reads back as. +pub fn id_of(record: &EventRecord) -> String { + record.event.id.to_string() +} + +fn mint(secret: &[u8], expires_at: i64) -> String { + session::create_token(&session::session_key(secret), expires_at) +} + +fn now_seconds(now_ms: u64) -> i64 { + i64::try_from(now_ms / 1_000).unwrap() +} + +fn write_settings(config_dir: &Path, document: &serde_yaml::Value) { + std::fs::write( + config_dir.join("settings.yaml"), + serde_yaml::to_string(document).unwrap(), + ) + .unwrap(); +} + +fn lines(path: &Path) -> Vec { + let Ok(raw) = std::fs::read_to_string(path) else { + return Vec::new(); + }; + raw.lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| serde_json::from_str(line).unwrap()) + .collect() +} diff --git a/crates/nostream-mcp/tests/fixtures/tools_list.json b/crates/nostream-mcp/tests/fixtures/tools_list.json new file mode 100644 index 000000000..cbd01cc62 --- /dev/null +++ b/crates/nostream-mcp/tests/fixtures/tools_list.json @@ -0,0 +1,105 @@ +{ + "tools": [ + { + "description": "Read one stored event by its exact 64-character hex id; null when no such id is stored", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "id": { + "description": "The event's 64-character lowercase hex id.", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "name": "get_event" + }, + { + "description": "List stored events matching the given kinds, authors, ids, since and until, up to limit", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "authors": { + "description": "Author pubkey hex prefixes.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "ids": { + "description": "Event id hex prefixes.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "kinds": { + "description": "Kinds to select; absent selects every kind.", + "items": { + "format": "uint64", + "minimum": 0, + "type": "integer" + }, + "type": [ + "array", + "null" + ] + }, + "limit": { + "description": "Page size; absent leaves the store's own default in charge.", + "format": "uint64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "since": { + "description": "Events created at or after this unix second.", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "until": { + "description": "Events created at or before this unix second.", + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + }, + "name": "list_events" + }, + { + "description": "Read the merged settings document, narrowed to the defaults' keys and redacted", + "inputSchema": { + "properties": {}, + "type": "object" + }, + "name": "settings_get" + }, + { + "description": "Write settings: one path as {\"path\": \"wot.enabled\", \"value\": false}, or several as {\"changes\": [{\"path\": …, \"value\": …}, …]}", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": true, + "type": "object" + }, + "name": "settings_set" + } + ] +} diff --git a/crates/nostream-mcp/tests/tool_payloads.rs b/crates/nostream-mcp/tests/tool_payloads.rs new file mode 100644 index 000000000..18c32ac73 --- /dev/null +++ b/crates/nostream-mcp/tests/tool_payloads.rs @@ -0,0 +1,349 @@ +//! AC9–AC20 — the oracle's payload half: one real call per tool, asserting the returned JSON +//! against a fixture of known rows, plus one refusal per tool path. +//! +//! | case | what it proves | +//! |---|---| +//! | `a_kind_filter_returns_only_those_kinds` | `list_events` returns the seeded kind-1 ids and no others, as rows | +//! | `a_limit_is_honoured` | a small `limit` bounds the page | +//! | `no_limit_uses_the_stores_default` | the tool invents no `limit`: 30 rows come back from a call with no arguments | +//! | `an_exact_id_returns_its_row` | `get_event` returns the row's own id, kind and content | +//! | `a_prefix_is_not_an_id` | a 4-character hex prefix is not an id: the payload's event is `null` | +//! | `a_secret_is_redacted` | `settings_get` masks the secret and leaves a non-secret path verbatim | +//! | `an_unknown_key_is_dropped` | `settings_get` drops a key the defaults lack | +//! | `a_set_writes_the_file_its_records_and_a_backup` | a write has the controller's four side effects and its body | +//! | `a_workers_change_is_restart_required` | the reload class is the path's own | +//! | `a_sealed_path_is_refused` | a write-protected path answers the controller's body and writes nothing | +//! | `a_null_value_is_a_validation_failure` | an explicit `null` reaches the validator | +//! | `an_empty_change_list_is_refused` | `{changes: []}` is `Invalid request`, and the attempt is audited | +//! | `an_unknown_tool_is_a_protocol_error` | an absent tool is JSON-RPC `-32602`, not a result | +//! | `bad_arguments_are_an_error_result` | wrong-typed arguments are an `isError` result, not a protocol error | + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use std::collections::BTreeSet; + +use common::{TestMcp, event, id_of, payload, text}; +use nostream_mcp::{TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET}; +use serde_json::{Value, json}; + +fn ids(events: &[Value]) -> BTreeSet { + events + .iter() + .map(|record| record["event"]["id"].as_str().unwrap().to_owned()) + .collect() +} + +#[tokio::test] +async fn a_kind_filter_returns_only_those_kinds() { + let fixture = TestMcp::start().await; + // Two kind-1 rows and one kind-7 row. The two kind-1 rows need their own secret and + // creation time: the same arguments twice are one event and one id. + let seeded = [ + event(1, 1, 1_699_999_900), + event(2, 1, 1_699_999_901), + event(3, 7, 1_699_999_902), + ]; + fixture.seed(&seeded).await; + let client = fixture.client().await; + + let result = client.call(TOOL_LIST_EVENTS, json!({ "kinds": [1] })).await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + let events = payload["events"].as_array().unwrap(); + assert_eq!(events.len(), 2, "{payload}"); + assert!( + events.iter().all(|record| record["event"]["kind"] == 1), + "every row is kind 1: {payload}" + ); + let expected: BTreeSet = seeded + .iter() + .filter(|record| record.event.kind.0 == 1) + .map(id_of) + .collect(); + assert_eq!(ids(events), expected, "the seeded kind-1 ids and no others"); +} + +#[tokio::test] +async fn a_limit_is_honoured() { + let fixture = TestMcp::start().await; + fixture + .seed(&[event(1, 1, 1_699_999_900), event(2, 1, 1_699_999_901)]) + .await; + let client = fixture.client().await; + + let result = client.call(TOOL_LIST_EVENTS, json!({ "limit": 1 })).await; + let payload = payload(&result); + assert_eq!(payload["events"].as_array().unwrap().len(), 1, "{payload}"); +} + +#[tokio::test] +async fn no_limit_uses_the_stores_default() { + let fixture = TestMcp::start().await; + let seeded: Vec<_> = (0..30) + .map(|index| { + event( + u8::try_from(index + 1).unwrap(), + 1, + 1_699_999_000 + i64::from(index), + ) + }) + .collect(); + fixture.seed(&seeded).await; + let client = fixture.client().await; + + // No arguments at all: a tool that wrote `limit.unwrap_or(20)` answers 20 here. + let result = client.call_without_arguments(TOOL_LIST_EVENTS).await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + assert_eq!( + payload["events"].as_array().unwrap().len(), + 30, + "the store's own default page leaves every seeded row" + ); +} + +#[tokio::test] +async fn an_exact_id_returns_its_row() { + let fixture = TestMcp::start().await; + let record = event(11, 1, 1_699_999_950); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let result = client.call(TOOL_GET_EVENT, json!({ "id": id })).await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + assert_eq!(payload["event"]["event"]["id"], id); + assert_eq!(payload["event"]["event"]["kind"], 1); + assert_eq!(payload["event"]["event"]["content"], "11-1699999950"); +} + +#[tokio::test] +async fn a_prefix_is_not_an_id() { + let fixture = TestMcp::start().await; + let record = event(12, 1, 1_699_999_951); + let id = id_of(&record); + let prefix = &id[..4]; + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + // The store's id plan widens a 4-character criterion to a whole-field range, so the read + // is not empty: only the equality compare makes this a miss. + let result = client.call(TOOL_GET_EVENT, json!({ "id": prefix })).await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + assert!( + payload["event"].is_null(), + "a prefix is not an id: {payload}" + ); +} + +#[tokio::test] +async fn a_secret_is_redacted() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let result = client.call(TOOL_SETTINGS_GET, json!({})).await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + assert_eq!(payload["settings"]["admin"]["passwordHash"], "***"); + assert_eq!( + payload["settings"]["info"]["relay_url"], "wss://relay.example", + "a non-secret path is verbatim: {payload}" + ); +} + +#[tokio::test] +async fn an_unknown_key_is_dropped() { + let fixture = TestMcp::start().await; + let mut settings: serde_yaml::Value = fixture.settings_file(); + settings = + nostream_config::path::set_by_path(&settings, "customKey", serde_yaml::Value::Bool(true)) + .unwrap(); + fixture.write_settings(&settings); + let client = fixture.client().await; + + let result = client.call(TOOL_SETTINGS_GET, json!({})).await; + let payload = payload(&result); + assert!( + payload["settings"].get("customKey").is_none(), + "an unknown key is dropped: {payload}" + ); + assert!( + payload["settings"]["admin"].get("passwordHash").is_some(), + "a passwordHash the defaults lack survives: {payload}" + ); +} + +#[tokio::test] +async fn a_set_writes_the_file_its_records_and_a_backup() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let result = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": false }), + ) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + assert_eq!( + payload(&result), + json!({ "ok": true, "path": "wot.enabled", "value": false, "reload": "hot-reload" }) + ); + + assert_eq!( + fixture.settings_file()["wot"]["enabled"], + serde_yaml::Value::Bool(false), + "the file carries the change" + ); + + let settings_audit = fixture.settings_audit_entries(); + assert_eq!(settings_audit.len(), 1, "{settings_audit:?}"); + assert_eq!(settings_audit[0]["action"], "settings.updated"); + assert_eq!(settings_audit[0]["changes"][0]["path"], "wot.enabled"); + + let audit = fixture.audit_entries(); + let actions: Vec<&Value> = audit.iter().map(|entry| &entry["action"]).collect(); + assert_eq!( + actions, + vec![&json!("mcp.settings_set"), &json!("settings.updated"),], + "the dispatch line first, then the shared write path's own" + ); + + let outbox = fixture.outbox().await; + let events: Vec<&str> = outbox.iter().map(|row| row.event_type.as_str()).collect(); + assert_eq!(events, vec!["settings.changed"], "one row, no others"); + + assert_eq!(fixture.backups().len(), 1, "one save, one backup"); +} + +#[tokio::test] +async fn a_workers_change_is_restart_required() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let result = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "workers.count", "value": 2 }), + ) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + assert_eq!(payload(&result)["reload"], "restart-required"); +} + +#[tokio::test] +async fn a_sealed_path_is_refused() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let result = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "admin.passwordHash", "value": "scrypt:a:b" }), + ) + .await; + assert_eq!(result.is_error, Some(true), "{}", text(&result)); + let refusal: Value = serde_json::from_str(&text(&result)).expect("the body is JSON"); + assert_eq!(refusal["error"], "Validation failed"); + assert_eq!( + refusal["issues"][0], + json!({ "path": "admin.passwordHash", "message": "Path is write-protected" }) + ); + + let actions: Vec = fixture + .audit_entries() + .iter() + .map(|entry| entry["action"].clone()) + .collect(); + assert_eq!( + actions, + vec![json!("mcp.settings_set")], + "the attempt is visible and the write is not" + ); + assert!( + fixture.settings_audit_entries().is_empty(), + "no settings line" + ); + assert!(fixture.backups().is_empty(), "no backup"); +} + +#[tokio::test] +async fn a_null_value_is_a_validation_failure() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let result = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "wot.seedPubkey", "value": null }), + ) + .await; + assert_eq!(result.is_error, Some(true), "{}", text(&result)); + let refusal: Value = serde_json::from_str(&text(&result)).expect("the body is JSON"); + assert_eq!(refusal["error"], "Validation failed"); + assert_eq!(refusal["issues"][0]["path"], "wot.seedPubkey"); + assert_eq!(refusal["issues"][0]["message"], "Expected string, got null"); +} + +#[tokio::test] +async fn an_empty_change_list_is_refused() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let result = client + .call(TOOL_SETTINGS_SET, json!({ "changes": [] })) + .await; + assert_eq!(result.is_error, Some(true), "{}", text(&result)); + let refusal: Value = serde_json::from_str(&text(&result)).expect("the body is JSON"); + assert_eq!(refusal["error"], "Invalid request"); + + let actions: Vec = fixture + .audit_entries() + .iter() + .map(|entry| entry["action"].clone()) + .collect(); + assert_eq!( + actions, + vec![json!("mcp.settings_set")], + "the dispatch line exists even though the body was refused" + ); + assert!(fixture.settings_audit_entries().is_empty()); + assert!(fixture.backups().is_empty()); +} + +#[tokio::test] +async fn an_unknown_tool_is_a_protocol_error() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let error = client + .try_call("delete_event", json!({})) + .await + .expect_err("an absent tool is a JSON-RPC error, not a result"); + let rmcp::ServiceError::McpError(error) = error else { + panic!("a protocol error, not a transport failure: {error:?}"); + }; + assert_eq!(error.code.0, -32602, "{error:?}"); + assert!(error.message.contains("tool not found"), "{error:?}"); +} + +#[tokio::test] +async fn bad_arguments_are_an_error_result() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let result = client + .try_call(TOOL_GET_EVENT, json!({ "id": 7 })) + .await + .expect("wrong-typed arguments are a result, not a protocol error"); + assert_eq!(result.is_error, Some(true), "{}", text(&result)); + assert!( + text(&result).contains("failed to deserialize parameters"), + "{}", + text(&result) + ); +} diff --git a/crates/nostream-mcp/tests/tools_list.rs b/crates/nostream-mcp/tests/tools_list.rs new file mode 100644 index 000000000..b0b5154e5 --- /dev/null +++ b/crates/nostream-mcp/tests/tools_list.rs @@ -0,0 +1,170 @@ +//! AC6–AC8 — the oracle's schema half: the whole `tools/list` document against a committed +//! snapshot. +//! +//! | case | what it proves | +//! |---|---| +//! | `the_tool_list_matches_the_snapshot` | every tool's name, description and `inputSchema`, by whole-document equality | +//! | `the_comparator_rejects_a_changed_list` | the comparator can fail: a removed tool, a changed description and a changed schema each fail through the same `compare` | +//! | `the_required_parameters_are_typed` | the shapes the values fix: an `Option` is a two-element type array, `get_event` carries `id`, `settings_set` names both accepted forms, no schema is empty | +//! | `the_server_version_is_what_the_composition_supplies` | `serverInfo.version` is the composition's, not this crate's | +//! +//! The snapshot is **name-sorted**, because rmcp sorts the list and array equality is +//! order-sensitive (R21). It is compared, never regenerated: nothing here writes a file. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::TestMcp; +use nostream_mcp::{TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET}; +use serde_json::{Value, json}; + +/// The committed snapshot, as a document. A missing fixture fails the case. +fn snapshot() -> Value { + let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("fixtures") + .join("tools_list.json"); + let raw = std::fs::read_to_string(&path) + .unwrap_or_else(|error| panic!("the committed snapshot {}: {error}", path.display())); + serde_json::from_str(&raw).expect("the snapshot is JSON") +} + +/// The one comparator both the snapshot case and the tampering case call (R21). +fn compare(actual: &Value, expected: &Value) -> Result<(), String> { + if actual == expected { + return Ok(()); + } + let tools = |document: &Value| { + document["tools"] + .as_array() + .cloned() + .unwrap_or_else(|| vec![document.clone()]) + }; + let (actual_tools, expected_tools) = (tools(actual), tools(expected)); + for expected_tool in &expected_tools { + let name = expected_tool["name"] + .as_str() + .unwrap_or_default() + .to_owned(); + let Some(actual_tool) = actual_tools.iter().find(|tool| tool["name"] == name) else { + return Err(format!("tool {name} is missing from the list")); + }; + for field in ["description", "inputSchema", "outputSchema"] { + if actual_tool[field] != expected_tool[field] { + return Err(format!("tool {name}: {field} differs")); + } + } + if actual_tool != expected_tool { + return Err(format!("tool {name}: the document differs")); + } + } + for actual_tool in &actual_tools { + let name = actual_tool["name"].as_str().unwrap_or_default().to_owned(); + if !expected_tools.iter().any(|tool| tool["name"] == name) { + return Err(format!("tool {name} is not in the snapshot")); + } + } + Err("the tool list differs".to_owned()) +} + +#[tokio::test] +async fn the_tool_list_matches_the_snapshot() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + let actual = json!({ "tools": client.tools().await }); + compare(&actual, &snapshot()).expect("the tool list equals the committed snapshot"); +} + +#[tokio::test] +async fn the_comparator_rejects_a_changed_list() { + let document = snapshot(); + + let mut removed = document.clone(); + removed["tools"].as_array_mut().unwrap().pop(); + assert!(compare(&document, &removed).is_err(), "a removed tool"); + + let mut description = document.clone(); + description["tools"][0]["description"] = + Value::String(format!("{} (drifted)", document["tools"][0]["description"])); + assert!(compare(&description, &document).is_err(), "a description"); + + let mut schema = document.clone(); + schema["tools"][1]["inputSchema"]["type"] = json!("array"); + assert!(compare(&schema, &document).is_err(), "a schema `type`"); +} + +#[tokio::test] +async fn the_required_parameters_are_typed() { + let document = snapshot(); + let tool = |name: &str| { + document["tools"] + .as_array() + .unwrap() + .iter() + .find(|tool| tool["name"] == name) + .unwrap_or_else(|| panic!("{name} is in the snapshot")) + .clone() + }; + + let limit = &tool(TOOL_LIST_EVENTS)["inputSchema"]["properties"]["limit"]["type"]; + let kinds = limit.as_array().expect("an Option is a type array"); + assert_eq!( + kinds.len(), + 2, + "an Option is a two-element type array: {limit}" + ); + assert_eq!(kinds[1], "null", "and its second member is null: {limit}"); + + assert!( + tool(TOOL_GET_EVENT)["inputSchema"]["properties"] + .get("id") + .is_some(), + "get_event declares `id`" + ); + + let description = tool(TOOL_SETTINGS_SET)["description"] + .as_str() + .unwrap_or_default() + .to_owned(); + assert!(description.contains("path"), "{description}"); + assert!(description.contains("changes"), "{description}"); + + for tool in document["tools"].as_array().unwrap() { + let schema = &tool["inputSchema"]; + assert_ne!(schema, &json!({}), "{} has a schema", tool["name"]); + assert_eq!(schema["type"], "object", "{}: {schema}", tool["name"]); + } + + let names: Vec<&str> = document["tools"] + .as_array() + .unwrap() + .iter() + .map(|tool| tool["name"].as_str().unwrap()) + .collect(); + assert_eq!( + names, + vec![ + TOOL_GET_EVENT, + TOOL_LIST_EVENTS, + TOOL_SETTINGS_GET, + TOOL_SETTINGS_SET + ], + "the four slice-1 tools, name-sorted" + ); +} + +#[tokio::test] +async fn the_server_version_is_what_the_composition_supplies() { + let fixture = TestMcp::start().await; + let client = fixture.client_with_version("9.9.9").await; + let info = client + .client + .peer() + .peer_info() + .expect("the initialize result arrived"); + let server = info.server_info.as_ref().expect("the server named itself"); + assert_eq!(server.name, nostream_mcp::MCP_SERVER_NAME); + assert_eq!(server.version, "9.9.9"); + assert_ne!(server.version, env!("CARGO_PKG_VERSION")); +} diff --git a/crates/nostreamd/Cargo.toml b/crates/nostreamd/Cargo.toml index a21a98bad..055861912 100644 --- a/crates/nostreamd/Cargo.toml +++ b/crates/nostreamd/Cargo.toml @@ -20,9 +20,11 @@ hyper-util.workspace = true nostream-admin.workspace = true nostream-config.workspace = true nostream-core.workspace = true +nostream-mcp.workspace = true nostream-relay.workspace = true nostream-services.workspace = true nostream-storage.workspace = true +rmcp.workspace = true serde_json.workspace = true tokio.workspace = true tracing.workspace = true diff --git a/crates/nostreamd/src/lib.rs b/crates/nostreamd/src/lib.rs index 2cfac7d2a..cf0d3541c 100644 --- a/crates/nostreamd/src/lib.rs +++ b/crates/nostreamd/src/lib.rs @@ -37,12 +37,15 @@ //! service the moment the connection that created it closes. The relay-monitor worker //! belongs to #865 and is not registered here. //! -//! The MCP server named in the issue is Phase 5 and has no TS counterpart at the capture; it -//! has no module here either. +//! The MCP server named in the issue has no TS counterpart at the capture. It is the +//! `crates/nostream-mcp` crate, which owns the tools, the credential gate and the audit sink; +//! this crate serves it inside the daemon's own process through `--mcp-stdio` +//! ([`mcp_stdio`]), on stdin/stdout and with no socket of its own. pub mod acceptor; pub mod admin_http; pub mod error; +pub mod mcp_stdio; pub mod settings_gate; pub mod telemetry; pub mod workers; diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs index cfbdaaef5..ead3eda30 100644 --- a/crates/nostreamd/src/main.rs +++ b/crates/nostreamd/src/main.rs @@ -38,6 +38,10 @@ struct Cli { /// Override the log level (info, debug, warn, error). #[arg(long)] log_level: Option, + + /// Serve the admin MCP server on stdin/stdout and exit when stdin closes. Binds no socket. + #[arg(long)] + mcp_stdio: bool, } fn main() -> ExitCode { @@ -81,12 +85,22 @@ fn run(cli: Cli) -> Result { return Err(DaemonError::MissingSecret); } + let writer = if cli.mcp_stdio { + telemetry::LogWriter::Stderr + } else { + telemetry::LogWriter::Stdout + }; telemetry::init( &settings, telemetry::resolve_filter(cli.log_level.as_deref()), + writer, ) .map_err(|error| DaemonError::Setup(error.to_string()))?; + let config_dir = paths.config_base_dir; + + // R17: the MCP mode serves stdin/stdout and returns; it binds no socket and opens no + // store of its own, so `--listen-port` is not read on this path. let port = cli .listen_port .or_else(|| { @@ -101,7 +115,6 @@ fn run(cli: Cli) -> Result { }) .unwrap_or(8008u16); let listen = SocketAddr::from((Ipv4Addr::UNSPECIFIED, port)); - let config_dir = paths.config_base_dir; // R4: `WORKER_COUNT`, then `workers.count`, then the CPU count. let worker_threads = nostream_services::scheduler::resolve_worker_count( @@ -119,6 +132,14 @@ fn run(cli: Cli) -> Result { .build() .map_err(|error| DaemonError::Setup(format!("tokio runtime: {error}")))?; + if cli.mcp_stdio { + let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + return runtime.block_on(async move { + nostreamd::mcp_stdio::serve(cwd, config_dir).await?; + Ok(ExitCode::SUCCESS) + }); + } + runtime.block_on(async move { serve(listen, settings, config_dir, port).await }) } diff --git a/crates/nostreamd/src/mcp_stdio.rs b/crates/nostreamd/src/mcp_stdio.rs new file mode 100644 index 000000000..bdc8e570f --- /dev/null +++ b/crates/nostreamd/src/mcp_stdio.rs @@ -0,0 +1,72 @@ +//! `--mcp-stdio`: the admin MCP server on stdin/stdout, in the daemon's own process. +//! +//! The mode binds **no socket** — `nostreamd` stays the crate that binds, and this mode is not +//! one of its listeners (D13) — and opens **no store of its own**: the admin state comes from +//! [`crate::admin_http::compose`] over the same `unavailable::stores()` bundle the relay path +//! hands over, so no second process ever opens the LMDB directory (ADR 0012 D9). While the store +//! is unwired, the store-backed tools answer the store's own `NotImplemented` message (R19). +//! +//! The credential is read once here and passed to the server as a value: the server never reads +//! the environment (R7). + +use std::path::PathBuf; +use std::sync::Arc; + +use nostream_config::SettingsPaths; +use nostream_core::nip05::Nip05Fetch; +use nostream_services::HttpClient; +use rmcp::ServiceExt; +use rmcp::model::Implementation; + +use crate::DaemonError; + +/// The session token a stdio caller presents, minted by `POST /admin/login` and verified with +/// the console's own function (R7). +pub const ADMIN_TOKEN_ENV: &str = "NOSTREAM_ADMIN_TOKEN"; + +/// The token the environment carries, when it carries a non-empty one. +pub fn token_from_env() -> Option { + std::env::var(ADMIN_TOKEN_ENV) + .ok() + .filter(|token| !token.is_empty()) +} + +/// Serves the MCP server on stdin/stdout until the peer closes stdin, then returns. +pub async fn serve(cwd: PathBuf, config_dir: PathBuf) -> Result<(), DaemonError> { + let stores = Arc::new(nostream_services::unavailable::stores()); + let client = Arc::new( + nostream_services::ReqwestClient::new() + .map_err(|error| DaemonError::Setup(error.to_string()))?, + ); + let http: Arc = client.clone(); + let fetch: Arc = client; + let paths = SettingsPaths::from_config_dir(&cwd, config_dir); + let (state, _router) = + crate::admin_http::compose(paths, cwd.join("resources"), stores, http, fetch)?; + + let server = nostream_mcp::AdminMcp::new( + state, + token_from_env(), + Implementation::new(nostream_mcp::MCP_SERVER_NAME, env!("CARGO_PKG_VERSION")), + ); + + // The one forced line: it is what tells a reader — and AC5's first case — that the banner + // went to stderr rather than into the JSON-RPC stream (R18). + tracing::info!("mcp server on stdio"); + + let service = match server.serve(rmcp::transport::stdio()).await { + Ok(service) => service, + // A peer that closes stdin before the handshake has gone away without asking for + // anything: there is nothing left to serve, and that is not a failure (R17). + Err(rmcp::service::ServerInitializeError::ConnectionClosed(context)) => { + tracing::info!(%context, "the peer closed stdin before the MCP handshake"); + return Ok(()); + } + Err(error) => return Err(DaemonError::Setup(format!("mcp stdio: {error}"))), + }; + service + .waiting() + .await + .map_err(|error| DaemonError::Setup(format!("mcp stdio: {error}")))?; + Ok(()) +} diff --git a/crates/nostreamd/src/settings_gate.rs b/crates/nostreamd/src/settings_gate.rs index 521362715..45649cdd9 100644 --- a/crates/nostreamd/src/settings_gate.rs +++ b/crates/nostreamd/src/settings_gate.rs @@ -7,8 +7,9 @@ //! //! This module is also the workspace's one library-position writer to stdout/stderr *outside //! the `tracing` subscriber*: every other write a library crate makes goes through `tracing` -//! and `telemetry::init`'s `tracing_subscriber::fmt()` layer (whose writer is stdout, and -//! whose output the `EnvFilter` governs). These three bypass that filter, so the rule that +//! and `telemetry::init`'s `tracing_subscriber::fmt()` layer (whose writer the mode chooses — +//! stdout for the relay path, stderr for `--mcp-stdio` — and whose output the `EnvFilter` +//! governs). These three bypass that filter, so the rule that //! keeps them honest is worth stating: output belongs to a process's entry point, and a //! library that writes to a stream the caller does not drain can block it — a per-record //! write stalls a whole subscription behind a full pipe. These writes are the operator report diff --git a/crates/nostreamd/src/telemetry.rs b/crates/nostreamd/src/telemetry.rs index 49123f438..ececfd8cf 100644 --- a/crates/nostreamd/src/telemetry.rs +++ b/crates/nostreamd/src/telemetry.rs @@ -1,12 +1,27 @@ -//! Telemetry: a tracing subscriber to stdout, plus an OTLP span exporter behind the `otlp` -//! feature (the Phase-5 OTEL exporter; the tracing-otlp crate named in the old spec does not -//! exist — the deviation is recorded in `docs/rewrite/decisions/0001-runtime-and-telemetry.md`). +//! Telemetry: a tracing subscriber, plus an OTLP span exporter behind the `otlp` feature (the +//! Phase-5 OTEL exporter; the tracing-otlp crate named in the old spec does not exist — the +//! deviation is recorded in `docs/rewrite/decisions/0001-runtime-and-telemetry.md`). +//! +//! The subscriber's writer is the caller's to choose, because one of the daemon's two modes +//! carries a protocol on stdout: the relay path logs there as it always has, and +//! `--mcp-stdio` logs to stderr so no log line can corrupt the JSON-RPC stream (R18). The +//! choice is made at initialisation, not bolted on afterwards — the subscriber is installed with +//! `try_init`, so a second one is a silent no-op that reports `Err`. use nostream_config::Settings; use tracing_subscriber::EnvFilter; use crate::error::DaemonError; +/// Where the installed subscriber writes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LogWriter { + /// The relay path's destination, where the daemon has always logged. + Stdout, + /// The stdio MCP mode's: stdout carries the protocol. + Stderr, +} + /// Resolves the log filter: `--log-level` first, then `LOG_LEVEL`, then `RUST_LOG`, else /// INFO. `EnvFilter::from_default_env` alone would read only `RUST_LOG` and default to /// ERROR, which silences the daemon's own startup lines. @@ -23,11 +38,11 @@ pub fn resolve_filter(cli_level: Option<&str>) -> EnvFilter { EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")) } -/// Installs the global subscriber from the settings. +/// Installs the global subscriber from the settings, writing where `writer` says. /// /// The OTLP endpoint comes from `OTEL_EXPORTER_OTLP_ENDPOINT` (the OTEL SDK convention), not /// from a settings field: the capture's settings carry no telemetry section. -pub fn init(settings: &Settings, filter: EnvFilter) -> Result<(), DaemonError> { +pub fn init(settings: &Settings, filter: EnvFilter, writer: LogWriter) -> Result<(), DaemonError> { let _ = settings; #[cfg(feature = "otlp")] { @@ -37,11 +52,14 @@ pub fn init(settings: &Settings, filter: EnvFilter) -> Result<(), DaemonError> { return init_otlp(); } } - tracing_subscriber::fmt() + let builder = tracing_subscriber::fmt() .with_env_filter(filter) - .with_target(false) - .try_init() - .map_err(|error| DaemonError::Setup(format!("telemetry: {error}"))) + .with_target(false); + match writer { + LogWriter::Stdout => builder.try_init(), + LogWriter::Stderr => builder.with_writer(std::io::stderr).try_init(), + } + .map_err(|error| DaemonError::Setup(format!("telemetry: {error}"))) } #[cfg(feature = "otlp")] diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs new file mode 100644 index 000000000..8a0246ee5 --- /dev/null +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -0,0 +1,321 @@ +//! AC5 — the stdio mode in the real binary: the flag, the JSON-RPC stream, the banner's stream, +//! the absent socket, the exit code and the unwired store's answer. +//! +//! | case | what it proves | +//! |---|---| +//! | `the_banner_is_on_stderr_and_stdout_is_json_rpc` | stdout carries only JSON-RPC, and the one INFO line is on stderr | +//! | `initialize_names_the_daemon` | `protocolVersion`, `serverInfo.name` and the daemon's version | +//! | `settings_get_answers_redacted_over_stdio` | a real call answers the redacted document | +//! | `the_mode_binds_no_socket` | the dialogue completes while the port the flag names is held by the test | +//! | `the_process_exits_zero_on_stdin_eof` | closing stdin ends the process with `0` | +//! | `the_store_backed_tools_report_the_unwired_store` | `list_events` answers the store's own `NotImplemented` message, not an empty list | +//! +//! The dialogue is hand-written JSON-RPC over the child's pipes: this target proves a property +//! of the process, so it spawns the binary the way an MCP client does. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::PathBuf; +use std::process::Stdio; +use std::time::Duration; + +use nostream_admin::utils::session; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout}; + +/// The literal `SECRET` the daemon signs sessions with here. +const SECRET: &str = "a-test-secret"; + +/// The fixture password hash `hashAdminPassword` writes for `hunter2`. +const PASSWORD_HASH: &str = "scrypt:BwcHBwcHBwcHBwcHBwcHBw==:r5daXU05UJ9EUDu45YoHMWUoQCmkVbwINYNntY1/dwrJPOt3fTi/1IWw1wp9+YXRj1Vm6IpFi+gSU0JdqZvWIw=="; + +/// A session token the daemon's own clock accepts, minted the way `POST /admin/login` does. +fn token() -> String { + let now: i64 = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() + .try_into() + .unwrap(); + let expires_at = now + 3_600; + session::create_token(&session::session_key(SECRET.as_bytes()), expires_at) +} + +/// One spawned `nostreamd --mcp-stdio`, and every stdout line it wrote. +struct Daemon { + child: Child, + stdin: Option, + stdout: BufReader, + stderr: ChildStderr, + lines: Vec, + next_id: u64, +} + +/// What a finished dialogue left behind. +struct Outcome { + status: std::process::ExitStatus, + stdout: Vec, + stderr: String, +} + +impl Drop for Daemon { + fn drop(&mut self) { + let _ = self.child.start_kill(); + } +} + +impl Daemon { + /// Spawns the binary on a fresh config dir. + fn start(token: Option<&str>, extra: &[String]) -> (Self, tempfile::TempDir) { + let temp = tempfile::tempdir().expect("tempdir"); + let config_dir = temp.path().join("config"); + std::fs::create_dir_all(&config_dir).expect("config dir"); + std::fs::write( + config_dir.join("settings.yaml"), + format!( + "info:\n name: Example\n relay_url: ws://127.0.0.1:8008\nadmin:\n enabled: true\n passwordHash: \"{PASSWORD_HASH}\"\n" + ), + ) + .expect("settings"); + + let workspace = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."); + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_nostreamd")); + command + .arg("--config-dir") + .arg(&config_dir) + .arg("--log-level") + .arg("info") + .arg("--mcp-stdio") + .args(extra) + .current_dir(&workspace) + .env("SECRET", SECRET) + .env("WORKER_COUNT", "1") + // The ambient environment must not decide whether this case is authenticated. + .env_remove("NOSTREAM_ADMIN_TOKEN") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + if let Some(token) = token { + command.env("NOSTREAM_ADMIN_TOKEN", token); + } + let mut child = command.spawn().expect("the daemon starts"); + let stdin = child.stdin.take(); + let stdout = BufReader::new(child.stdout.take().expect("stdout is piped")); + let stderr = child.stderr.take().expect("stderr is piped"); + ( + Self { + child, + stdin, + stdout, + stderr, + lines: Vec::new(), + next_id: 0, + }, + temp, + ) + } + + async fn send(&mut self, message: Value) { + let stdin = self.stdin.as_mut().expect("stdin is open"); + stdin + .write_all(format!("{message}\n").as_bytes()) + .await + .expect("the child reads"); + stdin.flush().await.expect("the child reads"); + } + + /// One stdout line, recorded so the banner case can hold every one of them to JSON. + async fn read_line(&mut self) -> String { + let mut line = String::new(); + let read = tokio::time::timeout(Duration::from_secs(15), self.stdout.read_line(&mut line)) + .await + .expect("a reply within fifteen seconds") + .expect("the pipe reads"); + assert!(read > 0, "the child closed stdout mid-dialogue"); + self.lines.push(line.clone()); + line + } + + /// The response carrying `id`, skipping anything else the server sends. + async fn response(&mut self, id: u64) -> Value { + loop { + let line = self.read_line().await; + let message: Value = serde_json::from_str(&line) + .unwrap_or_else(|error| panic!("stdout carried a non-JSON line ({error}): {line}")); + assert_eq!(message["jsonrpc"], "2.0", "{message}"); + if message["id"] == json!(id) { + return message; + } + } + } + + async fn request(&mut self, method: &str, params: Value) -> Value { + self.next_id += 1; + let id = self.next_id; + self.send(json!({ + "jsonrpc": "2.0", + "id": id, + "method": method, + "params": params, + })) + .await; + self.response(id).await + } + + /// The `initialize` handshake every dialogue starts with. + async fn initialize(&mut self) -> Value { + let result = self + .request( + "initialize", + json!({ + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": { "name": "mcp-stdio-test", "version": "0" }, + }), + ) + .await; + self.send(json!({ "jsonrpc": "2.0", "method": "notifications/initialized" })) + .await; + result + } + + async fn call(&mut self, tool: &str, arguments: Value) -> Value { + self.request( + "tools/call", + json!({ "name": tool, "arguments": arguments }), + ) + .await + } + + /// Closes stdin, waits for the exit, and drains both pipes. + async fn finish(mut self) -> Outcome { + drop(self.stdin.take()); + let status = tokio::time::timeout(Duration::from_secs(5), self.child.wait()) + .await + .expect("the child exits within five seconds when stdin closes") + .expect("the child is reaped"); + let mut rest = String::new(); + self.stdout + .read_to_string(&mut rest) + .await + .expect("stdout drains"); + let mut stderr = String::new(); + self.stderr + .read_to_string(&mut stderr) + .await + .expect("stderr drains"); + let mut stdout = std::mem::take(&mut self.lines); + stdout.extend( + rest.lines() + .filter(|line| !line.trim().is_empty()) + .map(str::to_owned), + ); + Outcome { + status, + stdout, + stderr, + } + } +} + +#[tokio::test] +async fn the_banner_is_on_stderr_and_stdout_is_json_rpc() { + let (mut daemon, _temp) = Daemon::start(Some(&token()), &[]); + daemon.initialize().await; + daemon.request("tools/list", json!({})).await; + let outcome = daemon.finish().await; + + assert!( + outcome + .stderr + .lines() + .any(|line| line.contains("mcp server on stdio")), + "the banner is on stderr: {}", + outcome.stderr + ); + assert!(!outcome.stdout.is_empty(), "the dialogue answered"); + for line in &outcome.stdout { + let message: Value = serde_json::from_str(line) + .unwrap_or_else(|error| panic!("stdout carried {line:?}: {error}")); + assert_eq!(message["jsonrpc"], "2.0", "{message}"); + } +} + +#[tokio::test] +async fn initialize_names_the_daemon() { + let (mut daemon, _temp) = Daemon::start(Some(&token()), &[]); + let result = daemon.initialize().await; + let outcome = daemon.finish().await; + + assert_eq!(result["result"]["protocolVersion"], "2025-06-18"); + assert_eq!(result["result"]["serverInfo"]["name"], "nostream"); + assert_eq!( + result["result"]["serverInfo"]["version"], + env!("CARGO_PKG_VERSION") + ); + assert!(outcome.status.success(), "{}", outcome.stderr); +} + +#[tokio::test] +async fn settings_get_answers_redacted_over_stdio() { + let (mut daemon, _temp) = Daemon::start(Some(&token()), &[]); + daemon.initialize().await; + let response = daemon.call("settings_get", json!({})).await; + let outcome = daemon.finish().await; + + assert_eq!(response["result"]["isError"], false, "{response}"); + assert_eq!( + response["result"]["structuredContent"]["settings"]["admin"]["passwordHash"], "***", + "{response}" + ); + assert!(outcome.status.success(), "{}", outcome.stderr); +} + +#[tokio::test] +async fn the_mode_binds_no_socket() { + // Held open for the whole dialogue: the child never binds it. + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("an ephemeral port"); + let port = listener.local_addr().expect("addr").port(); + + let (mut daemon, _temp) = Daemon::start( + Some(&token()), + &["--listen-port".to_owned(), port.to_string()], + ); + daemon.initialize().await; + let listed = daemon.request("tools/list", json!({})).await; + let outcome = daemon.finish().await; + + assert_eq!( + listed["result"]["tools"].as_array().map(Vec::len), + Some(4), + "{listed}" + ); + assert!(outcome.status.success(), "{}", outcome.stderr); + drop(listener); +} + +#[tokio::test] +async fn the_process_exits_zero_on_stdin_eof() { + let (daemon, _temp) = Daemon::start(Some(&token()), &[]); + let outcome = daemon.finish().await; + assert_eq!(outcome.status.code(), Some(0), "{}", outcome.stderr); +} + +#[tokio::test] +async fn the_store_backed_tools_report_the_unwired_store() { + let (mut daemon, _temp) = Daemon::start(Some(&token()), &[]); + daemon.initialize().await; + let response = daemon.call("list_events", json!({})).await; + let outcome = daemon.finish().await; + + assert_eq!(response["result"]["isError"], true, "{response}"); + let text = response["result"]["content"][0]["text"] + .as_str() + .unwrap_or_default(); + assert!( + text.contains("not implemented in Phase 1 (job 005): storage::backend::wiring"), + "{text}" + ); + assert!(outcome.status.success(), "{}", outcome.stderr); +} diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index c446ad652..ca3986735 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -272,6 +272,40 @@ route states. The LMDB backend's `count_by_filters` may complete synchronously i in which case the gather buys nothing on that backend and costs nothing; it is the Postgres backend, whose query is a real await, that the shape is for. +### D18 — The audit vocabulary gains one `mcp.*` action per tool + +The MCP server writes its calls to the same `/admin-audit.jsonl` (D9), one line per +executed call, and it extends the recorded action vocabulary by **four names** rather than +reusing one: + +| action | written by | +|---|---| +| `mcp.settings_get` | a dispatched `settings_get` | +| `mcp.settings_set` | a dispatched `settings_set` | +| `mcp.list_events` | a dispatched `list_events` | +| `mcp.get_event` | a dispatched `get_event` | + +**These extend the capture's nine names; they do not replace them.** The capture's vocabulary is +a closed nine-name union (`src/@types/admin-audit.ts:1-10`), and the rewrite's writer takes +`&str` (`crates/nostream-admin/src/state.rs:497`), so a new name is accepted and stored without +a schema change. Each name is `mcp.` plus the tool's own name, and each is a named constant in +`crates/nostream-mcp`. + +**One name per tool, not one `mcp.tool_call` with the tool in `detail`.** The console's trust page +renders `entry.action` verbatim (`resources/admin/assets/admin-trust.js:93`), so the action column +is the only place an operator reads *which* surface did what without opening the entry: a single +`mcp.tool_call` would print the same words for four different operations and push the distinction +into a field the page does not show. The cost is one more line in this record; the alternative +costs the column its meaning. + +**What each line carries.** `detail` holds `{"tool": ""}`, plus `{"paths": [...]}` for +`settings_set` (the paths requested, never a value), and `remoteAddress` is omitted because a +stdio caller has no address (`state.rs:509-525`). The line is appended at dispatch, before the +tool's work, so the file's order is the dispatch order: `mcp.settings_set` precedes the +`settings.updated` line the shared write path then appends, and a call the credential gate +refuses appends nothing at all — matching `admin_auth_middleware.rs:52-63`, which logs a warning +and writes nothing. + ## Evidence Measured in this job's worktree at `factory/032-admin-console-parity`: From 44d03725ae78d0e4c36370b94a3070b1d69bc56e Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Thu, 19 Nov 2026 17:51:53 -0500 Subject: [PATCH 03/24] fix(admin): answer the round-1 review of the admin MCP server --- CONFIGURATION.md | 1 + crates/nostream-mcp/src/error.rs | 6 + crates/nostream-mcp/src/lib.rs | 16 +- crates/nostream-mcp/src/server.rs | 268 ++++++++++++++--- crates/nostream-mcp/tests/audit.rs | 33 +++ crates/nostream-mcp/tests/common/mod.rs | 49 +++- .../tests/fixtures/tools_list.json | 64 +++- crates/nostream-mcp/tests/tool_payloads.rs | 275 +++++++++++++++++- crates/nostream-mcp/tests/tools_list.rs | 44 ++- crates/nostream-storage/src/lib.rs | 10 + crates/nostream-storage/src/lmdb/events.rs | 12 +- crates/nostream-storage/src/lmdb/mod.rs | 3 - crates/nostreamd/src/main.rs | 4 + crates/nostreamd/src/mcp_stdio.rs | 8 +- crates/nostreamd/tests/mcp_stdio.rs | 20 ++ .../decisions/0014-admin-http-surface.md | 18 +- 16 files changed, 749 insertions(+), 82 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index b6822996b..ef34e675f 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -11,6 +11,7 @@ The following environment variables can be set: | RELAY_PRIVATE_KEY | Relay's private key in hex | (auto-generated) | | WORKER_COUNT | Number of workers override | No. of available CPUs | | LOG_FORMAT | Set to `json` to replace the startup banner with one `relay starting` record, so every line the relay writes parses as JSON. | (banner) | +| NOSTREAM_ADMIN_TOKEN | Admin session token `nostreamd --mcp-stdio` authenticates every call with. Mint it by logging in to the admin console (`POST /admin/login`); the mode needs `admin.enabled: true` and `SECRET` set as well. | (none: every call answers `Unauthorized`) | | DB_URI | PostgreSQL URI (overrides DB_HOST, DB_PORT, etc.) | | | DB_HOST | PostgresSQL Hostname | | | DB_PORT | PostgreSQL Port | 5432 | diff --git a/crates/nostream-mcp/src/error.rs b/crates/nostream-mcp/src/error.rs index 0e7a58915..1cb83e2b3 100644 --- a/crates/nostream-mcp/src/error.rs +++ b/crates/nostream-mcp/src/error.rs @@ -25,6 +25,12 @@ pub enum McpError { #[error("the tool's arguments could not be read: {0}")] Arguments(String), + /// A criterion the tool refuses before it reads: an id or author that is not a + /// 4-to-64-character hex prefix, more criteria than one call may carry, or a page size + /// outside its bound. + #[error("{0}")] + Criterion(String), + /// A payload the tool built could not be serialised. #[error("the payload could not be serialised: {0}")] Serialise(#[from] serde_json::Error), diff --git a/crates/nostream-mcp/src/lib.rs b/crates/nostream-mcp/src/lib.rs index 78a1d787e..580e776df 100644 --- a/crates/nostream-mcp/src/lib.rs +++ b/crates/nostream-mcp/src/lib.rs @@ -2,9 +2,12 @@ //! credential gate and the audit sink. //! //! It owns no transport and no socket. `nostreamd --mcp-stdio` serves this server on -//! stdin/stdout through `rmcp`'s `transport-io`, in the daemon's own process, so the tools read -//! the same [`AdminState`](nostream_admin::AdminState) the HTTP console does: the same session -//! credential, the same `/admin-audit.jsonl` and the same repository bundle (D9, D13). +//! stdin/stdout through `rmcp`'s `transport-io`, in a process of its own: the mode composes its +//! own [`AdminState`](nostream_admin::AdminState) over the same config directory, so the tools +//! read the same session credential, the same `/admin-audit.jsonl` and the same +//! repository bundle (D9, D13). The two modes are alternatives — a daemon serving the console, +//! or a process serving the pipe — and running both against one config directory is outside D9: +//! the audit file and the settings write each assume one writer per configuration. //! //! **Deliberately not owned here** — a reader should be able to tell an omission from a gap: //! @@ -21,7 +24,8 @@ mod server; pub use error::McpError; pub use server::{ - AdminMcp, GetEventArgs, INTERNAL_SERVER_ERROR, ListEventsArgs, MCP_SERVER_NAME, NOT_FOUND, - SettingsSetArgs, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, - UNAUTHORIZED, audit_action, + AdminMcp, GetEventArgs, INTERNAL_SERVER_ERROR, ListEventsArgs, MAX_FILTER_TERMS, MAX_PAGE_ROWS, + MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, SettingsSetArgs, TOOL_ARGUMENTS, TOOL_GET_EVENT, + TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, UNAUTHORIZED, arguments_parse, + audit_action, }; diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index 681d2ec63..4c09a25a4 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -7,6 +7,7 @@ //! `mcp.` line written before the tool's own work, so the file's order is the dispatch //! order (R9). +use std::borrow::Cow; use std::sync::Arc; use nostream_admin::AdminState; @@ -22,7 +23,7 @@ use rmcp::model::{ CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Implementation, ServerCapabilities, ServerConfig, }; -use rmcp::schemars::{self, JsonSchema}; +use rmcp::schemars::{self, JsonSchema, Schema, SchemaGenerator, json_schema}; use rmcp::service::RequestContext; use rmcp::{RoleServer, ServerHandler, tool, tool_handler, tool_router}; use serde::Deserialize; @@ -33,12 +34,39 @@ use crate::error::McpError; /// The server name `initialize` reports: the server, not the SDK, which would name `rmcp` (R6). pub const MCP_SERVER_NAME: &str = "nostream"; +/// What `initialize`'s `instructions` carries: the route to a working call. +/// +/// The three refusals the gate answers name a symptom, not its cause, and nothing else on the +/// surface says what a caller needs — a client that reads `Not Found` for a tool it was just +/// told exists has nowhere to look. This is that place, and it is additive: the refusal texts +/// stay exactly as the console's layers word them. +pub const MCP_INSTRUCTIONS: &str = "\ +The nostream admin MCP server. It uses the admin console's own credential: a session token \ +minted by `POST /admin/login` and passed in `NOSTREAM_ADMIN_TOKEN`. Three things must hold, or \ +every call is refused with the reason: `admin.enabled` is true in the settings (else `Not \ +Found`), `SECRET` is set (else `Internal Server Error`), and `NOSTREAM_ADMIN_TOKEN` carries an \ +unexpired token (else `Unauthorized`). Each executed call appends one `mcp.` line to \ +`/admin-audit.jsonl`."; + /// The tool names slice 1 registers (R5). Each is also its audit action's suffix (R9). pub const TOOL_SETTINGS_GET: &str = "settings_get"; pub const TOOL_SETTINGS_SET: &str = "settings_set"; pub const TOOL_LIST_EVENTS: &str = "list_events"; pub const TOOL_GET_EVENT: &str = "get_event"; +/// The most `ids` or `authors` criteria one call may carry. +/// +/// Each criterion is its own index range, and an `ids` range is not in time order, so a call's +/// visit is bounded by this count rather than by the store — and this surface has no rate +/// limit (the spec removes it by design), so the count is the only bound there is. +pub const MAX_FILTER_TERMS: usize = 64; + +/// The most rows a `list_events` page may hold: the store's own ascending page +/// ([`nostream_storage::DEFAULT_PAGE_ROWS`]), which is what a filter carrying no `limit` +/// materialises. A larger page would need the store's limited iterator, which returns the +/// newest rows rather than the first. +pub const MAX_PAGE_ROWS: u64 = nostream_storage::DEFAULT_PAGE_ROWS; + /// The refusal for a token that is absent, malformed or expired — the HTTP gate's `401`. pub const UNAUTHORIZED: &str = "Unauthorized"; @@ -53,27 +81,75 @@ pub fn audit_action(tool: &str) -> String { format!("mcp.{tool}") } +/// Whether a call's arguments are the shape the tool's `inputSchema` states. +type ArgumentsCheck = fn(Option<&Map>) -> bool; + +/// The audit table: every tool the router registers, with the check that says whether a call's +/// arguments are the shape its `inputSchema` states (R9). +/// +/// The dispatch path looks a name up here and has no "everything else is audited" arm, so a +/// tool added to the router without an entry cannot execute unaudited: it fails +/// `every_registered_tool_is_in_the_audit_table`, which reads the router's own list. +pub const TOOL_ARGUMENTS: &[(&str, ArgumentsCheck)] = &[ + (TOOL_SETTINGS_GET, accepts_any_arguments), + (TOOL_SETTINGS_SET, settings_set_parses), + (TOOL_LIST_EVENTS, list_events_parse), + (TOOL_GET_EVENT, get_event_parses), +]; + +/// Whether `tool`'s arguments parse; `None` when the router registers no such tool. +pub fn arguments_parse(tool: &str, arguments: Option<&Map>) -> Option { + TOOL_ARGUMENTS + .iter() + .find(|(name, _)| *name == tool) + .map(|(_, parses)| parses(arguments)) +} + +/// `settings_get` takes no parameters, so the router deserialises nothing for it. +fn accepts_any_arguments(_: Option<&Map>) -> bool { + true +} + +fn settings_set_parses(arguments: Option<&Map>) -> bool { + serde_json::from_value::(arguments_value(arguments)).is_ok() +} + +fn list_events_parse(arguments: Option<&Map>) -> bool { + serde_json::from_value::(arguments_value(arguments)).is_ok() +} + +fn get_event_parses(arguments: Option<&Map>) -> bool { + serde_json::from_value::(arguments_value(arguments)).is_ok() +} + +fn arguments_value(arguments: Option<&Map>) -> Value { + Value::Object(arguments.cloned().unwrap_or_default()) +} + /// The `list_events` criteria: each maps to one [`Filter`] field (R15). #[derive(Debug, Clone, Default, Deserialize, JsonSchema)] pub struct ListEventsArgs { /// Kinds to select; absent selects every kind. pub kinds: Option>, - /// Author pubkey hex prefixes. + /// Author pubkey hex prefixes, 4 to 64 characters each in either case; at most 64 per + /// call. A criterion the wire would refuse is an error, not a narrower read. pub authors: Option>, - /// Event id hex prefixes. + /// Event id hex prefixes, 4 to 64 characters each in either case; at most 64 per call. pub ids: Option>, /// Events created at or after this unix second. pub since: Option, /// Events created at or before this unix second. pub until: Option, - /// Page size; absent leaves the store's own default in charge. + /// Page size: 1 to 500 rows, and they are the first rows in the payload's order; absent + /// uses 500, the store's own page. + #[schemars(range(min = 1, max = 500))] pub limit: Option, } /// The `get_event` arguments. #[derive(Debug, Clone, Deserialize, JsonSchema)] pub struct GetEventArgs { - /// The event's 64-character lowercase hex id. + /// The event's 64-character hex id, in either case. pub id: String, } @@ -82,13 +158,66 @@ pub struct GetEventArgs { /// Kept as a raw map rather than a typed struct because the schema's rule is that an explicit /// `null` is a value and not an absent key: a typed `Option` would collapse the two and /// turn the validator's `Expected string, got null` into `Invalid request`. -#[derive(Debug, Clone, Deserialize, JsonSchema)] +#[derive(Debug, Clone, Deserialize)] pub struct SettingsSetArgs { /// `{path, value}` or `{changes: [{path, value}, …]}`. #[serde(flatten)] pub body: Map, } +impl JsonSchema for SettingsSetArgs { + fn schema_name() -> Cow<'static, str> { + "SettingsSetArgs".into() + } + + /// The two shapes the write path takes and no others. + /// + /// A permissive `{"type": "object", "additionalProperties": true}` said every object was + /// valid while the handler refused six of the seven shapes a client could send, and the + /// refusal names no key. Modelled here instead: `{path, value}` or `{changes: [{path, + /// value}, …]}` with at least one entry, and `additionalProperties: false` on both, so a + /// validating client catches its own mistake and the schema and the handler agree. + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let change = || { + json!({ + "type": "object", + "properties": { + "path": { "type": "string" }, + "value": {}, + }, + "required": ["path", "value"], + "additionalProperties": false, + }) + }; + json_schema!({ + "type": "object", + "oneOf": [ + { + "type": "object", + "properties": { + "path": { "type": "string" }, + "value": {}, + }, + "required": ["path", "value"], + "additionalProperties": false, + }, + { + "type": "object", + "properties": { + "changes": { + "type": "array", + "minItems": 1, + "items": change(), + }, + }, + "required": ["changes"], + "additionalProperties": false, + }, + ], + }) + } +} + /// The server: the shared admin state, the resolved token and the composition's identity. #[derive(Debug, Clone)] pub struct AdminMcp { @@ -120,25 +249,25 @@ impl AdminMcp { /// `GET /admin/settings`: the merged document narrowed to the defaults' keys and /// redacted, by the same two functions in the same order the controller uses (R11). #[tool( - description = "Read the merged settings document, narrowed to the defaults' keys and redacted" + description = "Read the merged settings document, narrowed to the defaults' keys and redacted. The document arrives under `settings`" )] async fn settings_get(&self) -> CallToolResult { match self.settings_document() { - Ok(document) => CallToolResult::structured(json!({ "settings": document })), + Ok(document) => tool_ok(json!({ "settings": document })), Err(error) => tool_error(&error), } } /// `PATCH /admin/settings`, through the controller's own write function (R13). #[tool( - description = "Write settings: one path as {\"path\": \"wot.enabled\", \"value\": false}, or several as {\"changes\": [{\"path\": …, \"value\": …}, …]}" + description = "Write settings: one path as {\"path\": \"wot.enabled\", \"value\": false}, or several as {\"changes\": [{\"path\": …, \"value\": …}, …]}. No other keys are accepted" )] async fn settings_set( &self, Parameters(arguments): Parameters, ) -> CallToolResult { match patch_settings::apply(&self.state, &arguments.body, "").await { - Ok(SettingsWrite::Written(body)) => CallToolResult::structured(body), + Ok(SettingsWrite::Written(body)) => tool_ok(body), Ok(SettingsWrite::Refused { body, .. }) => tool_error_body(&body), Err(error) => tool_error(&McpError::from(error)), } @@ -147,14 +276,16 @@ impl AdminMcp { /// One `EventRepository` read over one [`Filter`], through `collect_records` so a vanished /// slot never reaches the payload (R15). #[tool( - description = "List stored events matching the given kinds, authors, ids, since and until, up to limit" + description = "List stored events matching the given kinds, authors, ids, since and until. Rows come back oldest first, and `limit` is the page size — the first rows in that order, at most 500; `truncated` is true when the page is full, so more rows may match" )] async fn list_events( &self, Parameters(criteria): Parameters, ) -> CallToolResult { match self.events(criteria).await { - Ok(records) => CallToolResult::structured(json!({ "events": records })), + Ok((records, truncated)) => { + tool_ok(json!({ "events": records, "truncated": truncated })) + } Err(error) => tool_error(&error), } } @@ -162,12 +293,12 @@ impl AdminMcp { /// One exact-id read: the filter selects prefixes, so the row's id is compared for equality /// before it is returned (R16). #[tool( - description = "Read one stored event by its exact 64-character hex id; null when no such id is stored" + description = "Read one stored event by its exact 64-character hex id, in either case; null when no such id is stored" )] async fn get_event(&self, Parameters(arguments): Parameters) -> CallToolResult { match self.event(&arguments.id).await { - Ok(Some(record)) => CallToolResult::structured(json!({ "event": record })), - Ok(None) => CallToolResult::structured(json!({ "event": null })), + Ok(Some(record)) => tool_ok(json!({ "event": record })), + Ok(None) => tool_ok(json!({ "event": null })), Err(error) => tool_error(&error), } } @@ -179,28 +310,38 @@ impl AdminMcp { Ok(serde_json::to_value(redacted)?) } - async fn events(&self, criteria: ListEventsArgs) -> Result, McpError> { - // No default limit: an absent `limit` leaves the store's `DEFAULT_FILTER_LIMIT` in - // charge, which is what a caller who passed none is entitled to (R15). + /// One page, oldest first, and whether it was full. + /// + /// No `limit` goes to the store, because the store picks its direction from it: a filter + /// carrying one is answered newest-first, which would make the payload's order depend on an + /// unrelated argument. Ascending is the store's unlimited page, whose bound is + /// [`MAX_PAGE_ROWS`], so `limit` is applied to that page here and the marker is + /// `len >= limit`. + async fn events(&self, criteria: ListEventsArgs) -> Result<(Vec, bool), McpError> { + let page = page_size(&criteria)?; let filter = Filter { kinds: criteria .kinds .map(|kinds| kinds.into_iter().map(Kind).collect()), - authors: criteria.authors, - ids: criteria.ids, + authors: prefixed("authors", criteria.authors)?, + ids: prefixed("ids", criteria.ids)?, since: criteria.since, until: criteria.until, - limit: criteria.limit, + limit: None, ..Filter::default() }; let filters = [filter]; let stream = self.state.stores().events.find_by_filters(&filters).await?; - Ok(collect_records(stream).await?) + let mut records = collect_records(stream).await?; + let truncated = records.len() >= page; + records.truncate(page); + Ok((records, truncated)) } async fn event(&self, id: &str) -> Result, McpError> { + let id = hex_prefix("id", id)?; let filters = [Filter { - ids: Some(vec![id.to_owned()]), + ids: Some(vec![id.clone()]), limit: Some(1), ..Filter::default() }]; @@ -254,23 +395,55 @@ impl AdminMcp { } } -/// Whether a call's arguments are the shape its `inputSchema` states. +/// The page a call asks for, checked against the bounds its `inputSchema` states. +fn page_size(criteria: &ListEventsArgs) -> Result { + let limit = criteria.limit.unwrap_or(MAX_PAGE_ROWS); + let page = usize::try_from(limit) + .ok() + .filter(|page| (1..=usize::try_from(MAX_PAGE_ROWS).unwrap_or(usize::MAX)).contains(page)); + page.ok_or_else(|| { + McpError::Criterion(format!( + "limit: a page holds between 1 and {MAX_PAGE_ROWS} rows, {limit} was given" + )) + }) +} + +/// One criterion list, normalised to lowercase hex: the wire's own floor, and at most +/// [`MAX_FILTER_TERMS`] of them. +fn prefixed(field: &str, values: Option>) -> Result>, McpError> { + let Some(values) = values else { + return Ok(None); + }; + if values.len() > MAX_FILTER_TERMS { + return Err(McpError::Criterion(format!( + "{field}: at most {MAX_FILTER_TERMS} criteria per call, {} were given", + values.len() + ))); + } + values + .iter() + .map(|value| hex_prefix(field, value)) + .collect::, _>>() + .map(Some) +} + +/// A criterion the store can answer in time. /// -/// The router answers a deserialisation failure with its own `isError` result, and R9 puts that -/// failure on the same footing as a refused credential: nothing is written. So the audit line is -/// emitted only for a call that will reach a tool, which needs the arguments checked before -/// dispatch — against the same types the tools take, so the two cannot drift. -fn arguments_parse(tool: &str, arguments: Option<&Map>) -> bool { - let arguments = Value::Object(arguments.cloned().unwrap_or_default()); - match tool { - // No parameters: the router deserialises nothing, so anything is accepted. - TOOL_SETTINGS_GET => true, - TOOL_SETTINGS_SET => serde_json::from_value::(arguments).is_ok(), - TOOL_LIST_EVENTS => serde_json::from_value::(arguments).is_ok(), - TOOL_GET_EVENT => serde_json::from_value::(arguments).is_ok(), - // An unknown tool is not dispatched at all: the router answers `-32602` and nothing runs. - _ => false, +/// The wire refuses what this path used to admit: `nostream_core::filter::validate_prefixes` +/// (`crates/nostream-core/src/filter.rs:386-401`) requires 4 to 64 lowercase hex characters on +/// every `ids`/`authors` criterion, and without it the store maps each byte outside `0-9a-fA-F` +/// to `0` (`crates/nostream-storage/src/lmdb/encoding.rs:426-432`) and widens a short criterion +/// to a whole-field range, so `{"id": ""}` visits the entire `events` database. Either case is +/// accepted and normalised, because the stored ids are lowercase: a caller that pasted an +/// uppercase id gets its row, not a confident "not found". +fn hex_prefix(field: &str, value: &str) -> Result { + let length = value.len(); + if !(4..=64).contains(&length) || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(McpError::Criterion(format!( + "{field}: {value:?} is not a 4-to-64-character hex prefix" + ))); } + Ok(value.to_ascii_lowercase()) } #[tool_handler(router = self.tool_router)] @@ -278,6 +451,7 @@ impl ServerHandler for AdminMcp { fn get_info(&self) -> ServerConfig { ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) .with_server_info(self.implementation.clone()) + .with_instructions(MCP_INSTRUCTIONS) } /// The gate and the audit sink, in front of the router's dispatch. @@ -293,7 +467,10 @@ impl ServerHandler for AdminMcp { tracing::warn!(tool = %request.name, refusal, "the MCP call was refused"); return Ok(CallToolResult::error(vec![ContentBlock::text(refusal)]).into()); } - if arguments_parse(&request.name, request.arguments.as_ref()) { + // `Some(false)` — the router answers the deserialisation failure — and `None` — no such + // tool, and the router answers `-32602` — both reach no tool, so neither writes a line + // (R9, Assumption 5). + if let Some(true) = arguments_parse(&request.name, request.arguments.as_ref()) { self.record_dispatch(&request.name, request.arguments.as_ref()); } let call = ToolCallContext::new(self, request, context); @@ -327,3 +504,16 @@ fn tool_error(error: &McpError) -> CallToolResult { fn tool_error_body(body: &Value) -> CallToolResult { CallToolResult::error(vec![ContentBlock::text(body.to_string())]) } + +/// A success: the payload in `structuredContent`, and no copy of it in `content`. +/// +/// `CallToolResult::structured` fills `content` with `value.to_string()` *and* sets +/// `structured_content`, so every page crossed the wire twice — 48.3% of a 5,000-row response +/// was a text copy nothing read. A client reads `structuredContent`; the protocol allows an +/// empty `content` array, which is what this sends. +fn tool_ok(payload: Value) -> CallToolResult { + let mut result = CallToolResult::default(); + result.structured_content = Some(payload); + result.is_error = Some(false); + result +} diff --git a/crates/nostream-mcp/tests/audit.rs b/crates/nostream-mcp/tests/audit.rs index c0b2e1741..91deeff61 100644 --- a/crates/nostream-mcp/tests/audit.rs +++ b/crates/nostream-mcp/tests/audit.rs @@ -4,6 +4,7 @@ //! |---|---| //! | `each_call_appends_one_line` | four calls append five lines in call order — the four `mcp.*` lines, then `settings_set`'s own `settings.updated` | //! | `a_refused_call_appends_nothing` | a call with bad arguments and a call with no token each leave the file untouched | +//! | `every_registered_tool_is_in_the_audit_table` | the audit table is total: no tool the router registers can execute unaudited | //! //! R9 appends the `mcp.*` line at dispatch, before the handler's work, so the order in the file //! is the order of the calls and a domain line always follows its own dispatch line. @@ -12,6 +13,8 @@ mod common; +use std::collections::BTreeSet; + use common::{Fixture, TestMcp, Token, event, id_of, text}; use nostream_mcp::{ TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, audit_action, @@ -110,3 +113,33 @@ async fn a_refused_call_appends_nothing() { "a refused credential writes nothing" ); } + +#[tokio::test] +async fn every_registered_tool_is_in_the_audit_table() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + // The router's own list: `tools/list` is what `ToolRouter::list_all()` answers, so a tool + // added with a `#[tool]` method and no table entry is in `registered` and nowhere else. + let registered: BTreeSet = client + .tools() + .await + .iter() + .map(|tool| tool.name.to_string()) + .collect(); + for name in ®istered { + assert!( + nostream_mcp::arguments_parse(name, None).is_some(), + "tool {name} is registered but has no TOOL_ARGUMENTS entry, so its calls would \ + execute unaudited" + ); + } + let tabled: BTreeSet = nostream_mcp::TOOL_ARGUMENTS + .iter() + .map(|(name, _)| (*name).to_owned()) + .collect(); + assert_eq!( + tabled, registered, + "the table names exactly the tools the router registers" + ); +} diff --git a/crates/nostream-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs index abadabc98..35f68e484 100644 --- a/crates/nostream-mcp/tests/common/mod.rs +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -71,6 +71,17 @@ pub enum Token { Expired, } +/// Which store bundle the composed state reads. +#[derive(Debug, Clone, Copy, Default)] +pub enum Stores { + /// The seeded LMDB backend: every tool's real read path. + #[default] + Seeded, + /// The daemon's own unwired bundle, where every repository call reports + /// `NotImplemented` (R19) — which tells a case what ran before the store was reached. + Unavailable, +} + /// What a test wants built. pub struct Fixture { /// The user settings document written to `/settings.yaml`. @@ -81,6 +92,8 @@ pub struct Fixture { pub token: Token, /// The starting clock reading. pub now_ms: u64, + /// The store bundle the state is composed over. + pub stores: Stores, } impl Default for Fixture { @@ -90,6 +103,7 @@ impl Default for Fixture { secret: Some(SECRET.to_vec()), token: Token::Valid, now_ms: NOW_MS, + stores: Stores::Seeded, } } } @@ -134,22 +148,29 @@ impl TestMcp { (Token::Expired, Some(secret)) => Some(mint(secret, now_seconds(fixture.now_ms) - 1)), }; + // The backend is always opened, so a case can seed it; when the fixture asks for the + // daemon's bundle the state reads `unavailable::stores()` instead, and the seeded rows + // are simply never reached. let backend = LmdbBackend::open(temp.path().join("store")).await.unwrap(); let backend = Arc::new(backend); - let stores = Arc::new(ServiceStores { - events: Arc::clone(&backend) as Arc, - users: Arc::clone(&backend) as Arc, - invoices: Arc::clone(&backend) - as Arc, - nip05: Arc::clone(&backend) - as Arc, - dvm_jobs: Arc::clone(&backend) - as Arc, - notification_outbox: Arc::clone(&backend) - as Arc, - notification_delivery_log: Arc::clone(&backend) - as Arc, - }); + let stores = match fixture.stores { + Stores::Seeded => Arc::new(ServiceStores { + events: Arc::clone(&backend) as Arc, + users: Arc::clone(&backend) + as Arc, + invoices: Arc::clone(&backend) + as Arc, + nip05: Arc::clone(&backend) + as Arc, + dvm_jobs: Arc::clone(&backend) + as Arc, + notification_outbox: Arc::clone(&backend) + as Arc, + notification_delivery_log: Arc::clone(&backend) + as Arc, + }), + Stores::Unavailable => Arc::new(nostream_services::unavailable::stores()), + }; let client = Arc::new(ReqwestClient::new().unwrap()); let http: Arc = client.clone(); diff --git a/crates/nostream-mcp/tests/fixtures/tools_list.json b/crates/nostream-mcp/tests/fixtures/tools_list.json index cbd01cc62..ba3e2734e 100644 --- a/crates/nostream-mcp/tests/fixtures/tools_list.json +++ b/crates/nostream-mcp/tests/fixtures/tools_list.json @@ -1,12 +1,12 @@ { "tools": [ { - "description": "Read one stored event by its exact 64-character hex id; null when no such id is stored", + "description": "Read one stored event by its exact 64-character hex id, in either case; null when no such id is stored", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "properties": { "id": { - "description": "The event's 64-character lowercase hex id.", + "description": "The event's 64-character hex id, in either case.", "type": "string" } }, @@ -18,12 +18,12 @@ "name": "get_event" }, { - "description": "List stored events matching the given kinds, authors, ids, since and until, up to limit", + "description": "List stored events matching the given kinds, authors, ids, since and until. Rows come back oldest first, and `limit` is the page size — the first rows in that order, at most 500; `truncated` is true when the page is full, so more rows may match", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "properties": { "authors": { - "description": "Author pubkey hex prefixes.", + "description": "Author pubkey hex prefixes, 4 to 64 characters each in either case; at most 64 per\ncall. A criterion the wire would refuse is an error, not a narrower read.", "items": { "type": "string" }, @@ -33,7 +33,7 @@ ] }, "ids": { - "description": "Event id hex prefixes.", + "description": "Event id hex prefixes, 4 to 64 characters each in either case; at most 64 per call.", "items": { "type": "string" }, @@ -55,9 +55,10 @@ ] }, "limit": { - "description": "Page size; absent leaves the store's own default in charge.", + "description": "Page size: 1 to 500 rows, and they are the first rows in the payload's order; absent\nuses 500, the store's own page.", "format": "uint64", - "minimum": 0, + "maximum": 500, + "minimum": 1, "type": [ "integer", "null" @@ -85,7 +86,7 @@ "name": "list_events" }, { - "description": "Read the merged settings document, narrowed to the defaults' keys and redacted", + "description": "Read the merged settings document, narrowed to the defaults' keys and redacted. The document arrives under `settings`", "inputSchema": { "properties": {}, "type": "object" @@ -93,13 +94,56 @@ "name": "settings_get" }, { - "description": "Write settings: one path as {\"path\": \"wot.enabled\", \"value\": false}, or several as {\"changes\": [{\"path\": …, \"value\": …}, …]}", + "description": "Write settings: one path as {\"path\": \"wot.enabled\", \"value\": false}, or several as {\"changes\": [{\"path\": …, \"value\": …}, …]}. No other keys are accepted", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": true, + "oneOf": [ + { + "additionalProperties": false, + "properties": { + "path": { + "type": "string" + }, + "value": {} + }, + "required": [ + "path", + "value" + ], + "type": "object" + }, + { + "additionalProperties": false, + "properties": { + "changes": { + "items": { + "additionalProperties": false, + "properties": { + "path": { + "type": "string" + }, + "value": {} + }, + "required": [ + "path", + "value" + ], + "type": "object" + }, + "minItems": 1, + "type": "array" + } + }, + "required": [ + "changes" + ], + "type": "object" + } + ], "type": "object" }, "name": "settings_set" } ] } + diff --git a/crates/nostream-mcp/tests/tool_payloads.rs b/crates/nostream-mcp/tests/tool_payloads.rs index 18c32ac73..70a41af4e 100644 --- a/crates/nostream-mcp/tests/tool_payloads.rs +++ b/crates/nostream-mcp/tests/tool_payloads.rs @@ -17,6 +17,13 @@ //! | `an_empty_change_list_is_refused` | `{changes: []}` is `Invalid request`, and the attempt is audited | //! | `an_unknown_tool_is_a_protocol_error` | an absent tool is JSON-RPC `-32602`, not a result | //! | `bad_arguments_are_an_error_result` | wrong-typed arguments are an `isError` result, not a protocol error | +//! | `an_uppercase_id_finds_its_row` | a stored id pasted in uppercase is the same id, not a confident `null` | +//! | `a_criterion_the_wire_would_refuse_is_an_argument_error` | a non-hex, short, oversized or over-counted criterion is refused, naming its field | +//! | `a_refused_criterion_never_reaches_the_store` | the refusal comes before the store: over the unwired store the argument error answers, not `NotImplemented` | +//! | `a_page_is_the_first_rows_oldest_first` | the payload is one order, and `limit` is its first N, with `truncated` marking a full page | +//! | `a_full_default_page_is_marked_truncated` | a page the store's own bound cut says so | +//! | `a_success_carries_one_copy_of_the_payload` | a success is in `structuredContent` only, never also as a text block | +//! | `the_settings_schema_forbids_what_the_handler_refuses` | the published schema and the handler agree on the two accepted shapes | #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -24,7 +31,7 @@ mod common; use std::collections::BTreeSet; -use common::{TestMcp, event, id_of, payload, text}; +use common::{Fixture, Stores, TestMcp, event, id_of, payload, text}; use nostream_mcp::{TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET}; use serde_json::{Value, json}; @@ -347,3 +354,269 @@ async fn bad_arguments_are_an_error_result() { text(&result) ); } + +#[tokio::test] +async fn an_uppercase_id_finds_its_row() { + let fixture = TestMcp::start().await; + let record = event(13, 1, 1_699_999_952); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let result = client + .call(TOOL_GET_EVENT, json!({ "id": id.to_uppercase() })) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + assert_eq!( + payload["event"]["event"]["id"], id, + "the uppercase form of a stored id is that id: {payload}" + ); +} + +#[tokio::test] +async fn a_criterion_the_wire_would_refuse_is_an_argument_error() { + let fixture = TestMcp::start().await; + let record = event(14, 1, 1_699_999_953); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let over_cap: Vec = (0..65).map(|index| format!("{index:04x}")).collect(); + let refused = [ + (TOOL_GET_EVENT, json!({ "id": "" }), "id"), + (TOOL_GET_EVENT, json!({ "id": "ze" }), "id"), + (TOOL_GET_EVENT, json!({ "id": &id[..3] }), "id"), + (TOOL_GET_EVENT, json!({ "id": format!("{id}0") }), "id"), + (TOOL_LIST_EVENTS, json!({ "ids": ["ze"] }), "ids"), + (TOOL_LIST_EVENTS, json!({ "ids": [&id[..3]] }), "ids"), + ( + TOOL_LIST_EVENTS, + json!({ "authors": ["npub1qqqq"] }), + "authors", + ), + (TOOL_LIST_EVENTS, json!({ "ids": over_cap }), "ids"), + (TOOL_LIST_EVENTS, json!({ "limit": 0 }), "limit"), + (TOOL_LIST_EVENTS, json!({ "limit": 501 }), "limit"), + ]; + for (tool, arguments, field) in refused { + let answer = client.call(tool, arguments.clone()).await; + assert_eq!( + answer.is_error, + Some(true), + "{tool} {arguments}: {}", + text(&answer) + ); + assert!( + text(&answer).starts_with(&format!("{field}:")), + "{tool} {arguments} names `{field}`: {}", + text(&answer) + ); + } + + // The control: the stored id is a criterion the wire takes. + let found = client.call(TOOL_GET_EVENT, json!({ "id": id })).await; + assert_eq!(found.is_error, Some(false), "{}", text(&found)); + assert_eq!(payload(&found)["event"]["event"]["id"], id); +} + +#[tokio::test] +async fn a_refused_criterion_never_reaches_the_store() { + let fixture = TestMcp::start_with(Fixture { + stores: Stores::Unavailable, + ..Fixture::default() + }) + .await; + let client = fixture.client().await; + + // Over the daemon's unwired bundle every read answers `NotImplemented`, so a refusal that + // arrives instead is one made before the store was touched. + let refused = client.call(TOOL_GET_EVENT, json!({ "id": "" })).await; + assert_eq!(refused.is_error, Some(true), "{}", text(&refused)); + assert!(text(&refused).starts_with("id:"), "{}", text(&refused)); + assert!( + !text(&refused).contains("storage::backend::wiring"), + "the refusal is not the store's: {}", + text(&refused) + ); + + let reached = client.call(TOOL_GET_EVENT, json!({ "id": "abcd" })).await; + assert_eq!(reached.is_error, Some(true), "{}", text(&reached)); + assert!( + text(&reached).contains("not implemented in Phase 1 (job 005): storage::backend::wiring"), + "a criterion the wire takes reaches the store: {}", + text(&reached) + ); +} + +#[tokio::test] +async fn a_page_is_the_first_rows_oldest_first() { + let fixture = TestMcp::start().await; + let seeded: Vec<_> = (0..12) + .map(|index| { + event( + u8::try_from(index + 40).unwrap(), + 1, + 1_699_998_000 + i64::from(index), + ) + }) + .collect(); + fixture.seed(&seeded).await; + let client = fixture.client().await; + + let result = client.call(TOOL_LIST_EVENTS, json!({ "limit": 5 })).await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let page = payload(&result); + let created: Vec = page["events"] + .as_array() + .unwrap() + .iter() + .map(|row| row["event"]["created_at"].as_i64().unwrap()) + .collect(); + assert_eq!( + created, + vec![ + 1_699_998_000, + 1_699_998_001, + 1_699_998_002, + 1_699_998_003, + 1_699_998_004 + ], + "a limited page is the first rows in the same order: {page}" + ); + assert_eq!(page["truncated"], json!(true), "the page is full: {page}"); + + let whole = client.call_without_arguments(TOOL_LIST_EVENTS).await; + let whole = payload(&whole); + assert_eq!(whole["events"].as_array().unwrap().len(), 12, "{whole}"); + assert_eq!( + whole["truncated"], + json!(false), + "nothing was cut, so the marker is false: {whole}" + ); +} + +#[tokio::test] +async fn a_full_default_page_is_marked_truncated() { + let fixture = TestMcp::start().await; + let seeded: Vec<_> = (0..=500) + .map(|index| event(1, 1, 1_699_000_000 + index)) + .collect(); + fixture.seed(&seeded).await; + let client = fixture.client().await; + + let result = client.call_without_arguments(TOOL_LIST_EVENTS).await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let payload = payload(&result); + let events = payload["events"].as_array().unwrap(); + assert_eq!(events.len(), 500, "the store's own page bound"); + assert_eq!( + events[0]["event"]["created_at"], + json!(1_699_000_000), + "and the page starts at the oldest row" + ); + assert_eq!( + payload["truncated"], + json!(true), + "501 rows match, so the full page is cut: {payload}" + ); +} + +#[tokio::test] +async fn a_success_carries_one_copy_of_the_payload() { + let fixture = TestMcp::start().await; + fixture + .seed(&[event(15, 1, 1_699_999_954), event(16, 1, 1_699_999_955)]) + .await; + let client = fixture.client().await; + + for (tool, arguments) in [ + (TOOL_SETTINGS_GET, json!({})), + (TOOL_LIST_EVENTS, json!({})), + (TOOL_GET_EVENT, json!({ "id": "abcd" })), + ( + TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": false }), + ), + ] { + let answer = client.call(tool, arguments).await; + assert_eq!(answer.is_error, Some(false), "{tool}: {}", text(&answer)); + assert!( + answer.content.is_empty(), + "{tool} sends the payload once, not also as a text block: {:?}", + answer.content + ); + assert!( + answer.structured_content.is_some(), + "{tool} answers with structured content" + ); + } +} + +#[tokio::test] +async fn the_settings_schema_forbids_what_the_handler_refuses() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let refused = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": true, "note": "x" }), + ) + .await; + assert_eq!(refused.is_error, Some(true), "{}", text(&refused)); + let refusal: Value = serde_json::from_str(&text(&refused)).expect("the body is JSON"); + assert_eq!(refusal["error"], "Invalid request"); + + let schema = client + .tools() + .await + .into_iter() + .find(|tool| tool.name == TOOL_SETTINGS_SET) + .expect("settings_set is listed"); + let schema = Value::Object((*schema.input_schema).clone()); + assert_eq!( + schema["oneOf"].as_array().map(Vec::len), + Some(2), + "the schema models exactly the two accepted bodies: {schema}" + ); + let shapes = schema["oneOf"].as_array().unwrap(); + for shape in shapes { + assert_eq!( + shape["additionalProperties"], + json!(false), + "no shape allows another key: {shape}" + ); + } + assert_eq!(shapes[0]["required"], json!(["path", "value"]), "{schema}"); + assert_eq!( + shapes[1]["properties"]["changes"]["items"]["additionalProperties"], + json!(false), + "a change carries `path` and `value` and nothing else: {schema}" + ); + assert_eq!( + shapes[1]["properties"]["changes"]["minItems"], + json!(1), + "{schema}" + ); + + // Every shape the schema allows, the handler takes. + let accepted = client + .call( + TOOL_SETTINGS_SET, + json!({ "changes": [{ "path": "wot.enabled", "value": false }] }), + ) + .await; + assert_eq!(accepted.is_error, Some(false), "{}", text(&accepted)); + let null_value = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "wot.seedPubkey", "value": null }), + ) + .await; + let null_value: Value = serde_json::from_str(&text(&null_value)).expect("a refusal body"); + assert_eq!( + null_value["error"], "Validation failed", + "an explicit null is a value the schema allows and the validator judges" + ); +} diff --git a/crates/nostream-mcp/tests/tools_list.rs b/crates/nostream-mcp/tests/tools_list.rs index b0b5154e5..fec1810db 100644 --- a/crates/nostream-mcp/tests/tools_list.rs +++ b/crates/nostream-mcp/tests/tools_list.rs @@ -7,6 +7,7 @@ //! | `the_comparator_rejects_a_changed_list` | the comparator can fail: a removed tool, a changed description and a changed schema each fail through the same `compare` | //! | `the_required_parameters_are_typed` | the shapes the values fix: an `Option` is a two-element type array, `get_event` carries `id`, `settings_set` names both accepted forms, no schema is empty | //! | `the_server_version_is_what_the_composition_supplies` | `serverInfo.version` is the composition's, not this crate's | +//! | `initialize_publishes_the_prerequisites` | `initialize`'s `instructions` name the three prerequisites and the credential | //! //! The snapshot is **name-sorted**, because rmcp sorts the list and array equality is //! order-sensitive (R21). It is compared, never regenerated: nothing here writes a file. @@ -16,7 +17,9 @@ mod common; use common::TestMcp; -use nostream_mcp::{TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET}; +use nostream_mcp::{ + MAX_PAGE_ROWS, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, +}; use serde_json::{Value, json}; /// The committed snapshot, as a document. A missing fixture fails the case. @@ -116,6 +119,22 @@ async fn the_required_parameters_are_typed() { ); assert_eq!(kinds[1], "null", "and its second member is null: {limit}"); + // The page contract the descriptions state, and the schema's own bound. + let listing = tool(TOOL_LIST_EVENTS); + let description = listing["description"].as_str().unwrap_or_default(); + assert!(description.contains("oldest first"), "{description}"); + assert!(description.contains("truncated"), "{description}"); + assert_eq!( + listing["inputSchema"]["properties"]["limit"]["minimum"], + json!(1), + "a page of zero rows is not a page: {description}" + ); + assert_eq!( + listing["inputSchema"]["properties"]["limit"]["maximum"], + json!(MAX_PAGE_ROWS), + "the schema's bound is the tool's page bound" + ); + assert!( tool(TOOL_GET_EVENT)["inputSchema"]["properties"] .get("id") @@ -168,3 +187,26 @@ async fn the_server_version_is_what_the_composition_supplies() { assert_eq!(server.version, "9.9.9"); assert_ne!(server.version, env!("CARGO_PKG_VERSION")); } + +#[tokio::test] +async fn initialize_publishes_the_prerequisites() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + let instructions = client + .client + .peer() + .peer_info() + .and_then(|info| info.instructions.clone()) + .expect("initialize carries instructions"); + for needle in [ + "admin.enabled", + "SECRET", + "NOSTREAM_ADMIN_TOKEN", + "POST /admin/login", + ] { + assert!( + instructions.contains(needle), + "the instructions name `{needle}`: {instructions}" + ); + } +} diff --git a/crates/nostream-storage/src/lib.rs b/crates/nostream-storage/src/lib.rs index 3ac2697e7..447636597 100644 --- a/crates/nostream-storage/src/lib.rs +++ b/crates/nostream-storage/src/lib.rs @@ -75,3 +75,13 @@ pub use postgres::{PostgresBackend, PostgresTransaction}; /// above this constant leaves Postgres able to serve more than the relay will believe, which /// suppresses `finish` where it could have been proved and never claims it where it should not. pub const MAX_PAGE_ROWS: u64 = 5_000; + +/// The page a read materialises when its filter carries no `limit`: the capture's own default, +/// `DEFAULT_FILTER_LIMIT` on both shipped backends. +/// +/// It is also the ceiling on an **ascending** page, because a backend picks its direction from +/// whether the filter carries a limit at all — LMDB walks newest-first only when one does +/// (`lmdb/events.rs:1166`) — so a caller that wants the first rows in time order, rather than +/// the newest, compares the rows it received against this value to know whether the page was +/// full. +pub const DEFAULT_PAGE_ROWS: u64 = 500; diff --git a/crates/nostream-storage/src/lmdb/events.rs b/crates/nostream-storage/src/lmdb/events.rs index d0b1c613b..df188365e 100644 --- a/crates/nostream-storage/src/lmdb/events.rs +++ b/crates/nostream-storage/src/lmdb/events.rs @@ -24,9 +24,9 @@ use super::encoding::{self, EventHeader}; use super::rows; use super::search; use super::{ - DEFAULT_FILTER_LIMIT, Databases, Gates, MAX_PAGE_KEYS, RETENTION_BATCH_SIZE, - STREAM_BATCH_ITEMS, STREAM_BATCH_KEYS, + Databases, Gates, MAX_PAGE_KEYS, RETENTION_BATCH_SIZE, STREAM_BATCH_ITEMS, STREAM_BATCH_KEYS, }; +use crate::DEFAULT_PAGE_ROWS; use crate::error::StorageError; use crate::records::{distinct_replacements, replaces_fields}; use crate::repositories::{ @@ -1103,7 +1103,7 @@ fn counted_earlier( /// The page a filter may materialise: its own limit or the capture's default, and never more /// than [`MAX_PAGE_KEYS`] however large the limit on the wire is. fn page_limit(filter: &Filter) -> usize { - count_limit(filter.limit.unwrap_or(DEFAULT_FILTER_LIMIT)) + count_limit(filter.limit.unwrap_or(DEFAULT_PAGE_ROWS)) } /// A wire limit clamped to [`MAX_PAGE_KEYS`], so no request chooses the size of an allocation. @@ -3698,13 +3698,13 @@ mod tests { .collect(), ), kinds: Some(vec![Kind(1)]), - limit: Some(DEFAULT_FILTER_LIMIT), + limit: Some(DEFAULT_PAGE_ROWS), ..Filter::default() }; let page = assert_page_sorts_once(&transaction, &databases, &filter, MAX_PAGE_KEYS); assert_eq!( created(&page), - (MAX_PAGE_KEYS as i64 - DEFAULT_FILTER_LIMIT as i64..MAX_PAGE_KEYS as i64) + (MAX_PAGE_KEYS as i64 - DEFAULT_PAGE_ROWS as i64..MAX_PAGE_KEYS as i64) .rev() .collect::>(), "the page is the newest `limit` authors, newest first" @@ -3721,7 +3721,7 @@ mod tests { let filter = Filter { authors: Some(vec![records[0].event.pubkey.to_string()]), kinds: Some(vec![Kind(1)]), - limit: Some(DEFAULT_FILTER_LIMIT), + limit: Some(DEFAULT_PAGE_ROWS), ..Filter::default() }; let page = assert_page_sorts_once(&transaction, &databases, &filter, 1); diff --git a/crates/nostream-storage/src/lmdb/mod.rs b/crates/nostream-storage/src/lmdb/mod.rs index d797dec43..f5abbca1a 100644 --- a/crates/nostream-storage/src/lmdb/mod.rs +++ b/crates/nostream-storage/src/lmdb/mod.rs @@ -59,9 +59,6 @@ pub const LMDB_MAX_DBS: u32 = 64; /// The number of concurrent read transactions the environment reserves. pub const LMDB_MAX_READERS: u32 = 512; -/// The capture's default page size (`DEFAULT_FILTER_LIMIT`). -pub(crate) const DEFAULT_FILTER_LIMIT: u64 = 500; - /// The largest page a read materialises, however large a limit the wire asks for. /// /// `limits.client.subscription.maxLimit` is the relay's own bound, but it is applied only when diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs index ead3eda30..3769bcb43 100644 --- a/crates/nostreamd/src/main.rs +++ b/crates/nostreamd/src/main.rs @@ -40,6 +40,10 @@ struct Cli { log_level: Option, /// Serve the admin MCP server on stdin/stdout and exit when stdin closes. Binds no socket. + /// + /// Every call is authenticated with an admin session token (minted by `POST /admin/login`) + /// in NOSTREAM_ADMIN_TOKEN, and needs `admin.enabled: true` in the settings and `SECRET` + /// set; without them a call answers Not Found, Internal Server Error or Unauthorized. #[arg(long)] mcp_stdio: bool, } diff --git a/crates/nostreamd/src/mcp_stdio.rs b/crates/nostreamd/src/mcp_stdio.rs index bdc8e570f..ea9238087 100644 --- a/crates/nostreamd/src/mcp_stdio.rs +++ b/crates/nostreamd/src/mcp_stdio.rs @@ -1,4 +1,10 @@ -//! `--mcp-stdio`: the admin MCP server on stdin/stdout, in the daemon's own process. +//! `--mcp-stdio`: the admin MCP server on stdin/stdout, in a process of its own. +//! +//! It composes an [`AdminState`](nostream_admin::AdminState) of its own over the same config +//! directory rather than sharing the console's: `--mcp-stdio` returns before the daemon's +//! `serve` loop would start, so the two modes are alternatives, and running both against one +//! directory is outside ADR 0012 D9 — the audit file and the settings write each assume one +//! writer per configuration (D18). //! //! The mode binds **no socket** — `nostreamd` stays the crate that binds, and this mode is not //! one of its listeners (D13) — and opens **no store of its own**: the admin state comes from diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index 8a0246ee5..052a0b31c 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -9,6 +9,7 @@ //! | `the_mode_binds_no_socket` | the dialogue completes while the port the flag names is held by the test | //! | `the_process_exits_zero_on_stdin_eof` | closing stdin ends the process with `0` | //! | `the_store_backed_tools_report_the_unwired_store` | `list_events` answers the store's own `NotImplemented` message, not an empty list | +//! | `the_help_text_names_the_credential` | `--help` names the three prerequisites and `NOSTREAM_ADMIN_TOKEN` | //! //! The dialogue is hand-written JSON-RPC over the child's pipes: this target proves a property //! of the process, so it spawns the binary the way an MCP client does. @@ -319,3 +320,22 @@ async fn the_store_backed_tools_report_the_unwired_store() { ); assert!(outcome.status.success(), "{}", outcome.stderr); } + +#[tokio::test] +async fn the_help_text_names_the_credential() { + let output = tokio::process::Command::new(env!("CARGO_BIN_EXE_nostreamd")) + .arg("--help") + .output() + .await + .expect("the binary answers --help"); + assert!(output.status.success(), "--help exits 0"); + let help = String::from_utf8_lossy(&output.stdout); + for needle in [ + "--mcp-stdio", + "NOSTREAM_ADMIN_TOKEN", + "admin.enabled", + "SECRET", + ] { + assert!(help.contains(needle), "the help names `{needle}`: {help}"); + } +} diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index ca3986735..5331b3a40 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -19,7 +19,7 @@ and the daemon answered no HTTP request at all — a plain `GET` died in the Web (`crates/nostream-relay/src/relay.rs:315-329`), measured as `curl: (52) Empty reply from server` on every admin path. -The seventeen decisions below are the ones a reader would otherwise have to reconstruct from +The eighteen decisions below are the ones a reader would otherwise have to reconstruct from the diff. Each is recorded with its reason and the evidence that produced it. ## Decisions @@ -306,6 +306,22 @@ tool's work, so the file's order is the dispatch order: `mcp.settings_set` prece refuses appends nothing at all — matching `admin_auth_middleware.rs:52-63`, which logs a warning and writes nothing. +**The mode is its own process, and the record says so.** `nostreamd --mcp-stdio` returns before +the daemon's `serve` loop starts (`crates/nostreamd/src/main.rs:135-141`), so the process that +serves a tool call composes its own `AdminState` over the same config directory rather than +sharing the console's: the two modes are alternatives, and running both against one directory is +outside ADR 0012 D9 — `admin-audit.jsonl` (whose compaction is a read, a write and a rename on a +shared staging path, `crates/nostream-admin/src/state.rs:715-733`) and the settings write both +assume one writer per configuration. + +**The audit table is total.** Every tool the router registers has its own entry in +`crates/nostream-mcp`'s `TOOL_ARGUMENTS` table, and the dispatch path looks a name up there +instead of defaulting: a tool added without an entry fails +`every_registered_tool_is_in_the_audit_table`, which reads the router's own list, so no call can +execute unaudited. "One line per executed call" therefore means what it says — a call whose +arguments do not parse and a call to a name the router does not register reach no tool and write +nothing, and every other call writes its line before the handler runs. + ## Evidence Measured in this job's worktree at `factory/032-admin-console-parity`: From dbce701df8a1c2d11717b21e748e668f2683cbc8 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Thu, 19 Nov 2026 23:53:10 -0500 Subject: [PATCH 04/24] fix(admin): answer the round-2 review of the admin MCP server --- crates/nostream-mcp/src/lib.rs | 19 +++-- crates/nostream-mcp/src/server.rs | 48 ++++++++---- crates/nostream-mcp/tests/audit.rs | 40 +++++++++- .../tests/fixtures/tools_list.json | 4 + crates/nostream-mcp/tests/tool_payloads.rs | 75 +++++++++++++++++++ crates/nostream-mcp/tests/tools_list.rs | 12 ++- crates/nostream-storage/src/lib.rs | 4 +- crates/nostream-storage/src/postgres/mod.rs | 14 +++- crates/nostreamd/src/mcp_stdio.rs | 10 ++- .../decisions/0014-admin-http-surface.md | 29 +++++-- 10 files changed, 217 insertions(+), 38 deletions(-) diff --git a/crates/nostream-mcp/src/lib.rs b/crates/nostream-mcp/src/lib.rs index 580e776df..bcf77781b 100644 --- a/crates/nostream-mcp/src/lib.rs +++ b/crates/nostream-mcp/src/lib.rs @@ -4,10 +4,13 @@ //! It owns no transport and no socket. `nostreamd --mcp-stdio` serves this server on //! stdin/stdout through `rmcp`'s `transport-io`, in a process of its own: the mode composes its //! own [`AdminState`](nostream_admin::AdminState) over the same config directory, so the tools -//! read the same session credential, the same `/admin-audit.jsonl` and the same -//! repository bundle (D9, D13). The two modes are alternatives — a daemon serving the console, -//! or a process serving the pipe — and running both against one config directory is outside D9: -//! the audit file and the settings write each assume one writer per configuration. +//! read the same session credential and the same `/admin-audit.jsonl` the console does, +//! over a repository bundle of the mode's own (D7, D18) — the daemon's bundle is composed in +//! `crates/nostreamd/src/main.rs`, this mode's in its `mcp_stdio` module, and the two are +//! independent `Arc`s that the store-wiring change has to move together. The two modes are +//! alternatives — a daemon serving the console, or a process serving the pipe — and running both +//! against one config directory is outside D9: the audit file and the settings write each assume +//! one writer per configuration. //! //! **Deliberately not owned here** — a reader should be able to tell an omission from a gap: //! @@ -24,8 +27,8 @@ mod server; pub use error::McpError; pub use server::{ - AdminMcp, GetEventArgs, INTERNAL_SERVER_ERROR, ListEventsArgs, MAX_FILTER_TERMS, MAX_PAGE_ROWS, - MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, SettingsSetArgs, TOOL_ARGUMENTS, TOOL_GET_EVENT, - TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, UNAUTHORIZED, arguments_parse, - audit_action, + AdminMcp, GetEventArgs, INTERNAL_SERVER_ERROR, ListEventsArgs, MAX_FILTER_TERMS, + MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, SettingsSetArgs, + TOOL_ARGUMENTS, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, + UNAUTHORIZED, arguments_parse, audit_action, }; diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index 4c09a25a4..0d3f6a017 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -65,7 +65,10 @@ pub const MAX_FILTER_TERMS: usize = 64; /// ([`nostream_storage::DEFAULT_PAGE_ROWS`]), which is what a filter carrying no `limit` /// materialises. A larger page would need the store's limited iterator, which returns the /// newest rows rather than the first. -pub const MAX_PAGE_ROWS: u64 = nostream_storage::DEFAULT_PAGE_ROWS; +/// +/// It is not `nostream_storage::MAX_PAGE_ROWS`, the relay's 5,000-row clamp: this is the page a +/// read materialises, which is the number a backend opens with. +pub const MAX_ROWS_PER_PAGE: u64 = nostream_storage::DEFAULT_PAGE_ROWS; /// The refusal for a token that is absent, malformed or expired — the HTTP gate's `401`. pub const UNAUTHORIZED: &str = "Unauthorized"; @@ -81,11 +84,18 @@ pub fn audit_action(tool: &str) -> String { format!("mcp.{tool}") } -/// Whether a call's arguments are the shape the tool's `inputSchema` states. +/// Whether the router can deserialise a call's arguments: the same type its handler takes. type ArgumentsCheck = fn(Option<&Map>) -> bool; -/// The audit table: every tool the router registers, with the check that says whether a call's -/// arguments are the shape its `inputSchema` states (R9). +/// The audit table: every tool the router registers, with the check that says whether the +/// router can deserialise a call's arguments (R9). +/// +/// The rule each entry keeps is **no stricter than the router's own deserialisation**, not "the +/// shape the `inputSchema` states". [`ServerHandler::call_tool`] writes the line when the check +/// answers `true` and then dispatches unconditionally, so a check that refused a call the router +/// runs would execute it unaudited — R9's guarantee failing open. The check exists to write the +/// line *before* the handler, never to refuse a call; `settings_set`'s is therefore deliberately +/// vacuous, because its arguments are a raw map and its `inputSchema` is the half that refuses. /// /// The dispatch path looks a name up here and has no "everything else is audited" arm, so a /// tool added to the router without an entry cannot execute unaudited: it fails @@ -127,7 +137,13 @@ fn arguments_value(arguments: Option<&Map>) -> Value { } /// The `list_events` criteria: each maps to one [`Filter`] field (R15). +/// +/// The set is closed. Every field is optional, so serde would otherwise drop a mistyped name — +/// `kind` for `kinds` is one character of plural away — and answer every row as if no criterion +/// had been given. `deny_unknown_fields` makes that an argument error and publishes +/// `additionalProperties: false`, which is the same rule a validating client reads. #[derive(Debug, Clone, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] pub struct ListEventsArgs { /// Kinds to select; absent selects every kind. pub kinds: Option>, @@ -146,8 +162,10 @@ pub struct ListEventsArgs { pub limit: Option, } -/// The `get_event` arguments. +/// The `get_event` arguments, and no others: an unknown key is an argument error, as it is for +/// [`ListEventsArgs`]. #[derive(Debug, Clone, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] pub struct GetEventArgs { /// The event's 64-character hex id, in either case. pub id: String, @@ -158,6 +176,10 @@ pub struct GetEventArgs { /// Kept as a raw map rather than a typed struct because the schema's rule is that an explicit /// `null` is a value and not an absent key: a typed `Option` would collapse the two and /// turn the validator's `Expected string, got null` into `Invalid request`. +/// +/// The `JsonSchema` below is the **advertisement** a validating client checks a body against; +/// `settings_patch` is the **enforcement**, in the handler, and the two state the same rule +/// twice on purpose — the schema cannot refuse a call, and the parser is not a schema. #[derive(Debug, Clone, Deserialize)] pub struct SettingsSetArgs { /// `{path, value}` or `{changes: [{path, value}, …]}`. @@ -182,7 +204,7 @@ impl JsonSchema for SettingsSetArgs { json!({ "type": "object", "properties": { - "path": { "type": "string" }, + "path": { "type": "string", "minLength": 1 }, "value": {}, }, "required": ["path", "value"], @@ -195,7 +217,7 @@ impl JsonSchema for SettingsSetArgs { { "type": "object", "properties": { - "path": { "type": "string" }, + "path": { "type": "string", "minLength": 1 }, "value": {}, }, "required": ["path", "value"], @@ -315,7 +337,7 @@ impl AdminMcp { /// No `limit` goes to the store, because the store picks its direction from it: a filter /// carrying one is answered newest-first, which would make the payload's order depend on an /// unrelated argument. Ascending is the store's unlimited page, whose bound is - /// [`MAX_PAGE_ROWS`], so `limit` is applied to that page here and the marker is + /// [`MAX_ROWS_PER_PAGE`], so `limit` is applied to that page here and the marker is /// `len >= limit`. async fn events(&self, criteria: ListEventsArgs) -> Result<(Vec, bool), McpError> { let page = page_size(&criteria)?; @@ -397,13 +419,13 @@ impl AdminMcp { /// The page a call asks for, checked against the bounds its `inputSchema` states. fn page_size(criteria: &ListEventsArgs) -> Result { - let limit = criteria.limit.unwrap_or(MAX_PAGE_ROWS); - let page = usize::try_from(limit) - .ok() - .filter(|page| (1..=usize::try_from(MAX_PAGE_ROWS).unwrap_or(usize::MAX)).contains(page)); + let limit = criteria.limit.unwrap_or(MAX_ROWS_PER_PAGE); + let page = usize::try_from(limit).ok().filter(|page| { + (1..=usize::try_from(MAX_ROWS_PER_PAGE).unwrap_or(usize::MAX)).contains(page) + }); page.ok_or_else(|| { McpError::Criterion(format!( - "limit: a page holds between 1 and {MAX_PAGE_ROWS} rows, {limit} was given" + "limit: a page holds between 1 and {MAX_ROWS_PER_PAGE} rows, {limit} was given" )) }) } diff --git a/crates/nostream-mcp/tests/audit.rs b/crates/nostream-mcp/tests/audit.rs index 91deeff61..921317b55 100644 --- a/crates/nostream-mcp/tests/audit.rs +++ b/crates/nostream-mcp/tests/audit.rs @@ -5,6 +5,7 @@ //! | `each_call_appends_one_line` | four calls append five lines in call order — the four `mcp.*` lines, then `settings_set`'s own `settings.updated` | //! | `a_refused_call_appends_nothing` | a call with bad arguments and a call with no token each leave the file untouched | //! | `every_registered_tool_is_in_the_audit_table` | the audit table is total: no tool the router registers can execute unaudited | +//! | `the_audit_check_is_no_stricter_than_the_router` | the table's rule is the router's deserialiser, not the schema: a stricter check would fail open | //! //! R9 appends the `mcp.*` line at dispatch, before the handler's work, so the order in the file //! is the order of the calls and a domain line always follows its own dispatch line. @@ -15,7 +16,7 @@ mod common; use std::collections::BTreeSet; -use common::{Fixture, TestMcp, Token, event, id_of, text}; +use common::{Fixture, TestMcp, Token, event, id_of, object, text}; use nostream_mcp::{ TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, audit_action, }; @@ -143,3 +144,40 @@ async fn every_registered_tool_is_in_the_audit_table() { "the table names exactly the tools the router registers" ); } + +/// The table's rule is "no stricter than the router's own deserialiser", not "the shape the +/// `inputSchema` states": `call_tool` writes the line and then dispatches unconditionally, so a +/// check that refused a call the router runs would execute it unaudited — R9 failing open. +#[tokio::test] +async fn the_audit_check_is_no_stricter_than_the_router() { + // `settings_set` takes a raw map, so its check is deliberately vacuous and its schema is the + // half that refuses. Repairing the check to `settings_patch(..).is_some()` — the obvious + // reading of "the shape the schema states" — would write no line for `{"foo": 1}` while the + // router still ran the handler. + assert_eq!( + nostream_mcp::arguments_parse(TOOL_SETTINGS_SET, Some(&object(json!({ "foo": 1 })))), + Some(true), + "a check stricter than the router's deserialisation fails open: the line is written \ + before the dispatch, so a call this refused would execute unaudited" + ); + + let fixture = TestMcp::start().await; + let client = fixture.client().await; + let refused = client.call(TOOL_SETTINGS_SET, json!({ "foo": 1 })).await; + assert_eq!(refused.is_error, Some(true), "{}", text(&refused)); + assert!( + text(&refused).contains("Invalid request"), + "the handler refused it, so the router ran it: {}", + text(&refused) + ); + let actions: Vec = fixture + .audit_entries() + .iter() + .map(|entry| entry["action"].as_str().unwrap_or_default().to_owned()) + .collect(); + assert_eq!( + actions, + vec![audit_action(TOOL_SETTINGS_SET)], + "the dispatched-but-refused call wrote its line" + ); +} diff --git a/crates/nostream-mcp/tests/fixtures/tools_list.json b/crates/nostream-mcp/tests/fixtures/tools_list.json index ba3e2734e..4fb5cee37 100644 --- a/crates/nostream-mcp/tests/fixtures/tools_list.json +++ b/crates/nostream-mcp/tests/fixtures/tools_list.json @@ -4,6 +4,7 @@ "description": "Read one stored event by its exact 64-character hex id, in either case; null when no such id is stored", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, "properties": { "id": { "description": "The event's 64-character hex id, in either case.", @@ -21,6 +22,7 @@ "description": "List stored events matching the given kinds, authors, ids, since and until. Rows come back oldest first, and `limit` is the page size — the first rows in that order, at most 500; `truncated` is true when the page is full, so more rows may match", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, "properties": { "authors": { "description": "Author pubkey hex prefixes, 4 to 64 characters each in either case; at most 64 per\ncall. A criterion the wire would refuse is an error, not a narrower read.", @@ -102,6 +104,7 @@ "additionalProperties": false, "properties": { "path": { + "minLength": 1, "type": "string" }, "value": {} @@ -120,6 +123,7 @@ "additionalProperties": false, "properties": { "path": { + "minLength": 1, "type": "string" }, "value": {} diff --git a/crates/nostream-mcp/tests/tool_payloads.rs b/crates/nostream-mcp/tests/tool_payloads.rs index 70a41af4e..d1f7f3e1e 100644 --- a/crates/nostream-mcp/tests/tool_payloads.rs +++ b/crates/nostream-mcp/tests/tool_payloads.rs @@ -17,6 +17,7 @@ //! | `an_empty_change_list_is_refused` | `{changes: []}` is `Invalid request`, and the attempt is audited | //! | `an_unknown_tool_is_a_protocol_error` | an absent tool is JSON-RPC `-32602`, not a result | //! | `bad_arguments_are_an_error_result` | wrong-typed arguments are an `isError` result, not a protocol error | +//! | `an_unknown_argument_is_an_argument_error` | a mistyped key is an argument error naming the accepted fields, not an unfiltered page | //! | `an_uppercase_id_finds_its_row` | a stored id pasted in uppercase is the same id, not a confident `null` | //! | `a_criterion_the_wire_would_refuse_is_an_argument_error` | a non-hex, short, oversized or over-counted criterion is refused, naming its field | //! | `a_refused_criterion_never_reaches_the_store` | the refusal comes before the store: over the unwired store the argument error answers, not `NotImplemented` | @@ -355,6 +356,57 @@ async fn bad_arguments_are_an_error_result() { ); } +#[tokio::test] +async fn an_unknown_argument_is_an_argument_error() { + let fixture = TestMcp::start().await; + fixture + .seed(&[event(31, 1, 1_699_999_956), event(32, 7, 1_699_999_957)]) + .await; + let client = fixture.client().await; + + // The field a client works from is `kinds`; `kind` is one character of plural away, and a + // serde struct that drops what it does not know answers every row as if no criterion had + // been given — a complete-looking page of the wrong rows. + let mistyped = client.call(TOOL_LIST_EVENTS, json!({ "kind": [1] })).await; + assert_eq!(mistyped.is_error, Some(true), "{}", text(&mistyped)); + let message = text(&mistyped); + assert!( + message.contains("unknown field `kind`") + && message.contains("`kinds`") + && message.contains("`limit`"), + "the refusal names the key it got and the keys it takes: {message}" + ); + assert!( + fixture.audit_entries().is_empty(), + "a call the router's deserialiser refuses reaches no tool and writes nothing" + ); + + // The same rule in the published schema, which a validating client reads before it calls. + let tools = client.tools().await; + for name in [TOOL_LIST_EVENTS, TOOL_GET_EVENT] { + let tool = tools + .iter() + .find(|tool| tool.name == name) + .unwrap_or_else(|| panic!("{name} is listed")); + let schema = Value::Object((*tool.input_schema).clone()); + assert_eq!( + schema["additionalProperties"], + json!(false), + "{name} admits no key its handler does not take: {schema}" + ); + } + + // The control: the right key is a page of exactly the rows that match. + let rows = client.call(TOOL_LIST_EVENTS, json!({ "kinds": [1] })).await; + assert_eq!(rows.is_error, Some(false), "{}", text(&rows)); + assert_eq!( + payload(&rows)["events"].as_array().unwrap().len(), + 1, + "{}", + text(&rows) + ); +} + #[tokio::test] async fn an_uppercase_id_finds_its_row() { let fixture = TestMcp::start().await; @@ -600,6 +652,29 @@ async fn the_settings_schema_forbids_what_the_handler_refuses() { "{schema}" ); + // `parse_change` refuses an empty path (`admin_json_body_middleware.rs:138-140`), so the + // advertisement says it too: the schema is what a validating client reads, the handler is + // what enforces. + assert_eq!( + shapes[0]["properties"]["path"]["minLength"], + json!(1), + "an empty path is not a change: {schema}" + ); + assert_eq!( + shapes[1]["properties"]["changes"]["items"]["properties"]["path"]["minLength"], + json!(1), + "nor is it one in a list: {schema}" + ); + let empty_path = client + .call(TOOL_SETTINGS_SET, json!({ "path": "", "value": 1 })) + .await; + assert_eq!(empty_path.is_error, Some(true), "{}", text(&empty_path)); + let empty_path: Value = serde_json::from_str(&text(&empty_path)).expect("a refusal body"); + assert_eq!( + empty_path["error"], "Invalid request", + "the handler refuses what the schema now forbids" + ); + // Every shape the schema allows, the handler takes. let accepted = client .call( diff --git a/crates/nostream-mcp/tests/tools_list.rs b/crates/nostream-mcp/tests/tools_list.rs index fec1810db..e0cf37058 100644 --- a/crates/nostream-mcp/tests/tools_list.rs +++ b/crates/nostream-mcp/tests/tools_list.rs @@ -18,7 +18,7 @@ mod common; use common::TestMcp; use nostream_mcp::{ - MAX_PAGE_ROWS, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, + MAX_ROWS_PER_PAGE, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, }; use serde_json::{Value, json}; @@ -129,9 +129,17 @@ async fn the_required_parameters_are_typed() { json!(1), "a page of zero rows is not a page: {description}" ); + + // One number, three readers: the store's no-limit page, the tool's constant and the schema + // a client validates against cannot drift apart. + assert_eq!( + MAX_ROWS_PER_PAGE, + nostream_storage::DEFAULT_PAGE_ROWS, + "the tool's page bound is the store's own page, the page `truncated` is derived from" + ); assert_eq!( listing["inputSchema"]["properties"]["limit"]["maximum"], - json!(MAX_PAGE_ROWS), + json!(MAX_ROWS_PER_PAGE), "the schema's bound is the tool's page bound" ); diff --git a/crates/nostream-storage/src/lib.rs b/crates/nostream-storage/src/lib.rs index 447636597..21e926829 100644 --- a/crates/nostream-storage/src/lib.rs +++ b/crates/nostream-storage/src/lib.rs @@ -77,7 +77,9 @@ pub use postgres::{PostgresBackend, PostgresTransaction}; pub const MAX_PAGE_ROWS: u64 = 5_000; /// The page a read materialises when its filter carries no `limit`: the capture's own default, -/// `DEFAULT_FILTER_LIMIT` on both shipped backends. +/// `DEFAULT_FILTER_LIMIT` in both shipped backends: LMDB reads this constant (`lmdb::events`) +/// and Postgres aliases it as its `DEFAULT_FILTER_LIMIT` (`postgres/mod.rs`), so neither backend +/// can carry a second number. /// /// It is also the ceiling on an **ascending** page, because a backend picks its direction from /// whether the filter carries a limit at all — LMDB walks newest-first only when one does diff --git a/crates/nostream-storage/src/postgres/mod.rs b/crates/nostream-storage/src/postgres/mod.rs index f1c1fd7b6..5573f0623 100644 --- a/crates/nostream-storage/src/postgres/mod.rs +++ b/crates/nostream-storage/src/postgres/mod.rs @@ -34,8 +34,18 @@ pub(crate) use sql::{Arg, Args, EventQuery, Gates, Nip50Gate}; pub(crate) const DEFAULT_TS_CONFIG: &str = "simple"; /// The default `nip50.maxQueryLength` (`src/repositories/event-repository.ts:50-52`). pub(crate) const DEFAULT_MAX_SEARCH_QUERY_LENGTH: u64 = 256; -/// The capture's default page size (`DEFAULT_FILTER_LIMIT`). -pub(crate) const DEFAULT_FILTER_LIMIT: u64 = 500; +/// The capture's default page size (`DEFAULT_FILTER_LIMIT`): the store's own no-limit page, +/// under the name this module's SQL reads it by. +pub(crate) use crate::DEFAULT_PAGE_ROWS as DEFAULT_FILTER_LIMIT; + +// The MCP surface publishes this number as `list_events`' page bound and derives `truncated` +// from it, so a Postgres read has to materialise exactly the page the tool reports on. The alias +// above makes the two one item; this fails the build if it is ever retyped as a literal. +const _: () = assert!( + DEFAULT_FILTER_LIMIT == crate::DEFAULT_PAGE_ROWS, + "the Postgres no-limit page is the store's own DEFAULT_PAGE_ROWS" +); + /// The retention batch size (`RETENTION_BATCH_SIZE`). pub(crate) const RETENTION_BATCH_SIZE: u64 = 1000; diff --git a/crates/nostreamd/src/mcp_stdio.rs b/crates/nostreamd/src/mcp_stdio.rs index ea9238087..89ddfd062 100644 --- a/crates/nostreamd/src/mcp_stdio.rs +++ b/crates/nostreamd/src/mcp_stdio.rs @@ -8,9 +8,13 @@ //! //! The mode binds **no socket** — `nostreamd` stays the crate that binds, and this mode is not //! one of its listeners (D13) — and opens **no store of its own**: the admin state comes from -//! [`crate::admin_http::compose`] over the same `unavailable::stores()` bundle the relay path -//! hands over, so no second process ever opens the LMDB directory (ADR 0012 D9). While the store -//! is unwired, the store-backed tools answer the store's own `NotImplemented` message (R19). +//! [`crate::admin_http::compose`] over an `unavailable::stores()` bundle composed here, as the +//! relay path composes its own in `crates/nostreamd/src/main.rs`'s `serve`. The two are +//! independent `Arc`s in two processes, not one shared value (D7, D18), and while the store is +//! unwired neither opens an LMDB directory at all — so ADR 0012 D9's second-writer hazard cannot +//! arise. When the store is wired, `main.rs`'s bundle and this one have to be wired together in +//! the same change, or this mode keeps answering the store-backed tools with the store's own +//! `NotImplemented` message (R19). //! //! The credential is read once here and passed to the server as a value: the server never reads //! the environment (R7). diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index 5331b3a40..acd6e738b 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -128,6 +128,10 @@ A consequence, stated so it is not read as a defect: the daemon still wires route answers `500` in the daemon until that job lands. The oracle proves those routes against a real LMDB store; the daemon's composition is what changes when the store is wired. +The one surface handed a bundle of its own is the MCP mode: `nostreamd --mcp-stdio` is a second +process, so it composes its own `unavailable::stores()` rather than this `Arc` (D18). The two +composition sites are independent, and wiring the store means wiring both. + ### D8 — Settings are read per request and written through a `nostream-config` store The capture's `createSettings()`/`loadMergedSettings()` re-reads the files on every call @@ -307,20 +311,29 @@ refuses appends nothing at all — matching `admin_auth_middleware.rs:52-63`, wh and writes nothing. **The mode is its own process, and the record says so.** `nostreamd --mcp-stdio` returns before -the daemon's `serve` loop starts (`crates/nostreamd/src/main.rs:135-141`), so the process that +the daemon's `serve` loop starts (`crates/nostreamd/src/main.rs:139-147`), so the process that serves a tool call composes its own `AdminState` over the same config directory rather than -sharing the console's: the two modes are alternatives, and running both against one directory is -outside ADR 0012 D9 — `admin-audit.jsonl` (whose compaction is a read, a write and a rename on a -shared staging path, `crates/nostream-admin/src/state.rs:715-733`) and the settings write both -assume one writer per configuration. +sharing the console's: the same session credential, the same `admin-audit.jsonl`, and a +repository bundle of its own — `unavailable::stores()` in `crates/nostreamd/src/mcp_stdio.rs`, +composed independently of the relay path's at `crates/nostreamd/src/main.rs:187`, which D7's +same-`Arc` rule covers for the console and not for this mode. Wiring the store means wiring the +two sites in one change; until then neither process opens an LMDB directory, so ADR 0012 D9's +second-writer hazard cannot arise. The two modes are alternatives, and running both against one +directory is outside ADR 0012 D9 — `admin-audit.jsonl` (whose compaction is a read, a write and a +rename on a shared staging path, `crates/nostream-admin/src/state.rs:715-733`) and the settings +write both assume one writer per configuration. **The audit table is total.** Every tool the router registers has its own entry in `crates/nostream-mcp`'s `TOOL_ARGUMENTS` table, and the dispatch path looks a name up there instead of defaulting: a tool added without an entry fails `every_registered_tool_is_in_the_audit_table`, which reads the router's own list, so no call can -execute unaudited. "One line per executed call" therefore means what it says — a call whose -arguments do not parse and a call to a name the router does not register reach no tool and write -nothing, and every other call writes its line before the handler runs. +execute unaudited. "One line per executed call" therefore means what it says — a call the +router's own deserialiser refuses, and a call to a name the router does not register, reach no +tool and write nothing, and every other call writes its line before the handler runs. The rule an +entry keeps is *no stricter than that deserialiser*, not "the shape the `inputSchema` states": +the line is written before the dispatch, which is unconditional, so a stricter check would let a +call run unaudited. `settings_set`'s entry is therefore vacuous by design — its arguments are a +raw map and its schema is the half that refuses. ## Evidence From 14b6bbcf836b3c76da9a703ccc04884d09663d58 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Thu, 19 Nov 2026 23:57:15 -0500 Subject: [PATCH 05/24] docs(admin): say how D18's mcp audit action is composed --- docs/rewrite/decisions/0014-admin-http-surface.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index acd6e738b..44c4cebec 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -292,8 +292,9 @@ reusing one: **These extend the capture's nine names; they do not replace them.** The capture's vocabulary is a closed nine-name union (`src/@types/admin-audit.ts:1-10`), and the rewrite's writer takes `&str` (`crates/nostream-admin/src/state.rs:497`), so a new name is accepted and stored without -a schema change. Each name is `mcp.` plus the tool's own name, and each is a named constant in -`crates/nostream-mcp`. +a schema change. Each name is `mcp.` plus the tool's own name: the tool name is a constant in +`crates/nostream-mcp` (`TOOL_*`) and the action is composed from it by `audit_action`, so no +`mcp.*` string is written at a call site. **One name per tool, not one `mcp.tool_call` with the tool in `detail`.** The console's trust page renders `entry.action` verbatim (`resources/admin/assets/admin-trust.js:93`), so the action column From 7a09de4627db1d8f27189253034e828c1b653cb1 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Thu, 19 Nov 2026 23:59:19 -0500 Subject: [PATCH 06/24] test(admin): pin get_event's refusal of an unknown key --- crates/nostream-mcp/tests/tool_payloads.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/nostream-mcp/tests/tool_payloads.rs b/crates/nostream-mcp/tests/tool_payloads.rs index d1f7f3e1e..450c8981d 100644 --- a/crates/nostream-mcp/tests/tool_payloads.rs +++ b/crates/nostream-mcp/tests/tool_payloads.rs @@ -396,6 +396,21 @@ async fn an_unknown_argument_is_an_argument_error() { ); } + // The same rule on `get_event`, whose `id` is required: an extra key used to be harmless + // there — the row came back — and is an argument error now. + let record = event(33, 7, 1_699_999_958); + let id = id_of(&record); + fixture.seed(std::slice::from_ref(&record)).await; + let extra = client + .call(TOOL_GET_EVENT, json!({ "id": id, "fields": ["content"] })) + .await; + assert_eq!(extra.is_error, Some(true), "{}", text(&extra)); + assert!( + text(&extra).contains("unknown field `fields`"), + "{}", + text(&extra) + ); + // The control: the right key is a page of exactly the rows that match. let rows = client.call(TOOL_LIST_EVENTS, json!({ "kinds": [1] })).await; assert_eq!(rows.is_error, Some(false), "{}", text(&rows)); From 80a631af195153057d04dc6fcf5192cf4e461499 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 00:37:21 -0500 Subject: [PATCH 07/24] docs(admin): the changeset says the MCP mode is its own process --- .changeset/admin-mcp-server.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/admin-mcp-server.md b/.changeset/admin-mcp-server.md index 9fda19ba7..f53c28d30 100644 --- a/.changeset/admin-mcp-server.md +++ b/.changeset/admin-mcp-server.md @@ -4,8 +4,8 @@ feat(admin): the admin MCP server, slice 1 — four tools over stdio A new Rust crate serves `settings_get`, `settings_set`, `list_events` and -`get_event` on stdin/stdout through `rmcp`, inside the daemon's own process -(`--mcp-stdio`). Every call is gated by the console's own session token and +`get_event` on stdin/stdout through `rmcp`, served by `nostreamd --mcp-stdio` as a process +of its own over the same config directory. Every call is gated by the console's own session token and audited to `admin-audit.jsonl` under one `mcp.` action; the four names are recorded as ADR 0014 D18. From d6b374251315142911726d0cec0dfbfbbcad7c03 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 00:57:49 -0500 Subject: [PATCH 08/24] fix(admin): list_events counts page slots, not surviving rows A page's size is the slots the store spent. collect_records drops StreamedEvent::Vanished, which is the store's signal that a selected key was removed before its value was read (a replacement hard-deletes the row it supersedes, a retention pass removes a soft-deleted one), so a full page that lost a row answered 499 rows with truncated: false while another matching row remained unread. collect_page returns the rows and the slots beside them, the tool derives the marker from the slots, and a case drives a real page whose second selected slot vanished. --- Cargo.lock | 2 + crates/nostream-mcp/Cargo.toml | 2 + crates/nostream-mcp/src/server.rs | 15 +- crates/nostream-mcp/tests/common/mod.rs | 152 +++++++++++++++++++- crates/nostream-mcp/tests/tool_payloads.rs | 49 +++++++ crates/nostream-storage/src/repositories.rs | 48 ++++++- 6 files changed, 255 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0c927155..a084c7ccd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1469,6 +1469,8 @@ dependencies = [ name = "nostream-mcp" version = "0.1.0" dependencies = [ + "futures-core", + "futures-util", "nostream-admin", "nostream-config", "nostream-core", diff --git a/crates/nostream-mcp/Cargo.toml b/crates/nostream-mcp/Cargo.toml index e2c3fcc66..fc7d64264 100644 --- a/crates/nostream-mcp/Cargo.toml +++ b/crates/nostream-mcp/Cargo.toml @@ -19,6 +19,8 @@ thiserror.workspace = true tracing.workspace = true [dev-dependencies] +futures-core.workspace = true +futures-util.workspace = true nostream-services.workspace = true rmcp = { workspace = true, features = ["client"] } serde_yaml.workspace = true diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index 0d3f6a017..d8f1f5283 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -15,7 +15,7 @@ use nostream_admin::controllers::admin_json_body_middleware::settings_patch; use nostream_admin::controllers::patch_settings::{self, SettingsWrite}; use nostream_admin::utils::session; use nostream_core::{Filter, Kind}; -use nostream_storage::repositories::{EventRecord, collect_records}; +use nostream_storage::repositories::{EventRecord, collect_page, collect_records}; use rmcp::handler::server::router::tool::ToolRouter; use rmcp::handler::server::tool::ToolCallContext; use rmcp::handler::server::wrapper::Parameters; @@ -296,7 +296,8 @@ impl AdminMcp { } /// One `EventRepository` read over one [`Filter`], through `collect_records` so a vanished - /// slot never reaches the payload (R15). + /// slot never reaches the payload (R15), and through `collect_page` where the page's size + /// decides something, so a spent slot is not read as a short page. #[tool( description = "List stored events matching the given kinds, authors, ids, since and until. Rows come back oldest first, and `limit` is the page size — the first rows in that order, at most 500; `truncated` is true when the page is full, so more rows may match" )] @@ -337,8 +338,10 @@ impl AdminMcp { /// No `limit` goes to the store, because the store picks its direction from it: a filter /// carrying one is answered newest-first, which would make the payload's order depend on an /// unrelated argument. Ascending is the store's unlimited page, whose bound is - /// [`MAX_ROWS_PER_PAGE`], so `limit` is applied to that page here and the marker is - /// `len >= limit`. + /// [`MAX_ROWS_PER_PAGE`], so `limit` is applied to that page here and the marker counts + /// **slots**, not rows: a page that selected a key a concurrent replacement or a retention + /// pass then removed spends that slot and yields no row, and counting the surviving rows + /// would answer `truncated: false` to a caller with more rows still to read. async fn events(&self, criteria: ListEventsArgs) -> Result<(Vec, bool), McpError> { let page = page_size(&criteria)?; let filter = Filter { @@ -354,8 +357,8 @@ impl AdminMcp { }; let filters = [filter]; let stream = self.state.stores().events.find_by_filters(&filters).await?; - let mut records = collect_records(stream).await?; - let truncated = records.len() >= page; + let (mut records, slots) = collect_page(stream).await?; + let truncated = slots >= page; records.truncate(page); Ok((records, truncated)) } diff --git a/crates/nostream-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs index 35f68e484..f35f65cae 100644 --- a/crates/nostream-mcp/tests/common/mod.rs +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -12,6 +12,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; +use futures_util::StreamExt; use nostream_admin::state::AdminStateConfig; use nostream_admin::utils::session; use nostream_admin::{AdminState, GrafanaSettings}; @@ -19,11 +20,14 @@ use nostream_config::SettingsPaths; use nostream_core::clock::TestClock; use nostream_core::nip05::Nip05Fetch; use nostream_core::random::SystemRandom; -use nostream_core::{Event, EventId, Kind, Pubkey, Signature}; +use nostream_core::{Event, EventId, Filter, Kind, Pubkey, Signature}; use nostream_mcp::{AdminMcp, MCP_SERVER_NAME}; use nostream_services::{HttpClient, ReqwestClient, ServiceStores}; +use nostream_storage::error::StorageError; use nostream_storage::lmdb::LmdbBackend; -use nostream_storage::repositories::{EventRecord, EventRepository}; +use nostream_storage::repositories::{ + EventRecord, EventRepository, QueryStream, StorageFuture, StreamedEvent, +}; use rmcp::model::{ CallToolRequestParams, CallToolResult, ClientCapabilities, ClientConfig, Implementation, ProtocolVersion, Tool, @@ -117,6 +121,10 @@ impl Fixture { } } +/// Builds the event repository a case wants over the harness's own backend. +pub type EventRepositoryFactory = + Arc) -> Arc + Send + Sync>; + /// One composed server over a temporary config dir, and what it was composed with. pub struct TestMcp { pub state: Arc, @@ -135,6 +143,16 @@ impl TestMcp { /// Builds a case's composition. pub async fn start_with(fixture: Fixture) -> Self { + Self::start_with_events(fixture, None).await + } + + /// The same, with the event repository a case supplies in place of the backend — for the + /// cases that need a page the store cannot be made to produce on demand, such as one whose + /// selected key was removed before its value was read. + pub async fn start_with_events( + fixture: Fixture, + events: Option, + ) -> Self { let temp = tempfile::tempdir().unwrap(); let config_dir = temp.path().join("config"); std::fs::create_dir_all(&config_dir).unwrap(); @@ -155,7 +173,10 @@ impl TestMcp { let backend = Arc::new(backend); let stores = match fixture.stores { Stores::Seeded => Arc::new(ServiceStores { - events: Arc::clone(&backend) as Arc, + events: events.as_ref().map_or_else( + || Arc::clone(&backend) as Arc, + |wrap| wrap(Arc::clone(&backend)), + ), users: Arc::clone(&backend) as Arc, invoices: Arc::clone(&backend) @@ -404,3 +425,128 @@ fn lines(path: &Path) -> Vec { .map(|line| serde_json::from_str(line).unwrap()) .collect() } + +/// The real backend, with one page slot reported as vanished. +/// +/// `StreamedEvent::Vanished` is what the LMDB stream emits for a key it selected and could not +/// read — a replacement hard-deletes the row it supersedes and a retention pass removes a +/// soft-deleted one, and both can land between the selection and the batch read. That window +/// cannot be opened from outside the store, so a case that needs the marker takes a real page +/// and has the `nth` record inside it answered as the marker instead. Every other method is the +/// backend's own. +pub struct VanishingRepository { + inner: Arc, + nth: usize, +} + +impl VanishingRepository { + /// The backend, with the `nth` record of every page reported as vanished. + pub fn new(inner: Arc, nth: usize) -> Self { + Self { inner, nth } + } +} + +impl EventRepository for VanishingRepository { + fn create<'a>(&'a self, record: &'a EventRecord) -> StorageFuture<'a, u64> { + self.inner.create(record) + } + + fn create_many<'a>(&'a self, records: &'a [EventRecord]) -> StorageFuture<'a, u64> { + self.inner.create_many(records) + } + + fn upsert<'a>(&'a self, record: &'a EventRecord) -> StorageFuture<'a, u64> { + self.inner.upsert(record) + } + + fn upsert_many<'a>(&'a self, records: &'a [EventRecord]) -> StorageFuture<'a, u64> { + self.inner.upsert_many(records) + } + + fn find_by_filters<'a>( + &'a self, + filters: &'a [Filter], + ) -> StorageFuture<'a, QueryStream<'a, StreamedEvent>> { + Box::pin(async move { + let stream = self.inner.find_by_filters(filters).await?; + let items: Vec> = stream.collect().await; + let nth = self.nth; + let mut seen = 0usize; + let mapped = items.into_iter().map(move |item| { + item.map(|event| match event { + StreamedEvent::Record(record) => { + seen += 1; + if seen == nth { + StreamedEvent::Vanished + } else { + StreamedEvent::Record(record) + } + } + marker => marker, + }) + }); + Ok(Box::pin(futures_util::stream::iter(mapped)) as QueryStream<'a, StreamedEvent>) + }) + } + + fn count_by_filters<'a>(&'a self, filters: &'a [Filter]) -> StorageFuture<'a, u64> { + self.inner.count_by_filters(filters) + } + + fn page_bound(&self) -> u64 { + self.inner.page_bound() + } + + fn search_rule(&self) -> nostream_storage::repositories::SearchRule { + self.inner.search_rule() + } + + fn empty_tag_rule(&self) -> nostream_storage::repositories::EmptyTagRule { + self.inner.empty_tag_rule() + } + + fn find_reconciliation_items<'a>( + &'a self, + filter: &'a Filter, + ) -> StorageFuture<'a, QueryStream<'a, nostream_storage::repositories::ReconciliationItem>> + { + self.inner.find_reconciliation_items(filter) + } + + fn delete_by_pubkey_and_ids<'a>( + &'a self, + pubkey: &'a Pubkey, + ids: &'a [EventId], + ) -> StorageFuture<'a, u64> { + self.inner.delete_by_pubkey_and_ids(pubkey, ids) + } + + fn delete_by_addresses<'a>( + &'a self, + pubkey: &'a Pubkey, + addresses: &'a [(Kind, String)], + not_after: i64, + ) -> StorageFuture<'a, u64> { + self.inner.delete_by_addresses(pubkey, addresses, not_after) + } + + fn delete_by_pubkey_except_kinds<'a>( + &'a self, + pubkey: &'a Pubkey, + excluded_kinds: &'a [Kind], + ) -> StorageFuture<'a, u64> { + self.inner + .delete_by_pubkey_except_kinds(pubkey, excluded_kinds) + } + + fn has_active_request_to_vanish<'a>(&'a self, pubkey: &'a Pubkey) -> StorageFuture<'a, bool> { + self.inner.has_active_request_to_vanish(pubkey) + } + + fn delete_expired_and_retained<'a>( + &'a self, + options: &'a nostream_storage::repositories::EventRetentionOptions, + ) -> StorageFuture<'a, nostream_storage::repositories::EventPurgeCounts> { + self.inner.delete_expired_and_retained(options) + } +} diff --git a/crates/nostream-mcp/tests/tool_payloads.rs b/crates/nostream-mcp/tests/tool_payloads.rs index 450c8981d..f2995ff5a 100644 --- a/crates/nostream-mcp/tests/tool_payloads.rs +++ b/crates/nostream-mcp/tests/tool_payloads.rs @@ -34,6 +34,7 @@ use std::collections::BTreeSet; use common::{Fixture, Stores, TestMcp, event, id_of, payload, text}; use nostream_mcp::{TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET}; +use nostream_storage::repositories::EventRepository; use serde_json::{Value, json}; fn ids(events: &[Value]) -> BTreeSet { @@ -710,3 +711,51 @@ async fn the_settings_schema_forbids_what_the_handler_refuses() { "an explicit null is a value the schema allows and the validator judges" ); } + +/// A page that spent its slots and lost one to a vanished row is complete, not short. +/// +/// `truncated` answers "may more rows match", and a page's size is the slots it spent: the +/// store selects a bounded number of keys, then reads their values in batches, so a replacement +/// (which hard-deletes the row it supersedes) or a retention pass can remove a selected key +/// between the two. `StreamedEvent::Vanished` is the store's own signal for that slot, and a +/// caller that counted the surviving rows would answer `truncated: false` with a matching row +/// still unread — the "silent short page" the page obligation forbids. +#[tokio::test] +async fn a_page_that_lost_a_slot_is_still_marked_truncated() { + use std::sync::Arc; + + let fixture = TestMcp::start_with_events( + Fixture::default(), + Some(Arc::new( + |backend: Arc| { + Arc::new(common::VanishingRepository::new(backend, 2)) as Arc + }, + )), + ) + .await; + let seeded = [event(1, 1, 1_699_999_900), event(2, 1, 1_699_999_901)]; + fixture.seed(&seeded).await; + let client = fixture.client().await; + + // Both selected slots are the page, and the second one vanished: one row survives, and + // another row may still match. + let result = client + .call(TOOL_LIST_EVENTS, json!({ "kinds": [1], "limit": 2 })) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let full = payload(&result); + let events = full["events"].as_array().unwrap(); + assert_eq!(events.len(), 1, "the vanished slot carries no row: {full}"); + assert_eq!( + full["truncated"], true, + "two slots were spent, so the page is complete and more may match: {full}" + ); + + // The control: the same page under a bound it does not reach is not truncated, so the + // marker answers the page's size rather than being always true. + let result = client + .call(TOOL_LIST_EVENTS, json!({ "kinds": [1], "limit": 3 })) + .await; + let control = payload(&result); + assert_eq!(control["truncated"], false, "{control}"); +} diff --git a/crates/nostream-storage/src/repositories.rs b/crates/nostream-storage/src/repositories.rs index f37d49164..aed9e78e2 100644 --- a/crates/nostream-storage/src/repositories.rs +++ b/crates/nostream-storage/src/repositories.rs @@ -109,19 +109,41 @@ pub enum StreamedEvent { /// /// This is the helper for every call site that does not account for vanished slots: the marker /// is a fact about the page, not a row, so a consumer that only wants rows cannot inherit it. +/// A call site that decides anything from the page's size — "is there another page", "was the +/// `limit` honoured" — uses [`collect_page`] instead, because the rows alone undercount a page +/// that lost a slot. pub fn collect_records<'a>( - mut stream: QueryStream<'a, StreamedEvent>, + stream: QueryStream<'a, StreamedEvent>, ) -> StorageFuture<'a, Vec> { + Box::pin(async move { Ok(collect_page(stream).await?.0) }) +} + +/// Drains a filter read into the rows it yielded and the number of slots the page spent. +/// +/// The two differ exactly when the backend selected a key it could not read: +/// [`StreamedEvent::Vanished`] spends its slot and yields no row, so a page that lost a row to a +/// concurrent replacement or a retention pass reads as `slots == limit` with `rows == limit - 1`. +/// The marker is dropped from the rows because a payload has no row to carry, and the slot is +/// kept in the count because that is the unit +/// [`EventRepository::find_by_filters`] states the page obligation in. +pub fn collect_page<'a>( + mut stream: QueryStream<'a, StreamedEvent>, +) -> StorageFuture<'a, (Vec, usize)> { Box::pin(async move { let mut records = Vec::new(); + let mut slots = 0usize; while let Some(item) = std::future::poll_fn(|context| stream.as_mut().poll_next(context)).await { - if let StreamedEvent::Record(record) = item? { - records.push(record); + match item? { + StreamedEvent::Record(record) => { + slots = slots.saturating_add(1); + records.push(record); + } + StreamedEvent::Vanished => slots = slots.saturating_add(1), } } - Ok(records) + Ok((records, slots)) }) } @@ -899,4 +921,22 @@ mod tests { assert_eq!(contents, vec!["one", "two"]); } + + /// The page's size is its slots, not its rows: one vanished slot reads as two rows out of + /// three spent, and a caller that counted rows would call that page short. + #[tokio::test] + async fn collect_page_counts_the_slots_the_marker_spent() { + let items = vec![ + Ok(StreamedEvent::Record(record("one"))), + Ok(StreamedEvent::Vanished), + Ok(StreamedEvent::Record(record("two"))), + Ok(StreamedEvent::Vanished), + ]; + let stream: QueryStream<'_, StreamedEvent> = Box::pin(Items(items.into_iter())); + + let (rows, slots) = collect_page(stream).await.expect("the read drains"); + + assert_eq!(rows.len(), 2, "two rows survived"); + assert_eq!(slots, 4, "four slots were spent, two of them on markers"); + } } From 30fc4e7189fca1319756d75a8997d7b02e80071c Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 07:13:39 -0500 Subject: [PATCH 09/24] feat(admin): give the stdio door its own scoped credential --- crates/nostream-mcp/src/credential.rs | 187 +++++++++++++++ crates/nostream-mcp/src/error.rs | 5 + crates/nostream-mcp/src/lib.rs | 17 +- crates/nostream-mcp/src/server.rs | 128 ++++++---- crates/nostream-mcp/tests/audit.rs | 20 +- crates/nostream-mcp/tests/auth.rs | 238 ++++++++++++++---- crates/nostream-mcp/tests/common/mod.rs | 114 ++++++--- crates/nostream-mcp/tests/tools_list.rs | 9 +- crates/nostreamd/src/lib.rs | 8 +- crates/nostreamd/src/main.rs | 44 +++- crates/nostreamd/src/mcp_stdio.rs | 58 ++++- crates/nostreamd/tests/mcp_stdio.rs | 305 +++++++++++++++++++----- 12 files changed, 916 insertions(+), 217 deletions(-) create mode 100644 crates/nostream-mcp/src/credential.rs diff --git a/crates/nostream-mcp/src/credential.rs b/crates/nostream-mcp/src/credential.rs new file mode 100644 index 000000000..9fb125afe --- /dev/null +++ b/crates/nostream-mcp/src/credential.rs @@ -0,0 +1,187 @@ +//! The stdio door's own credential: a scoped token document, delivered by file or descriptor. +//! +//! It is neither the console's session token nor an environment variable (R26–R29). A session +//! token belongs to the HTTP gate, whose one shared key and clock-based expiry leave the operator +//! no way to revoke this door on its own; an environment variable is readable at +//! `/proc//environ` and inherited by every child process. The document below is a file the +//! operator owns, or a descriptor a parent handed over, and either way it can be taken away +//! without touching anything else. +//! +//! The two forms differ in exactly the property that matters: the **file** is re-read on the path +//! that decides a call, so deleting or rewriting it *is* the revocation, while the **descriptor** +//! is read once at start, so its lifetime is the process's. Nothing here is cached for the file +//! form, deliberately — one small file per call is the price of a revocation that needs no +//! server-side store. + +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; + +use serde::Deserialize; + +use crate::error::McpError; + +/// The one scope beyond reading: the right to call `settings_set` (R28). +pub const SCOPE_WRITE: &str = "write"; + +/// The scopes a token document may name, as a refusal states them. +pub const ACCEPTED_SCOPES: &[&str] = &[SCOPE_WRITE]; + +/// The mode a token file must carry: owner read and write, and nothing for anyone else (R27). +pub const TOKEN_FILE_MODE: u32 = 0o600; + +/// The bits a token file must not carry: any group or other permission, write included — a file +/// another user could rewrite is not one this door may trust. +const GROUP_OR_OTHER: u32 = 0o077; + +/// The scopes a token document grants. +/// +/// Reading is not a scope: every accepted document reads (R28). `write` is the one name a +/// document may add, and it is what makes `settings_set` callable. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Scopes { + write: bool, +} + +impl Scopes { + /// The grant a document with no `scopes` carries: the three read tools. + pub fn read_only() -> Self { + Self::default() + } + + /// The grant a document naming [`SCOPE_WRITE`] carries. + pub fn writing() -> Self { + Self { write: true } + } + + /// Whether this grant covers `scope`. + pub fn includes(&self, scope: &str) -> bool { + scope == SCOPE_WRITE && self.write + } +} + +/// The token document's shape: `{"scopes": ["write"]}`, with `scopes` optional (R27). +/// +/// The set is closed. A document carrying any other key — a half-migrated one still holding a +/// session token under `token`, say — is refused rather than read for less than it says. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct TokenDocument { + #[serde(default)] + scopes: Vec, +} + +impl TokenDocument { + fn parse(text: &str, location: &str) -> Result { + serde_json::from_str(text).map_err(|error| { + McpError::Credential(format!( + "the admin token document {location} is not JSON of the shape \ + {{\"scopes\": [\"{SCOPE_WRITE}\"]}}: {error}" + )) + }) + } + + /// The grant, or the refusal that stops the mode starting (R27). + /// + /// An unknown scope is never silently dropped: a document that says `admin` and is read as + /// "no scopes" would answer `Forbidden` to calls the operator believed it allowed, with the + /// typo nowhere in sight. + fn scopes(&self) -> Result { + let mut scopes = Scopes::read_only(); + for name in &self.scopes { + if name == SCOPE_WRITE { + scopes = Scopes::writing(); + } else { + return Err(McpError::Credential(format!( + "the admin token document names an unknown scope {name:?}: the accepted set \ + is {ACCEPTED_SCOPES:?}, and reading is granted to every token" + ))); + } + } + Ok(scopes) + } +} + +/// Where the credential is read from: the file, or the document a descriptor carried (R29). +#[derive(Debug, Clone, PartialEq, Eq)] +enum Source { + /// A file, re-read on every call: rewriting or deleting it is the revocation. + File(PathBuf), + /// The document a descriptor carried, read once at start: the process's lifetime is its own. + Delivered(Scopes), +} + +/// The stdio door's credential: the token document and where it is read from (R27). +#[derive(Debug, Clone)] +pub struct Credential { + source: Source, +} + +impl Credential { + /// A document delivered by file. + /// + /// Reads it once here so the mode refuses to start on a file it could not accept (R27); every + /// call then reads it again, because the file's lifetime is the credential's (R29). + pub fn from_file(path: impl Into) -> Result { + let path = path.into(); + read_file(&path)?; + Ok(Self { + source: Source::File(path), + }) + } + + /// The same document on a descriptor the parent passed (`--admin-token-fd`), read once. + /// + /// `/proc/self/fd/` is the readable path to a descriptor this process inherited and needs + /// no `unsafe`: the workspace denies `unsafe_code` and its one carve-out is the storage + /// crate's (`CLAUDE.md`). It reads a regular file and a pipe alike, from the descriptor's own + /// offset. + pub fn from_descriptor(fd: i32) -> Result { + let path = PathBuf::from(format!("/proc/self/fd/{fd}")); + let text = std::fs::read_to_string(&path).map_err(|error| { + McpError::Credential(format!( + "--admin-token-fd {fd} could not be read: {error} — pass the token document on an \ + open descriptor, conventionally 3" + )) + })?; + let document = TokenDocument::parse(&text, &format!("on descriptor {fd}"))?; + Ok(Self { + source: Source::Delivered(document.scopes()?), + }) + } + + /// The grant the current document carries — the decision point of every call. + /// + /// The file form reads the file now, so a rewrite or a deletion has taken effect by the time + /// this returns (R29). + pub fn grant(&self) -> Result { + match &self.source { + Source::File(path) => read_file(path), + Source::Delivered(scopes) => Ok(*scopes), + } + } +} + +/// One token file, checked and read: the mode's file rule, in one place (R27). +fn read_file(path: &Path) -> Result { + let metadata = std::fs::metadata(path).map_err(|error| { + McpError::Credential(format!( + "the admin token file {} could not be read: {error}", + path.display() + )) + })?; + let mode = metadata.permissions().mode() & 0o777; + if mode & GROUP_OR_OTHER != 0 { + return Err(McpError::Credential(format!( + "the admin token file {} is mode {mode:04o}: it must be {TOKEN_FILE_MODE:04o}, \ + readable and writable by its owner alone", + path.display() + ))); + } + let text = std::fs::read_to_string(path).map_err(|error| { + McpError::Credential(format!( + "the admin token file {} could not be read: {error}", + path.display() + )) + })?; + TokenDocument::parse(&text, &path.display().to_string())?.scopes() +} diff --git a/crates/nostream-mcp/src/error.rs b/crates/nostream-mcp/src/error.rs index 1cb83e2b3..07ed99e58 100644 --- a/crates/nostream-mcp/src/error.rs +++ b/crates/nostream-mcp/src/error.rs @@ -31,6 +31,11 @@ pub enum McpError { #[error("{0}")] Criterion(String), + /// The credential document this door was started with could not be read, or names something + /// it does not accept (R27). A start-up failure, not a tool's. + #[error("{0}")] + Credential(String), + /// A payload the tool built could not be serialised. #[error("the payload could not be serialised: {0}")] Serialise(#[from] serde_json::Error), diff --git a/crates/nostream-mcp/src/lib.rs b/crates/nostream-mcp/src/lib.rs index bcf77781b..23034de6e 100644 --- a/crates/nostream-mcp/src/lib.rs +++ b/crates/nostream-mcp/src/lib.rs @@ -1,10 +1,10 @@ //! `nostream-mcp` owns the admin MCP server: the tool router, the four slice-1 tools, the -//! credential gate and the audit sink. +//! credential and its scopes, and the audit sink. //! //! It owns no transport and no socket. `nostreamd --mcp-stdio` serves this server on //! stdin/stdout through `rmcp`'s `transport-io`, in a process of its own: the mode composes its //! own [`AdminState`](nostream_admin::AdminState) over the same config directory, so the tools -//! read the same session credential and the same `/admin-audit.jsonl` the console does, +//! read the same settings and append to the same `/admin-audit.jsonl` the console does, //! over a repository bundle of the mode's own (D7, D18) — the daemon's bundle is composed in //! `crates/nostreamd/src/main.rs`, this mode's in its `mcp_stdio` module, and the two are //! independent `Arc`s that the store-wiring change has to move together. The two modes are @@ -12,23 +12,30 @@ //! against one config directory is outside D9: the audit file and the settings write each assume //! one writer per configuration. //! +//! **The credential is this door's own** ([`Credential`]): a scoped token document delivered by +//! file or descriptor (D19), never the console's session token and never an environment variable. +//! The file form is re-read on every call, so rewriting or deleting it is the revocation; the +//! descriptor form is read once at start and lives as long as the process. +//! //! **Deliberately not owned here** — a reader should be able to tell an omission from a gap: //! //! - the runtime, the signals, the socket and the stdio mode — `nostreamd`; -//! - the admin state, the session token, the audit file and the settings write path — +//! - the admin state, the console's session token, the audit file and the settings write path — //! `nostream-admin` (used here, not re-implemented); //! - the settings merge, validation, redaction and the guided catalogue — `nostream-config`; //! - the event store and the repositories — `nostream-storage`; //! - every tool family outside slice 1: `relay_status`, `delete_event`, `user_admin`, //! `invoices_*`, `reports_*` and `maintenance_*` are later slices of #1183. +mod credential; mod error; mod server; +pub use credential::{ACCEPTED_SCOPES, Credential, SCOPE_WRITE, Scopes, TOKEN_FILE_MODE}; pub use error::McpError; pub use server::{ - AdminMcp, GetEventArgs, INTERNAL_SERVER_ERROR, ListEventsArgs, MAX_FILTER_TERMS, + AUDIT_DENIED, AdminMcp, FORBIDDEN, GetEventArgs, ListEventsArgs, MAX_FILTER_TERMS, MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, SettingsSetArgs, TOOL_ARGUMENTS, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, - UNAUTHORIZED, arguments_parse, audit_action, + UNAUTHORIZED, arguments_parse, audit_action, required_scope, }; diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index d8f1f5283..aab8683ff 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -2,8 +2,9 @@ //! //! Every tool is a thin handler over a seam that already exists — `AdminState` for the settings, //! `EventRepository` for the events — and nothing here knows what an HTTP status is (R3). The -//! gate and the audit line live in [`ServerHandler::call_tool`], at dispatch: a call the gate -//! refuses reaches no tool and writes nothing (R8), and a call that reaches a tool has its +//! gate and the audit line live in [`ServerHandler::call_tool`], at dispatch: a call the +//! credential refuses reaches no tool and writes nothing (R8), a call its scopes deny writes the +//! one `mcp.denied` line that records the denial (R28), and a call that reaches a tool has its //! `mcp.` line written before the tool's own work, so the file's order is the dispatch //! order (R9). @@ -13,7 +14,6 @@ use std::sync::Arc; use nostream_admin::AdminState; use nostream_admin::controllers::admin_json_body_middleware::settings_patch; use nostream_admin::controllers::patch_settings::{self, SettingsWrite}; -use nostream_admin::utils::session; use nostream_core::{Filter, Kind}; use nostream_storage::repositories::{EventRecord, collect_page, collect_records}; use rmcp::handler::server::router::tool::ToolRouter; @@ -29,6 +29,7 @@ use rmcp::{RoleServer, ServerHandler, tool, tool_handler, tool_router}; use serde::Deserialize; use serde_json::{Map, Value, json}; +use crate::credential::{Credential, SCOPE_WRITE, Scopes}; use crate::error::McpError; /// The server name `initialize` reports: the server, not the SDK, which would name `rmcp` (R6). @@ -36,17 +37,19 @@ pub const MCP_SERVER_NAME: &str = "nostream"; /// What `initialize`'s `instructions` carries: the route to a working call. /// -/// The three refusals the gate answers name a symptom, not its cause, and nothing else on the -/// surface says what a caller needs — a client that reads `Not Found` for a tool it was just -/// told exists has nowhere to look. This is that place, and it is additive: the refusal texts -/// stay exactly as the console's layers word them. +/// The refusals the gate answers name a symptom, not its cause, and nothing else on the surface +/// says what a caller needs — a client that reads `Not Found` for a tool it was just told exists +/// has nowhere to look. This is that place, and it is additive: the refusal texts stay exactly as +/// the console's layers word them. pub const MCP_INSTRUCTIONS: &str = "\ -The nostream admin MCP server. It uses the admin console's own credential: a session token \ -minted by `POST /admin/login` and passed in `NOSTREAM_ADMIN_TOKEN`. Three things must hold, or \ -every call is refused with the reason: `admin.enabled` is true in the settings (else `Not \ -Found`), `SECRET` is set (else `Internal Server Error`), and `NOSTREAM_ADMIN_TOKEN` carries an \ -unexpired token (else `Unauthorized`). Each executed call appends one `mcp.` line to \ -`/admin-audit.jsonl`."; +The nostream admin MCP server. Every call is decided by the scoped token document the mode was \ +started with — `--admin-token-file ` or `--admin-token-fd `, exactly one, its shape \ +{\"scopes\": [\"write\"]}: the document's presence authorises `settings_get`, `list_events` and \ +`get_event`, and the \"write\" scope authorises `settings_set` (else the call is `Forbidden`). \ +`admin.enabled` must be true in the settings, or every call answers `Not Found`; a document \ +that cannot be read answers `Unauthorized`. Each executed call appends one `mcp.` line to \ +`/admin-audit.jsonl`, and a call the document's scopes deny appends one `mcp.denied` \ +line."; /// The tool names slice 1 registers (R5). Each is also its audit action's suffix (R9). pub const TOOL_SETTINGS_GET: &str = "settings_get"; @@ -70,20 +73,36 @@ pub const MAX_FILTER_TERMS: usize = 64; /// read materialises, which is the number a backend opens with. pub const MAX_ROWS_PER_PAGE: u64 = nostream_storage::DEFAULT_PAGE_ROWS; -/// The refusal for a token that is absent, malformed or expired — the HTTP gate's `401`. +/// The refusal for a credential whose document is absent, unreadable or no longer a document this +/// door accepts — the HTTP gate's `401`. pub const UNAUTHORIZED: &str = "Unauthorized"; -/// The refusal for a surface whose `SECRET` is absent — the HTTP gate's `500`. -pub const INTERNAL_SERVER_ERROR: &str = "Internal Server Error"; +/// The refusal for a call the credential's scopes do not cover — the HTTP gate's `403`. It is the +/// one refusal that describes a call the door authenticated (R28), so it is the one that is +/// written down. +pub const FORBIDDEN: &str = "Forbidden"; /// The refusal for a surface `admin.enabled` does not turn on — the console's `404`. pub const NOT_FOUND: &str = "Not Found"; +/// The audit action a call its credential's scopes denied records (R28). +pub const AUDIT_DENIED: &str = "mcp.denied"; + /// The audit action one dispatched call records: `mcp.` (R9). pub fn audit_action(tool: &str) -> String { format!("mcp.{tool}") } +/// The scope a tool needs beyond the read grant every token carries (R28). +/// +/// The three read tools name nothing because reading is the document's default; the one tool that +/// changes the relay is the one a document has to opt into. A tool added to the router without an +/// entry here is a read tool, which is the safe direction: the failure it would produce is a +/// `Forbidden` a case can see, not an unnoticed write. +pub fn required_scope(tool: &str) -> Option<&'static str> { + (tool == TOOL_SETTINGS_SET).then_some(SCOPE_WRITE) +} + /// Whether the router can deserialise a call's arguments: the same type its handler takes. type ArgumentsCheck = fn(Option<&Map>) -> bool; @@ -240,13 +259,14 @@ impl JsonSchema for SettingsSetArgs { } } -/// The server: the shared admin state, the resolved token and the composition's identity. +/// The server: the shared admin state, the credential and the composition's identity. #[derive(Debug, Clone)] pub struct AdminMcp { state: Arc, - /// `NOSTREAM_ADMIN_TOKEN` as a value, read once by the composition root (R7). Never the - /// environment: a gate that read it per call could not be tested without racing. - token: Option, + /// The door's own credential, built by the composition root from its two flags (R27). Never + /// the environment and never the console's session token: a gate that read either could not + /// be revoked per door, and could not be tested without racing. + credential: Credential, implementation: Implementation, tool_router: ToolRouter, } @@ -257,12 +277,12 @@ impl AdminMcp { /// the daemon's version and not this crate's (R6). pub fn new( state: Arc, - token: Option, + credential: Credential, implementation: Implementation, ) -> Self { Self { state, - token, + credential, implementation, tool_router: Self::tool_router(), } @@ -379,22 +399,29 @@ impl AdminMcp { .find(|record| record.event.id.to_string() == id)) } - /// The gate's refusal, if the call cannot run (R7): the console's enabled predicate first, - /// then its `SECRET`, then its session token — the three checks its own layers make, in the - /// order its router makes them. - fn refusal(&self) -> Option<&'static str> { + /// The grant the call runs under, or the refusal that stops it (R27–R29): the console's + /// enabled predicate first, then the document — which the file form reads right here, so a + /// rewrite or a deletion is in force by the time this answers. + /// + /// The document's own failure is the operator's to read, not the caller's: `Unauthorized` is + /// what a pipe sees, and the reason goes to the log where the file's path is meaningful. + fn grant(&self) -> Result { if !self.surface_enabled() { - return Some(NOT_FOUND); + return Err(NOT_FOUND); } - let Some(secret) = self.state.secret() else { - return Some(INTERNAL_SERVER_ERROR); - }; - let key = session::session_key(secret); - match &self.token { - Some(token) if session::is_valid_token(&key, token, self.state.clock().now_secs()) => { - None - } - _ => Some(UNAUTHORIZED), + self.credential.grant().map_err(|error| { + tracing::warn!(%error, "the MCP credential was refused"); + UNAUTHORIZED + }) + } + + /// R28's line: an authenticated call the document's scopes deny. It carries the tool and the + /// scope it needed, never an argument value, and it is written before the refusal is + /// returned, so a denied write is visible in `admin-audit.jsonl` rather than absent from it. + fn record_denial(&self, tool: &str, scope: &str) { + let detail = json!({ "tool": tool, "scope": scope }); + if let Err(error) = self.state.append_audit(AUDIT_DENIED, None, Some(detail)) { + tracing::warn!(%error, tool, "the MCP denial was not recorded"); } } @@ -482,15 +509,30 @@ impl ServerHandler for AdminMcp { /// The gate and the audit sink, in front of the router's dispatch. /// /// `tools/list` is not gated (R8): a client discovers the surface before it presents a - /// credential, and the refusal is at the call. + /// credential, and the refusal is at the call. The order is the console's — the enabled + /// predicate, then the credential — with the scopes after them, because a scope is only + /// meaningful once the document that names it has been read (R28). async fn call_tool( &self, request: CallToolRequestParams, context: RequestContext, ) -> Result { - if let Some(refusal) = self.refusal() { - tracing::warn!(tool = %request.name, refusal, "the MCP call was refused"); - return Ok(CallToolResult::error(vec![ContentBlock::text(refusal)]).into()); + let scopes = match self.grant() { + Ok(scopes) => scopes, + Err(refusal) => { + tracing::warn!(tool = %request.name, refusal, "the MCP call was refused"); + return Ok(tool_refusal(refusal).into()); + } + }; + if let Some(scope) = required_scope(&request.name) + && !scopes.includes(scope) + { + self.record_denial(&request.name, scope); + return Ok(tool_refusal(&format!( + "{FORBIDDEN}: {} needs the \"{scope}\" scope", + request.name + )) + .into()); } // `Some(false)` — the router answers the deserialisation failure — and `None` — no such // tool, and the router answers `-32602` — both reach no tool, so neither writes a line @@ -525,6 +567,12 @@ fn tool_error(error: &McpError) -> CallToolResult { CallToolResult::error(vec![ContentBlock::text(error.to_string())]) } +/// A gate refusal as an `isError: true` result: the credential is the caller's to fix, and a +/// JSON-RPC error would read as the server's fault (R28). +fn tool_refusal(text: &str) -> CallToolResult { + CallToolResult::error(vec![ContentBlock::text(text)]) +} + /// A refusal body as an `isError: true` result — the controller's own JSON, rendered (R13). fn tool_error_body(body: &Value) -> CallToolResult { CallToolResult::error(vec![ContentBlock::text(body.to_string())]) diff --git a/crates/nostream-mcp/tests/audit.rs b/crates/nostream-mcp/tests/audit.rs index 921317b55..ccf53fee6 100644 --- a/crates/nostream-mcp/tests/audit.rs +++ b/crates/nostream-mcp/tests/audit.rs @@ -1,14 +1,16 @@ -//! AC22 — one audit line per executed call, and none for a refused one. +//! AC22 — one audit line per executed call, and none for a call no tool reached. //! //! | case | what it proves | //! |---|---| //! | `each_call_appends_one_line` | four calls append five lines in call order — the four `mcp.*` lines, then `settings_set`'s own `settings.updated` | -//! | `a_refused_call_appends_nothing` | a call with bad arguments and a call with no token each leave the file untouched | +//! | `a_refused_call_appends_nothing` | a call with bad arguments and a call with no credential each leave the file untouched | //! | `every_registered_tool_is_in_the_audit_table` | the audit table is total: no tool the router registers can execute unaudited | //! | `the_audit_check_is_no_stricter_than_the_router` | the table's rule is the router's deserialiser, not the schema: a stricter check would fail open | //! //! R9 appends the `mcp.*` line at dispatch, before the handler's work, so the order in the file -//! is the order of the calls and a domain line always follows its own dispatch line. +//! is the order of the calls and a domain line always follows its own dispatch line. The one +//! refusal that does write is a credential's scope denial — `mcp.denied`, R28 — and it has its +//! own case beside the credential, in `tests/auth.rs`. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -16,7 +18,7 @@ mod common; use std::collections::BTreeSet; -use common::{Fixture, TestMcp, Token, event, id_of, object, text}; +use common::{TestMcp, event, id_of, object, text}; use nostream_mcp::{ TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, audit_action, }; @@ -100,12 +102,10 @@ async fn a_refused_call_appends_nothing() { "an argument the schema refuses is refused before dispatch" ); - // A second server, built with no token, over its own config dir. - let untokened = TestMcp::start_with(Fixture { - token: Token::Absent, - ..Fixture::default() - }) - .await; + // A second server whose token file is deleted before the call: the credential is gone, so + // there is nothing to attribute a line to (R28). + let untokened = TestMcp::start().await; + untokened.revoke(); let unauthenticated = untokened.client().await; let refused = unauthenticated.call(TOOL_SETTINGS_GET, json!({})).await; assert_eq!(refused.is_error, Some(true)); diff --git a/crates/nostream-mcp/tests/auth.rs b/crates/nostream-mcp/tests/auth.rs index ca8bed9b8..fa08a8dbb 100644 --- a/crates/nostream-mcp/tests/auth.rs +++ b/crates/nostream-mcp/tests/auth.rs @@ -1,75 +1,116 @@ -//! AC21 — unauthenticated calls are refused, four ways, without touching the environment. +//! AC29–AC34 — the door's own credential: a scoped token document, by file or descriptor. //! //! | case | what it proves | //! |---|---| -//! | `no_token_refuses_every_tool` | a server built with no token refuses all four tools with `Unauthorized`, and still lists them | -//! | `an_expired_token_is_refused` | a token that expired one second ago is `Unauthorized` | +//! | `a_revoked_token_refuses_every_tool` | a deleted document answers `Unauthorized` to all four tools, writes nothing, and still lists them | +//! | `a_read_only_token_is_refused_the_write` | a document with no scope reads and is refused `settings_set`, and the denial is a line in `admin-audit.jsonl` | //! | `a_disabled_surface_is_refused` | `admin.enabled: false` answers `Not Found`, as the console does | -//! | `a_missing_secret_is_refused` | no `SECRET` answers `Internal Server Error` | +//! | `an_unknown_scope_refuses_the_load` | a document naming a scope the door does not know is refused when it is loaded, naming the scope and the accepted set | +//! | `a_file_rewrite_changes_the_decision` | rewriting the file on a running server narrows the write, and rewriting it back restores it: the file's lifetime is the credential's | +//! | `an_inherited_descriptor_authenticates` | the descriptor form answers `tools/list` and a read, and keeps the grant it was handed when the file it came from changes | +//! | `only_the_writing_tool_needs_a_scope` | the read tools need no scope, and `settings_set` is the one that does | //! -//! Each case builds its own server with the token as a **value**, and none sets an environment -//! variable: four cases in one binary run in parallel, so an environment-based gate would race. -//! The three texts are distinct on purpose — a gate that collapsed them could pass a case -//! written against the wrong arm. +//! Each case builds its own server with the credential as a **value**, and none sets an +//! environment variable: cases in one binary run in parallel, so an environment-based credential +//! would race. The two refusal texts are distinct on purpose — a gate that collapsed `Not Found` +//! and `Unauthorized` could pass a case written against the wrong arm. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod common; -use common::{Fixture, TestMcp, Token, text}; -use nostream_mcp::{INTERNAL_SERVER_ERROR, NOT_FOUND, TOOL_GET_EVENT, UNAUTHORIZED}; +use std::os::fd::AsRawFd; + +use common::{Fixture, Grant, TestMcp, text, write_token}; +use nostream_mcp::{ + AUDIT_DENIED, Credential, FORBIDDEN, NOT_FOUND, TOOL_GET_EVENT, TOOL_LIST_EVENTS, + TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, UNAUTHORIZED, audit_action, required_scope, +}; use serde_json::json; /// The four tools, each with arguments its schema accepts, so the refusal cannot be a /// deserialisation failure in disguise. fn calls() -> [(&'static str, serde_json::Value); 4] { [ - (nostream_mcp::TOOL_SETTINGS_GET, json!({})), + (TOOL_SETTINGS_GET, json!({})), ( - nostream_mcp::TOOL_SETTINGS_SET, - json!({ "path": "wot.enabled", "value": true }), + TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": false }), ), - (nostream_mcp::TOOL_LIST_EVENTS, json!({ "kinds": [1] })), - (TOOL_GET_EVENT, json!({ "id": "00".repeat(32) })), + (TOOL_LIST_EVENTS, json!({})), + (TOOL_GET_EVENT, json!({ "id": "0123456789abcdef" })), ] } #[tokio::test] -async fn no_token_refuses_every_tool() { - let fixture = TestMcp::start_with(Fixture { - token: Token::Absent, - ..Fixture::default() - }) - .await; +async fn a_revoked_token_refuses_every_tool() { + let fixture = TestMcp::start().await; + // Deleting the file is the revocation (R29): no store, no restart, no session to expire. + fixture.revoke(); let client = fixture.client().await; assert_eq!(client.tools().await.len(), 4, "tools/list is not gated"); for (tool, arguments) in calls() { let result = client.call(tool, arguments).await; - assert_eq!(result.is_error, Some(true), "{tool}"); + assert_eq!(result.is_error, Some(true), "{tool}: {}", text(&result)); assert_eq!(text(&result), UNAUTHORIZED, "{tool}"); } assert!( fixture.audit_entries().is_empty(), - "a refusal writes nothing" + "a call with no credential has nothing to attribute a line to" ); } #[tokio::test] -async fn an_expired_token_is_refused() { +async fn a_read_only_token_is_refused_the_write() { let fixture = TestMcp::start_with(Fixture { - token: Token::Expired, + grant: Grant::Read, ..Fixture::default() }) .await; let client = fixture.client().await; - let result = client - .call(nostream_mcp::TOOL_SETTINGS_GET, json!({})) + let read = client.call(TOOL_SETTINGS_GET, json!({})).await; + assert_eq!(read.is_error, Some(false), "{}", text(&read)); + + let denied = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": false }), + ) .await; - assert_eq!(result.is_error, Some(true)); - assert_eq!(text(&result), UNAUTHORIZED); - assert!(fixture.audit_entries().is_empty()); + assert_eq!(denied.is_error, Some(true), "{}", text(&denied)); + let refusal = text(&denied); + assert!(refusal.contains(FORBIDDEN), "{refusal}"); + assert!(refusal.contains(TOOL_SETTINGS_SET), "{refusal}"); + assert!(refusal.contains("write"), "{refusal}"); + + // The refusal is an authenticated call that was denied, so it is written down (R28) — after + // the read's own dispatch line, in call order. + let entries = fixture.audit_entries(); + let actions: Vec<&str> = entries + .iter() + .map(|entry| entry["action"].as_str().unwrap_or_default()) + .collect(); + assert_eq!( + actions, + vec![audit_action(TOOL_SETTINGS_GET).as_str(), AUDIT_DENIED], + "{entries:?}" + ); + assert_eq!(entries[1]["detail"]["tool"], TOOL_SETTINGS_SET); + assert_eq!(entries[1]["detail"]["scope"], "write"); + assert!( + entries[1].get("remoteAddress").is_none(), + "a stdio caller has no address" + ); + + // Nothing of the write ran: no file change, no audit line of its own, no backup. + assert!( + fixture.settings_file()["wot"]["enabled"].is_null(), + "the refused write left the file alone" + ); + assert!(fixture.settings_audit_entries().is_empty()); + assert!(fixture.backups().is_empty(), "no backup"); } #[tokio::test] @@ -77,27 +118,136 @@ async fn a_disabled_surface_is_refused() { let fixture = TestMcp::start_with(Fixture::default().with("admin.enabled", json!(false))).await; let client = fixture.client().await; - let result = client - .call(nostream_mcp::TOOL_SETTINGS_GET, json!({})) - .await; + let result = client.call(TOOL_SETTINGS_GET, json!({})).await; assert_eq!(result.is_error, Some(true)); assert_eq!(text(&result), NOT_FOUND); assert!(fixture.audit_entries().is_empty()); } #[tokio::test] -async fn a_missing_secret_is_refused() { - let fixture = TestMcp::start_with(Fixture { - secret: None, - ..Fixture::default() - }) - .await; +async fn an_unknown_scope_refuses_the_load() { + let temp = tempfile::tempdir().unwrap(); + let document = write_token(temp.path(), &["admin"]); + + let refused = Credential::from_file(&document).expect_err("an unknown scope is not a grant"); + let message = refused.to_string(); + assert!(message.contains("\"admin\""), "{message}"); + assert!(message.contains("write"), "the accepted set: {message}"); + + // A document still carrying the retired session token is refused for its shape, not read for + // less than it says: the load names the key it did not expect. + let half_migrated = temp.path().join("half-migrated.json"); + common::write_private(&half_migrated, r#"{"token": "a-session-token"}"#); + let refused = Credential::from_file(&half_migrated).expect_err("the shape is closed"); + assert!(refused.to_string().contains("token"), "{refused}"); + + // The load check is the mode's start-up check: a token file at a mode anyone but the owner + // can read is refused before the door serves anything (R27). + let readable = temp.path().join("readable.json"); + common::write_private(&readable, &common::token_document(&["write"])); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&readable, std::fs::Permissions::from_mode(0o644)).unwrap(); + } + let refused = Credential::from_file(&readable).expect_err("0644 is not 0600"); + assert!(refused.to_string().contains("0644"), "{refused}"); + assert!(refused.to_string().contains("0600"), "{refused}"); +} + +#[tokio::test] +async fn a_file_rewrite_changes_the_decision() { + let fixture = TestMcp::start().await; let client = fixture.client().await; - let result = client - .call(nostream_mcp::TOOL_SETTINGS_GET, json!({})) + let written = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": false }), + ) .await; - assert_eq!(result.is_error, Some(true)); - assert_eq!(text(&result), INTERNAL_SERVER_ERROR); - assert!(fixture.audit_entries().is_empty()); + assert_eq!(written.is_error, Some(false), "{}", text(&written)); + + // The document is narrowed to reads on a running server: nothing else happens. + fixture.write_scopes(&[]); + let denied = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": true }), + ) + .await; + assert_eq!(denied.is_error, Some(true), "{}", text(&denied)); + assert!(text(&denied).contains(FORBIDDEN), "{}", text(&denied)); + let actions: Vec = fixture + .audit_entries() + .iter() + .map(|entry| entry["action"].as_str().unwrap_or_default().to_owned()) + .collect(); + assert_eq!(actions.last().map(String::as_str), Some(AUDIT_DENIED)); + assert!( + fixture.settings_file()["wot"]["enabled"] == serde_yaml::Value::Bool(false), + "the denied write left the file as it was" + ); + + let read = client.call(TOOL_SETTINGS_GET, json!({})).await; + assert_eq!(read.is_error, Some(false), "{}", text(&read)); + + // And back: the next call is decided by the file as it stands now. + fixture.write_scopes(&["write"]); + let restored = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": false }), + ) + .await; + assert_eq!(restored.is_error, Some(false), "{}", text(&restored)); +} + +#[tokio::test] +async fn an_inherited_descriptor_authenticates() { + let fixture = TestMcp::start().await; + let file = fixture.descriptor(); + let credential = Credential::from_descriptor(file.as_raw_fd()).expect("the document loads"); + let client = fixture.client_with_credential(credential).await; + + let names: Vec = client + .tools() + .await + .iter() + .map(|tool| tool.name.to_string()) + .collect(); + assert_eq!(names.len(), 4, "{names:?}"); + + let read = client.call(TOOL_SETTINGS_GET, json!({})).await; + assert_eq!(read.is_error, Some(false), "{}", text(&read)); + + // The descriptor was read once at start, so it holds the grant it carried: the file it came + // from is not consulted again, which is the asymmetry the mode's documentation states (R29). + fixture.write_scopes(&[]); + let written = client + .call( + TOOL_SETTINGS_SET, + json!({ "path": "wot.enabled", "value": false }), + ) + .await; + assert_eq!(written.is_error, Some(false), "{}", text(&written)); +} + +#[tokio::test] +async fn only_the_writing_tool_needs_a_scope() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let scoped: Vec = client + .tools() + .await + .iter() + .filter(|tool| required_scope(&tool.name).is_some()) + .map(|tool| tool.name.to_string()) + .collect(); + assert_eq!( + scoped, + vec![TOOL_SETTINGS_SET.to_owned()], + "reading is the document's default; the one tool that changes the relay is the one it \ + has to opt into" + ); } diff --git a/crates/nostream-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs index f35f65cae..3ffaf92d9 100644 --- a/crates/nostream-mcp/tests/common/mod.rs +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -6,6 +6,10 @@ //! seeding pattern (`crates/nostream-storage/tests/parity_lmdb.rs:84-92`) and the console's real //! `resources/` tree as the schema source. The client is `rmcp`'s over `tokio::io::duplex`, which //! is the only way to call a tool without a transport (`Peer::new` is `pub(crate)` in the SDK). +//! +//! The credential is a token file the fixture writes at mode 0600 (R27), handed to the server as +//! a [`Credential`]: a case narrows or revokes it by rewriting or deleting that file, because the +//! file's lifetime is the credential's (R29). #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, dead_code)] @@ -14,14 +18,13 @@ use std::sync::Arc; use futures_util::StreamExt; use nostream_admin::state::AdminStateConfig; -use nostream_admin::utils::session; use nostream_admin::{AdminState, GrafanaSettings}; use nostream_config::SettingsPaths; use nostream_core::clock::TestClock; use nostream_core::nip05::Nip05Fetch; use nostream_core::random::SystemRandom; use nostream_core::{Event, EventId, Filter, Kind, Pubkey, Signature}; -use nostream_mcp::{AdminMcp, MCP_SERVER_NAME}; +use nostream_mcp::{AdminMcp, Credential, MCP_SERVER_NAME, SCOPE_WRITE}; use nostream_services::{HttpClient, ReqwestClient, ServiceStores}; use nostream_storage::error::StorageError; use nostream_storage::lmdb::LmdbBackend; @@ -50,7 +53,7 @@ pub fn resources_root() -> PathBuf { /// The fixture password hash `hashAdminPassword` writes for `hunter2`. pub const PASSWORD_HASH: &str = "scrypt:BwcHBwcHBwcHBwcHBwcHBw==:r5daXU05UJ9EUDu45YoHMWUoQCmkVbwINYNntY1/dwrJPOt3fTi/1IWw1wp9+YXRj1Vm6IpFi+gSU0JdqZvWIw=="; -/// The literal `SECRET` the fixture signs sessions with. +/// The literal `SECRET` the fixture composes `AdminState` with. pub const SECRET: &[u8] = b"a-test-secret"; /// The clock the fixture starts at. @@ -64,15 +67,23 @@ pub fn base_settings() -> serde_yaml::Value { .unwrap() } -/// The token a case presents. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Token { - /// A valid session token minted from the fixture's `SECRET`. - Valid, - /// No token at all. - Absent, - /// A token that expired one second before the fixture's clock. - Expired, +/// The scopes the fixture's token document names. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Grant { + /// `{"scopes": ["write"]}`: the three read tools and `settings_set`. + #[default] + Write, + /// `{"scopes": []}`: the read tools only — the door's default (R28). + Read, +} + +impl Grant { + fn names(self) -> &'static [&'static str] { + match self { + Self::Write => &[SCOPE_WRITE], + Self::Read => &[], + } + } } /// Which store bundle the composed state reads. @@ -90,10 +101,10 @@ pub enum Stores { pub struct Fixture { /// The user settings document written to `/settings.yaml`. pub settings: serde_yaml::Value, - /// `SECRET` as a value; `None` is the missing-secret case. + /// `SECRET` as a value, for the `AdminState` the tools read through. pub secret: Option>, - /// The token the server is built with. - pub token: Token, + /// The scopes the token document the server reads carries (R28). + pub grant: Grant, /// The starting clock reading. pub now_ms: u64, /// The store bundle the state is composed over. @@ -105,7 +116,7 @@ impl Default for Fixture { Self { settings: base_settings(), secret: Some(SECRET.to_vec()), - token: Token::Valid, + grant: Grant::Write, now_ms: NOW_MS, stores: Stores::Seeded, } @@ -131,7 +142,9 @@ pub struct TestMcp { pub clock: Arc, pub config_dir: PathBuf, pub backend: Arc, - token: Option, + /// The file the credential is read from on every call (R29). + pub token_path: PathBuf, + credential: Credential, _temp: tempfile::TempDir, } @@ -158,13 +171,10 @@ impl TestMcp { std::fs::create_dir_all(&config_dir).unwrap(); write_settings(&config_dir, &fixture.settings); - // `is_valid_token` refuses `expires_at <= now`, so a token minted for the second before - // the clock is a token that has just expired. - let token = match (fixture.token, fixture.secret.as_deref()) { - (Token::Absent, _) | (_, None) => None, - (Token::Valid, Some(secret)) => Some(mint(secret, now_seconds(fixture.now_ms) + 3_600)), - (Token::Expired, Some(secret)) => Some(mint(secret, now_seconds(fixture.now_ms) - 1)), - }; + // The document the door reads on every call (R27, R29): a case narrows it by rewriting + // this file, which is the revocation the file form exists for. + let token_path = write_token(&config_dir, fixture.grant.names()); + let credential = Credential::from_file(&token_path).unwrap(); // The backend is always opened, so a case can seed it; when the fixture asks for the // daemon's bundle the state reads `unavailable::stores()` instead, and the seeded rows @@ -222,21 +232,34 @@ impl TestMcp { clock, config_dir, backend, - token, + token_path, + credential, _temp: temp, } } /// A client over an in-process duplex, served by a server on the fixture's state. pub async fn client(&self) -> Mcp { - self.client_with_version(env!("CARGO_PKG_VERSION")).await + self.client_with_credential(self.credential.clone()).await } /// The same, with the `serverInfo` version the composition would supply (R6). pub async fn client_with_version(&self, version: &str) -> Mcp { + self.client_with_version_and(version, self.credential.clone()) + .await + } + + /// The same, with the credential a case supplies in place of the fixture's — for the + /// descriptor-delivered document, which the mode reads once instead of per call (R29). + pub async fn client_with_credential(&self, credential: Credential) -> Mcp { + self.client_with_version_and(env!("CARGO_PKG_VERSION"), credential) + .await + } + + async fn client_with_version_and(&self, version: &str, credential: Credential) -> Mcp { let server = AdminMcp::new( Arc::clone(&self.state), - self.token.clone(), + credential, Implementation::new(MCP_SERVER_NAME, version), ); let (server_io, client_io) = tokio::io::duplex(64 * 1024); @@ -268,6 +291,22 @@ impl TestMcp { write_settings(&self.config_dir, document); } + /// Rewrites the token file the running server reads on every call (R29): what the next call + /// is decided by is what is here now, and nothing has to be restarted. + pub fn write_scopes(&self, scopes: &[&str]) { + write_private(&self.token_path, &token_document(scopes)); + } + + /// Deletes the token file: the credential's lifetime ends with it (R29). + pub fn revoke(&self) { + std::fs::remove_file(&self.token_path).unwrap(); + } + + /// A descriptor holding the same document, for the mode's other delivery form (R27). + pub fn descriptor(&self) -> std::fs::File { + std::fs::File::open(&self.token_path).unwrap() + } + /// The user settings document as it stands on disk. pub fn settings_file(&self) -> serde_yaml::Value { serde_yaml::from_str( @@ -400,12 +439,25 @@ pub fn id_of(record: &EventRecord) -> String { record.event.id.to_string() } -fn mint(secret: &[u8], expires_at: i64) -> String { - session::create_token(&session::session_key(secret), expires_at) +/// The token document's text: `{"scopes": [...]}`, and `[]` for a read-only token (R27). +pub fn token_document(scopes: &[&str]) -> String { + serde_json::to_string(&serde_json::json!({ "scopes": scopes })).unwrap() } -fn now_seconds(now_ms: u64) -> i64 { - i64::try_from(now_ms / 1_000).unwrap() +/// Writes the document the door is started with, at the mode it requires (R27). +pub fn write_token(config_dir: &Path, scopes: &[&str]) -> PathBuf { + let path = config_dir.join("admin-token.json"); + write_private(&path, &token_document(scopes)); + path +} + +/// Writes `contents` to `path` with mode `0600`: the only mode the token file may carry, so a +/// fixture that wrote anything else would be refused before any case ran (R27). +pub fn write_private(path: &Path, contents: &str) { + use std::os::unix::fs::PermissionsExt; + + std::fs::write(path, contents).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); } fn write_settings(config_dir: &Path, document: &serde_yaml::Value) { diff --git a/crates/nostream-mcp/tests/tools_list.rs b/crates/nostream-mcp/tests/tools_list.rs index e0cf37058..63a82e182 100644 --- a/crates/nostream-mcp/tests/tools_list.rs +++ b/crates/nostream-mcp/tests/tools_list.rs @@ -7,7 +7,7 @@ //! | `the_comparator_rejects_a_changed_list` | the comparator can fail: a removed tool, a changed description and a changed schema each fail through the same `compare` | //! | `the_required_parameters_are_typed` | the shapes the values fix: an `Option` is a two-element type array, `get_event` carries `id`, `settings_set` names both accepted forms, no schema is empty | //! | `the_server_version_is_what_the_composition_supplies` | `serverInfo.version` is the composition's, not this crate's | -//! | `initialize_publishes_the_prerequisites` | `initialize`'s `instructions` name the three prerequisites and the credential | +//! | `initialize_publishes_the_prerequisites` | `initialize`'s `instructions` name the credential, its scopes and the surface's one remaining prerequisite | //! //! The snapshot is **name-sorted**, because rmcp sorts the list and array equality is //! order-sensitive (R21). It is compared, never regenerated: nothing here writes a file. @@ -207,10 +207,11 @@ async fn initialize_publishes_the_prerequisites() { .and_then(|info| info.instructions.clone()) .expect("initialize carries instructions"); for needle in [ + "--admin-token-file", + "--admin-token-fd", "admin.enabled", - "SECRET", - "NOSTREAM_ADMIN_TOKEN", - "POST /admin/login", + "write", + "mcp.denied", ] { assert!( instructions.contains(needle), diff --git a/crates/nostreamd/src/lib.rs b/crates/nostreamd/src/lib.rs index cf0d3541c..35caa6220 100644 --- a/crates/nostreamd/src/lib.rs +++ b/crates/nostreamd/src/lib.rs @@ -38,9 +38,11 @@ //! belongs to #865 and is not registered here. //! //! The MCP server named in the issue has no TS counterpart at the capture. It is the -//! `crates/nostream-mcp` crate, which owns the tools, the credential gate and the audit sink; -//! this crate serves it inside the daemon's own process through `--mcp-stdio` -//! ([`mcp_stdio`]), on stdin/stdout and with no socket of its own. +//! `crates/nostream-mcp` crate, which owns the tools, the credential and its scopes, and the +//! audit sink; this crate serves it inside the daemon's own process through `--mcp-stdio` +//! ([`mcp_stdio`]), on stdin/stdout and with no socket of its own, and it hands the mode its +//! credential from `--admin-token-file` or `--admin-token-fd` — never the console's session token +//! and never `NOSTREAM_ADMIN_TOKEN`, which is retired (ADR 0014 D19). pub mod acceptor; pub mod admin_http; diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs index 3769bcb43..ef840b9dd 100644 --- a/crates/nostreamd/src/main.rs +++ b/crates/nostreamd/src/main.rs @@ -41,11 +41,41 @@ struct Cli { /// Serve the admin MCP server on stdin/stdout and exit when stdin closes. Binds no socket. /// - /// Every call is authenticated with an admin session token (minted by `POST /admin/login`) - /// in NOSTREAM_ADMIN_TOKEN, and needs `admin.enabled: true` in the settings and `SECRET` - /// set; without them a call answers Not Found, Internal Server Error or Unauthorized. + /// Every call is decided by a scoped token document, delivered either by a file + /// (`--admin-token-file `, which must be mode 0600 and is re-read on every call, so + /// deleting or rewriting it revokes or narrows the credential) or on an inherited descriptor + /// (`--admin-token-fd `, read once at start and valid for the life of the process). + /// Exactly one of the two is required. + /// + /// The document is `{"scopes": ["write"]}`; a document with no scopes grants the read tools + /// (`settings_get`, `list_events`, `get_event`), and the "write" scope adds `settings_set`. + /// An unknown scope refuses to start, naming it. The mode also needs `admin.enabled: true` in + /// the settings. + /// + /// NOSTREAM_ADMIN_TOKEN is retired: a console session token does not authenticate this mode, + /// and setting the variable makes the mode refuse to start. #[arg(long)] mcp_stdio: bool, + + /// The token document the MCP mode reads, on every call. Mode 0600 or the mode refuses to + /// start; deleting or rewriting the file is the revocation. + #[arg( + long, + value_name = "PATH", + requires = "mcp_stdio", + conflicts_with = "admin_token_fd" + )] + admin_token_file: Option, + + /// The same token document on an inherited descriptor (conventionally 3), read once at + /// start: the credential then lives as long as the process. + #[arg( + long, + value_name = "N", + requires = "mcp_stdio", + conflicts_with = "admin_token_file" + )] + admin_token_fd: Option, } fn main() -> ExitCode { @@ -137,9 +167,15 @@ fn run(cli: Cli) -> Result { .map_err(|error| DaemonError::Setup(format!("tokio runtime: {error}")))?; if cli.mcp_stdio { + // R26, R27: the credential is resolved before the pipe is served, so a retired variable + // or a document this door cannot accept fails the start rather than every call. + let credential = nostreamd::mcp_stdio::resolve_credential( + cli.admin_token_file.as_deref(), + cli.admin_token_fd, + )?; let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); return runtime.block_on(async move { - nostreamd::mcp_stdio::serve(cwd, config_dir).await?; + nostreamd::mcp_stdio::serve(cwd, config_dir, credential).await?; Ok(ExitCode::SUCCESS) }); } diff --git a/crates/nostreamd/src/mcp_stdio.rs b/crates/nostreamd/src/mcp_stdio.rs index 89ddfd062..a32599aec 100644 --- a/crates/nostreamd/src/mcp_stdio.rs +++ b/crates/nostreamd/src/mcp_stdio.rs @@ -16,33 +16,65 @@ //! the same change, or this mode keeps answering the store-backed tools with the store's own //! `NotImplemented` message (R19). //! -//! The credential is read once here and passed to the server as a value: the server never reads -//! the environment (R7). +//! The credential is this mode's own and comes from its two flags, never the environment: the +//! variable that used to carry a console session token is retired, and a mode started with it +//! refuses to run rather than quietly ignoring it (R26, D19). The server takes the credential as +//! a value and re-reads a file-delivered document on every call, so a rewrite or a deletion is +//! the revocation. -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; use nostream_config::SettingsPaths; use nostream_core::nip05::Nip05Fetch; +use nostream_mcp::Credential; use nostream_services::HttpClient; use rmcp::ServiceExt; use rmcp::model::Implementation; use crate::DaemonError; -/// The session token a stdio caller presents, minted by `POST /admin/login` and verified with -/// the console's own function (R7). -pub const ADMIN_TOKEN_ENV: &str = "NOSTREAM_ADMIN_TOKEN"; +/// The variable that carried a console session token to this mode, until it was retired (R26). +pub const RETIRED_TOKEN_ENV: &str = "NOSTREAM_ADMIN_TOKEN"; -/// The token the environment carries, when it carries a non-empty one. -pub fn token_from_env() -> Option { - std::env::var(ADMIN_TOKEN_ENV) - .ok() - .filter(|token| !token.is_empty()) +/// The credential the mode's flags name (R27): exactly one of the two, and never the environment. +/// +/// Every refusal here happens before the pipe is served, so a half-migrated deployment fails to +/// start with the fix named instead of answering `Unauthorized` to every call. +pub fn resolve_credential(file: Option<&Path>, fd: Option) -> Result { + if std::env::var_os(RETIRED_TOKEN_ENV).is_some() { + return Err(DaemonError::Setup(format!( + "{RETIRED_TOKEN_ENV} is retired: a console session token does not authenticate \ + --mcp-stdio. Start the mode with --admin-token-file (mode 0600) or \ + --admin-token-fd ." + ))); + } + match (file, fd) { + (Some(path), None) => Credential::from_file(path).map_err(start_up), + (None, Some(fd)) => Credential::from_descriptor(fd).map_err(start_up), + (None, None) => Err(DaemonError::Setup( + "--mcp-stdio needs a credential: pass --admin-token-file or \ + --admin-token-fd " + .to_owned(), + )), + (Some(_), Some(_)) => Err(DaemonError::Setup( + "--mcp-stdio takes one credential, not two: pass --admin-token-file or \ + --admin-token-fd " + .to_owned(), + )), + } +} + +fn start_up(error: nostream_mcp::McpError) -> DaemonError { + DaemonError::Setup(error.to_string()) } /// Serves the MCP server on stdin/stdout until the peer closes stdin, then returns. -pub async fn serve(cwd: PathBuf, config_dir: PathBuf) -> Result<(), DaemonError> { +pub async fn serve( + cwd: PathBuf, + config_dir: PathBuf, + credential: Credential, +) -> Result<(), DaemonError> { let stores = Arc::new(nostream_services::unavailable::stores()); let client = Arc::new( nostream_services::ReqwestClient::new() @@ -56,7 +88,7 @@ pub async fn serve(cwd: PathBuf, config_dir: PathBuf) -> Result<(), DaemonError> let server = nostream_mcp::AdminMcp::new( state, - token_from_env(), + credential, Implementation::new(nostream_mcp::MCP_SERVER_NAME, env!("CARGO_PKG_VERSION")), ); diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index 052a0b31c..0bd51640b 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -1,5 +1,6 @@ -//! AC5 — the stdio mode in the real binary: the flag, the JSON-RPC stream, the banner's stream, -//! the absent socket, the exit code and the unwired store's answer. +//! AC5, AC29, AC30, AC33 — the stdio mode in the real binary: the flag, the JSON-RPC stream, the +//! banner's stream, the absent socket, the exit code, the unwired store's answer, and the two +//! ways the mode refuses to start with a credential it cannot accept. //! //! | case | what it proves | //! |---|---| @@ -9,14 +10,19 @@ //! | `the_mode_binds_no_socket` | the dialogue completes while the port the flag names is held by the test | //! | `the_process_exits_zero_on_stdin_eof` | closing stdin ends the process with `0` | //! | `the_store_backed_tools_report_the_unwired_store` | `list_events` answers the store's own `NotImplemented` message, not an empty list | -//! | `the_help_text_names_the_credential` | `--help` names the three prerequisites and `NOSTREAM_ADMIN_TOKEN` | +//! | `the_help_text_names_the_credential` | `--help` names the two flags, the document's shape and scopes, the file rule and the retired variable | +//! | `a_console_session_token_in_the_environment_refuses_to_start` | the retired variable is named rather than ignored, even when it carries a token the console would accept | +//! | `a_group_readable_token_file_refuses_to_start` | mode 0644 fails the start, and the message names both modes | +//! | `the_mode_needs_one_credential_flag` | neither flag is an error naming both, and both is an error naming both | +//! | `an_inherited_descriptor_authenticates` | a document delivered on descriptor 3 answers `tools/list` and a read, with nothing on the command line or in the environment | //! //! The dialogue is hand-written JSON-RPC over the child's pipes: this target proves a property //! of the process, so it spawns the binary the way an MCP client does. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use std::path::PathBuf; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; use std::process::Stdio; use std::time::Duration; @@ -25,22 +31,83 @@ use serde_json::{Value, json}; use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout}; -/// The literal `SECRET` the daemon signs sessions with here. +/// The literal `SECRET` the daemon is composed with here; the MCP credential does not use it. const SECRET: &str = "a-test-secret"; /// The fixture password hash `hashAdminPassword` writes for `hunter2`. const PASSWORD_HASH: &str = "scrypt:BwcHBwcHBwcHBwcHBwcHBw==:r5daXU05UJ9EUDu45YoHMWUoQCmkVbwINYNntY1/dwrJPOt3fTi/1IWw1wp9+YXRj1Vm6IpFi+gSU0JdqZvWIw=="; -/// A session token the daemon's own clock accepts, minted the way `POST /admin/login` does. -fn token() -> String { +/// A session token the console's own gate would accept, minted the way `POST /admin/login` does — +/// which this mode must not treat as a credential (R26). +fn session_token() -> String { let now: i64 = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs() .try_into() .unwrap(); - let expires_at = now + 3_600; - session::create_token(&session::session_key(SECRET.as_bytes()), expires_at) + session::create_token(&session::session_key(SECRET.as_bytes()), now + 3_600) +} + +/// The repository root, which the mode reads its `resources/` tree from. +fn workspace_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +/// The token document's text: `{"scopes": [...]}` (R27). +fn token_document(scopes: &[&str]) -> String { + serde_json::to_string(&json!({ "scopes": scopes })).unwrap() +} + +/// Writes `contents` to `path` at mode 0600, the mode the credential requires (R27). +fn write_private(path: &Path, contents: &str) { + std::fs::write(path, contents).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); +} + +/// One config dir with the fixture settings, and the token file the mode is started with. +struct Prepared { + _temp: tempfile::TempDir, + config_dir: PathBuf, + token: PathBuf, +} + +impl Prepared { + fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let config_dir = temp.path().join("config"); + std::fs::create_dir_all(&config_dir).unwrap(); + std::fs::write( + config_dir.join("settings.yaml"), + format!( + "info:\n name: Example\n relay_url: ws://127.0.0.1:8008\nadmin:\n enabled: true\n passwordHash: \"{PASSWORD_HASH}\"\n" + ), + ) + .unwrap(); + let token = temp.path().join("admin-token.json"); + write_private(&token, &token_document(&["write"])); + Self { + _temp: temp, + config_dir, + token, + } + } + + /// The mode's arguments for a dialogue: the config dir, the log level, the mode flag and the + /// token file. + fn arguments(&self, extra: &[String]) -> Vec { + let mut arguments = vec![ + "--config-dir".to_owned(), + self.config_dir.display().to_string(), + "--log-level".to_owned(), + "info".to_owned(), + "--mcp-stdio".to_owned(), + "--admin-token-file".to_owned(), + self.token.display().to_string(), + ]; + arguments.extend_from_slice(extra); + arguments + } } /// One spawned `nostreamd --mcp-stdio`, and every stdout line it wrote. @@ -67,54 +134,28 @@ impl Drop for Daemon { } impl Daemon { - /// Spawns the binary on a fresh config dir. - fn start(token: Option<&str>, extra: &[String]) -> (Self, tempfile::TempDir) { - let temp = tempfile::tempdir().expect("tempdir"); - let config_dir = temp.path().join("config"); - std::fs::create_dir_all(&config_dir).expect("config dir"); - std::fs::write( - config_dir.join("settings.yaml"), - format!( - "info:\n name: Example\n relay_url: ws://127.0.0.1:8008\nadmin:\n enabled: true\n passwordHash: \"{PASSWORD_HASH}\"\n" - ), - ) - .expect("settings"); - - let workspace = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."); - let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_nostreamd")); - command - .arg("--config-dir") - .arg(&config_dir) - .arg("--log-level") - .arg("info") - .arg("--mcp-stdio") - .args(extra) - .current_dir(&workspace) - .env("SECRET", SECRET) - .env("WORKER_COUNT", "1") - // The ambient environment must not decide whether this case is authenticated. - .env_remove("NOSTREAM_ADMIN_TOKEN") - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - if let Some(token) = token { - command.env("NOSTREAM_ADMIN_TOKEN", token); - } + /// Spawns the binary on the prepared config dir and token file. + fn start(prepared: &Prepared, extra: &[String]) -> Self { + let mut command = base_command(); + command.args(prepared.arguments(extra)); + Self::spawn(command) + } + + /// The same, from a command a case built itself — the descriptor case runs the binary under + /// `sh`, so its parent can open the document as descriptor 3. + fn spawn(mut command: tokio::process::Command) -> Self { let mut child = command.spawn().expect("the daemon starts"); let stdin = child.stdin.take(); let stdout = BufReader::new(child.stdout.take().expect("stdout is piped")); let stderr = child.stderr.take().expect("stderr is piped"); - ( - Self { - child, - stdin, - stdout, - stderr, - lines: Vec::new(), - next_id: 0, - }, - temp, - ) + Self { + child, + stdin, + stdout, + stderr, + lines: Vec::new(), + next_id: 0, + } } async fn send(&mut self, message: Value) { @@ -220,9 +261,46 @@ impl Daemon { } } +/// The binary, with the ambient environment removed and the fixture's set: the retired variable +/// must not decide whether a case is authenticated (R26). +fn base_command() -> tokio::process::Command { + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_nostreamd")); + command + .current_dir(workspace_root()) + .env("SECRET", SECRET) + .env("WORKER_COUNT", "1") + .env_remove("NOSTREAM_ADMIN_TOKEN") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + command +} + +/// Spawns the mode with these arguments and environment, and waits for it to exit without a +/// dialogue: for the cases whose point is that it refuses to start. +async fn refusal(arguments: &[String], environment: &[(&str, &str)]) -> (Option, String) { + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_nostreamd")); + command + .args(arguments) + .current_dir(workspace_root()) + .env("SECRET", SECRET) + .env("WORKER_COUNT", "1") + .env_remove("NOSTREAM_ADMIN_TOKEN") + .envs(environment.iter().copied()) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let output = command.output().await.expect("the binary runs"); + ( + output.status.code(), + String::from_utf8_lossy(&output.stderr).into_owned(), + ) +} + #[tokio::test] async fn the_banner_is_on_stderr_and_stdout_is_json_rpc() { - let (mut daemon, _temp) = Daemon::start(Some(&token()), &[]); + let prepared = Prepared::new(); + let mut daemon = Daemon::start(&prepared, &[]); daemon.initialize().await; daemon.request("tools/list", json!({})).await; let outcome = daemon.finish().await; @@ -245,7 +323,8 @@ async fn the_banner_is_on_stderr_and_stdout_is_json_rpc() { #[tokio::test] async fn initialize_names_the_daemon() { - let (mut daemon, _temp) = Daemon::start(Some(&token()), &[]); + let prepared = Prepared::new(); + let mut daemon = Daemon::start(&prepared, &[]); let result = daemon.initialize().await; let outcome = daemon.finish().await; @@ -260,7 +339,8 @@ async fn initialize_names_the_daemon() { #[tokio::test] async fn settings_get_answers_redacted_over_stdio() { - let (mut daemon, _temp) = Daemon::start(Some(&token()), &[]); + let prepared = Prepared::new(); + let mut daemon = Daemon::start(&prepared, &[]); daemon.initialize().await; let response = daemon.call("settings_get", json!({})).await; let outcome = daemon.finish().await; @@ -279,10 +359,8 @@ async fn the_mode_binds_no_socket() { let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("an ephemeral port"); let port = listener.local_addr().expect("addr").port(); - let (mut daemon, _temp) = Daemon::start( - Some(&token()), - &["--listen-port".to_owned(), port.to_string()], - ); + let prepared = Prepared::new(); + let mut daemon = Daemon::start(&prepared, &["--listen-port".to_owned(), port.to_string()]); daemon.initialize().await; let listed = daemon.request("tools/list", json!({})).await; let outcome = daemon.finish().await; @@ -298,14 +376,16 @@ async fn the_mode_binds_no_socket() { #[tokio::test] async fn the_process_exits_zero_on_stdin_eof() { - let (daemon, _temp) = Daemon::start(Some(&token()), &[]); + let prepared = Prepared::new(); + let daemon = Daemon::start(&prepared, &[]); let outcome = daemon.finish().await; assert_eq!(outcome.status.code(), Some(0), "{}", outcome.stderr); } #[tokio::test] async fn the_store_backed_tools_report_the_unwired_store() { - let (mut daemon, _temp) = Daemon::start(Some(&token()), &[]); + let prepared = Prepared::new(); + let mut daemon = Daemon::start(&prepared, &[]); daemon.initialize().await; let response = daemon.call("list_events", json!({})).await; let outcome = daemon.finish().await; @@ -332,10 +412,109 @@ async fn the_help_text_names_the_credential() { let help = String::from_utf8_lossy(&output.stdout); for needle in [ "--mcp-stdio", + "--admin-token-file", + "--admin-token-fd", "NOSTREAM_ADMIN_TOKEN", + "0600", + "scopes", + "write", "admin.enabled", - "SECRET", ] { assert!(help.contains(needle), "the help names `{needle}`: {help}"); } } + +/// Proof 1: a console session token in the retired variable does not start the door — the mode +/// names the variable and the flag that replaces it, rather than serving and refusing every call +/// (R26). +#[tokio::test] +async fn a_console_session_token_in_the_environment_refuses_to_start() { + let prepared = Prepared::new(); + let session_token = session_token(); + let (code, stderr) = refusal( + &prepared.arguments(&[]), + &[("NOSTREAM_ADMIN_TOKEN", session_token.as_str())], + ) + .await; + + assert_eq!( + code, + Some(1), + "the mode exits 1 rather than serving: {stderr}" + ); + assert!(stderr.contains("NOSTREAM_ADMIN_TOKEN"), "{stderr}"); + assert!(stderr.contains("retired"), "{stderr}"); + assert!(stderr.contains("--admin-token-file"), "{stderr}"); +} + +/// Proof 2: a token file anyone in the file's group can read is refused at start, and the message +/// names the mode it found and the mode it needs (R27). +#[tokio::test] +async fn a_group_readable_token_file_refuses_to_start() { + let prepared = Prepared::new(); + std::fs::set_permissions(&prepared.token, std::fs::Permissions::from_mode(0o644)).unwrap(); + let (code, stderr) = refusal(&prepared.arguments(&[]), &[]).await; + + assert_eq!(code, Some(1), "{stderr}"); + assert!(stderr.contains("0644"), "the mode it found: {stderr}"); + assert!(stderr.contains("0600"), "the mode it needs: {stderr}"); +} + +#[tokio::test] +async fn the_mode_needs_one_credential_flag() { + let prepared = Prepared::new(); + let neither = vec![ + "--config-dir".to_owned(), + prepared.config_dir.display().to_string(), + "--mcp-stdio".to_owned(), + ]; + let (code, stderr) = refusal(&neither, &[]).await; + assert_eq!(code, Some(1), "{stderr}"); + assert!(stderr.contains("--admin-token-file"), "{stderr}"); + assert!(stderr.contains("--admin-token-fd"), "{stderr}"); + + let mut both = prepared.arguments(&[]); + both.extend(["--admin-token-fd".to_owned(), "3".to_owned()]); + let (code, stderr) = refusal(&both, &[]).await; + assert_eq!(code, Some(2), "clap refuses the pair: {stderr}"); + assert!(stderr.contains("--admin-token-file"), "{stderr}"); + assert!(stderr.contains("--admin-token-fd"), "{stderr}"); +} + +/// Proof 5: the descriptor form, end to end — the parent opens the document as descriptor 3 and +/// the mode inherits it, so the secret is on neither the command line nor the environment. +#[tokio::test] +async fn an_inherited_descriptor_authenticates() { + let prepared = Prepared::new(); + let mut shell = tokio::process::Command::new("sh"); + shell + .arg("-c") + .arg( + "exec 3<\"$TOKEN\"; exec \"$BIN\" --config-dir \"$CFG\" --log-level info \ + --mcp-stdio --admin-token-fd 3", + ) + .current_dir(workspace_root()) + .env("TOKEN", &prepared.token) + .env("BIN", env!("CARGO_BIN_EXE_nostreamd")) + .env("CFG", &prepared.config_dir) + .env("SECRET", SECRET) + .env("WORKER_COUNT", "1") + .env_remove("NOSTREAM_ADMIN_TOKEN") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + + let mut daemon = Daemon::spawn(shell); + daemon.initialize().await; + let listed = daemon.request("tools/list", json!({})).await; + let read = daemon.call("settings_get", json!({})).await; + let outcome = daemon.finish().await; + + assert_eq!( + listed["result"]["tools"].as_array().map(Vec::len), + Some(4), + "{listed}" + ); + assert_eq!(read["result"]["isError"], false, "{read}"); + assert_eq!(outcome.status.code(), Some(0), "{}", outcome.stderr); +} From 9dbd43ea0346b3021c755224e5406a6bbe5aba6e Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 07:13:41 -0500 Subject: [PATCH 10/24] docs(admin): record the scoped credential in CONFIGURATION, ADR D19 and the changeset --- .changeset/admin-mcp-server.md | 11 ++- CONFIGURATION.md | 45 +++++++++- .../decisions/0014-admin-http-surface.md | 84 +++++++++++++++++-- 3 files changed, 131 insertions(+), 9 deletions(-) diff --git a/.changeset/admin-mcp-server.md b/.changeset/admin-mcp-server.md index f53c28d30..dd2dee0f8 100644 --- a/.changeset/admin-mcp-server.md +++ b/.changeset/admin-mcp-server.md @@ -5,8 +5,13 @@ feat(admin): the admin MCP server, slice 1 — four tools over stdio A new Rust crate serves `settings_get`, `settings_set`, `list_events` and `get_event` on stdin/stdout through `rmcp`, served by `nostreamd --mcp-stdio` as a process -of its own over the same config directory. Every call is gated by the console's own session token and -audited to `admin-audit.jsonl` under one `mcp.` action; the four names are -recorded as ADR 0014 D18. +of its own over the same config directory. Every call is decided by a scoped token document +the mode is handed by file (`--admin-token-file`, mode 0600, re-read on every call so deleting +or rewriting it is the revocation) or by an inherited descriptor (`--admin-token-fd`, read once +at start); `settings_set` needs the document's `write` scope, and a denied write is refused and +recorded as `mcp.denied`. A console session token no longer authenticates the mode and +`NOSTREAM_ADMIN_TOKEN` is retired: setting it refuses the start. Executed calls are audited to +`admin-audit.jsonl` under one `mcp.` action; those names are recorded as ADR 0014 D18 and +the credential as D19. Rust only: no published package changes, so this changeset is deliberately empty. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index ef34e675f..3219618b3 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -11,7 +11,7 @@ The following environment variables can be set: | RELAY_PRIVATE_KEY | Relay's private key in hex | (auto-generated) | | WORKER_COUNT | Number of workers override | No. of available CPUs | | LOG_FORMAT | Set to `json` to replace the startup banner with one `relay starting` record, so every line the relay writes parses as JSON. | (banner) | -| NOSTREAM_ADMIN_TOKEN | Admin session token `nostreamd --mcp-stdio` authenticates every call with. Mint it by logging in to the admin console (`POST /admin/login`); the mode needs `admin.enabled: true` and `SECRET` set as well. | (none: every call answers `Unauthorized`) | +| NOSTREAM_ADMIN_TOKEN | **Retired.** It used to carry a console session token to `nostreamd --mcp-stdio`; it grants nothing now, and setting it makes the mode refuse to start. See [The admin MCP mode](#the-admin-mcp-mode---mcp-stdio). | (unset: the mode refuses to start if it is set) | | DB_URI | PostgreSQL URI (overrides DB_HOST, DB_PORT, etc.) | | | DB_HOST | PostgresSQL Hostname | | | DB_PORT | PostgreSQL Port | 5432 | @@ -72,6 +72,49 @@ The following environment variables can be set: | ZEBEDEE_API_KEY | Zebedee Project API Key | | | NWC_URL | NWC connection URL (`nostr+walletconnect://...`) | | +## The admin MCP mode (`--mcp-stdio`) + +`nostreamd --mcp-stdio` serves the admin MCP server (`settings_get`, `settings_set`, +`list_events`, `get_event`) on stdin/stdout and exits when stdin closes. It binds no socket, +opens no store of its own, and writes its log lines to **stderr** so nothing but JSON-RPC crosses +stdout. + +Its credential is a **scoped token document** of its own — never a console session token and never +an environment variable. Deliver it one of two ways; exactly one is required: + +| Flag | What it reads | +|---|---| +| `--admin-token-file ` | The document in a file. It must be mode `0600` (owner read and write, nothing for group or other) or the mode refuses to start, naming the mode it found and the mode it needs. It is re-read on **every call**, so deleting or rewriting it is the revocation: narrowing it to reads takes effect on the next call, with nothing restarted. | +| `--admin-token-fd ` | The same document on an inherited descriptor, conventionally `3` (`exec 3 needs the "write" scope` and recorded as one `mcp.denied` line in +`/admin-audit.jsonl`, because it is a call the door authenticated and then denied; a call +with no readable document answers `Unauthorized` and is not recorded, because there is nothing to +attribute it to. + +The mode also needs `admin.enabled: true` in the settings (else every call answers `Not Found`). +`SECRET` is **not** a prerequisite: the door derives no session key. The console's own HTTP +surface is unchanged and still authenticates with `SECRET` and `POST /admin/login` sessions. + +```sh +install -m 0600 /dev/null /etc/nostream/admin-token.json +printf '{"scopes": ["write"]}\n' > /etc/nostream/admin-token.json +nostreamd --config-dir /etc/nostream --mcp-stdio --admin-token-file /etc/nostream/admin-token.json +``` + ## I2P I2P support is provided as a sidecar container (i2pd) via `docker-compose.i2p.yml`, mirroring the Tor setup. No application-level environment variables are needed — the i2pd container creates an I2P server tunnel that forwards traffic to nostream's WebSocket port. diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index 44c4cebec..1c8d83d41 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -19,7 +19,7 @@ and the daemon answered no HTTP request at all — a plain `GET` died in the Web (`crates/nostream-relay/src/relay.rs:315-329`), measured as `curl: (52) Empty reply from server` on every admin path. -The eighteen decisions below are the ones a reader would otherwise have to reconstruct from +The nineteen decisions below are the ones a reader would otherwise have to reconstruct from the diff. Each is recorded with its reason and the evidence that produced it. ## Decisions @@ -307,14 +307,15 @@ costs the column its meaning. `settings_set` (the paths requested, never a value), and `remoteAddress` is omitted because a stdio caller has no address (`state.rs:509-525`). The line is appended at dispatch, before the tool's work, so the file's order is the dispatch order: `mcp.settings_set` precedes the -`settings.updated` line the shared write path then appends, and a call the credential gate -refuses appends nothing at all — matching `admin_auth_middleware.rs:52-63`, which logs a warning -and writes nothing. +`settings.updated` line the shared write path then appends, and a call the credential refuses +appends nothing at all — matching `admin_auth_middleware.rs:52-63`, which logs a warning and +writes nothing. A call the credential *authenticates* and then denies for its scopes is D19's: +it writes one `mcp.denied` line, because the door knows who asked. **The mode is its own process, and the record says so.** `nostreamd --mcp-stdio` returns before the daemon's `serve` loop starts (`crates/nostreamd/src/main.rs:139-147`), so the process that serves a tool call composes its own `AdminState` over the same config directory rather than -sharing the console's: the same session credential, the same `admin-audit.jsonl`, and a +sharing the console's: the same settings files, the same `admin-audit.jsonl`, and a repository bundle of its own — `unavailable::stores()` in `crates/nostreamd/src/mcp_stdio.rs`, composed independently of the relay path's at `crates/nostreamd/src/main.rs:187`, which D7's same-`Arc` rule covers for the console and not for this mode. Wiring the store means wiring the @@ -336,6 +337,79 @@ the line is written before the dispatch, which is unconditional, so a stricter c call run unaudited. `settings_set`'s entry is therefore vacuous by design — its arguments are a raw map and its schema is the half that refuses. +### D19 — The stdio door's credential is a scoped token document of its own + +Slice 1 first authenticated `nostreamd --mcp-stdio` with the console's credential: a session token +minted by `POST /admin/login`, handed to the mode in **`NOSTREAM_ADMIN_TOKEN`** and verified with +the console's own `session_key`/`is_valid_token` pair (D18). The operator retired that on +2026-11-20 — *"narrow the credential"* — for two reasons, and both are measured: + +1. **An environment variable is not a credential boundary.** `/proc//environ` is readable by + anything with the right to inspect the process, and the variable is inherited by every child + the daemon starts. A secret there is one `ps`-adjacent read away from any process that can see + the daemon's environment at all. +2. **A session token cannot be revoked per door.** Every admin door shares one HMAC key derived + from `SECRET`, and a session's only lifetime is the clock: revoking this door's access meant + rotating `SECRET` — logging every console operator out — or waiting out the TTL. There was no + way to narrow *this* door and leave the console alone. + +The credential is now the mode's own artifact, a **token document** delivered one of two ways: + +| flag | delivery | lifetime | +|---|---|---| +| `--admin-token-file ` | a file, which must be mode `0600` (`mode & 0o077 == 0`) | **the file's**: it is re-read on the path that decides every call, so deleting or rewriting it is the revocation | +| `--admin-token-fd ` | a descriptor the parent passed, conventionally `3` | **the process's**: it is read once at start, so a rewrite of its source changes nothing until a restart | + +Exactly one of the two is required; both is a refusal, and neither is a refusal naming both. +`NOSTREAM_ADMIN_TOKEN` is retired: a mode started with it **refuses to start**, naming the variable +and the flag that replaces it, because a silent ignore would leave a half-migrated deployment +serving calls nobody could attribute. + +**The document declares what it may do.** `{"scopes": ["write"]}`, with `scopes` optional, and the +set closed (`deny_unknown_fields`): a document still carrying a session token under `token` is +refused for its shape rather than read for less than it says. Reading is not a scope — every +accepted document may call `settings_get`, `list_events` and `get_event` — and `write` is the one +name a document may add, the right to call `settings_set`. A name the door does not know refuses +the load, naming the scope and the accepted set, because a typo narrowed silently would answer +`Forbidden` to calls the operator believed it allowed with the typo nowhere in sight. A call the +document's scopes deny is refused **and audited**: action `mcp.denied`, `detail` +`{"tool", "scope"}`, no argument values. A call with no readable document answers `Unauthorized` +and appends nothing, because there is nothing to attribute it to — that is D18's rule, unchanged. + +**What is deliberately not checked, and why.** Beyond the mode the file must carry, no ownership +check is made: the process's own effective uid is not readable through `std` without adding +`libc`, and `0600` is already the rule that decides who can read the file — including the group +and other *write* bits, which is what would let another user replace the document. A symlink is +followed, so a `0600` link to a `0644` target is refused on the target's mode. The descriptor form +has no mode to check: the parent already opened it. + +**Revocation is the file's lifetime, with no server-side store.** The file form calls +`std::fs::metadata`, `std::fs::read_to_string` and a small JSON parse **per call** — measured at +`9.70 µs` for a 20-byte document over 10 000 grants in a debug build (`crates/nostream-mcp`'s +`Credential::grant`, the same path `call_tool` takes), against a tool call that reaches an LMDB +read or a settings write. That is the price of a revocation that needs no session store, no +notification path and no restart: narrowing a running door is `printf '{"scopes": []}' >` the file. +The descriptor form's asymmetry is stated rather than implied away, in `CONFIGURATION.md`, in the +mode's `--help`, in the crate's docs and here: it is read once, so its lifetime is the process's. + +**What D19 does not change.** The console's HTTP surface keeps `SECRET`, `POST /admin/login` and +session tokens exactly as D3–D18 recorded them. `admin.enabled` still gates this door, because a +surface the operator turned off is off on every transport. `SECRET` no longer gates it: the door +derives no session key, so requiring `SECRET` would refuse a correctly configured deployment for +a reason that has nothing to do with the credential it presents. + +**Measured red for each proof, at `d6b37425`** — the tests are `crates/nostream-mcp/tests/auth.rs` +and `crates/nostreamd/tests/mcp_stdio.rs`: + +| proof | at `d6b37425` | +|---|---| +| a session token in the variable refuses the start | the mode served: exit `0`, and stderr carried only `mcp server on stdio` | +| a `0644` token file refuses the start | `error: unexpected argument '--admin-token-file' found`, exit `2` | +| a read-only token is refused the write and audited | `left: Some(false) right: Some(true)` — the write succeeded | +| an unknown scope refuses the load | `error[E0433]: cannot find Credential in nostream_mcp` | +| a descriptor-delivered token authenticates | `error: unexpected argument '--admin-token-fd' found`, exit `2` | +| a rewrite changes the write decision | `left: Some(false) right: Some(true)` — the rewrite changed nothing | + ## Evidence Measured in this job's worktree at `factory/032-admin-console-parity`: From ab570bbd6a102306785135ed4c2d319e2a82d76f Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 07:21:00 -0500 Subject: [PATCH 11/24] fix(admin): check the token file's mode on the descriptor it was opened as --- crates/nostream-mcp/src/credential.rs | 50 ++++++++++++++++++--------- crates/nostreamd/tests/mcp_stdio.rs | 14 ++++++++ 2 files changed, 47 insertions(+), 17 deletions(-) diff --git a/crates/nostream-mcp/src/credential.rs b/crates/nostream-mcp/src/credential.rs index 9fb125afe..3d97a7d28 100644 --- a/crates/nostream-mcp/src/credential.rs +++ b/crates/nostream-mcp/src/credential.rs @@ -13,6 +13,7 @@ //! form, deliberately — one small file per call is the price of a revocation that needs no //! server-side store. +use std::io::Read; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; @@ -131,10 +132,12 @@ impl Credential { /// The same document on a descriptor the parent passed (`--admin-token-fd`), read once. /// - /// `/proc/self/fd/` is the readable path to a descriptor this process inherited and needs - /// no `unsafe`: the workspace denies `unsafe_code` and its one carve-out is the storage - /// crate's (`CLAUDE.md`). It reads a regular file and a pipe alike, from the descriptor's own - /// offset. + /// It reads a regular file and a pipe alike, from the descriptor's own offset. + /// + /// `shortcut: /proc/self/fd/ is the readable path to an inherited descriptor and needs no + /// unsafe — the workspace denies unsafe_code and its one carve-out is the storage crate's + /// (CLAUDE.md) — upgrade when the daemon has to run where /proc is not mounted, which is the + /// point at which a raw-fd handle earns its audited unsafe block` pub fn from_descriptor(fd: i32) -> Result { let path = PathBuf::from(format!("/proc/self/fd/{fd}")); let text = std::fs::read_to_string(&path).map_err(|error| { @@ -162,14 +165,23 @@ impl Credential { } /// One token file, checked and read: the mode's file rule, in one place (R27). +/// +/// The file is opened once and checked on the descriptor it was opened as, rather than by path +/// and then again by path: a `metadata` that answered `0600` and a read that then opened whatever +/// the name pointed at would leave a window between the check and the use. +/// +/// `shortcut: the mode is the only ownership check — the process's own euid is not readable +/// through std without adding libc, and 0600 already decides who may read the file, group and +/// other write bits included — upgrade when a root-run mode has to refuse a file owned by another +/// user, which needs a dependency this crate was not given` fn read_file(path: &Path) -> Result { - let metadata = std::fs::metadata(path).map_err(|error| { - McpError::Credential(format!( - "the admin token file {} could not be read: {error}", - path.display() - )) - })?; - let mode = metadata.permissions().mode() & 0o777; + let mut file = std::fs::File::open(path).map_err(|error| unreadable(path, &error))?; + let mode = file + .metadata() + .map_err(|error| unreadable(path, &error))? + .permissions() + .mode() + & 0o777; if mode & GROUP_OR_OTHER != 0 { return Err(McpError::Credential(format!( "the admin token file {} is mode {mode:04o}: it must be {TOKEN_FILE_MODE:04o}, \ @@ -177,11 +189,15 @@ fn read_file(path: &Path) -> Result { path.display() ))); } - let text = std::fs::read_to_string(path).map_err(|error| { - McpError::Credential(format!( - "the admin token file {} could not be read: {error}", - path.display() - )) - })?; + let mut text = String::new(); + file.read_to_string(&mut text) + .map_err(|error| unreadable(path, &error))?; TokenDocument::parse(&text, &path.display().to_string())?.scopes() } + +fn unreadable(path: &Path, error: &std::io::Error) -> McpError { + McpError::Credential(format!( + "the admin token file {} could not be read: {error}", + path.display() + )) +} diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index 0bd51640b..7fdbeb3c2 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -479,6 +479,20 @@ async fn the_mode_needs_one_credential_flag() { assert_eq!(code, Some(2), "clap refuses the pair: {stderr}"); assert!(stderr.contains("--admin-token-file"), "{stderr}"); assert!(stderr.contains("--admin-token-fd"), "{stderr}"); + + // A credential flag on the relay path is refused rather than ignored: a daemon started with + // one and no `--mcp-stdio` would look configured and serve the console. `--check` is there so + // that a silently accepted flag validates the settings and exits rather than binding a socket. + let mut without_mode = vec![ + "--config-dir".to_owned(), + prepared.config_dir.display().to_string(), + "--admin-token-file".to_owned(), + prepared.token.display().to_string(), + ]; + without_mode.push("--check".to_owned()); + let (code, stderr) = refusal(&without_mode, &[]).await; + assert_eq!(code, Some(2), "{stderr}"); + assert!(stderr.contains("--mcp-stdio"), "{stderr}"); } /// Proof 5: the descriptor form, end to end — the parent opens the document as descriptor 3 and From 1d92d1f6e384d982b2f3731d9c5b8e704709aa87 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 07:21:02 -0500 Subject: [PATCH 12/24] docs(admin): cite the re-measured per-call read in D19 --- docs/rewrite/decisions/0014-admin-http-surface.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index 1c8d83d41..8b6866cd4 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -385,7 +385,7 @@ has no mode to check: the parent already opened it. **Revocation is the file's lifetime, with no server-side store.** The file form calls `std::fs::metadata`, `std::fs::read_to_string` and a small JSON parse **per call** — measured at -`9.70 µs` for a 20-byte document over 10 000 grants in a debug build (`crates/nostream-mcp`'s +`9.67 µs` for a 20-byte document over 10 000 grants in a debug build (`crates/nostream-mcp`'s `Credential::grant`, the same path `call_tool` takes), against a tool call that reaches an LMDB read or a settings write. That is the price of a revocation that needs no session store, no notification path and no restart: narrowing a running door is `printf '{"scopes": []}' >` the file. From 8cae06f204899a395d990123a2a70dd30c8bdd8e Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 07:30:31 -0500 Subject: [PATCH 13/24] fix(admin): keep the payments refusal on the relay path, not the stdio door --- crates/nostreamd/src/main.rs | 15 +++-- crates/nostreamd/tests/mcp_stdio.rs | 94 +++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+), 5 deletions(-) diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs index ef840b9dd..a4de8646c 100644 --- a/crates/nostreamd/src/main.rs +++ b/crates/nostreamd/src/main.rs @@ -113,11 +113,9 @@ fn run(cli: Cli) -> Result { let settings = outcome.settings; - // R9: payments cannot be enabled without a usable SECRET. This is the capture's one - // startup refusal (`src/app/app.ts:86-94`) and it exits 1, not `InvalidSettings`' 2. - if payments_enabled(&settings) && secret_missing() { - return Err(DaemonError::MissingSecret); - } + // R9's payments refusal belongs to the relay path only, and is checked below, after the + // `--mcp-stdio` branch returns: the stdio door serves no payments, and D19 retired `SECRET` + // as a prerequisite for it, so a payment-enabled instance without one can still open it. let writer = if cli.mcp_stdio { telemetry::LogWriter::Stderr @@ -180,6 +178,13 @@ fn run(cli: Cli) -> Result { }); } + // R9: payments cannot be enabled without a usable `SECRET`. This is the capture's one + // startup refusal (`src/app/app.ts:86-94`) and it exits 1, not `InvalidSettings`' 2. It is + // checked here, after the stdio mode has returned, because that door serves no payments. + if payments_enabled(&settings) && secret_missing() { + return Err(DaemonError::MissingSecret); + } + runtime.block_on(async move { serve(listen, settings, config_dir, port).await }) } diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index 7fdbeb3c2..6095ef144 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -93,6 +93,18 @@ impl Prepared { } } + /// The same fixture with payments turned on: the relay path refuses to start without `SECRET` + /// (`src/app/app.ts:86-94`), and the stdio door, which serves no payments, must not inherit + /// that refusal (D19: `SECRET` is not a prerequisite for this door). + fn with_payments() -> Self { + let prepared = Self::new(); + let settings = prepared.config_dir.join("settings.yaml"); + let mut document = std::fs::read_to_string(&settings).unwrap(); + document.push_str("payments:\n enabled: true\n"); + std::fs::write(&settings, document).unwrap(); + prepared + } + /// The mode's arguments for a dialogue: the config dir, the log level, the mode flag and the /// token file. fn arguments(&self, extra: &[String]) -> Vec { @@ -297,6 +309,36 @@ async fn refusal(arguments: &[String], environment: &[(&str, &str)]) -> (Option< ) } +/// The binary with **no** `SECRET`, for the payments refusal: the relay path must answer it and +/// the stdio door must not. Bounded, because a build that lost the refusal would serve a relay +/// here instead of exiting. +async fn without_a_secret(arguments: &[String]) -> (Option, String) { + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_nostreamd")); + command + .args(arguments) + .current_dir(workspace_root()) + .env_remove("SECRET") + .env("WORKER_COUNT", "1") + .env_remove("NOSTREAM_ADMIN_TOKEN") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = command.spawn().expect("the binary runs"); + let mut pipe = child.stderr.take().expect("stderr is piped"); + let status = match tokio::time::timeout(Duration::from_secs(20), child.wait()).await { + Ok(status) => status.expect("the child is reaped"), + Err(_) => { + let _ = child.start_kill(); + panic!("the process neither refused nor exited within twenty seconds"); + } + }; + let mut stderr = String::new(); + pipe.read_to_string(&mut stderr) + .await + .expect("stderr drains"); + (status.code(), stderr) +} + #[tokio::test] async fn the_banner_is_on_stderr_and_stdout_is_json_rpc() { let prepared = Prepared::new(); @@ -532,3 +574,55 @@ async fn an_inherited_descriptor_authenticates() { assert_eq!(read["result"]["isError"], false, "{read}"); assert_eq!(outcome.status.code(), Some(0), "{}", outcome.stderr); } + +/// The payments refusal is the relay path's, not the door's: a payment-enabled instance with no +/// `SECRET` still opens the stdio door when its token document is good (D19). +#[tokio::test] +async fn payments_without_a_secret_do_not_stop_the_door() { + let prepared = Prepared::with_payments(); + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_nostreamd")); + command + .args(prepared.arguments(&[])) + .current_dir(workspace_root()) + .env_remove("SECRET") + .env("WORKER_COUNT", "1") + .env_remove("NOSTREAM_ADMIN_TOKEN") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut daemon = Daemon::spawn(command); + let result = daemon.initialize().await; + let outcome = daemon.finish().await; + + assert_eq!( + result["result"]["serverInfo"]["name"], "nostream", + "{result}" + ); + assert!( + outcome + .stderr + .lines() + .any(|line| line.contains("mcp server on stdio")), + "the mode reached its banner: {}", + outcome.stderr + ); + assert_eq!(outcome.status.code(), Some(0), "{}", outcome.stderr); +} + +/// The counterpart: moving the refusal must not be deleting it. The relay path with the same +/// settings and no `SECRET` still refuses, with the capture's own message and exit code `1`. +#[tokio::test] +async fn the_relay_path_still_needs_a_secret_for_payments() { + let prepared = Prepared::with_payments(); + let arguments = vec![ + "--config-dir".to_owned(), + prepared.config_dir.display().to_string(), + ]; + let (code, stderr) = without_a_secret(&arguments).await; + + assert_eq!(code, Some(1), "{stderr}"); + assert!( + stderr.contains("Please configure the secret using the SECRET environment variable."), + "{stderr}" + ); +} From 06d4621f727e65bbff27d3ce8b644fe1ed7df1fb Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 07:55:22 -0500 Subject: [PATCH 14/24] fix(admin): refuse a token file that is not a regular file --- CONFIGURATION.md | 2 +- crates/nostream-mcp/src/credential.rs | 45 ++++++++++++++++++----- crates/nostreamd/src/main.rs | 6 ++-- crates/nostreamd/tests/mcp_stdio.rs | 51 ++++++++++++++++++++++----- 4 files changed, 82 insertions(+), 22 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 3219618b3..8389e41ea 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -84,7 +84,7 @@ an environment variable. Deliver it one of two ways; exactly one is required: | Flag | What it reads | |---|---| -| `--admin-token-file ` | The document in a file. It must be mode `0600` (owner read and write, nothing for group or other) or the mode refuses to start, naming the mode it found and the mode it needs. It is re-read on **every call**, so deleting or rewriting it is the revocation: narrowing it to reads takes effect on the next call, with nothing restarted. | +| `--admin-token-file ` | The document in a **regular** file. It must be mode `0600` (owner read and write, nothing for group or other) or the mode refuses to start, naming the mode it found and the mode it needs; a FIFO, a device or a directory there is refused the same way, because the mode re-opens the file on every call and opening a FIFO waits for a writer. It is re-read on **every call**, so deleting or rewriting it is the revocation: narrowing it to reads takes effect on the next call, with nothing restarted. | | `--admin-token-fd ` | The same document on an inherited descriptor, conventionally `3` (`exec 3 Result { + // Before the open: a FIFO's open blocks, so the type has to be known first. + let kind = std::fs::metadata(path).map_err(|error| unreadable(path, &error))?; + if !kind.is_file() { + return Err(not_regular(path)); + } let mut file = std::fs::File::open(path).map_err(|error| unreadable(path, &error))?; - let mode = file - .metadata() - .map_err(|error| unreadable(path, &error))? - .permissions() - .mode() - & 0o777; + let metadata = file.metadata().map_err(|error| unreadable(path, &error))?; + if !metadata.is_file() { + return Err(not_regular(path)); + } + let mode = metadata.permissions().mode() & 0o777; if mode & GROUP_OR_OTHER != 0 { return Err(McpError::Credential(format!( "the admin token file {} is mode {mode:04o}: it must be {TOKEN_FILE_MODE:04o}, \ @@ -195,6 +214,14 @@ fn read_file(path: &Path) -> Result { TokenDocument::parse(&text, &path.display().to_string())?.scopes() } +fn not_regular(path: &Path) -> McpError { + McpError::Credential(format!( + "the admin token file {} is not a regular file: the door re-reads it on every call, and a \ + pipe or a device there would stall that read", + path.display() + )) +} + fn unreadable(path: &Path, error: &std::io::Error) -> McpError { McpError::Credential(format!( "the admin token file {} could not be read: {error}", diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs index a4de8646c..9ff5e1db9 100644 --- a/crates/nostreamd/src/main.rs +++ b/crates/nostreamd/src/main.rs @@ -41,7 +41,7 @@ struct Cli { /// Serve the admin MCP server on stdin/stdout and exit when stdin closes. Binds no socket. /// - /// Every call is decided by a scoped token document, delivered either by a file + /// Every call is decided by a scoped token document, delivered either by a regular file /// (`--admin-token-file `, which must be mode 0600 and is re-read on every call, so /// deleting or rewriting it revokes or narrows the credential) or on an inherited descriptor /// (`--admin-token-fd `, read once at start and valid for the life of the process). @@ -57,8 +57,8 @@ struct Cli { #[arg(long)] mcp_stdio: bool, - /// The token document the MCP mode reads, on every call. Mode 0600 or the mode refuses to - /// start; deleting or rewriting the file is the revocation. + /// The token document the MCP mode reads, on every call. A regular file at mode 0600 or the + /// mode refuses to start; deleting or rewriting the file is the revocation. #[arg( long, value_name = "PATH", diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index 6095ef144..8398d5b06 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -1,6 +1,7 @@ -//! AC5, AC29, AC30, AC33 — the stdio mode in the real binary: the flag, the JSON-RPC stream, the -//! banner's stream, the absent socket, the exit code, the unwired store's answer, and the two -//! ways the mode refuses to start with a credential it cannot accept. +//! AC5, AC29, AC30, AC33, AC36, AC37 — the stdio mode in the real binary: the flag, the JSON-RPC +//! stream, the banner's stream, the absent socket, the exit code, the unwired store's answer, the +//! ways the mode refuses to start with a credential it cannot accept, and the payments refusal +//! that belongs to the relay path rather than to this door. //! //! | case | what it proves | //! |---|---| @@ -13,6 +14,7 @@ //! | `the_help_text_names_the_credential` | `--help` names the two flags, the document's shape and scopes, the file rule and the retired variable | //! | `a_console_session_token_in_the_environment_refuses_to_start` | the retired variable is named rather than ignored, even when it carries a token the console would accept | //! | `a_group_readable_token_file_refuses_to_start` | mode 0644 fails the start, and the message names both modes | +//! | `a_fifo_token_file_refuses_to_start` | a FIFO in the token file's place is refused, not opened: a read of one would stall the door | //! | `the_mode_needs_one_credential_flag` | neither flag is an error naming both, and both is an error naming both | //! | `an_inherited_descriptor_authenticates` | a document delivered on descriptor 3 answers `tools/list` and a read, with nothing on the command line or in the environment | //! @@ -309,20 +311,23 @@ async fn refusal(arguments: &[String], environment: &[(&str, &str)]) -> (Option< ) } -/// The binary with **no** `SECRET`, for the payments refusal: the relay path must answer it and -/// the stdio door must not. Bounded, because a build that lost the refusal would serve a relay -/// here instead of exiting. -async fn without_a_secret(arguments: &[String]) -> (Option, String) { +/// The binary, bounded, for the cases whose bug would be a process that neither refuses nor exits: +/// a build that lost the payments refusal would serve a relay, and a FIFO token file that is not +/// refused yields no open at all. Twenty seconds. `secret: None` removes `SECRET`. +async fn bounded(arguments: &[String], secret: Option<&str>) -> (Option, String) { let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_nostreamd")); command .args(arguments) .current_dir(workspace_root()) - .env_remove("SECRET") .env("WORKER_COUNT", "1") .env_remove("NOSTREAM_ADMIN_TOKEN") .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); + match secret { + Some(secret) => command.env("SECRET", secret), + None => command.env_remove("SECRET"), + }; let mut child = command.spawn().expect("the binary runs"); let mut pipe = child.stderr.take().expect("stderr is piped"); let status = match tokio::time::timeout(Duration::from_secs(20), child.wait()).await { @@ -502,6 +507,34 @@ async fn a_group_readable_token_file_refuses_to_start() { assert!(stderr.contains("0600"), "the mode it needs: {stderr}"); } +/// A FIFO in the token file's place is refused rather than opened: the door re-reads the document +/// on every call, and opening a FIFO read-only waits for a writer that never comes (R27). +#[tokio::test] +async fn a_fifo_token_file_refuses_to_start() { + let prepared = Prepared::new(); + let fifo = prepared.token.with_file_name("admin-token.fifo"); + let made = std::process::Command::new("mkfifo") + .args(["-m", "0600"]) + .arg(&fifo) + .status() + .expect("mkfifo runs"); + assert!(made.success(), "the fixture writes the FIFO at 0600"); + + let arguments = vec![ + "--config-dir".to_owned(), + prepared.config_dir.display().to_string(), + "--log-level".to_owned(), + "info".to_owned(), + "--mcp-stdio".to_owned(), + "--admin-token-file".to_owned(), + fifo.display().to_string(), + ]; + let (code, stderr) = bounded(&arguments, Some(SECRET)).await; + + assert_eq!(code, Some(1), "{stderr}"); + assert!(stderr.contains("not a regular file"), "{stderr}"); +} + #[tokio::test] async fn the_mode_needs_one_credential_flag() { let prepared = Prepared::new(); @@ -618,7 +651,7 @@ async fn the_relay_path_still_needs_a_secret_for_payments() { "--config-dir".to_owned(), prepared.config_dir.display().to_string(), ]; - let (code, stderr) = without_a_secret(&arguments).await; + let (code, stderr) = bounded(&arguments, None).await; assert_eq!(code, Some(1), "{stderr}"); assert!( From 1acec51b7f5dc647ebe4a6db58c08ec02a53133c Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 07:55:24 -0500 Subject: [PATCH 15/24] docs(admin): state D19's revocation as the calls the code makes --- .../decisions/0014-admin-http-surface.md | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index 8b6866cd4..9a7cdfe1d 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -357,9 +357,16 @@ The credential is now the mode's own artifact, a **token document** delivered on | flag | delivery | lifetime | |---|---|---| -| `--admin-token-file ` | a file, which must be mode `0600` (`mode & 0o077 == 0`) | **the file's**: it is re-read on the path that decides every call, so deleting or rewriting it is the revocation | +| `--admin-token-file ` | a regular file, which must be mode `0600` (`mode & 0o077 == 0`) | **the file's**: it is re-read on the path that decides every call, so deleting or rewriting it is the revocation | | `--admin-token-fd ` | a descriptor the parent passed, conventionally `3` | **the process's**: it is read once at start, so a rewrite of its source changes nothing until a restart | +**One shape: a regular file.** The type is checked on the path before the open and again on the +descriptor it was opened as, so a FIFO, a device or a directory is refused rather than opened: a +FIFO's open waits for a writer, and this door re-opens the file on every call, so a pipe in its +place would stall a call instead of failing it. The pre-open check is the one check made by path; +a FIFO swapped in between it and the open stalls one call, which is the same writer who could +drop in their own `0600` document — the boundary below. + Exactly one of the two is required; both is a refusal, and neither is a refusal naming both. `NOSTREAM_ADMIN_TOKEN` is retired: a mode started with it **refuses to start**, naming the variable and the flag that replaces it, because a silent ignore would leave a half-migrated deployment @@ -383,12 +390,14 @@ and other *write* bits, which is what would let another user replace the documen followed, so a `0600` link to a `0644` target is refused on the target's mode. The descriptor form has no mode to check: the parent already opened it. -**Revocation is the file's lifetime, with no server-side store.** The file form calls -`std::fs::metadata`, `std::fs::read_to_string` and a small JSON parse **per call** — measured at -`9.67 µs` for a 20-byte document over 10 000 grants in a debug build (`crates/nostream-mcp`'s -`Credential::grant`, the same path `call_tool` takes), against a tool call that reaches an LMDB -read or a settings write. That is the price of a revocation that needs no session store, no -notification path and no restart: narrowing a running door is `printf '{"scopes": []}' >` the file. +**Revocation is the file's lifetime, with no server-side store.** The file form opens the path, +fstats **the descriptor it just opened** for the mode and the type, and reads the document from +that same handle — `File::open`, `File::metadata()`, `File::read_to_string` and a small JSON parse +**per call** — measured at `10.6 µs` for a 20-byte document over 10 000 grants in a debug build +(`crates/nostream-mcp`'s `Credential::grant`, the same path `call_tool` takes), against a tool call +that reaches an LMDB read or a settings write. That is the price of a revocation that +needs no session store, no notification path and no restart: narrowing a running door is +`printf '{"scopes": []}' >` the file. The descriptor form's asymmetry is stated rather than implied away, in `CONFIGURATION.md`, in the mode's `--help`, in the crate's docs and here: it is read once, so its lifetime is the process's. From 6f53811baf889d419624a7241de6d4c06aa08f09 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 08:36:22 -0500 Subject: [PATCH 16/24] fix(admin): make the scope table total and check the descriptor's target --- crates/nostream-mcp/src/credential.rs | 105 +++++++++++++------ crates/nostream-mcp/src/lib.rs | 8 +- crates/nostream-mcp/src/server.rs | 113 +++++++++++++++------ crates/nostream-mcp/tests/audit.rs | 20 ++-- crates/nostream-mcp/tests/auth.rs | 129 +++++++++++++++++++++--- crates/nostream-mcp/tests/common/mod.rs | 4 +- crates/nostreamd/src/main.rs | 17 ++-- crates/nostreamd/src/mcp_stdio.rs | 4 +- crates/nostreamd/tests/mcp_stdio.rs | 25 ++++- 9 files changed, 319 insertions(+), 106 deletions(-) diff --git a/crates/nostream-mcp/src/credential.rs b/crates/nostream-mcp/src/credential.rs index bf651cc39..576940367 100644 --- a/crates/nostream-mcp/src/credential.rs +++ b/crates/nostream-mcp/src/credential.rs @@ -12,6 +12,12 @@ //! is read once at start, so its lifetime is the process's. Nothing here is cached for the file //! form, deliberately — one small file per call is the price of a revocation that needs no //! server-side store. +//! +//! Both forms are checked the same way before the document is parsed: the target must be a +//! regular file, it must carry **no group or other permission** (`mode & 0o077 == 0`, which a +//! `0600` file satisfies and a read-only `0400` one does too), and it must be no larger than +//! [`MAX_TOKEN_DOCUMENT_BYTES`]. The checks read the metadata of the object the location names, +//! so a `0644` document is refused whichever way it is delivered (R27). use std::io::Read; use std::os::unix::fs::PermissionsExt; @@ -27,13 +33,22 @@ pub const SCOPE_WRITE: &str = "write"; /// The scopes a token document may name, as a refusal states them. pub const ACCEPTED_SCOPES: &[&str] = &[SCOPE_WRITE]; -/// The mode a token file must carry: owner read and write, and nothing for anyone else (R27). +/// The mode a token document is usually written with: owner read and write, and nothing for +/// anyone else. It is the number the refusal names as its example; the rule is [`GROUP_OR_OTHER`]'s +/// — no group or other permission — which a read-only `0400` document satisfies too (R27). pub const TOKEN_FILE_MODE: u32 = 0o600; -/// The bits a token file must not carry: any group or other permission, write included — a file -/// another user could rewrite is not one this door may trust. +/// The bits a token document must not carry: any group or other permission, write included — a +/// file another user could rewrite is not one this door may trust. const GROUP_OR_OTHER: u32 = 0o077; +/// The most bytes a token document may hold: it names scopes and carries nothing else, so a file +/// larger than this is a wrong path — a log, a data file — rather than a credential (R27). +/// +/// The bound is what keeps the read from being an amount of work the path can choose: the file +/// form re-reads the document on every call, and neither form may hang on a path that never ends. +pub const MAX_TOKEN_DOCUMENT_BYTES: u64 = 4 * 1024; + /// The scopes a token document grants. /// /// Reading is not a scope: every accepted document reads (R28). `write` is the one name a @@ -90,16 +105,17 @@ impl TokenDocument { /// /// An unknown scope is never silently dropped: a document that says `admin` and is read as /// "no scopes" would answer `Forbidden` to calls the operator believed it allowed, with the - /// typo nowhere in sight. - fn scopes(&self) -> Result { + /// typo nowhere in sight. `location` names the document the way [`TokenDocument::parse`] + /// does, so every document refusal says which document is being read. + fn scopes(&self, location: &str) -> Result { let mut scopes = Scopes::read_only(); for name in &self.scopes { if name == SCOPE_WRITE { scopes = Scopes::writing(); } else { return Err(McpError::Credential(format!( - "the admin token document names an unknown scope {name:?}: the accepted set \ - is {ACCEPTED_SCOPES:?}, and reading is granted to every token" + "the admin token document {location} names an unknown scope {name:?}: the \ + accepted set is {ACCEPTED_SCOPES:?}, and reading is granted to every token" ))); } } @@ -137,7 +153,11 @@ impl Credential { /// The same document on a descriptor the parent passed (`--admin-token-fd`), read once. /// - /// It reads a regular file and a pipe alike, from the descriptor's own offset. + /// The descriptor must carry a **regular file**, checked exactly as the file form's target is + /// — type, mode and size, from the metadata of the object the `/proc` path names — because a + /// descriptor is a way to deliver the document, not a way around its rules (R27). The text is + /// then read through that path, which opens the file afresh from its start rather than + /// continuing from whatever offset the parent left. /// /// `shortcut: /proc/self/fd/ is the readable path to an inherited descriptor and needs no /// unsafe — the workspace denies unsafe_code and its one carve-out is the storage crate's @@ -145,15 +165,19 @@ impl Credential { /// point at which a raw-fd handle earns its audited unsafe block` pub fn from_descriptor(fd: i32) -> Result { let path = PathBuf::from(format!("/proc/self/fd/{fd}")); - let text = std::fs::read_to_string(&path).map_err(|error| { + let location = format!("the admin token document on descriptor {fd}"); + let metadata = std::fs::metadata(&path).map_err(|error| { McpError::Credential(format!( "--admin-token-fd {fd} could not be read: {error} — pass the token document on an \ open descriptor, conventionally 3" )) })?; - let document = TokenDocument::parse(&text, &format!("on descriptor {fd}"))?; + checked(&metadata, &location)?; + let text = std::fs::read_to_string(&path).map_err(|error| unreadable(&location, &error))?; + let named = format!("on descriptor {fd}"); + let document = TokenDocument::parse(&text, &named)?; Ok(Self { - source: Source::Delivered(document.scopes()?), + source: Source::Delivered(document.scopes(&named)?), }) } @@ -190,41 +214,58 @@ impl Credential { /// other write bits included — upgrade when a root-run mode has to refuse a file owned by another /// user, which needs a dependency this crate was not given` fn read_file(path: &Path) -> Result { + let location = format!("the admin token file {}", path.display()); + let named = path.display().to_string(); // Before the open: a FIFO's open blocks, so the type has to be known first. - let kind = std::fs::metadata(path).map_err(|error| unreadable(path, &error))?; + let kind = std::fs::metadata(path).map_err(|error| unreadable(&location, &error))?; if !kind.is_file() { - return Err(not_regular(path)); + return Err(not_regular(&location)); } - let mut file = std::fs::File::open(path).map_err(|error| unreadable(path, &error))?; - let metadata = file.metadata().map_err(|error| unreadable(path, &error))?; + let mut file = std::fs::File::open(path).map_err(|error| unreadable(&location, &error))?; + let metadata = file + .metadata() + .map_err(|error| unreadable(&location, &error))?; + checked(&metadata, &location)?; + let mut text = String::new(); + file.read_to_string(&mut text) + .map_err(|error| unreadable(&location, &error))?; + TokenDocument::parse(&text, &named)?.scopes(&named) +} + +/// The three checks both forms make, from the metadata already in hand: a regular file, no group +/// or other permission, and a size the document's bound allows (R27). +/// +/// The metadata is the one the object the location names answers — the descriptor's own for the +/// file form, and the target the `/proc` link resolves to for the descriptor form — so both forms +/// are judged on the same three facts, and neither read is one a caller can grow or stall. +fn checked(metadata: &std::fs::Metadata, location: &str) -> Result<(), McpError> { if !metadata.is_file() { - return Err(not_regular(path)); + return Err(not_regular(location)); } let mode = metadata.permissions().mode() & 0o777; if mode & GROUP_OR_OTHER != 0 { return Err(McpError::Credential(format!( - "the admin token file {} is mode {mode:04o}: it must be {TOKEN_FILE_MODE:04o}, \ - readable and writable by its owner alone", - path.display() + "{location} is mode {mode:04o}: it must carry no group or other permission \ + ({TOKEN_FILE_MODE:04o} is the usual mode), so no one but its owner can rewrite it" ))); } - let mut text = String::new(); - file.read_to_string(&mut text) - .map_err(|error| unreadable(path, &error))?; - TokenDocument::parse(&text, &path.display().to_string())?.scopes() + let size = metadata.len(); + if size > MAX_TOKEN_DOCUMENT_BYTES { + return Err(McpError::Credential(format!( + "{location} is {size} bytes: a token document is at most {MAX_TOKEN_DOCUMENT_BYTES} \ + bytes — it lists scope names and carries nothing else" + ))); + } + Ok(()) } -fn not_regular(path: &Path) -> McpError { +fn not_regular(location: &str) -> McpError { McpError::Credential(format!( - "the admin token file {} is not a regular file: the door re-reads it on every call, and a \ - pipe or a device there would stall that read", - path.display() + "{location} is not a regular file: the document is read as a file of bytes, so a pipe, a \ + device or a directory there would stall that read, never end it, or give it nothing" )) } -fn unreadable(path: &Path, error: &std::io::Error) -> McpError { - McpError::Credential(format!( - "the admin token file {} could not be read: {error}", - path.display() - )) +fn unreadable(location: &str, error: &std::io::Error) -> McpError { + McpError::Credential(format!("{location} could not be read: {error}")) } diff --git a/crates/nostream-mcp/src/lib.rs b/crates/nostream-mcp/src/lib.rs index 23034de6e..9ae77f90f 100644 --- a/crates/nostream-mcp/src/lib.rs +++ b/crates/nostream-mcp/src/lib.rs @@ -31,11 +31,13 @@ mod credential; mod error; mod server; -pub use credential::{ACCEPTED_SCOPES, Credential, SCOPE_WRITE, Scopes, TOKEN_FILE_MODE}; +pub use credential::{ + ACCEPTED_SCOPES, Credential, MAX_TOKEN_DOCUMENT_BYTES, SCOPE_WRITE, Scopes, TOKEN_FILE_MODE, +}; pub use error::McpError; pub use server::{ AUDIT_DENIED, AdminMcp, FORBIDDEN, GetEventArgs, ListEventsArgs, MAX_FILTER_TERMS, - MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, SettingsSetArgs, - TOOL_ARGUMENTS, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, + MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, Requires, SettingsSetArgs, + TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOLS, Tool, UNAUTHORIZED, arguments_parse, audit_action, required_scope, }; diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index aab8683ff..6f3d619f4 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -93,45 +93,94 @@ pub fn audit_action(tool: &str) -> String { format!("mcp.{tool}") } -/// The scope a tool needs beyond the read grant every token carries (R28). +/// The scope a call needs from the document (R28). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Requires { + /// Reading: the grant every accepted document carries, so no scope names it and none is + /// asked for at dispatch. The three read tools say this in the table rather than leaving + /// the column empty. + Read, + /// [`SCOPE_WRITE`]: the one scope a document may add, and the right to call `settings_set`. + Write, +} + +/// One tool the router registers: its name, the check that says whether the router can +/// deserialise a call's arguments (R9), and the scope the call needs (R28). +/// +/// The two facts are one row because they are one decision: a `#[tool]` method added to the +/// router has to appear here once, and both the audit line and the gate read the row it lands +/// in. +#[derive(Debug, Clone, Copy)] +pub struct Tool { + /// The name `tools/list` publishes, which is also its audit action's suffix. + pub name: &'static str, + /// Whether the router can deserialise a call's arguments: the audit line's condition. + pub parses: ArgumentsCheck, + /// What the call needs from the document. + pub needs: Requires, +} + +/// The scope a call needs (R28). /// -/// The three read tools name nothing because reading is the document's default; the one tool that -/// changes the relay is the one a document has to opt into. A tool added to the router without an -/// entry here is a read tool, which is the safe direction: the failure it would produce is a -/// `Forbidden` a case can see, not an unnoticed write. -pub fn required_scope(tool: &str) -> Option<&'static str> { - (tool == TOOL_SETTINGS_SET).then_some(SCOPE_WRITE) +/// A name the table does not carry needs [`Requires::Write`], not [`Requires::Read`]: the router +/// grows one `#[tool]` method at a time, and a tool that arrived without its row is the case to +/// fail closed on. The safe direction is the other way round from the one that reads well — a +/// miss there would let a document that grants nothing but reads call a write — so the default +/// here is the write, and `every_registered_tool_has_a_table_row` (`tests/audit.rs`) reads the +/// router's own list against the table, which makes the missing row a red case rather than a +/// silent grant. +pub fn required_scope(tool: &str) -> Requires { + row(tool).map_or(Requires::Write, |entry| entry.needs) } /// Whether the router can deserialise a call's arguments: the same type its handler takes. type ArgumentsCheck = fn(Option<&Map>) -> bool; -/// The audit table: every tool the router registers, with the check that says whether the -/// router can deserialise a call's arguments (R9). +/// The table: every tool the router registers, once, with both dispatch-time facts (R9, R28). /// -/// The rule each entry keeps is **no stricter than the router's own deserialisation**, not "the -/// shape the `inputSchema` states". [`ServerHandler::call_tool`] writes the line when the check -/// answers `true` and then dispatches unconditionally, so a check that refused a call the router -/// runs would execute it unaudited — R9's guarantee failing open. The check exists to write the -/// line *before* the handler, never to refuse a call; `settings_set`'s is therefore deliberately -/// vacuous, because its arguments are a raw map and its `inputSchema` is the half that refuses. +/// The rule each [`Tool::parses`] keeps is **no stricter than the router's own deserialisation**, +/// not "the shape the `inputSchema` states". [`ServerHandler::call_tool`] writes the line when +/// the check answers `true` and then dispatches unconditionally, so a check that refused a call +/// the router runs would execute it unaudited — R9's guarantee failing open. The check exists to +/// write the line *before* the handler, never to refuse a call; `settings_set`'s is therefore +/// deliberately vacuous, because its arguments are a raw map and its `inputSchema` is the half +/// that refuses. /// -/// The dispatch path looks a name up here and has no "everything else is audited" arm, so a -/// tool added to the router without an entry cannot execute unaudited: it fails -/// `every_registered_tool_is_in_the_audit_table`, which reads the router's own list. -pub const TOOL_ARGUMENTS: &[(&str, ArgumentsCheck)] = &[ - (TOOL_SETTINGS_GET, accepts_any_arguments), - (TOOL_SETTINGS_SET, settings_set_parses), - (TOOL_LIST_EVENTS, list_events_parse), - (TOOL_GET_EVENT, get_event_parses), +/// The dispatch path looks a name up here and has no "everything else" arm, so a tool added to +/// the router without a row cannot execute unaudited, and cannot execute ungated either: +/// `every_registered_tool_has_a_table_row` reads the router's own list, and both +/// [`arguments_parse`] and [`required_scope`] answer this table alone. +pub const TOOLS: &[Tool] = &[ + Tool { + name: TOOL_SETTINGS_GET, + parses: accepts_any_arguments, + needs: Requires::Read, + }, + Tool { + name: TOOL_SETTINGS_SET, + parses: settings_set_parses, + needs: Requires::Write, + }, + Tool { + name: TOOL_LIST_EVENTS, + parses: list_events_parse, + needs: Requires::Read, + }, + Tool { + name: TOOL_GET_EVENT, + parses: get_event_parses, + needs: Requires::Read, + }, ]; -/// Whether `tool`'s arguments parse; `None` when the router registers no such tool. +/// `tool`'s row; `None` when the table does not name it. +fn row(tool: &str) -> Option<&'static Tool> { + TOOLS.iter().find(|entry| entry.name == tool) +} + +/// Whether `tool`'s arguments parse; `None` when the table does not name it. pub fn arguments_parse(tool: &str, arguments: Option<&Map>) -> Option { - TOOL_ARGUMENTS - .iter() - .find(|(name, _)| *name == tool) - .map(|(_, parses)| parses(arguments)) + row(tool).map(|entry| (entry.parses)(arguments)) } /// `settings_get` takes no parameters, so the router deserialises nothing for it. @@ -524,12 +573,12 @@ impl ServerHandler for AdminMcp { return Ok(tool_refusal(refusal).into()); } }; - if let Some(scope) = required_scope(&request.name) - && !scopes.includes(scope) + if let Requires::Write = required_scope(&request.name) + && !scopes.includes(SCOPE_WRITE) { - self.record_denial(&request.name, scope); + self.record_denial(&request.name, SCOPE_WRITE); return Ok(tool_refusal(&format!( - "{FORBIDDEN}: {} needs the \"{scope}\" scope", + "{FORBIDDEN}: {} needs the \"{SCOPE_WRITE}\" scope", request.name )) .into()); diff --git a/crates/nostream-mcp/tests/audit.rs b/crates/nostream-mcp/tests/audit.rs index ccf53fee6..cb17965c1 100644 --- a/crates/nostream-mcp/tests/audit.rs +++ b/crates/nostream-mcp/tests/audit.rs @@ -4,9 +4,8 @@ //! |---|---| //! | `each_call_appends_one_line` | four calls append five lines in call order — the four `mcp.*` lines, then `settings_set`'s own `settings.updated` | //! | `a_refused_call_appends_nothing` | a call with bad arguments and a call with no credential each leave the file untouched | -//! | `every_registered_tool_is_in_the_audit_table` | the audit table is total: no tool the router registers can execute unaudited | +//! | `every_registered_tool_has_a_table_row` | the table is total over the router's own list, so no tool can execute unaudited or ungated | //! | `the_audit_check_is_no_stricter_than_the_router` | the table's rule is the router's deserialiser, not the schema: a stricter check would fail open | -//! //! R9 appends the `mcp.*` line at dispatch, before the handler's work, so the order in the file //! is the order of the calls and a domain line always follows its own dispatch line. The one //! refusal that does write is a credential's scope denial — `mcp.denied`, R28 — and it has its @@ -20,7 +19,7 @@ use std::collections::BTreeSet; use common::{TestMcp, event, id_of, object, text}; use nostream_mcp::{ - TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, audit_action, + TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOLS, audit_action, }; use serde_json::json; @@ -116,12 +115,12 @@ async fn a_refused_call_appends_nothing() { } #[tokio::test] -async fn every_registered_tool_is_in_the_audit_table() { +async fn every_registered_tool_has_a_table_row() { let fixture = TestMcp::start().await; let client = fixture.client().await; // The router's own list: `tools/list` is what `ToolRouter::list_all()` answers, so a tool - // added with a `#[tool]` method and no table entry is in `registered` and nowhere else. + // added with a `#[tool]` method and no row is in `registered` and nowhere else. let registered: BTreeSet = client .tools() .await @@ -130,15 +129,12 @@ async fn every_registered_tool_is_in_the_audit_table() { .collect(); for name in ®istered { assert!( - nostream_mcp::arguments_parse(name, None).is_some(), - "tool {name} is registered but has no TOOL_ARGUMENTS entry, so its calls would \ - execute unaudited" + TOOLS.iter().any(|row| row.name == name), + "tool {name} is registered but has no TOOLS row, so its calls would execute \ + unaudited and with no scope declared" ); } - let tabled: BTreeSet = nostream_mcp::TOOL_ARGUMENTS - .iter() - .map(|(name, _)| (*name).to_owned()) - .collect(); + let tabled: BTreeSet = TOOLS.iter().map(|row| row.name.to_owned()).collect(); assert_eq!( tabled, registered, "the table names exactly the tools the router registers" diff --git a/crates/nostream-mcp/tests/auth.rs b/crates/nostream-mcp/tests/auth.rs index fa08a8dbb..4384c7e1f 100644 --- a/crates/nostream-mcp/tests/auth.rs +++ b/crates/nostream-mcp/tests/auth.rs @@ -1,4 +1,5 @@ -//! AC29–AC34 — the door's own credential: a scoped token document, by file or descriptor. +//! AC29–AC34, AC38, AC39 — the door's own credential: a scoped token document, by file or +//! descriptor, and the scope table that decides what it may call. //! //! | case | what it proves | //! |---|---| @@ -8,7 +9,10 @@ //! | `an_unknown_scope_refuses_the_load` | a document naming a scope the door does not know is refused when it is loaded, naming the scope and the accepted set | //! | `a_file_rewrite_changes_the_decision` | rewriting the file on a running server narrows the write, and rewriting it back restores it: the file's lifetime is the credential's | //! | `an_inherited_descriptor_authenticates` | the descriptor form answers `tools/list` and a read, and keeps the grant it was handed when the file it came from changes | -//! | `only_the_writing_tool_needs_a_scope` | the read tools need no scope, and `settings_set` is the one that does | +//! | `only_the_writing_tool_needs_a_scope` | the table names every registered tool and declares a scope for each: the three read tools read, `settings_set` needs `write`, and a name the table does not carry needs `write` | +//! | `a_group_readable_descriptor_refuses_to_start` | a `0644` document on a descriptor is refused as the same file by path is | +//! | `a_device_descriptor_refuses_to_start` | a device on the descriptor is refused before a byte is read, so `/dev/zero` cannot hang the start | +//! | `an_oversized_document_is_refused` | a document over the size bound is refused on both forms, naming its size and the cap | //! //! Each case builds its own server with the credential as a **value**, and none sets an //! environment variable: cases in one binary run in parallel, so an environment-based credential @@ -19,12 +23,15 @@ mod common; +use std::collections::BTreeSet; use std::os::fd::AsRawFd; +use std::os::unix::fs::PermissionsExt; use common::{Fixture, Grant, TestMcp, text, write_token}; use nostream_mcp::{ - AUDIT_DENIED, Credential, FORBIDDEN, NOT_FOUND, TOOL_GET_EVENT, TOOL_LIST_EVENTS, - TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, UNAUTHORIZED, audit_action, required_scope, + AUDIT_DENIED, Credential, FORBIDDEN, MAX_TOKEN_DOCUMENT_BYTES, NOT_FOUND, Requires, + TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOLS, UNAUTHORIZED, + audit_action, required_scope, }; use serde_json::json; @@ -133,6 +140,12 @@ async fn an_unknown_scope_refuses_the_load() { let message = refused.to_string(); assert!(message.contains("\"admin\""), "{message}"); assert!(message.contains("write"), "the accepted set: {message}"); + // The one document refusal that used to leave the location implicit: it names the file now, + // as the parse refusal beside it does (R27). + assert!( + message.contains(&document.display().to_string()), + "the document it read: {message}" + ); // A document still carrying the retired session token is refused for its shape, not read for // less than it says: the load names the key it did not expect. @@ -145,10 +158,7 @@ async fn an_unknown_scope_refuses_the_load() { // can read is refused before the door serves anything (R27). let readable = temp.path().join("readable.json"); common::write_private(&readable, &common::token_document(&["write"])); - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&readable, std::fs::Permissions::from_mode(0o644)).unwrap(); - } + std::fs::set_permissions(&readable, std::fs::Permissions::from_mode(0o644)).unwrap(); let refused = Credential::from_file(&readable).expect_err("0644 is not 0600"); assert!(refused.to_string().contains("0644"), "{refused}"); assert!(refused.to_string().contains("0600"), "{refused}"); @@ -237,17 +247,108 @@ async fn only_the_writing_tool_needs_a_scope() { let fixture = TestMcp::start().await; let client = fixture.client().await; - let scoped: Vec = client + // The expected sets come from the table's own column and the router's own list, never from + // `required_scope`: a case that filtered `tools/list` through the function under test would + // drop the tool the function has no row for, which is the tool this case exists to catch. + let registered: BTreeSet = client .tools() .await .iter() - .filter(|tool| required_scope(&tool.name).is_some()) .map(|tool| tool.name.to_string()) .collect(); + let tabled: BTreeSet = TOOLS.iter().map(|row| row.name.to_owned()).collect(); + assert_eq!(tabled, registered, "every registered tool declares a scope"); + + let mut reading: Vec<&str> = TOOLS + .iter() + .filter(|row| row.needs == Requires::Read) + .map(|row| row.name) + .collect(); + let mut writing: Vec<&str> = TOOLS + .iter() + .filter(|row| row.needs == Requires::Write) + .map(|row| row.name) + .collect(); + reading.sort_unstable(); + writing.sort_unstable(); + assert_eq!( + reading, + vec![TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_SETTINGS_GET], + "reading is the grant every document carries" + ); assert_eq!( - scoped, - vec![TOOL_SETTINGS_SET.to_owned()], - "reading is the document's default; the one tool that changes the relay is the one it \ - has to opt into" + writing, + vec![TOOL_SETTINGS_SET], + "the one tool that changes the relay is the one a document opts into" + ); + + // A name the table does not carry needs the write: that is what a later slice's tool meets + // before its row lands, and the reason a missing row fails closed rather than open. + assert_eq!(required_scope("delete_event"), Requires::Write); +} + +/// The descriptor is a way to deliver the document, not a way around its rules: a `0644` file on +/// a descriptor is refused as the same file by path is (R27). +#[tokio::test] +async fn a_group_readable_descriptor_refuses_to_start() { + let fixture = TestMcp::start().await; + // The descriptor is opened before the mode widens, so the case refuses the mode and not an + // open. + let file = fixture.descriptor(); + std::fs::set_permissions(&fixture.token_path, std::fs::Permissions::from_mode(0o644)).unwrap(); + + let refused = Credential::from_descriptor(file.as_raw_fd()) + .expect_err("the descriptor's target carries a group permission"); + let message = refused.to_string(); + assert!(message.contains("0644"), "{message}"); + assert!(message.contains("0600"), "the usual mode: {message}"); + assert!( + message.contains("no group or other permission"), + "{message}" + ); +} + +/// A device on the descriptor is refused before a byte is read, so `/dev/zero` — which never ends +/// a read — cannot hang the start (R27). +#[tokio::test] +async fn a_device_descriptor_refuses_to_start() { + let zero = std::fs::File::open("/dev/zero").expect("/dev/zero is a device this host has"); + let refused = Credential::from_descriptor(zero.as_raw_fd()) + .expect_err("a device is not a token document"); + assert!( + refused.to_string().contains("not a regular file"), + "{refused}" + ); +} + +/// The document's size is bounded, so neither read is an amount of work the path chooses: a file +/// over the bound is refused, naming the size it found and the cap (R27). +#[tokio::test] +async fn an_oversized_document_is_refused() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("oversized.json"); + let over = usize::try_from(MAX_TOKEN_DOCUMENT_BYTES).unwrap() + 1; + common::write_private(&path, &" ".repeat(over)); + + let refused = Credential::from_file(&path).expect_err("a document has a size bound"); + let message = refused.to_string(); + assert!( + message.contains(&over.to_string()), + "the size it found: {message}" + ); + assert!( + message.contains(&MAX_TOKEN_DOCUMENT_BYTES.to_string()), + "the cap: {message}" + ); + + // The same bound on the descriptor's target: one comparison on the metadata both forms + // already read. + let file = std::fs::File::open(&path).unwrap(); + let refused = Credential::from_descriptor(file.as_raw_fd()).expect_err("the same bound"); + assert!( + refused + .to_string() + .contains(&MAX_TOKEN_DOCUMENT_BYTES.to_string()), + "{refused}" ); } diff --git a/crates/nostream-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs index 3ffaf92d9..82fbd0fc2 100644 --- a/crates/nostream-mcp/tests/common/mod.rs +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -451,8 +451,8 @@ pub fn write_token(config_dir: &Path, scopes: &[&str]) -> PathBuf { path } -/// Writes `contents` to `path` with mode `0600`: the only mode the token file may carry, so a -/// fixture that wrote anything else would be refused before any case ran (R27). +/// Writes `contents` to `path` at mode `0600`, which satisfies the token document's rule — no +/// group or other permission — so no case is refused at start for its mode (R27). pub fn write_private(path: &Path, contents: &str) { use std::os::unix::fs::PermissionsExt; diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs index 9ff5e1db9..54574dc60 100644 --- a/crates/nostreamd/src/main.rs +++ b/crates/nostreamd/src/main.rs @@ -42,10 +42,12 @@ struct Cli { /// Serve the admin MCP server on stdin/stdout and exit when stdin closes. Binds no socket. /// /// Every call is decided by a scoped token document, delivered either by a regular file - /// (`--admin-token-file `, which must be mode 0600 and is re-read on every call, so - /// deleting or rewriting it revokes or narrows the credential) or on an inherited descriptor + /// (`--admin-token-file `, re-read on every call, so deleting or rewriting it revokes + /// or narrows the credential) or on an inherited descriptor /// (`--admin-token-fd `, read once at start and valid for the life of the process). - /// Exactly one of the two is required. + /// Exactly one of the two is required. Either way the target must be a regular file that + /// carries no group or other permission — 0600 is the usual mode; a 0644 file refuses the + /// start — and at most 4 KiB. /// /// The document is `{"scopes": ["write"]}`; a document with no scopes grants the read tools /// (`settings_get`, `list_events`, `get_event`), and the "write" scope adds `settings_set`. @@ -57,8 +59,9 @@ struct Cli { #[arg(long)] mcp_stdio: bool, - /// The token document the MCP mode reads, on every call. A regular file at mode 0600 or the - /// mode refuses to start; deleting or rewriting the file is the revocation. + /// The token document the MCP mode reads, on every call. A regular file that carries no + /// group or other permission (0600 is the usual mode) or the mode refuses to start; deleting + /// or rewriting the file is the revocation. #[arg( long, value_name = "PATH", @@ -68,7 +71,9 @@ struct Cli { admin_token_file: Option, /// The same token document on an inherited descriptor (conventionally 3), read once at - /// start: the credential then lives as long as the process. + /// start: the credential then lives as long as the process. The descriptor's target is held + /// to the same rule as `--admin-token-file`: a regular file with no group or other + /// permission. #[arg( long, value_name = "N", diff --git a/crates/nostreamd/src/mcp_stdio.rs b/crates/nostreamd/src/mcp_stdio.rs index a32599aec..44682f881 100644 --- a/crates/nostreamd/src/mcp_stdio.rs +++ b/crates/nostreamd/src/mcp_stdio.rs @@ -45,8 +45,8 @@ pub fn resolve_credential(file: Option<&Path>, fd: Option) -> Result (mode 0600) or \ - --admin-token-fd ." + --mcp-stdio. Start the mode with --admin-token-file (a regular file with no \ + group or other permission, 0600 being the usual mode) or --admin-token-fd ." ))); } match (file, fd) { diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index 8398d5b06..a4729a468 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -61,7 +61,8 @@ fn token_document(scopes: &[&str]) -> String { serde_json::to_string(&json!({ "scopes": scopes })).unwrap() } -/// Writes `contents` to `path` at mode 0600, the mode the credential requires (R27). +/// Writes `contents` to `path` at mode 0600: no group or other permission, which is what the +/// credential requires (R27). fn write_private(path: &Path, contents: &str) { std::fs::write(path, contents).unwrap(); std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); @@ -456,12 +457,20 @@ async fn the_help_text_names_the_credential() { .await .expect("the binary answers --help"); assert!(output.status.success(), "--help exits 0"); - let help = String::from_utf8_lossy(&output.stdout); + // Clap wraps at the terminal width, so a phrase needle is matched against the flattened text. + let help = String::from_utf8_lossy(&output.stdout) + .split_whitespace() + .collect::>() + .join(" "); + // The mode rule, not only its usual mode: `0600` is the example, and a `0400` document is + // accepted, so the help has to state the rule the door enforces (R27, R30). for needle in [ "--mcp-stdio", "--admin-token-file", "--admin-token-fd", "NOSTREAM_ADMIN_TOKEN", + "regular file", + "no group or other permission", "0600", "scopes", "write", @@ -469,6 +478,10 @@ async fn the_help_text_names_the_credential() { ] { assert!(help.contains(needle), "the help names `{needle}`: {help}"); } + assert!( + !help.contains("must be mode 0600"), + "the help states the rule rather than an example of it: {help}" + ); } /// Proof 1: a console session token in the retired variable does not start the door — the mode @@ -504,7 +517,13 @@ async fn a_group_readable_token_file_refuses_to_start() { assert_eq!(code, Some(1), "{stderr}"); assert!(stderr.contains("0644"), "the mode it found: {stderr}"); - assert!(stderr.contains("0600"), "the mode it needs: {stderr}"); + assert!(stderr.contains("0600"), "the usual mode: {stderr}"); + // The rule, not only one example of it: `0400` is accepted, so the refusal has to say what it + // enforces (R27). + assert!( + stderr.contains("no group or other permission"), + "the rule it enforces: {stderr}" + ); } /// A FIFO in the token file's place is refused rather than opened: the door re-reads the document From a4b3919546efafb5e85b66557f8accba9e332ed0 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 08:36:25 -0500 Subject: [PATCH 17/24] docs(admin): say the permission rule, not an example of it --- .changeset/admin-mcp-server.md | 9 +-- CONFIGURATION.md | 7 ++- .../decisions/0014-admin-http-surface.md | 60 ++++++++++++------- 3 files changed, 47 insertions(+), 29 deletions(-) diff --git a/.changeset/admin-mcp-server.md b/.changeset/admin-mcp-server.md index dd2dee0f8..cdef18f82 100644 --- a/.changeset/admin-mcp-server.md +++ b/.changeset/admin-mcp-server.md @@ -6,10 +6,11 @@ feat(admin): the admin MCP server, slice 1 — four tools over stdio A new Rust crate serves `settings_get`, `settings_set`, `list_events` and `get_event` on stdin/stdout through `rmcp`, served by `nostreamd --mcp-stdio` as a process of its own over the same config directory. Every call is decided by a scoped token document -the mode is handed by file (`--admin-token-file`, mode 0600, re-read on every call so deleting -or rewriting it is the revocation) or by an inherited descriptor (`--admin-token-fd`, read once -at start); `settings_set` needs the document's `write` scope, and a denied write is refused and -recorded as `mcp.denied`. A console session token no longer authenticates the mode and +the mode is handed by file (`--admin-token-file`, a regular file with no group or other +permission — 0600 is the usual mode — re-read on every call so deleting or rewriting it is the +revocation) or by an inherited descriptor (`--admin-token-fd`, held to the same rules and read +once at start); `settings_set` needs the document's `write` scope, and a denied write is refused +and recorded as `mcp.denied`. A console session token no longer authenticates the mode and `NOSTREAM_ADMIN_TOKEN` is retired: setting it refuses the start. Executed calls are audited to `admin-audit.jsonl` under one `mcp.` action; those names are recorded as ADR 0014 D18 and the credential as D19. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 8389e41ea..94ef9aad3 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -84,8 +84,8 @@ an environment variable. Deliver it one of two ways; exactly one is required: | Flag | What it reads | |---|---| -| `--admin-token-file ` | The document in a **regular** file. It must be mode `0600` (owner read and write, nothing for group or other) or the mode refuses to start, naming the mode it found and the mode it needs; a FIFO, a device or a directory there is refused the same way, because the mode re-opens the file on every call and opening a FIFO waits for a writer. It is re-read on **every call**, so deleting or rewriting it is the revocation: narrowing it to reads takes effect on the next call, with nothing restarted. | -| `--admin-token-fd ` | The same document on an inherited descriptor, conventionally `3` (`exec 3` | The document in a **regular** file that carries **no group or other permission** — `mode & 0o077 == 0`, which `0600` satisfies and a read-only `0400` does too — of at most 4 KiB. Anything else refuses the start, naming what it found: a group- or world-accessible mode, a FIFO, a device or a directory there (the mode re-opens the file on every call, and opening a FIFO waits for a writer), or a file too large to be a document. It is re-read on **every call**, so deleting or rewriting it is the revocation: narrowing it to reads takes effect on the next call, with nothing restarted. | +| `--admin-token-fd ` | The same document on an inherited descriptor, conventionally `3` (`exec 3 /etc/nostream/admin-token.json diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index 9a7cdfe1d..662ea01fe 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -325,17 +325,20 @@ directory is outside ADR 0012 D9 — `admin-audit.jsonl` (whose compaction is a rename on a shared staging path, `crates/nostream-admin/src/state.rs:715-733`) and the settings write both assume one writer per configuration. -**The audit table is total.** Every tool the router registers has its own entry in -`crates/nostream-mcp`'s `TOOL_ARGUMENTS` table, and the dispatch path looks a name up there -instead of defaulting: a tool added without an entry fails -`every_registered_tool_is_in_the_audit_table`, which reads the router's own list, so no call can -execute unaudited. "One line per executed call" therefore means what it says — a call the -router's own deserialiser refuses, and a call to a name the router does not register, reach no -tool and write nothing, and every other call writes its line before the handler runs. The rule an -entry keeps is *no stricter than that deserialiser*, not "the shape the `inputSchema` states": -the line is written before the dispatch, which is unconditional, so a stricter check would let a -call run unaudited. `settings_set`'s entry is therefore vacuous by design — its arguments are a -raw map and its schema is the half that refuses. +**The table is total, and it carries both dispatch-time facts.** Every tool the router registers +has one row in `crates/nostream-mcp`'s `TOOLS` table: its name, the check that says whether the +router can deserialise a call's arguments (R9), and the scope the call needs (R28). The dispatch +path looks a name up there instead of defaulting, and `every_registered_tool_has_a_table_row` +reads the router's own list, so no call can execute unaudited and none can execute ungated. The +scope column names the read tools explicitly and keeps `settings_set` as the only `write`; a name +the table does not carry is answered as `write`, which is the failure-closed default the next +slice's tool meets before its row lands. "One line per executed call" therefore means what it +says — a call the router's own deserialiser refuses, and a call to a name the router does not +register, reach no tool and write nothing, and every other call writes its line before the handler +runs. The rule the argument check keeps is *no stricter than that deserialiser*, not "the shape +the `inputSchema` states": the line is written before the dispatch, which is unconditional, so a +stricter check would let a call run unaudited. `settings_set`'s check is therefore vacuous by +design — its arguments are a raw map and its schema is the half that refuses. ### D19 — The stdio door's credential is a scoped token document of its own @@ -357,8 +360,8 @@ The credential is now the mode's own artifact, a **token document** delivered on | flag | delivery | lifetime | |---|---|---| -| `--admin-token-file ` | a regular file, which must be mode `0600` (`mode & 0o077 == 0`) | **the file's**: it is re-read on the path that decides every call, so deleting or rewriting it is the revocation | -| `--admin-token-fd ` | a descriptor the parent passed, conventionally `3` | **the process's**: it is read once at start, so a rewrite of its source changes nothing until a restart | +| `--admin-token-file ` | a regular file that carries **no group or other permission** (`mode & 0o077 == 0`; `0600` is the usual mode, and a read-only `0400` is accepted) | **the file's**: it is re-read on the path that decides every call, so deleting or rewriting it is the revocation | +| `--admin-token-fd ` | a descriptor the parent passed, conventionally `3`, whose target is held to the same rules as the file form's | **the process's**: it is read once at start, so a rewrite of its source changes nothing until a restart | **One shape: a regular file.** The type is checked on the path before the open and again on the descriptor it was opened as, so a FIFO, a device or a directory is refused rather than opened: a @@ -367,6 +370,13 @@ place would stall a call instead of failing it. The pre-open check is the one ch a FIFO swapped in between it and the open stalls one call, which is the same writer who could drop in their own `0600` document — the boundary below. +**One size, too.** A token document names scopes and carries nothing else, so it is bounded at +4 KiB (`MAX_TOKEN_DOCUMENT_BYTES`) and refused above that, naming the size it found and the cap. +The bound is one comparison on metadata both forms already read: without it the file form's +per-call read would be an amount of work the path chooses, and the descriptor form's single read +could be asked for a `/dev/zero` that never ends — the type check above is what refuses the +device, and the bound is what keeps a wrong path from being simply a large one. + Exactly one of the two is required; both is a refusal, and neither is a refusal naming both. `NOSTREAM_ADMIN_TOKEN` is retired: a mode started with it **refuses to start**, naming the variable and the flag that replaces it, because a silent ignore would leave a half-migrated deployment @@ -383,17 +393,21 @@ document's scopes deny is refused **and audited**: action `mcp.denied`, `detail` `{"tool", "scope"}`, no argument values. A call with no readable document answers `Unauthorized` and appends nothing, because there is nothing to attribute it to — that is D18's rule, unchanged. -**What is deliberately not checked, and why.** Beyond the mode the file must carry, no ownership -check is made: the process's own effective uid is not readable through `std` without adding -`libc`, and `0600` is already the rule that decides who can read the file — including the group -and other *write* bits, which is what would let another user replace the document. A symlink is +**What is deliberately not checked, and why.** Beyond the mode the document must carry, no +ownership check is made: the process's own effective uid is not readable through `std` without +adding `libc`, and the mode rule is already what decides who can rewrite the file — the group and +other *write* bits, which is what would let another user replace the document. A symlink is followed, so a `0600` link to a `0644` target is refused on the target's mode. The descriptor form -has no mode to check: the parent already opened it. - -**Revocation is the file's lifetime, with no server-side store.** The file form opens the path, -fstats **the descriptor it just opened** for the mode and the type, and reads the document from -that same handle — `File::open`, `File::metadata()`, `File::read_to_string` and a small JSON parse -**per call** — measured at `10.6 µs` for a 20-byte document over 10 000 grants in a debug build +is checked rather than excused: `stat` on `/proc/self/fd/` answers the target's type, mode and +size, so a `0644` document on a descriptor is refused exactly as the same file by path is. Its +mode rule does guard less than the file form's, though — the document is read once at start, so a +mode change afterwards can neither escalate nor revoke the grant the process already holds. + +**Revocation is the file's lifetime, with no server-side store.** The file form stats the path for +the type, opens it, then fstats **the descriptor it just opened** for the type, the mode and the +size, and reads the document from that same handle — `std::fs::metadata` by path, `File::open`, +`File::metadata()`, `File::read_to_string` and a small JSON parse **per call** — measured at +`10.6 µs` for a 20-byte document over 10 000 grants in a debug build (`crates/nostream-mcp`'s `Credential::grant`, the same path `call_tool` takes), against a tool call that reaches an LMDB read or a settings write. That is the price of a revocation that needs no session store, no notification path and no restart: narrowing a running door is From 1094c262df137ffc94bb666c48ffdc646c88855b Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 09:26:03 -0500 Subject: [PATCH 18/24] fix(admin): refuse a tool name the tool table does not carry --- crates/nostream-mcp/src/server.rs | 69 +++++++++++++++++++++---------- crates/nostream-mcp/tests/auth.rs | 56 +++++++++++++++++++++---- 2 files changed, 95 insertions(+), 30 deletions(-) diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index 6f3d619f4..1a798475b 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -120,15 +120,21 @@ pub struct Tool { pub needs: Requires, } +/// The router's own answer for a name it does not register, word for word +/// (`ToolRouter::call`, `rmcp`): the door answers an unknown name before the scope decision so a +/// rowless tool is refused rather than dispatched, and it must be the same refusal the router +/// would have given. +const TOOL_NOT_FOUND: &str = "tool not found"; + /// The scope a call needs (R28). /// -/// A name the table does not carry needs [`Requires::Write`], not [`Requires::Read`]: the router -/// grows one `#[tool]` method at a time, and a tool that arrived without its row is the case to -/// fail closed on. The safe direction is the other way round from the one that reads well — a -/// miss there would let a document that grants nothing but reads call a write — so the default -/// here is the write, and `every_registered_tool_has_a_table_row` (`tests/audit.rs`) reads the -/// router's own list against the table, which makes the missing row a red case rather than a -/// silent grant. +/// A name the table does not carry needs [`Requires::Write`], not [`Requires::Read`]: a name the +/// table does not carry is the case to fail closed on, and the safe direction is the other way +/// round from the one that reads well — a miss there would let a document that grants nothing but +/// reads call a write. [`ServerHandler::call_tool`] refuses such a name before it asks this +/// question, with the router's own `tool not found`, so the default is the answer to a total +/// function rather than a path a call travels; `every_registered_tool_has_a_table_row` +/// (`tests/audit.rs`) is what keeps the table and the router one list. pub fn required_scope(tool: &str) -> Requires { row(tool).map_or(Requires::Write, |entry| entry.needs) } @@ -146,10 +152,12 @@ type ArgumentsCheck = fn(Option<&Map>) -> bool; /// deliberately vacuous, because its arguments are a raw map and its `inputSchema` is the half /// that refuses. /// -/// The dispatch path looks a name up here and has no "everything else" arm, so a tool added to -/// the router without a row cannot execute unaudited, and cannot execute ungated either: -/// `every_registered_tool_has_a_table_row` reads the router's own list, and both -/// [`arguments_parse`] and [`required_scope`] answer this table alone. +/// The dispatch path looks a name up here and has no "everything else" arm: a name the table does +/// not carry is refused with the router's own `-32602 tool not found`, before the scope decision +/// and before any line is written, so a tool added to the router without a row is unreachable +/// rather than unaudited — and cannot execute ungated either. `every_registered_tool_has_a_table_row` +/// reads the router's own list, so the two are one list by case as well as by shape, and this +/// refusal is the fallback for the day they are not. pub const TOOLS: &[Tool] = &[ Tool { name: TOOL_SETTINGS_GET, @@ -179,6 +187,9 @@ fn row(tool: &str) -> Option<&'static Tool> { } /// Whether `tool`'s arguments parse; `None` when the table does not name it. +/// +/// `call_tool` refuses such a name before it asks, so the `None` is this function's contract and +/// not a branch a call reaches. pub fn arguments_parse(tool: &str, arguments: Option<&Map>) -> Option { row(tool).map(|entry| (entry.parses)(arguments)) } @@ -467,7 +478,11 @@ impl AdminMcp { /// R28's line: an authenticated call the document's scopes deny. It carries the tool and the /// scope it needed, never an argument value, and it is written before the refusal is /// returned, so a denied write is visible in `admin-audit.jsonl` rather than absent from it. - fn record_denial(&self, tool: &str, scope: &str) { + /// + /// The name is one of [`TOOLS`]' constants rather than the caller's text: `call_tool` refuses + /// a name the table does not carry before it reaches this, so the size of the line is the + /// table's, not the caller's. + fn record_denial(&self, tool: &'static str, scope: &str) { let detail = json!({ "tool": tool, "scope": scope }); if let Err(error) = self.state.append_audit(AUDIT_DENIED, None, Some(detail)) { tracing::warn!(%error, tool, "the MCP denial was not recorded"); @@ -559,8 +574,10 @@ impl ServerHandler for AdminMcp { /// /// `tools/list` is not gated (R8): a client discovers the surface before it presents a /// credential, and the refusal is at the call. The order is the console's — the enabled - /// predicate, then the credential — with the scopes after them, because a scope is only - /// meaningful once the document that names it has been read (R28). + /// predicate, then the credential — after which the table answers: whether the name is one the + /// router serves, then what scope it needs, then whether its arguments parse (R9, R28). A scope + /// is only meaningful once the document that names it has been read, and a name the table does + /// not carry is a refusal rather than a tool. async fn call_tool( &self, request: CallToolRequestParams, @@ -573,21 +590,29 @@ impl ServerHandler for AdminMcp { return Ok(tool_refusal(refusal).into()); } }; - if let Requires::Write = required_scope(&request.name) + // The table answers first, and an absence is a refusal, not a dispatch: a name it does + // not carry is not a tool this router serves, so it is answered exactly as the router + // answers it — `-32602 tool not found` — before the scopes are consulted and before any + // line is written. A tool added to the router without its row is therefore unreachable + // rather than unaudited (R9), and the name a line records is one of these constants. + let Some(entry) = row(&request.name) else { + return Err(rmcp::ErrorData::invalid_params(TOOL_NOT_FOUND, None)); + }; + if let Requires::Write = entry.needs && !scopes.includes(SCOPE_WRITE) { - self.record_denial(&request.name, SCOPE_WRITE); + self.record_denial(entry.name, SCOPE_WRITE); return Ok(tool_refusal(&format!( "{FORBIDDEN}: {} needs the \"{SCOPE_WRITE}\" scope", - request.name + entry.name )) .into()); } - // `Some(false)` — the router answers the deserialisation failure — and `None` — no such - // tool, and the router answers `-32602` — both reach no tool, so neither writes a line - // (R9, Assumption 5). - if let Some(true) = arguments_parse(&request.name, request.arguments.as_ref()) { - self.record_dispatch(&request.name, request.arguments.as_ref()); + // `false` — the router answers a deserialisation failure with its own error result — + // reaches no tool, so it writes no line (R9, Assumption 5); `true` writes the line before + // the handler runs, which is what the check is for. + if (entry.parses)(request.arguments.as_ref()) { + self.record_dispatch(entry.name, request.arguments.as_ref()); } let call = ToolCallContext::new(self, request, context); self.tool_router.call(call).await diff --git a/crates/nostream-mcp/tests/auth.rs b/crates/nostream-mcp/tests/auth.rs index 4384c7e1f..22c89ffcc 100644 --- a/crates/nostream-mcp/tests/auth.rs +++ b/crates/nostream-mcp/tests/auth.rs @@ -10,6 +10,7 @@ //! | `a_file_rewrite_changes_the_decision` | rewriting the file on a running server narrows the write, and rewriting it back restores it: the file's lifetime is the credential's | //! | `an_inherited_descriptor_authenticates` | the descriptor form answers `tools/list` and a read, and keeps the grant it was handed when the file it came from changes | //! | `only_the_writing_tool_needs_a_scope` | the table names every registered tool and declares a scope for each: the three read tools read, `settings_set` needs `write`, and a name the table does not carry needs `write` | +//! | `an_unregistered_tool_is_refused_before_the_scopes` | a name the surface does not register is refused with the router's own `-32602` before the scope decision, so a read-only document writes no denial line for it | //! | `a_group_readable_descriptor_refuses_to_start` | a `0644` document on a descriptor is refused as the same file by path is | //! | `a_device_descriptor_refuses_to_start` | a device on the descriptor is refused before a byte is read, so `/dev/zero` cannot hang the start | //! | `an_oversized_document_is_refused` | a document over the size bound is refused on both forms, naming its size and the cap | @@ -282,11 +283,41 @@ async fn only_the_writing_tool_needs_a_scope() { "the one tool that changes the relay is the one a document opts into" ); - // A name the table does not carry needs the write: that is what a later slice's tool meets - // before its row lands, and the reason a missing row fails closed rather than open. + // A name the table does not carry needs the write: that is this helper's answer for it, and + // the reason a missing row fails closed rather than open. `call_tool` refuses such a name + // before it asks — see `an_unregistered_tool_is_refused_before_the_scopes` — so a rowless tool + // never reaches dispatch at all. assert_eq!(required_scope("delete_event"), Requires::Write); } +/// A name the surface does not register is refused before the scope decision, so a document that +/// grants no write writes nothing for it: the answer is the router's own `-32602 tool not found`, +/// the same one a `write` document gets (R9, R28). A registered tool that arrived without its row +/// is refused by the same check, which is what makes it unreachable rather than unaudited. +#[tokio::test] +async fn an_unregistered_tool_is_refused_before_the_scopes() { + let fixture = TestMcp::start_with(Fixture { + grant: Grant::Read, + ..Fixture::default() + }) + .await; + let client = fixture.client().await; + + let error = client + .try_call("delete_event", json!({})) + .await + .expect_err("a name the table does not carry is not a tool"); + let rmcp::ServiceError::McpError(error) = error else { + panic!("a protocol error, not a transport failure: {error:?}"); + }; + assert_eq!(error.code.0, -32602, "{error:?}"); + assert!(error.message.contains("tool not found"), "{error:?}"); + assert!( + fixture.audit_entries().is_empty(), + "an unknown name is not a denied write, so it writes no line" + ); +} + /// The descriptor is a way to deliver the document, not a way around its rules: a `0644` file on /// a descriptor is refused as the same file by path is (R27). #[tokio::test] @@ -309,16 +340,25 @@ async fn a_group_readable_descriptor_refuses_to_start() { } /// A device on the descriptor is refused before a byte is read, so `/dev/zero` — which never ends -/// a read — cannot hang the start (R27). +/// a read — cannot hang the start (R27). The call runs on a thread of its own under a deadline: +/// the failure this case exists to catch is one that never returns, and a bound inside the case's +/// own thread could not fire on a call that blocks it, so a regression would hang the suite +/// instead of failing it. #[tokio::test] async fn a_device_descriptor_refuses_to_start() { let zero = std::fs::File::open("/dev/zero").expect("/dev/zero is a device this host has"); - let refused = Credential::from_descriptor(zero.as_raw_fd()) + let (sender, receiver) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let answer = Credential::from_descriptor(zero.as_raw_fd()) + .map(|_| ()) + .map_err(|error| error.to_string()); + let _ = sender.send(answer); + }); + let refused = receiver + .recv_timeout(std::time::Duration::from_secs(5)) + .expect("reading /dev/zero as a token document returned in five seconds") .expect_err("a device is not a token document"); - assert!( - refused.to_string().contains("not a regular file"), - "{refused}" - ); + assert!(refused.contains("not a regular file"), "{refused}"); } /// The document's size is bounded, so neither read is an amount of work the path chooses: a file From 59e6fe4961df18d0a4198352ae26518f4daf18ea Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 09:26:05 -0500 Subject: [PATCH 19/24] fix(admin): bound the token document's read, not only its size --- .changeset/admin-mcp-server.md | 13 +-- CONFIGURATION.md | 2 +- crates/nostream-mcp/src/credential.rs | 89 ++++++++++++++++--- crates/nostreamd/src/main.rs | 10 +-- crates/nostreamd/tests/mcp_stdio.rs | 5 +- .../decisions/0014-admin-http-surface.md | 65 ++++++++------ 6 files changed, 134 insertions(+), 50 deletions(-) diff --git a/.changeset/admin-mcp-server.md b/.changeset/admin-mcp-server.md index cdef18f82..9b698f717 100644 --- a/.changeset/admin-mcp-server.md +++ b/.changeset/admin-mcp-server.md @@ -6,13 +6,14 @@ feat(admin): the admin MCP server, slice 1 — four tools over stdio A new Rust crate serves `settings_get`, `settings_set`, `list_events` and `get_event` on stdin/stdout through `rmcp`, served by `nostreamd --mcp-stdio` as a process of its own over the same config directory. Every call is decided by a scoped token document -the mode is handed by file (`--admin-token-file`, a regular file with no group or other -permission — 0600 is the usual mode — re-read on every call so deleting or rewriting it is the -revocation) or by an inherited descriptor (`--admin-token-fd`, held to the same rules and read -once at start); `settings_set` needs the document's `write` scope, and a denied write is refused -and recorded as `mcp.denied`. A console session token no longer authenticates the mode and +the mode is handed by file (`--admin-token-file`, a regular file of at most 4 KiB with no group +or other permission — 0600 is the usual mode — re-read on every call so deleting or rewriting it +is the revocation) or by an inherited descriptor (`--admin-token-fd`, held to the same rules and +read once at start); `settings_set` needs the document's `write` scope, and a denied write is +refused and recorded as `mcp.denied`. A console session token no longer authenticates the mode and `NOSTREAM_ADMIN_TOKEN` is retired: setting it refuses the start. Executed calls are audited to `admin-audit.jsonl` under one `mcp.` action; those names are recorded as ADR 0014 D18 and the credential as D19. -Rust only: no published package changes, so this changeset is deliberately empty. +Rust only: no published package changes, so this entry carries no version bump. The +operator-facing carriers are the mode's `--help`, `CONFIGURATION.md` and ADR 0014 D19. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 94ef9aad3..08269283c 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -110,7 +110,7 @@ The mode also needs `admin.enabled: true` in the settings (else every call answe surface is unchanged and still authenticates with `SECRET` and `POST /admin/login` sessions. Run it from the directory that holds `resources/` — the daemon reads its default settings from -`resources/default-settings.yaml` beside the working directory — and from nowhere else: +`resources/default-settings.yaml`, resolved against the working directory — and from nowhere else: ```sh install -m 0600 /dev/null /etc/nostream/admin-token.json diff --git a/crates/nostream-mcp/src/credential.rs b/crates/nostream-mcp/src/credential.rs index 576940367..e96b561cd 100644 --- a/crates/nostream-mcp/src/credential.rs +++ b/crates/nostream-mcp/src/credential.rs @@ -17,7 +17,8 @@ //! regular file, it must carry **no group or other permission** (`mode & 0o077 == 0`, which a //! `0600` file satisfies and a read-only `0400` one does too), and it must be no larger than //! [`MAX_TOKEN_DOCUMENT_BYTES`]. The checks read the metadata of the object the location names, -//! so a `0644` document is refused whichever way it is delivered (R27). +//! so a `0644` document is refused whichever way it is delivered, and the read itself is bounded +//! too, so a metadata reading the read does not agree with cannot make that read larger (R27). use std::io::Read; use std::os::unix::fs::PermissionsExt; @@ -45,8 +46,12 @@ const GROUP_OR_OTHER: u32 = 0o077; /// The most bytes a token document may hold: it names scopes and carries nothing else, so a file /// larger than this is a wrong path — a log, a data file — rather than a credential (R27). /// -/// The bound is what keeps the read from being an amount of work the path can choose: the file -/// form re-reads the document on every call, and neither form may hang on a path that never ends. +/// The bound holds twice: `checked` refuses the document from the metadata both forms already +/// read, and [`read_bounded`] stops the read one byte past it. Either alone would leave a path the +/// other misses — a `st_size` of `0` on a procfs file, a document a writer grows between the stat +/// and the read — and the file form re-reads the document on every call, so the read is what has +/// to stay the same amount of work whatever the path answers. Neither form may hang on a path +/// that never ends: the type check refuses a pipe or a device before the read. pub const MAX_TOKEN_DOCUMENT_BYTES: u64 = 4 * 1024; /// The scopes a token document grants. @@ -173,7 +178,8 @@ impl Credential { )) })?; checked(&metadata, &location)?; - let text = std::fs::read_to_string(&path).map_err(|error| unreadable(&location, &error))?; + let file = std::fs::File::open(&path).map_err(|error| unreadable(&location, &error))?; + let text = read_bounded(file, &location)?; let named = format!("on descriptor {fd}"); let document = TokenDocument::parse(&text, &named)?; Ok(Self { @@ -221,23 +227,45 @@ fn read_file(path: &Path) -> Result { if !kind.is_file() { return Err(not_regular(&location)); } - let mut file = std::fs::File::open(path).map_err(|error| unreadable(&location, &error))?; + let file = std::fs::File::open(path).map_err(|error| unreadable(&location, &error))?; let metadata = file .metadata() .map_err(|error| unreadable(&location, &error))?; checked(&metadata, &location)?; - let mut text = String::new(); - file.read_to_string(&mut text) - .map_err(|error| unreadable(&location, &error))?; + let text = read_bounded(file, &location)?; TokenDocument::parse(&text, &named)?.scopes(&named) } +/// The document's text, with the bound applied to the read itself and not only to the metadata. +/// +/// [`checked`] refuses the document from a size both forms already hold; this is the half that +/// holds when the two disagree — a procfs file whose `st_size` is `0`, or a document a writer grows +/// between the `stat` and the read. `take` stops one byte past the cap, so the read is bounded +/// whatever the path answers, and a document that outgrew its metadata is refused naming the cap +/// rather than read whole. +fn read_bounded(source: impl Read, location: &str) -> Result { + let cap = usize::try_from(MAX_TOKEN_DOCUMENT_BYTES).unwrap_or(usize::MAX); + let mut text = String::new(); + source + .take(MAX_TOKEN_DOCUMENT_BYTES + 1) + .read_to_string(&mut text) + .map_err(|error| unreadable(location, &error))?; + if text.len() > cap { + return Err(McpError::Credential(format!( + "{location} carries more than {MAX_TOKEN_DOCUMENT_BYTES} bytes: a token document is at \ + most that many — it lists scope names and carries nothing else" + ))); + } + Ok(text) +} + /// The three checks both forms make, from the metadata already in hand: a regular file, no group /// or other permission, and a size the document's bound allows (R27). /// /// The metadata is the one the object the location names answers — the descriptor's own for the /// file form, and the target the `/proc` link resolves to for the descriptor form — so both forms -/// are judged on the same three facts, and neither read is one a caller can grow or stall. +/// are judged on the same three facts, and neither read is one a caller can grow or stall, because +/// [`read_bounded`] holds the read to the same size this check refuses on. fn checked(metadata: &std::fs::Metadata, location: &str) -> Result<(), McpError> { if !metadata.is_file() { return Err(not_regular(location)); @@ -246,7 +274,8 @@ fn checked(metadata: &std::fs::Metadata, location: &str) -> Result<(), McpError> if mode & GROUP_OR_OTHER != 0 { return Err(McpError::Credential(format!( "{location} is mode {mode:04o}: it must carry no group or other permission \ - ({TOKEN_FILE_MODE:04o} is the usual mode), so no one but its owner can rewrite it" + ({TOKEN_FILE_MODE:04o} is the usual mode), so no one but its owner can read or \ + rewrite it" ))); } let size = metadata.len(); @@ -269,3 +298,43 @@ fn not_regular(location: &str) -> McpError { fn unreadable(location: &str, error: &std::io::Error) -> McpError { McpError::Credential(format!("{location} could not be read: {error}")) } + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use std::io::Cursor; + + use super::*; + + /// [`checked`] refuses the document from metadata; the read does not trust it. A reader that + /// answers more than the metadata did — a procfs file whose `st_size` is `0`, a document a + /// writer grew between the `stat` and the read — is stopped one byte past the cap rather than + /// read whole (R27), which is what the `take` in [`read_bounded`] is for. + #[test] + fn the_read_stops_one_byte_past_the_cap() { + let cap = usize::try_from(MAX_TOKEN_DOCUMENT_BYTES).unwrap(); + let mut document = Cursor::new(vec![b' '; cap * 2]); + let refused = read_bounded(&mut document, "the document").expect_err("a read past the cap"); + assert!( + refused.to_string().contains("more than 4096"), + "the refusal names the cap: {refused}" + ); + // Without the `take` the read runs to the end of whatever the path answers, which is how + // a `st_size` of `0` became a 103 539-byte read. + assert_eq!( + document.position(), + MAX_TOKEN_DOCUMENT_BYTES + 1, + "the read stopped one byte past the cap" + ); + } + + /// A document inside the cap is read whole: the bound refuses the wrong path, not the + /// credential. + #[test] + fn a_document_at_the_cap_is_read() { + let cap = usize::try_from(MAX_TOKEN_DOCUMENT_BYTES).unwrap(); + let document = Cursor::new(vec![b' '; cap]); + assert_eq!(read_bounded(document, "the document").unwrap().len(), cap); + } +} diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs index 54574dc60..6342e9c0f 100644 --- a/crates/nostreamd/src/main.rs +++ b/crates/nostreamd/src/main.rs @@ -59,9 +59,9 @@ struct Cli { #[arg(long)] mcp_stdio: bool, - /// The token document the MCP mode reads, on every call. A regular file that carries no - /// group or other permission (0600 is the usual mode) or the mode refuses to start; deleting - /// or rewriting the file is the revocation. + /// The token document the MCP mode reads, on every call. A regular file of at most 4 KiB that + /// carries no group or other permission (0600 is the usual mode) or the mode refuses to + /// start; deleting or rewriting the file is the revocation. #[arg( long, value_name = "PATH", @@ -72,8 +72,8 @@ struct Cli { /// The same token document on an inherited descriptor (conventionally 3), read once at /// start: the credential then lives as long as the process. The descriptor's target is held - /// to the same rule as `--admin-token-file`: a regular file with no group or other - /// permission. + /// to the same rule as `--admin-token-file`: a regular file of at most 4 KiB with no group or + /// other permission. #[arg( long, value_name = "N", diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index a4729a468..663c0e5a6 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -463,7 +463,9 @@ async fn the_help_text_names_the_credential() { .collect::>() .join(" "); // The mode rule, not only its usual mode: `0600` is the example, and a `0400` document is - // accepted, so the help has to state the rule the door enforces (R27, R30). + // accepted, so the help has to state the rule the door enforces (R27, R30). `4 KiB` is there + // for the same reason: the size rule is a refusal an operator meets, and the flag entries + // state it beside the mode rule rather than leaving it to the mode's paragraph. for needle in [ "--mcp-stdio", "--admin-token-file", @@ -472,6 +474,7 @@ async fn the_help_text_names_the_credential() { "regular file", "no group or other permission", "0600", + "4 KiB", "scopes", "write", "admin.enabled", diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index 662ea01fe..53a1223aa 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -331,14 +331,18 @@ router can deserialise a call's arguments (R9), and the scope the call needs (R2 path looks a name up there instead of defaulting, and `every_registered_tool_has_a_table_row` reads the router's own list, so no call can execute unaudited and none can execute ungated. The scope column names the read tools explicitly and keeps `settings_set` as the only `write`; a name -the table does not carry is answered as `write`, which is the failure-closed default the next -slice's tool meets before its row lands. "One line per executed call" therefore means what it -says — a call the router's own deserialiser refuses, and a call to a name the router does not -register, reach no tool and write nothing, and every other call writes its line before the handler -runs. The rule the argument check keeps is *no stricter than that deserialiser*, not "the shape -the `inputSchema` states": the line is written before the dispatch, which is unconditional, so a -stricter check would let a call run unaudited. `settings_set`'s check is therefore vacuous by -design — its arguments are a raw map and its schema is the half that refuses. +the table does not carry is **refused there**, with the router's own `-32602 tool not found`, +before the scope decision and before any line is written — so a tool that arrived without its row +is unreachable rather than unaudited, and the name an audit line records is always one of the +table's constants. The scope column's own default (`required_scope` answers `write` for a name the +table lacks) is the helper's answer to a question `call_tool` no longer has to ask, not a path a +call travels. "One line per executed call" therefore means what it says — a call the router's own +deserialiser refuses, and a call to a name the router does not register, reach no tool and write +nothing, and every other call writes its line before the handler runs. The rule the argument check +keeps is *no stricter than that deserialiser*, not "the shape the `inputSchema` states": the line +is written before the dispatch, which is unconditional, so a stricter check would let a call run +unaudited. `settings_set`'s check is therefore vacuous by design — its arguments are a raw map and +its schema is the half that refuses. ### D19 — The stdio door's credential is a scoped token document of its own @@ -370,12 +374,18 @@ place would stall a call instead of failing it. The pre-open check is the one ch a FIFO swapped in between it and the open stalls one call, which is the same writer who could drop in their own `0600` document — the boundary below. -**One size, too.** A token document names scopes and carries nothing else, so it is bounded at -4 KiB (`MAX_TOKEN_DOCUMENT_BYTES`) and refused above that, naming the size it found and the cap. -The bound is one comparison on metadata both forms already read: without it the file form's -per-call read would be an amount of work the path chooses, and the descriptor form's single read -could be asked for a `/dev/zero` that never ends — the type check above is what refuses the -device, and the bound is what keeps a wrong path from being simply a large one. +**One size, too, and it bounds the read.** A token document names scopes and carries nothing else, +so it is bounded at 4 KiB (`MAX_TOKEN_DOCUMENT_BYTES`) and refused above that, naming the size it +found and the cap. The bound is applied twice, because one place is not enough: a comparison on +metadata both forms already read refuses a document that says it is large, and the read itself is +taken through `take(cap + 1)` so a document that does not say so is still refused rather than read +whole — a procfs file whose `st_size` is `0` (`/proc/self/environ` answers `0` and then a body as +long as the environment is), or a document a writer grows between the `stat` and the read. Without +the first, the file form's per-call read would be an amount of work the path chooses; without the +second it would be an amount the path's own metadata chooses. The descriptor form's single read +could be asked for a +`/dev/zero` that never ends — the type check above is what refuses the device — and the bound is +what keeps a wrong path from being simply a large one. Exactly one of the two is required; both is a refusal, and neither is a refusal naming both. `NOSTREAM_ADMIN_TOKEN` is retired: a mode started with it **refuses to start**, naming the variable @@ -395,23 +405,24 @@ and appends nothing, because there is nothing to attribute it to — that is D18 **What is deliberately not checked, and why.** Beyond the mode the document must carry, no ownership check is made: the process's own effective uid is not readable through `std` without -adding `libc`, and the mode rule is already what decides who can rewrite the file — the group and -other *write* bits, which is what would let another user replace the document. A symlink is -followed, so a `0600` link to a `0644` target is refused on the target's mode. The descriptor form -is checked rather than excused: `stat` on `/proc/self/fd/` answers the target's type, mode and -size, so a `0644` document on a descriptor is refused exactly as the same file by path is. Its -mode rule does guard less than the file form's, though — the document is read once at start, so a -mode change afterwards can neither escalate nor revoke the grant the process already holds. +adding `libc`, and the mode rule is already what decides who may read the document and who may +replace it — any group or other bit, so a `0640` file is refused for its group *read* exactly as +a `0660` one is for its group *write*. A symlink is followed, so a `0600` link to a `0644` +target is refused on the target's mode. The descriptor form is checked rather than excused: +`stat` on `/proc/self/fd/` answers the target's type, mode and size, so a `0644` document on a +descriptor is refused exactly as the same file by path is. Its mode rule does guard less than the +file form's, though — the document is read once at start, so a mode change afterwards can neither +escalate nor revoke the grant the process already holds. **Revocation is the file's lifetime, with no server-side store.** The file form stats the path for the type, opens it, then fstats **the descriptor it just opened** for the type, the mode and the size, and reads the document from that same handle — `std::fs::metadata` by path, `File::open`, -`File::metadata()`, `File::read_to_string` and a small JSON parse **per call** — measured at -`10.6 µs` for a 20-byte document over 10 000 grants in a debug build -(`crates/nostream-mcp`'s `Credential::grant`, the same path `call_tool` takes), against a tool call -that reaches an LMDB read or a settings write. That is the price of a revocation that -needs no session store, no notification path and no restart: narrowing a running door is -`printf '{"scopes": []}' >` the file. +`File::metadata()`, `File::read_to_string` through the `take` the size paragraph names, and a small +JSON parse **per call** — measured at `10.6 µs` for a 20-byte document over 10 000 grants in a +debug build (`crates/nostream-mcp`'s `Credential::grant`, the same path `call_tool` takes), +against a tool call that reaches an LMDB read or a settings write. That is the price of a +revocation that needs no session store, no notification path and no restart: narrowing a running +door is `printf '{"scopes": []}' >` the file. The descriptor form's asymmetry is stated rather than implied away, in `CONFIGURATION.md`, in the mode's `--help`, in the crate's docs and here: it is read once, so its lifetime is the process's. From 2c977e87f2d8d599d468cc6b52fa116ec8a0f192 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 10:07:47 -0500 Subject: [PATCH 20/24] test(admind): assert the size rule inside each flag entry --- crates/nostreamd/tests/mcp_stdio.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index 663c0e5a6..6e09e9b62 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -463,9 +463,7 @@ async fn the_help_text_names_the_credential() { .collect::>() .join(" "); // The mode rule, not only its usual mode: `0600` is the example, and a `0400` document is - // accepted, so the help has to state the rule the door enforces (R27, R30). `4 KiB` is there - // for the same reason: the size rule is a refusal an operator meets, and the flag entries - // state it beside the mode rule rather than leaving it to the mode's paragraph. + // accepted, so the help has to state the rule the door enforces (R27, R30). for needle in [ "--mcp-stdio", "--admin-token-file", @@ -474,13 +472,35 @@ async fn the_help_text_names_the_credential() { "regular file", "no group or other permission", "0600", - "4 KiB", "scopes", "write", "admin.enabled", ] { assert!(help.contains(needle), "the help names `{needle}`: {help}"); } + // The size rule is asserted inside each flag entry's own slice, not against the page: one + // `4 KiB` anywhere satisfies a page-wide needle, and the mode paragraph carried it alone while + // both flag entries omitted it. The labels include clap's value name, so the mode paragraph's + // mention of a flag is not mistaken for that flag's entry. + let labels = [ + "--mcp-stdio", + "--admin-token-file ", + "--admin-token-fd ", + ]; + for (index, label) in labels.iter().enumerate() { + let start = help + .find(*label) + .unwrap_or_else(|| panic!("the help names `{label}`: {help}")); + let end = labels + .get(index + 1) + .and_then(|next| help[start..].find(*next)) + .map_or(help.len(), |offset| start + offset); + let entry = &help[start..end]; + assert!( + entry.contains("4 KiB"), + "the `{label}` entry states the size rule: {entry}" + ); + } assert!( !help.contains("must be mode 0600"), "the help states the rule rather than an example of it: {help}" From d54a6dbbe8594f68c53b11f9d9d40e2e1c6f1e29 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 10:07:51 -0500 Subject: [PATCH 21/24] fix(admin): refuse a name the router does not dispatch --- crates/nostream-mcp/src/server.rs | 63 ++++++++++++++++++---- crates/nostream-mcp/tests/tool_payloads.rs | 8 +++ 2 files changed, 61 insertions(+), 10 deletions(-) diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index 1a798475b..a28d40056 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -186,6 +186,18 @@ fn row(tool: &str) -> Option<&'static Tool> { TOOLS.iter().find(|entry| entry.name == tool) } +/// `tool`'s row, when the router dispatches it too: the door serves a name the table carries +/// **and** the router's own map holds (D18). +/// +/// The two lists are one by case — `every_registered_tool_has_a_table_row`, and the equality +/// `tests/audit.rs` and `tests/auth.rs` assert — but a call is dispatched from the router's map, +/// so that is the membership the refusal asks as well: a row whose `#[tool]` method is absent is +/// refused exactly as a name the table does not carry is, rather than audited for a call that +/// reaches no tool. +fn served(router: &ToolRouter, tool: &str) -> Option<&'static Tool> { + row(tool).filter(|entry| router.has_route(entry.name)) +} + /// Whether `tool`'s arguments parse; `None` when the table does not name it. /// /// `call_tool` refuses such a name before it asks, so the `None` is this function's contract and @@ -574,10 +586,10 @@ impl ServerHandler for AdminMcp { /// /// `tools/list` is not gated (R8): a client discovers the surface before it presents a /// credential, and the refusal is at the call. The order is the console's — the enabled - /// predicate, then the credential — after which the table answers: whether the name is one the - /// router serves, then what scope it needs, then whether its arguments parse (R9, R28). A scope - /// is only meaningful once the document that names it has been read, and a name the table does - /// not carry is a refusal rather than a tool. + /// predicate, then the credential — after which the name is asked of the table **and** the + /// router: is it one this door serves, then what scope it needs, then whether its arguments + /// parse (R9, R28). A scope is only meaningful once the document that names it has been read, + /// and a name either of them does not carry is a refusal rather than a tool. async fn call_tool( &self, request: CallToolRequestParams, @@ -590,12 +602,13 @@ impl ServerHandler for AdminMcp { return Ok(tool_refusal(refusal).into()); } }; - // The table answers first, and an absence is a refusal, not a dispatch: a name it does - // not carry is not a tool this router serves, so it is answered exactly as the router - // answers it — `-32602 tool not found` — before the scopes are consulted and before any - // line is written. A tool added to the router without its row is therefore unreachable - // rather than unaudited (R9), and the name a line records is one of these constants. - let Some(entry) = row(&request.name) else { + // The table and the router answer together, and an absence from either is a refusal, not + // a dispatch: a name neither serves is answered exactly as the router answers it — + // `-32602 tool not found` — before the scopes are consulted and before any line is + // written. A tool added to the router without its row is therefore unreachable rather + // than unaudited, and a row whose method is absent writes no line for a call that reached + // nothing (R9, D18); the name a line records is one of these constants. + let Some(entry) = served(&self.tool_router, &request.name) else { return Err(rmcp::ErrorData::invalid_params(TOOL_NOT_FOUND, None)); }; if let Requires::Write = entry.needs @@ -647,6 +660,7 @@ fn tool_refusal(text: &str) -> CallToolResult { CallToolResult::error(vec![ContentBlock::text(text)]) } + /// A refusal body as an `isError: true` result — the controller's own JSON, rendered (R13). fn tool_error_body(body: &Value) -> CallToolResult { CallToolResult::error(vec![ContentBlock::text(body.to_string())]) @@ -664,3 +678,32 @@ fn tool_ok(payload: Value) -> CallToolResult { result.is_error = Some(false); result } + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use super::*; + + /// The door serves a name the table carries **and** the router dispatches. `TOOLS` is a + /// `const`, so a row with no `#[tool]` method cannot be added by a case; removing the route + /// from the router's `map` is the same disagreement from the other side, and it is the state + /// D18 forbids a line for: the table's `row` still answers, the dispatch does not. + #[test] + fn a_row_without_a_route_is_not_served() { + let mut router = AdminMcp::tool_router(); + assert!( + served(&router, TOOL_SETTINGS_GET).is_some(), + "the row and the route agree to begin with" + ); + router.map.remove(TOOL_SETTINGS_GET); + assert!( + row(TOOL_SETTINGS_GET).is_some(), + "the table still carries the name" + ); + assert!( + served(&router, TOOL_SETTINGS_GET).is_none(), + "the router's map decides dispatch, so it decides the refusal" + ); + } +} diff --git a/crates/nostream-mcp/tests/tool_payloads.rs b/crates/nostream-mcp/tests/tool_payloads.rs index f2995ff5a..e70952799 100644 --- a/crates/nostream-mcp/tests/tool_payloads.rs +++ b/crates/nostream-mcp/tests/tool_payloads.rs @@ -338,6 +338,14 @@ async fn an_unknown_tool_is_a_protocol_error() { }; assert_eq!(error.code.0, -32602, "{error:?}"); assert!(error.message.contains("tool not found"), "{error:?}"); + // The refusal precedes the scope decision and the dispatch line on this arm too: the read-only + // arm's case asserts the same empty file (`tests/auth.rs`), and this is the one that would have + // caught a line for a call that reached no tool. + assert!( + fixture.audit_entries().is_empty(), + "an absent name writes no line: {:?}", + fixture.audit_entries() + ); } #[tokio::test] From 6b71490106031769d2c1b077b0c5d150403d49b4 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 10:08:00 -0500 Subject: [PATCH 22/24] perf(admin): reserve the token document's read buffer --- crates/nostream-mcp/src/credential.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/nostream-mcp/src/credential.rs b/crates/nostream-mcp/src/credential.rs index e96b561cd..74e26fb0c 100644 --- a/crates/nostream-mcp/src/credential.rs +++ b/crates/nostream-mcp/src/credential.rs @@ -243,9 +243,13 @@ fn read_file(path: &Path) -> Result { /// between the `stat` and the read. `take` stops one byte past the cap, so the read is bounded /// whatever the path answers, and a document that outgrew its metadata is refused naming the cap /// rather than read whole. +/// +/// The buffer is reserved once, at the bound, because the `take` alone would let the read grow it +/// to fit: a bare `String` is a doubling sequence above the first 32 bytes — 8 reallocations and 9 +/// `read` calls for a 4 KiB document, against 0 and 2 reserved here. fn read_bounded(source: impl Read, location: &str) -> Result { let cap = usize::try_from(MAX_TOKEN_DOCUMENT_BYTES).unwrap_or(usize::MAX); - let mut text = String::new(); + let mut text = String::with_capacity(cap + 1); source .take(MAX_TOKEN_DOCUMENT_BYTES + 1) .read_to_string(&mut text) @@ -253,7 +257,7 @@ fn read_bounded(source: impl Read, location: &str) -> Result { if text.len() > cap { return Err(McpError::Credential(format!( "{location} carries more than {MAX_TOKEN_DOCUMENT_BYTES} bytes: a token document is at \ - most that many — it lists scope names and carries nothing else" + most {MAX_TOKEN_DOCUMENT_BYTES} bytes — it lists scope names and carries nothing else" ))); } Ok(text) @@ -337,4 +341,19 @@ mod tests { let document = Cursor::new(vec![b' '; cap]); assert_eq!(read_bounded(document, "the document").unwrap().len(), cap); } + + /// The bound is the buffer as well as the refusal: the read reserves `cap + 1` once, so a + /// document it accepts is one allocation and two reads. A bare `String` grew to fit instead — + /// 256 bytes of capacity for a 100-byte document, and a doubling sequence above that. + #[test] + fn the_read_reserves_the_buffer_once() { + let cap = usize::try_from(MAX_TOKEN_DOCUMENT_BYTES).unwrap(); + let document = Cursor::new(vec![b' '; 100]); + let text = read_bounded(document, "the document").unwrap(); + assert_eq!( + text.capacity(), + cap + 1, + "the read reserves the bound once rather than growing to fit" + ); + } } From 2886cb7296094dbe5d2884c38ee886392d63bb29 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 10:08:04 -0500 Subject: [PATCH 23/24] fix(admin): cut and escape the caller's name in the log --- crates/nostream-mcp/src/server.rs | 32 ++++++++++++++++++- crates/nostreamd/tests/mcp_stdio.rs | 48 +++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 1 deletion(-) diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index a28d40056..8d292af6c 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -598,7 +598,11 @@ impl ServerHandler for AdminMcp { let scopes = match self.grant() { Ok(scopes) => scopes, Err(refusal) => { - tracing::warn!(tool = %request.name, refusal, "the MCP call was refused"); + // The caller's text reaches one record on this arm, and it is written before any + // credential is checked: the line carries a cut, escaped prefix, so the name can + // neither size it nor end it and start one of its own. + let name = logged_name(&request.name); + tracing::warn!(tool = %name, refusal, "the MCP call was refused"); return Ok(tool_refusal(refusal).into()); } }; @@ -660,6 +664,20 @@ fn tool_refusal(text: &str) -> CallToolResult { CallToolResult::error(vec![ContentBlock::text(text)]) } +/// The most of a caller's tool name a log line carries: the log is a diagnostic, and the name is +/// the caller's text on an arm reached before any credential. +const LOGGED_NAME_CHARS: usize = 64; + +/// Caller text as a log line may carry it: at most [`LOGGED_NAME_CHARS`] characters, with anything +/// that is not printable escaped, so a name can neither set the line's length nor end it and start +/// one of its own. The audit file's caller-text sink is closed the same way — `record_denial` +/// takes a [`TOOLS`] constant — and this is the remaining place a caller chooses a record's shape. +fn logged_name(name: &str) -> String { + name.chars() + .take(LOGGED_NAME_CHARS) + .flat_map(|character| character.escape_debug()) + .collect() +} /// A refusal body as an `isError: true` result — the controller's own JSON, rendered (R13). fn tool_error_body(body: &Value) -> CallToolResult { @@ -706,4 +724,16 @@ mod tests { "the router's map decides dispatch, so it decides the refusal" ); } + + /// The log line takes a prefix of the caller's name and no control character from it: the + /// name is unbounded and newline-capable, the line is neither. + #[test] + fn a_logged_name_is_cut_and_escaped() { + assert_eq!(logged_name(&"n".repeat(200_000)).len(), LOGGED_NAME_CHARS); + assert_eq!( + logged_name("probe\nWARN forged line"), + r"probe\nWARN forged line" + ); + assert_eq!(logged_name(TOOL_SETTINGS_GET), TOOL_SETTINGS_GET); + } } diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index 6e09e9b62..74a774f55 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -17,6 +17,7 @@ //! | `a_fifo_token_file_refuses_to_start` | a FIFO in the token file's place is refused, not opened: a read of one would stall the door | //! | `the_mode_needs_one_credential_flag` | neither flag is an error naming both, and both is an error naming both | //! | `an_inherited_descriptor_authenticates` | a document delivered on descriptor 3 answers `tools/list` and a read, with nothing on the command line or in the environment | +//! | `a_caller_chosen_name_cannot_size_or_forge_the_log` | the one arm reached before any credential cuts and escapes the caller's name, so the log cannot be sized or forged by it | //! //! The dialogue is hand-written JSON-RPC over the child's pipes: this target proves a property //! of the process, so it spawns the binary the way an MCP client does. @@ -701,3 +702,50 @@ async fn the_relay_path_still_needs_a_secret_for_payments() { "{stderr}" ); } + +/// The log line an unauthenticated call reaches carries a cut and escaped name. That arm runs +/// before any credential is checked, so the caller chooses the only text on it: the line must +/// neither take its length from that text nor let a newline in it start a line of the log's own +/// (R28 leaves the name unbounded, and the audit file's own caller-text sink was closed the same +/// way — `record_denial` takes a table constant). +#[tokio::test] +async fn a_caller_chosen_name_cannot_size_or_forge_the_log() { + let prepared = Prepared::new(); + let mut daemon = Daemon::start(&prepared, &[]); + daemon.initialize().await; + // Deleting the document is the revocation (R29), and it is what puts these calls on the arm + // that logs before it refuses. + std::fs::remove_file(&prepared.token).expect("the token file is the fixture's"); + + // Wide enough that a line carrying it is unmistakably the caller's, short enough that the + // write itself cannot fill an undrained stderr pipe: at 200 000 characters the log write + // blocks the daemon before it answers at all, which is the same sink measured a second way. + let long = "n".repeat(4_000); + let refused = daemon.call(&long, json!({})).await; + let forged = "probe\nWARN forged line"; + let injected = daemon.call(forged, json!({})).await; + let outcome = daemon.finish().await; + + for response in [&refused, &injected] { + assert_eq!(response["result"]["isError"], true, "{response}"); + assert_eq!( + response["result"]["content"][0]["text"], "Unauthorized", + "{response}" + ); + } + assert!( + !outcome.stderr.contains(&long), + "the log carries a prefix of the name, not the name: {} bytes of stderr", + outcome.stderr.len() + ); + assert!( + !outcome.stderr.contains("\nWARN forged line"), + "a newline in the name cannot start a line of the log's own: {}", + outcome.stderr + ); + assert!( + outcome.stderr.lines().all(|line| line.len() < 1024), + "every log line is a line, not a payload: {:?}", + outcome.stderr.lines().max_by_key(|line| line.len()) + ); +} From 3c83570b8dd1b1421daee4514cf4010b44c4470d Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 20 Nov 2026 10:08:04 -0500 Subject: [PATCH 24/24] docs(admin): say what D18's refusal asks and what D19's read names --- .../decisions/0014-admin-http-surface.md | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index 53a1223aa..507e9048b 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -334,10 +334,14 @@ scope column names the read tools explicitly and keeps `settings_set` as the onl the table does not carry is **refused there**, with the router's own `-32602 tool not found`, before the scope decision and before any line is written — so a tool that arrived without its row is unreachable rather than unaudited, and the name an audit line records is always one of the -table's constants. The scope column's own default (`required_scope` answers `write` for a name the -table lacks) is the helper's answer to a question `call_tool` no longer has to ask, not a path a -call travels. "One line per executed call" therefore means what it says — a call the router's own -deserialiser refuses, and a call to a name the router does not register, reach no tool and write +table's constants. The refusal asks the router as well as the table: the two are one list by +case, but a call is dispatched from the router's own map, so a name is served only when both +carry it — a row whose `#[tool]` method is absent is refused exactly as an absent row is, rather +than answered `-32602` after a line was written for a call that reached no tool. The scope +column's own default (`required_scope` answers `write` for a name the table lacks) is the +helper's answer to a question `call_tool` no longer has to ask, not a path a call travels. "One +line per executed call" therefore means what it says — a call the router's own deserialiser +refuses, and a call to a name neither the table nor the router carries, reach no tool and write nothing, and every other call writes its line before the handler runs. The rule the argument check keeps is *no stricter than that deserialiser*, not "the shape the `inputSchema` states": the line is written before the dispatch, which is unconditional, so a stricter check would let a call run @@ -375,17 +379,19 @@ a FIFO swapped in between it and the open stalls one call, which is the same wri drop in their own `0600` document — the boundary below. **One size, too, and it bounds the read.** A token document names scopes and carries nothing else, -so it is bounded at 4 KiB (`MAX_TOKEN_DOCUMENT_BYTES`) and refused above that, naming the size it -found and the cap. The bound is applied twice, because one place is not enough: a comparison on +so it is bounded at 4 KiB (`MAX_TOKEN_DOCUMENT_BYTES`) and refused above that, naming the cap — +and the size its metadata stated, when the metadata is the half that refused. The read's own +refusal names the cap alone, because the `take` stops one byte past it and the document's true +size was never read. The bound is applied twice, because one place is not enough: a comparison on metadata both forms already read refuses a document that says it is large, and the read itself is taken through `take(cap + 1)` so a document that does not say so is still refused rather than read whole — a procfs file whose `st_size` is `0` (`/proc/self/environ` answers `0` and then a body as -long as the environment is), or a document a writer grows between the `stat` and the read. Without -the first, the file form's per-call read would be an amount of work the path chooses; without the -second it would be an amount the path's own metadata chooses. The descriptor form's single read -could be asked for a -`/dev/zero` that never ends — the type check above is what refuses the device — and the bound is -what keeps a wrong path from being simply a large one. +long as the environment is), or a document a writer grows between the `stat` and the read. The +read reserves its buffer at that same bound, so the bound is one allocation instead of a doubling +sequence. Without the first, the file form's per-call read would be an amount of work the path +chooses; without the second it would be an amount the path's own metadata chooses. The descriptor +form's single read could be asked for a `/dev/zero` that never ends — the type check above is what +refuses the device — and the bound is what keeps a wrong path from being simply a large one. Exactly one of the two is required; both is a refusal, and neither is a refusal naming both. `NOSTREAM_ADMIN_TOKEN` is retired: a mode started with it **refuses to start**, naming the variable