ctb_workspace_ipc/
router.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Central IPC message router dispatching RPC calls and events.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::auth::capability::CapabilitySet;
30use crate::error::Error;
31use crate::protocol::{Event, MethodId, Request, Response, RpcError};
32use crate::services::parent::SERVICE_NAME as PARENT_SERVICE_NAME;
33use crate::services::parent::api::ParentMessenger;
34use crate::services::process::SERVICE_NAME as PROCESS_SERVICE_NAME;
35use crate::services::process::api::ProcessService;
36use crate::types::ConnectionId;
37use async_trait::async_trait;
38use std::collections::HashMap;
39use std::sync::Arc;
40use tokio::time::Instant;
41
42use tracing::Instrument as _;
43
44pub mod heartbeat;
45pub mod token_bucket;
46
47mod ipc_ctx;
48mod registry;
49
50/// Central router interface responsible for:
51/// - binding connections to capability sets
52/// - enforcing authorization
53/// - dispatching requests to services
54/// - emitting events
55#[async_trait]
56pub trait Router: Send + Sync {
57    /// Register a new connection after handshake.
58    async fn register_connection(
59        &self,
60        ctx: ConnectionContext,
61    ) -> Result<(), Error>;
62
63    /// Resolve and dispatch a request to a target service method.
64    async fn dispatch(
65        &self,
66        ctx: &ConnectionContext,
67        request: Request,
68    ) -> Result<Response, Error>;
69
70    /// Emit an event to a connection or broadcast to all with appropriate policies.
71    async fn emit_event(&self, event: Event) -> Result<(), Error>;
72
73    /// Check whether a given method is allowed by a connection’s capabilities.
74    fn is_authorized(
75        &self,
76        ctx: &ConnectionContext,
77        method: &MethodId,
78    ) -> Result<(), RpcError>;
79
80    /// Observe a cancellation request for auditing/metrics.
81    ///
82    /// Implementations may ignore this. Cancellation itself is enforced by the
83    /// IPC server loop via cooperative checks and/or task abort.
84    async fn observe_cancel(
85        &self,
86        _ctx: &ConnectionContext,
87        _id: u64,
88    ) -> Result<(), Error> {
89        Ok(())
90    }
91}
92
93/// Context bound to a connection for authorization and audit.
94#[derive(Debug, Clone)]
95pub struct ConnectionContext {
96    pub id: ConnectionId,
97    pub capabilities: CapabilitySet,
98    /// Optional additional metadata (process kind, user, document id, etc.)
99    pub metadata: Option<serde_json::Value>,
100}
101
102/// A simple in-memory router that registers connections, authorizes requests,
103/// and returns a canned 'not implemented' response for authorized calls.
104#[derive(Debug)]
105pub struct IpcRouter {
106    // Keep a minimal registry. Avoid panics; ignore duplicates by replacing.
107    connections: std::sync::RwLock<Vec<ConnectionContext>>,
108    pub(crate) process_service: Option<Arc<dyn ProcessService>>,
109    pub(crate) parent_messenger: Option<Arc<dyn ParentMessenger>>,
110    rate_limiter: tokio::sync::Mutex<
111        HashMap<token_bucket::RateKey, token_bucket::TokenBucket>,
112    >,
113}
114
115impl Default for IpcRouter {
116    fn default() -> Self {
117        Self::new()
118    }
119}
120
121impl IpcRouter {
122    /// Create a new `IpcRouter`.
123    pub fn new() -> Self {
124        Self {
125            connections: std::sync::RwLock::new(Vec::new()),
126            process_service: None,
127            parent_messenger: None,
128            rate_limiter: tokio::sync::Mutex::new(HashMap::new()),
129        }
130    }
131
132    /// Set the process service.
133    #[must_use]
134    pub fn with_process_service(
135        mut self,
136        svc: Arc<dyn ProcessService>,
137    ) -> Self {
138        self.process_service = Some(svc);
139        self
140    }
141
142    /// Set the parent messenger used by child processes to communicate with
143    /// their parent.
144    #[must_use]
145    pub fn with_parent_messenger(
146        mut self,
147        messenger: Arc<dyn ParentMessenger>,
148    ) -> Self {
149        self.parent_messenger = Some(messenger);
150        self
151    }
152
153    fn should_rate_limit(service: &str) -> bool {
154        service == "io" || service == "network"
155    }
156
157    fn match_quotas(
158        ctx: &ConnectionContext,
159        method: &MethodId,
160    ) -> Result<Option<crate::auth::capability::QuotaSet>, RpcError> {
161        use crate::auth::capability::{MethodRule, ServiceName};
162
163        let service_key = ServiceName(method.service.clone());
164        let Some(rules) = ctx.capabilities.allowed.get(&service_key) else {
165            return Err(RpcError::unauthorized(format!(
166                "service '{}' is not allowed",
167                method.service
168            )));
169        };
170
171        let matched: Option<&MethodRule> = rules
172            .iter()
173            .find(|rule| rule.method.matches(&method.service, &method.method));
174
175        let Some(rule) = matched else {
176            return Err(RpcError::unauthorized(format!(
177                "method '{}.{}' is not allowed",
178                method.service, method.method
179            )));
180        };
181
182        Ok(rule.quotas.clone())
183    }
184
185    async fn enforce_rate_limits(
186        &self,
187        ctx: &ConnectionContext,
188        method: &MethodId,
189        request_bytes: usize,
190    ) -> Result<(), RpcError> {
191        if !Self::should_rate_limit(method.service.as_str()) {
192            return Ok(());
193        }
194
195        let quotas = Self::match_quotas(ctx, method)?;
196        let Some(quotas) = quotas else {
197            return Ok(());
198        };
199
200        let now = Instant::now();
201
202        if let Some(rate) = quotas.bytes_per_sec {
203            let Some(burst) = quotas.effective_burst_bytes() else {
204                return Ok(());
205            };
206
207            let cost_u64 = u64::try_from(request_bytes).map_err(|e| {
208                RpcError::capability_denied(format!(
209                    "request size too large for limiter: {e}"
210                ))
211            })?;
212
213            let key = token_bucket::RateKey::bytes(
214                ctx.id,
215                method.service.clone(),
216                method.method.clone(),
217            );
218
219            let mut guard = self.rate_limiter.lock().await;
220            let bucket = guard.entry(key).or_insert_with(|| {
221                token_bucket::TokenBucket::new(rate, burst, now)
222            });
223
224            if !bucket.try_take(cost_u64, now) {
225                return Err(RpcError::capability_denied(format!(
226                    "rate limit exceeded for {}.{} (bytes/sec)",
227                    method.service, method.method
228                )));
229            }
230        }
231
232        Ok(())
233    }
234
235    /// Helper to create an error response.
236    pub fn error_response(id: u64, code: &str, message: &str) -> Response {
237        Response {
238            id,
239            ok: false,
240            result: None,
241            error: Some(RpcError {
242                code: code.into(),
243                message: message.into(),
244            }),
245        }
246    }
247
248    /// Helper to create a success response with serialized bytes.
249    fn success_response(id: u64, bytes: Vec<u8>) -> Response {
250        Response {
251            id,
252            ok: true,
253            result: Some(bytes),
254            error: None,
255        }
256    }
257
258    /// Helper to check if a service is configured.
259    pub(crate) fn check_service<T>(
260        service: Option<&T>,
261        service_name: &str,
262        id: u64,
263    ) -> Result<(), Response> {
264        if service.is_none() {
265            return Err(Self::error_response(
266                id,
267                "not_implemented",
268                &format!("{service_name} service not configured"),
269            ));
270        }
271        Ok(())
272    }
273
274    /// Helper to decode a request from bytes.
275    pub(crate) fn decode_request<T: serde::de::DeserializeOwned>(
276        args: &[u8],
277        method: &str,
278        id: u64,
279    ) -> Result<T, Response> {
280        postcard_helpers::decode(args, &format!("{method}.args")).map_err(|e| {
281            Self::error_response(
282                id,
283                "invalid_args",
284                &format!("invalid {method}.args: {e}"),
285            )
286        })
287    }
288
289    /// Helper to handle service call and serialize response.
290    pub(crate) async fn handle_service_call<
291        T: serde::Serialize,
292        E: std::fmt::Display,
293    >(
294        &self,
295        call: impl std::future::Future<Output = Result<T, E>>,
296        id: u64,
297    ) -> Result<Response, Error> {
298        match call.await {
299            Ok(resp) => {
300                let bytes = postcard_helpers::encode(&resp, "response")?;
301                Ok(Self::success_response(id, bytes))
302            }
303            Err(e) => Ok(Self::error_response(id, "internal", &e.to_string())),
304        }
305    }
306
307    async fn dispatch_impl(
308        &self,
309        ctx: &ConnectionContext,
310        ipc_ctx: Arc<dyn ctb_utilities::ipc::registry::IpcRequestContext>,
311        request: Request,
312    ) -> Result<Response, Error> {
313        let span = tracing::info_span!(
314            "ipc.dispatch",
315            conn_id = %ctx.id,
316            request_id = request.id,
317            service = %request.method.service,
318            method = %request.method.method
319        );
320
321        async move {
322            match self.is_authorized(ctx, &request.method) {
323                Ok(()) => {
324                    if let Err(e) = self
325                        .enforce_rate_limits(
326                            ctx,
327                            &request.method,
328                            request.args.len(),
329                        )
330                        .await
331                    {
332                        return Ok(Response {
333                            id: request.id,
334                            ok: false,
335                            result: None,
336                            error: Some(e),
337                        });
338                    }
339
340                    if let Some(resp) = Self::dispatch_registry_with_ctx(
341                        Arc::clone(&ipc_ctx),
342                        &request,
343                    )
344                    .await?
345                    {
346                        return Ok(resp);
347                    }
348
349                    if request.method.service == PROCESS_SERVICE_NAME {
350                        return crate::services::process::dispatch_process(
351                            self, request,
352                        )
353                        .await;
354                    }
355
356                    if request.method.service == PARENT_SERVICE_NAME {
357                        return crate::services::parent::dispatch_parent(
358                            self, ctx, request,
359                        )
360                        .await;
361                    }
362
363                    Ok(Response {
364                        id: request.id,
365                        ok: false,
366                        result: None,
367                        error: Some(RpcError {
368                            code: "not_implemented".into(),
369                            message: "method not implemented".into(),
370                        }),
371                    })
372                }
373                Err(e) => {
374                    tracing::error!(
375                        conn_id = %ctx.id,
376                        request_id = request.id,
377                        service = %request.method.service,
378                        method = %request.method.method,
379                        code = %e.code,
380                        message = %e.message,
381                        "IPC request denied by capability router"
382                    );
383
384                    Ok(Response {
385                        id: request.id,
386                        ok: false,
387                        result: None,
388                        error: Some(e),
389                    })
390                }
391            }
392        }
393        .instrument(span)
394        .await
395    }
396}
397
398#[async_trait]
399impl Router for IpcRouter {
400    /// Register a new connection after handshake.
401    async fn register_connection(
402        &self,
403        ctx: ConnectionContext,
404    ) -> Result<(), Error> {
405        if let Ok(mut guard) = self.connections.write() {
406            if let Some(pos) = guard.iter().position(|c| c.id == ctx.id) {
407                if let Some(existing) = guard.get_mut(pos) {
408                    *existing = ctx;
409                }
410            } else {
411                guard.push(ctx);
412            }
413        }
414        Ok(())
415    }
416
417    /// Resolve and dispatch a request to a target service method.
418    async fn dispatch(
419        &self,
420        ctx: &ConnectionContext,
421        request: Request,
422    ) -> Result<Response, Error> {
423        self.dispatch_impl(ctx, Self::no_fd_ipc_ctx(), request)
424            .await
425    }
426
427    async fn emit_event(&self, event: Event) -> Result<(), Error> {
428        let span = tracing::info_span!("ipc.emit_event", topic = ?event.topic);
429        async move {
430            // No-op for now.
431            Ok(())
432        }
433        .instrument(span)
434        .await
435    }
436
437    /// Check whether a given method is allowed by a connection’s capabilities.
438    fn is_authorized(
439        &self,
440        ctx: &ConnectionContext,
441        method: &MethodId,
442    ) -> Result<(), RpcError> {
443        use crate::auth::capability::{MethodRule, ServiceName};
444
445        let service_key = ServiceName(method.service.clone());
446        let Some(rules) = ctx.capabilities.allowed.get(&service_key) else {
447            return Err(RpcError {
448                code: "unauthorized".into(),
449                message: format!("service '{}' is not allowed", method.service),
450            });
451        };
452
453        let allowed = rules.iter().any(|rule: &MethodRule| {
454            rule.method.matches(&method.service, &method.method)
455        });
456
457        if allowed {
458            Ok(())
459        } else {
460            Err(RpcError {
461                code: "unauthorized".into(),
462                message: format!(
463                    "method '{}.{}' is not allowed",
464                    method.service, method.method
465                ),
466            })
467        }
468    }
469
470    async fn observe_cancel(
471        &self,
472        _ctx: &ConnectionContext,
473        _id: u64,
474    ) -> Result<(), Error> {
475        Ok(())
476    }
477}
478
479impl IpcRouter {
480    /// Retrieve a registered connection by id.
481    pub fn get(&self, id: &ConnectionId) -> Option<ConnectionContext> {
482        if let Ok(guard) = self.connections.read() {
483            guard.iter().find(|c| c.id == *id).cloned()
484        } else {
485            None
486        }
487    }
488}
489
490#[cfg(test)]
491#[allow(
492    clippy::panic,
493    clippy::expect_used,
494    clippy::unwrap_used,
495    clippy::unwrap_in_result,
496    clippy::panic_in_result_fn,
497    clippy::indexing_slicing,
498    clippy::arithmetic_side_effects,
499    reason = "Standard repository test boilerplate"
500)]
501mod registry_dispatch_tests {
502    use super::*;
503
504    use crate::auth::capability::{
505        CapabilitySet, MethodRule, MethodSelector, ServiceName,
506    };
507
508    #[ipc_method]
509    #[expect(
510        clippy::unnecessary_wraps,
511        reason = "uniform service trait API mapping patterns"
512    )]
513    fn ping(input: u8) -> Result<u8> {
514        Ok(input.saturating_add(1))
515    }
516
517    #[crate::ctb_test("tokio")]
518    async fn routes_registry_method() -> Result<()> {
519        // This relies on the above #[ipc_method] to have registered the method.
520        // When this test started failing, it was because of "a naming
521        // mismatch: `#[ipc_method]` derives `(service, method)` from the *crate
522        // name*. In the `ctb-workspace-ipc` crate, `ping` registers as
523        // `service="workspace"`, `method="ipc.ping"`, but the test was calling
524        // `service="ctoolbox"`, `method="ping"`, so the registry lookup
525        // returned `None` and the router fell through to `not_implemented`."
526        let router = IpcRouter::new();
527
528        let mut allowed = std::collections::HashMap::new();
529        allowed.insert(
530            ServiceName("workspace".to_string()),
531            vec![MethodRule {
532                method: MethodSelector::Exact("ipc.ping".into()),
533                quotas: None,
534            }],
535        );
536
537        let ctx = ConnectionContext {
538            id: crate::types::ConnectionId::default(),
539            capabilities: CapabilitySet {
540                allowed,
541                global_limits: None,
542            },
543            metadata: None,
544        };
545
546        let args = postcard_helpers::encode(&41u8, "test args")?;
547        let req = Request {
548            id: 1,
549            method: MethodId {
550                service: "workspace".into(),
551                method: "ipc.ping".into(),
552            },
553            args,
554        };
555
556        let resp = router.dispatch(&ctx, req).await?;
557        anyhow::ensure!(resp.ok, "expected ok response, got: {resp:?}");
558        let bytes = resp
559            .result
560            .ok_or_else(|| anyhow::anyhow!("missing result bytes"))?;
561        let decoded: u8 = postcard_helpers::decode(&bytes, "test result")?;
562        anyhow::ensure!(decoded == 42, "unexpected decoded: {decoded}");
563        Ok(())
564    }
565}
566
567#[cfg(test)]
568#[allow(
569    clippy::panic,
570    clippy::expect_used,
571    clippy::unwrap_used,
572    clippy::unwrap_in_result,
573    clippy::panic_in_result_fn,
574    clippy::indexing_slicing,
575    clippy::arithmetic_side_effects,
576    reason = "Standard repository test boilerplate"
577)]
578mod tests {
579    use super::*;
580
581    use crate::auth::capability::{
582        CapabilitySet, MethodRule, MethodSelector, QuotaSet, ServiceName,
583    };
584
585    use crate::protocol::{MethodId, Request};
586
587    use crate::assert_ipc_response_error;
588
589    use anyhow::Result;
590    use std::collections::HashMap;
591
592    fn ctx_with_rules(
593        service: &str,
594        rules: Vec<MethodRule>,
595    ) -> ConnectionContext {
596        let mut allowed: HashMap<ServiceName, Vec<MethodRule>> = HashMap::new();
597        allowed.insert(ServiceName(service.to_string()), rules);
598        ConnectionContext {
599            id: ConnectionId::default(),
600            capabilities: CapabilitySet {
601                allowed,
602                global_limits: None,
603            },
604            metadata: None,
605        }
606    }
607
608    fn req(service: &str, method: &str) -> Request {
609        Request {
610            id: Default::default(),
611            method: MethodId {
612                service: service.into(),
613                method: method.into(),
614            },
615            args: vec![],
616        }
617    }
618
619    /// Exact selector should allow only the exact method.
620    #[crate::ctb_test("tokio")]
621    async fn auth_exact_allows() -> Result<()> {
622        let router = IpcRouter::new();
623        let ctx = ctx_with_rules(
624            "svc",
625            vec![MethodRule {
626                method: MethodSelector::Exact("do_work".into()),
627                quotas: None,
628            }],
629        );
630
631        let resp = router.dispatch(&ctx, req("svc", "do_work")).await?;
632        anyhow::ensure!(!resp.ok, "expected error response: {resp:?}");
633        let err = resp
634            .error
635            .as_ref()
636            .ok_or_else(|| anyhow::anyhow!("missing error: {resp:?}"))?;
637        anyhow::ensure!(
638            err.code == "not_implemented",
639            "unexpected error code: {err:?}"
640        );
641
642        let resp2 = router.dispatch(&ctx, req("svc", "other")).await?;
643        anyhow::ensure!(!resp2.ok, "expected error response: {resp2:?}");
644        let err2 = resp2
645            .error
646            .as_ref()
647            .ok_or_else(|| anyhow::anyhow!("missing error: {resp2:?}"))?;
648        anyhow::ensure!(
649            err2.code == "unauthorized",
650            "unexpected error code: {err2:?}"
651        );
652        Ok(())
653    }
654
655    /// Prefix selector should allow matching prefix and deny others.
656    #[crate::ctb_test("tokio")]
657    async fn auth_prefix() -> Result<()> {
658        let router = IpcRouter::new();
659        let ctx = ctx_with_rules(
660            "svc",
661            vec![MethodRule {
662                method: MethodSelector::Prefix("do_".into()),
663                quotas: None,
664            }],
665        );
666
667        let ok_resp = router.dispatch(&ctx, req("svc", "do_stuff")).await?;
668        anyhow::ensure!(!ok_resp.ok, "expected error response: {ok_resp:?}");
669        let ok_err = ok_resp
670            .error
671            .as_ref()
672            .ok_or_else(|| anyhow::anyhow!("missing error: {ok_resp:?}"))?;
673        anyhow::ensure!(
674            ok_err.code == "not_implemented",
675            "unexpected error code: {ok_err:?}"
676        );
677
678        let deny_resp = router.dispatch(&ctx, req("svc", "list")).await?;
679        anyhow::ensure!(
680            !deny_resp.ok,
681            "expected error response: {deny_resp:?}"
682        );
683        let deny_err = deny_resp
684            .error
685            .as_ref()
686            .ok_or_else(|| anyhow::anyhow!("missing error: {deny_resp:?}"))?;
687        anyhow::ensure!(
688            deny_err.code == "unauthorized",
689            "unexpected error code: {deny_err:?}"
690        );
691        Ok(())
692    }
693
694    /// Any selector allows all methods within the service. Absence of service
695    /// entry denies all methods.
696    #[crate::ctb_test("tokio")]
697    async fn auth_any_and_missing_service() -> Result<()> {
698        let router = IpcRouter::new();
699
700        // Any allows all for 'svc'
701        let ctx_any = ctx_with_rules(
702            "svc",
703            vec![MethodRule {
704                method: MethodSelector::Any,
705                quotas: None,
706            }],
707        );
708
709        let ok_resp = router.dispatch(&ctx_any, req("svc", "x")).await?;
710        anyhow::ensure!(!ok_resp.ok, "expected error response: {ok_resp:?}");
711        let ok_err = ok_resp
712            .error
713            .as_ref()
714            .ok_or_else(|| anyhow::anyhow!("missing error: {ok_resp:?}"))?;
715        anyhow::ensure!(
716            ok_err.code == "not_implemented",
717            "unexpected error code: {ok_err:?}"
718        );
719
720        // No entry for 'other' -> unauthorized
721        let deny_resp = router.dispatch(&ctx_any, req("other", "x")).await?;
722        anyhow::ensure!(
723            !deny_resp.ok,
724            "expected error response: {deny_resp:?}"
725        );
726        let deny_err = deny_resp
727            .error
728            .as_ref()
729            .ok_or_else(|| anyhow::anyhow!("missing error: {deny_resp:?}"))?;
730        anyhow::ensure!(
731            deny_err.code == "unauthorized",
732            "unexpected error code: {deny_err:?}"
733        );
734        Ok(())
735    }
736
737    /// Selectors with fully-qualified strings should also match.
738    #[crate::ctb_test("tokio")]
739    async fn auth_fully_qualified_selectors() -> Result<()> {
740        let router = IpcRouter::new();
741        let ctx = ctx_with_rules(
742            "svc",
743            vec![
744                MethodRule {
745                    method: MethodSelector::Exact("svc.do_a".into()),
746                    quotas: None,
747                },
748                MethodRule {
749                    method: MethodSelector::Prefix("svc.do_".into()),
750                    quotas: None,
751                },
752            ],
753        );
754
755        // Exact match
756        let r1 = router.dispatch(&ctx, req("svc", "do_a")).await?;
757        let e1 = r1
758            .error
759            .as_ref()
760            .ok_or_else(|| anyhow::anyhow!("missing error: {r1:?}"))?;
761        anyhow::ensure!(
762            e1.code == "not_implemented",
763            "unexpected error code: {e1:?}"
764        );
765
766        // Prefix match
767        let r2 = router.dispatch(&ctx, req("svc", "do_b")).await?;
768        let e2 = r2
769            .error
770            .as_ref()
771            .ok_or_else(|| anyhow::anyhow!("missing error: {r2:?}"))?;
772        anyhow::ensure!(
773            e2.code == "not_implemented",
774            "unexpected error code: {e2:?}"
775        );
776
777        // Non-matching method
778        let r3 = router.dispatch(&ctx, req("svc", "list")).await?;
779        let e3 = r3
780            .error
781            .as_ref()
782            .ok_or_else(|| anyhow::anyhow!("missing error: {r3:?}"))?;
783        anyhow::ensure!(
784            e3.code == "unauthorized",
785            "unexpected error code: {e3:?}"
786        );
787
788        Ok(())
789    }
790
791    /// `Register_connection` stores the `ConnectionContext`.
792    #[crate::ctb_test("tokio")]
793    async fn register_stores_context() -> Result<()> {
794        let router = IpcRouter::new();
795        let ctx = ConnectionContext {
796            id: ConnectionId::default(),
797            capabilities: CapabilitySet::default(),
798            metadata: Some(serde_json::json!({"k":"v"})),
799        };
800        router.register_connection(ctx.clone()).await?;
801        let got = router
802            .get(&ctx.id)
803            .ok_or_else(|| anyhow::anyhow!("expected stored context"))?;
804        anyhow::ensure!(got.id == ctx.id, "unexpected id: {got:?}");
805        anyhow::ensure!(
806            got.metadata == ctx.metadata,
807            "unexpected metadata: {got:?}"
808        );
809        Ok(())
810    }
811
812    /// Exceeding bytes/sec should yield a `capability_denied` error.
813    #[crate::ctb_test("tokio")]
814    async fn rate_limit_bytes_per_sec_is_enforced_for_io_and_network()
815    -> Result<()> {
816        let router = IpcRouter::new();
817
818        let mut allowed: HashMap<ServiceName, Vec<MethodRule>> = HashMap::new();
819        allowed.insert(
820            ServiceName("io".to_string()),
821            vec![MethodRule {
822                method: MethodSelector::Exact("read".into()),
823                quotas: Some(QuotaSet {
824                    bytes_per_sec: Some(10),
825                    ops_per_sec: None,
826                    burst: Some(10),
827                }),
828            }],
829        );
830
831        let ctx = ConnectionContext {
832            id: ConnectionId::default(),
833            capabilities: CapabilitySet {
834                allowed,
835                global_limits: None,
836            },
837            metadata: None,
838        };
839
840        let mk_req = |n: usize| Request {
841            id: Default::default(),
842            method: MethodId {
843                service: "io".into(),
844                method: "read".into(),
845            },
846            args: vec![0u8; n],
847        };
848
849        // First request consumes full burst.
850        let r1 = router.dispatch(&ctx, mk_req(10)).await?;
851        let e1 = r1
852            .error
853            .as_ref()
854            .ok_or_else(|| anyhow::anyhow!("missing error: {r1:?}"))?;
855        anyhow::ensure!(
856            e1.code == "not_implemented",
857            "unexpected error code: {e1:?}"
858        );
859
860        // Second request should be denied immediately.
861        let r2 = router.dispatch(&ctx, mk_req(1)).await?;
862        assert_ipc_response_error(&r2);
863        let e2 = r2
864            .error
865            .as_ref()
866            .ok_or_else(|| anyhow::anyhow!("missing error: {r2:?}"))?;
867        anyhow::ensure!(
868            e2.code == "capability_denied",
869            "unexpected error code: {e2:?}"
870        );
871
872        Ok(())
873    }
874}