Skip to main content

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