mcpmesh_local_api/service.rs
1//! The shared plugin-platform seam (`service` feature): everything a plugin daemon
2//! (kb, loc, …) needs to face the platform, extracted from the kb/loc byte-duplicates so
3//! each rule has ONE home:
4//!
5//! - UDS faces: [`ensure_private_dir`] + [`bind_uds`] + [`check_peer_uid`] (0700
6//! symlink-refused owned runtime dir, 0600 socket, same-uid gate). The mcpmesh daemon's
7//! own control socket (`cli/src/ipc.rs`) binds through the SAME rule.
8//! - THE audience-authz expansion: [`peer_audiences`] — `groups ∪ {name} ∪ {user_id}`,
9//! default-deny. The single implementation both kb and loc gate on.
10//! - `[services.*]` self-registration: [`register_service`] (empty allowlist; failures
11//! logged, never silently swallowed).
12//! - `*-local/1` JSON-RPC conventions: [`ok`]/[`err`]/[`reply`]/[`internal`], the strict
13//! [`required_string_array`] param parse, and [`people_from_status`].
14//! - the `*-local/1` Hello first frame: [`send_hello`].
15//!
16//! Deliberately NOT here: mcpmesh control-endpoint resolution. That is the featureless
17//! [`crate::paths`] rule ([`crate::paths::default_endpoint`]) — ONE home for daemon, CLI,
18//! and plugins, correct on both platforms (a named pipe on windows, never a joined
19//! filesystem path).
20//!
21//! Deliberately NOT extracted (KISS until a third plugin proves the abstraction): state
22//! models, Paths structs, tool dispatch/specs, fan-out policy, and each plugin's MCP
23//! session skeleton in `remote.rs`.
24//!
25//! [`ensure_private_dir`]: crate::service::ensure_private_dir
26//! [`bind_uds`]: crate::service::bind_uds
27//! [`check_peer_uid`]: crate::service::check_peer_uid
28//! [`peer_audiences`]: crate::service::peer_audiences
29//! [`register_service`]: crate::service::register_service
30//! [`ok`]: crate::service::ok
31//! [`err`]: crate::service::err
32//! [`reply`]: crate::service::reply
33//! [`internal`]: crate::service::internal
34//! [`required_string_array`]: crate::service::required_string_array
35//! [`people_from_status`]: crate::service::people_from_status
36//! [`send_hello`]: crate::service::send_hello
37use std::io;
38use std::path::Path;
39
40use serde_json::{Value, json};
41use tokio::io::AsyncWrite;
42// The UDS-face check is exercised by the unix test module below (`UnixStream::connect`);
43// non-test code reaches these faces through `crate::transport`, so the import is test-only
44// and unix-only (the windows transport has no UDS fixtures).
45#[cfg(all(test, unix))]
46use tokio::net::UnixStream;
47
48use crate::client::{ClientError, connect_control};
49use crate::codec::write_frame;
50use crate::protocol::{BackendSpec, Hello, RegisterServiceParams, Request};
51
52// ---------------------------------------------------------------------------------------
53// UDS faces
54// ---------------------------------------------------------------------------------------
55
56// The implementation now lives in `crate::transport` (the platform local-endpoint seam):
57// on unix it is the SAME hardened UDS rule, moved verbatim. These unix-native names remain
58// the plugin API on unix — the private monorepo consumes
59// `mcpmesh_local_api::service::{ensure_private_dir, bind_uds, check_peer_uid}`, so they are
60// re-exported here with identical signatures. Unix-only: `bind_uds`/`check_peer_uid`/
61// `ensure_private_dir` are the UDS hardening rule (0700 dir, 0600 socket, peer-euid
62// gate) and have no meaning on Windows, where the pipe's owner-only DACL is the whole
63// gate (see `transport::windows`). The plugin consumers (kb, loc) are unix today.
64#[cfg(unix)]
65pub use crate::transport::{bind_uds, check_peer_uid, ensure_private_dir};
66
67// ---------------------------------------------------------------------------------------
68// THE audience-authz expansion (default-deny)
69// ---------------------------------------------------------------------------------------
70
71/// `peer_audiences = peer.groups ∪ {peer.name} ∪ {peer.user_id}` — THE ONE
72/// implementation of the caller-audience expansion every plugin gates on (kb re-exports it
73/// as `effective_audiences`). An absent/empty peer yields an EMPTY set — default deny.
74///
75/// Never trusts a self-asserted value: the whole peer object is the platform-injected,
76/// forge-proof `_meta["mcpmesh/peer"]` (the mcpmesh daemon authoritatively OVERWRITES it, so
77/// `groups`/`user_id` can't be caller-forged).
78///
79/// `user_id` is the person's self-sovereign id (`b64u:<user_pk>`, present once a device→user
80/// binding is verified — pairing OR roster). Including it means content shared to a PERSON
81/// reaches ALL their devices (each presents the same verified user_id under a distinct
82/// nickname), whereas `name` (the nickname) scopes to one device and `groups` to a roster set —
83/// three legitimate granularities.
84///
85/// If authz is ever re-keyed on `endpoint_id` instead of the display nickname (a planned
86/// identity hardening), that change lands HERE, once.
87pub fn peer_audiences(peer: &Value) -> Vec<String> {
88 // The expansion itself is THE shared `principal_set` (crate::principals — the flat
89 // namespace, one implementation for the mesh allow check, this seam, and the blob-scope
90 // gate); this fn only adapts the platform-injected peer JSON onto it.
91 let groups: Vec<String> = peer
92 .get("groups")
93 .and_then(|g| g.as_array())
94 .map(|arr| {
95 arr.iter()
96 .filter_map(|g| g.as_str().map(str::to_owned))
97 .collect()
98 })
99 .unwrap_or_default();
100 crate::principal_set(
101 peer.get("name").and_then(|v| v.as_str()),
102 peer.get("user_id").and_then(|v| v.as_str()),
103 &groups,
104 )
105 .into_iter()
106 .map(str::to_owned)
107 .collect()
108}
109
110// ---------------------------------------------------------------------------------------
111// [services.*] self-registration
112// ---------------------------------------------------------------------------------------
113
114/// Register (or idempotently update) `[services.<service_name>]` on the running mcpmesh
115/// daemon: a SOCKET backend pointing at `backend_sock`, with an EMPTY allowlist — local-only
116/// until the user explicitly grants a peer (reachability is a user grant; the
117/// content itself is gated per-audience inside each plugin's service).
118///
119/// A failure is ALWAYS logged here (`tracing::warn`) before being returned, so a
120/// daemon treating registration as best-effort (`let _ =` — the mcpmesh daemon may not be up
121/// in a headless test) can never silently swallow it.
122pub async fn register_service(
123 control_sock: &Path,
124 service_name: &str,
125 backend_sock: &Path,
126) -> Result<(), ClientError> {
127 let result = async {
128 let mut client = connect_control(control_sock).await?;
129 client
130 .request(Request::RegisterService(RegisterServiceParams {
131 name: service_name.to_string(),
132 backend: BackendSpec::Socket {
133 path: backend_sock.to_string_lossy().into_owned(),
134 },
135 allow: vec![],
136 // This helper connects → registers → disconnects, so it MUST be persistent: an
137 // ephemeral registration would be torn down the instant this connection closes.
138 // Ephemeral (#36) is for embedders that hold a ControlClient open for the
139 // service's lifetime (see ControlClient::register_service_with).
140 ephemeral: false,
141 }))
142 .await?;
143 Ok(())
144 }
145 .await;
146 if let Err(e) = &result {
147 tracing::warn!(
148 service = service_name,
149 control_sock = %control_sock.display(),
150 error = %e,
151 "mcpmesh service registration failed — service stays unregistered until the daemon restarts"
152 );
153 }
154 result
155}
156
157// ---------------------------------------------------------------------------------------
158// *-local/1 JSON-RPC conventions
159// ---------------------------------------------------------------------------------------
160
161/// JSON-RPC error code: invalid params. (An unknown method answers `-32601`, the standard
162/// JSON-RPC code — see `docs/local-protocol.md` "Error codes".)
163pub const ERR_PARAMS: i64 = -32602;
164/// JSON-RPC error code: internal error.
165pub const ERR_INTERNAL: i64 = -32603;
166
167/// A JSON-RPC success frame (absent id → null, the notification-shaped degenerate case).
168pub fn ok(id: Option<Value>, result: Value) -> Value {
169 json!({"jsonrpc":"2.0","id": id.unwrap_or(Value::Null),"result": result})
170}
171
172/// A JSON-RPC error frame.
173pub fn err(id: Option<Value>, code: i64, message: &str) -> Value {
174 json!({"jsonrpc":"2.0","id": id.unwrap_or(Value::Null),"error":{"code":code,"message":message}})
175}
176
177/// Wrap a handler's `Result` into a JSON-RPC response frame (the `*-local/1` dispatch shape).
178pub fn reply(id: Value, r: Result<Value, (i64, String)>) -> Value {
179 match r {
180 Ok(v) => json!({"jsonrpc":"2.0","id":id,"result":v}),
181 Err((code, message)) => {
182 json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message}})
183 }
184 }
185}
186
187/// Map an internal failure to `(ERR_INTERNAL, "internal error")`: log the detail locally,
188/// NEVER echo it to the caller (a retriever IO error may embed a filesystem path — e.g. a
189/// hashed audience dir — that must not reach a peer or even the owner surface).
190pub fn internal(e: impl std::fmt::Display) -> (i64, String) {
191 tracing::warn!(error = %e, "internal error (detail withheld from the caller)");
192 (ERR_INTERNAL, "internal error".to_string())
193}
194
195/// STRICT `params[key]` string-array parse: the key must be present, an array, and every
196/// element a string — anything else is `ERR_PARAMS`. Destructive setters (share lists) MUST
197/// use this: a lenient `unwrap_or_default()` would read a malformed request as "share with
198/// NOBODY" and persist `[]` — an accidental unshare-everyone.
199pub fn required_string_array(params: &Value, key: &str) -> Result<Vec<String>, (i64, String)> {
200 let arr = params
201 .get(key)
202 .and_then(|v| v.as_array())
203 .ok_or((ERR_PARAMS, format!("{key} (array of strings) is required")))?;
204 arr.iter()
205 .map(|v| {
206 v.as_str()
207 .map(str::to_owned)
208 .ok_or((ERR_PARAMS, format!("{key} must contain only strings")))
209 })
210 .collect()
211}
212
213/// Extract the friendly people directory from an mcpmesh `status` result (`share_targets`):
214/// one entry per paired peer — the owner's nickname for it + its verified `user_id` (or
215/// null). Pure over the JSON so it is unit-tested without a live mcpmesh. Surface-clean:
216/// nickname + user_id only, never a transport id / service list.
217pub fn people_from_status(status: &Value) -> Vec<Value> {
218 status["peers"]
219 .as_array()
220 .map(|peers| {
221 peers
222 .iter()
223 .filter_map(|p| {
224 let name = p["name"].as_str()?;
225 Some(json!({ "name": name, "user_id": p["user_id"].as_str() }))
226 })
227 .collect()
228 })
229 .unwrap_or_default()
230}
231
232// ---------------------------------------------------------------------------------------
233// The *-local/1 Hello first frame
234// ---------------------------------------------------------------------------------------
235
236/// Write the `*-local/N` Hello first frame (the shared handshake convention: every owner-face
237/// server sends `{api, api_version, stack_version}` before anything else).
238pub async fn send_hello<W: AsyncWrite + Unpin>(
239 writer: &mut W,
240 api: &str,
241 api_version: &str,
242 api_minor: u32,
243 stack_version: &str,
244) -> io::Result<()> {
245 let hello = serde_json::to_value(Hello {
246 api: api.into(),
247 api_version: api_version.into(),
248 api_minor,
249 stack_version: stack_version.into(),
250 })
251 .expect("Hello serializes");
252 write_frame(writer, &hello).await
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258 use crate::codec::{FrameReader, Inbound, MAX_FRAME_BYTES};
259 // Only the unix-gated `register_service` stub below uses these Hello constants.
260 #[cfg(unix)]
261 use crate::protocol::{API_NAME, API_VERSION};
262 use serde_json::json;
263
264 #[test]
265 fn peer_audiences_is_groups_union_name_union_user_id() {
266 let peer = json!({"name":"bob-laptop","user_id":"b64u:BOB","groups":["eng","ops"]});
267 let mut a = peer_audiences(&peer);
268 a.sort();
269 assert_eq!(a, vec!["b64u:BOB", "bob-laptop", "eng", "ops"]);
270 // DEFAULT-DENY: an absent/empty peer yields nothing.
271 assert!(peer_audiences(&json!({})).is_empty());
272 // Empty-string name/user_id never become audiences.
273 assert_eq!(
274 peer_audiences(&json!({"name":"bob","user_id":"","groups":[]})),
275 vec!["bob"]
276 );
277 }
278
279 #[test]
280 fn people_from_status_extracts_nickname_and_user_id() {
281 let status = json!({"peers":[
282 {"name":"bob","services":["kb"],"user_id":"b64u:CGnYVhFY"},
283 {"name":"carol","services":[]}
284 ]});
285 assert_eq!(
286 people_from_status(&status),
287 vec![
288 json!({"name":"bob","user_id":"b64u:CGnYVhFY"}),
289 json!({"name":"carol","user_id":null}),
290 ]
291 );
292 assert!(people_from_status(&json!({})).is_empty());
293 }
294
295 #[test]
296 fn internal_error_does_not_echo_detail() {
297 // A retriever IO error may embed a hashed audience-dir path — it must NOT reach a peer.
298 let (code, msg) =
299 internal("open /home/me/.local/share/kb/index/abc123def456/notes.jsonl: No such file");
300 assert_eq!(code, ERR_INTERNAL);
301 assert!(
302 !msg.contains("/home/me"),
303 "no filesystem path in the caller-visible message"
304 );
305 assert!(
306 !msg.contains("index/"),
307 "no index dir in the caller-visible message"
308 );
309 assert_eq!(msg, "internal error");
310 }
311
312 #[test]
313 fn required_string_array_is_strict() {
314 // Present + array of strings → the values.
315 let ok_p = json!({"audiences": ["b64u:BOB", "eng"]});
316 assert_eq!(
317 required_string_array(&ok_p, "audiences").unwrap(),
318 vec!["b64u:BOB".to_string(), "eng".to_string()]
319 );
320 // Empty array is a VALID explicit "share with nobody".
321 assert_eq!(
322 required_string_array(&json!({"audiences": []}), "audiences").unwrap(),
323 Vec::<String>::new()
324 );
325 // Missing key, wrong type, or a non-string element → ERR_PARAMS (never an implicit []).
326 for bad in [
327 json!({}),
328 json!({"audiences": "eng"}),
329 json!({"audiences": 42}),
330 json!({"audiences": ["eng", 7]}),
331 json!({"audiences": null}),
332 ] {
333 let e = required_string_array(&bad, "audiences").unwrap_err();
334 assert_eq!(e.0, ERR_PARAMS, "payload {bad} must be a params error");
335 }
336 }
337
338 #[test]
339 fn ok_err_and_reply_shape_json_rpc_frames() {
340 let o = ok(Some(json!(1)), json!({"x": true}));
341 assert_eq!(o["id"], 1);
342 assert_eq!(o["result"]["x"], true);
343 let e = err(None, ERR_PARAMS, "bad");
344 assert_eq!(e["id"], Value::Null);
345 assert_eq!(e["error"]["code"], ERR_PARAMS);
346 let r = reply(json!(7), Err((ERR_INTERNAL, "internal error".into())));
347 assert_eq!(r["error"]["code"], ERR_INTERNAL);
348 assert_eq!(
349 reply(json!(8), Ok(json!({"ok":true})))["result"]["ok"],
350 true
351 );
352 }
353
354 // Unix-only: exercises the UDS hardening rule (0600/0700 bits, symlink refusal,
355 // peer-euid gate). The windows transport's equivalent guarantee is the owner-only
356 // DACL, covered by tests in `transport::windows`.
357 #[cfg(unix)]
358 #[tokio::test]
359 async fn bind_uds_forces_0600_socket_and_0700_parent() {
360 use std::os::unix::fs::PermissionsExt;
361 let dir = tempfile::tempdir().unwrap();
362 let run = dir.path().join("plug");
363 // Pre-create the runtime dir LAX (0755) — bind_uds must tighten it (loc-L6).
364 std::fs::create_dir_all(&run).unwrap();
365 std::fs::set_permissions(&run, std::fs::Permissions::from_mode(0o755)).unwrap();
366 let sock = run.join("plug.sock");
367 let _listener = bind_uds(&sock).unwrap();
368 let dir_mode = std::fs::metadata(&run).unwrap().permissions().mode() & 0o777;
369 assert_eq!(dir_mode, 0o700, "runtime dir forced private");
370 let sock_mode = std::fs::metadata(&sock).unwrap().permissions().mode() & 0o777;
371 assert_eq!(sock_mode, 0o600, "socket is owner-only");
372 // Re-bind over a stale socket file succeeds (crash recovery).
373 drop(_listener);
374 let _again = bind_uds(&sock).unwrap();
375 }
376
377 /// Hardening parity: a SYMLINKED runtime dir is refused before any chmod/bind — a
378 /// planted `link -> dir` must never redirect the socket (same rule as the
379 /// daemon control socket).
380 #[cfg(unix)]
381 #[tokio::test]
382 async fn bind_uds_refuses_a_symlinked_runtime_dir() {
383 let dir = tempfile::tempdir().unwrap();
384 let real = dir.path().join("real");
385 std::fs::create_dir_all(&real).unwrap();
386 let link = dir.path().join("link");
387 std::os::unix::fs::symlink(&real, &link).unwrap();
388 let err = bind_uds(&link.join("plug.sock")).unwrap_err();
389 assert!(
390 err.to_string().contains("symlink"),
391 "refusal names the symlink: {err}"
392 );
393 // And ensure_private_dir itself refuses directly too.
394 assert!(ensure_private_dir(&link).is_err());
395 // The real dir still binds fine (the check refuses links, not dirs).
396 let _ok = bind_uds(&real.join("plug.sock")).unwrap();
397 }
398
399 #[cfg(unix)]
400 #[tokio::test]
401 async fn check_peer_uid_accepts_a_same_uid_peer() {
402 let dir = tempfile::tempdir().unwrap();
403 let sock = dir.path().join("uid.sock");
404 let listener = bind_uds(&sock).unwrap();
405 let client = UnixStream::connect(&sock).await.unwrap();
406 let (server, _) = listener.accept().await.unwrap();
407 // Both ends of a same-process connection are, by construction, the same uid.
408 assert!(check_peer_uid(&server));
409 assert!(check_peer_uid(&client));
410 }
411
412 #[tokio::test]
413 async fn send_hello_writes_the_family_hello_frame() {
414 let (mut a, b) = tokio::io::duplex(1024);
415 send_hello(&mut a, "loc-local/1", "1", 0, "0.1.0")
416 .await
417 .unwrap();
418 drop(a);
419 let mut reader = FrameReader::new(b, MAX_FRAME_BYTES);
420 let frame = match reader.next().await.unwrap().unwrap() {
421 Inbound::Frame(v) => v,
422 Inbound::Violation(v) => panic!("violation: {v:?}"),
423 };
424 assert_eq!(frame["api"], "loc-local/1");
425 assert_eq!(frame["api_version"], "1");
426 assert_eq!(frame["stack_version"], "0.1.0");
427 }
428
429 /// A stub mcpmesh daemon that answers one `register_service`, asserting the wire shape.
430 /// Unix-only for now: the stub daemon binds a raw `UnixListener`; porting it to the
431 /// transport seam would let it run on windows too.
432 #[cfg(unix)]
433 #[tokio::test]
434 async fn register_service_registers_a_socket_backend_with_empty_allow() {
435 let dir = tempfile::tempdir().unwrap();
436 let control = dir.path().join("mcpmesh.sock");
437 let listener = tokio::net::UnixListener::bind(&control).unwrap();
438 let server = tokio::spawn(async move {
439 let (stream, _) = listener.accept().await.unwrap();
440 let (read_half, mut writer) = stream.into_split();
441 write_frame(
442 &mut writer,
443 &serde_json::to_value(Hello {
444 api: API_NAME.into(),
445 api_version: API_VERSION.into(),
446 api_minor: 0,
447 stack_version: "0.1.0".into(),
448 })
449 .unwrap(),
450 )
451 .await
452 .unwrap();
453 let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
454 let req = match reader.next().await.unwrap().unwrap() {
455 Inbound::Frame(v) => v,
456 Inbound::Violation(_) => panic!("violation"),
457 };
458 assert_eq!(req["method"], "register_service");
459 assert_eq!(req["params"]["name"], "loc");
460 assert_eq!(
461 req["params"]["backend"]["socket"]["path"],
462 "/run/x/loc/loc.sock"
463 );
464 assert_eq!(req["params"]["allow"], json!([]));
465 write_frame(
466 &mut writer,
467 &json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
468 )
469 .await
470 .unwrap();
471 });
472 register_service(&control, "loc", Path::new("/run/x/loc/loc.sock"))
473 .await
474 .unwrap();
475 server.await.unwrap();
476
477 // And the failure path returns Err (after logging) instead of swallowing (loc-L2).
478 let gone = dir.path().join("nobody-home.sock");
479 assert!(
480 register_service(&gone, "loc", Path::new("/x"))
481 .await
482 .is_err()
483 );
484 }
485}