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