ctb_workspace_ipc/auth/
capability.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//! Granular capability tokens and permission checks for IPC services.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace prelude"
26)]
27use crate::utilities::*;
28
29use ipc::ChildKind;
30use serde::{Deserialize, Serialize};
31use std::collections::HashMap;
32
33/// An unguessable capability token bound to a single connection/process.
34#[derive(
35    Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default,
36)]
37pub struct CapabilityToken(pub String);
38
39/// A set of capabilities for a process, not including a token.
40#[derive(Debug, Clone, Serialize, Deserialize, Default)]
41pub struct CapabilitySet {
42    /// Allowed methods per service, including optional quotas/limits.
43    pub allowed: HashMap<ServiceName, Vec<MethodRule>>,
44    /// Optional global quotas or ceilings.
45    pub global_limits: Option<GlobalLimits>,
46}
47
48/// Logical service identifier (human-readable, stable across versions).
49#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
50pub struct ServiceName(pub String);
51
52/// Pattern/rule controlling access to a method with optional quotas.
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct MethodRule {
55    pub method: MethodSelector,
56    pub quotas: Option<QuotaSet>,
57}
58
59/// A method selector can be exact or wildcard.
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub enum MethodSelector {
62    /// Exact service.method string, e.g., "storage.get".
63    Exact(String),
64    /// Prefix match, e.g., "network." allows "network.get" and "network.post".
65    Prefix(String),
66    /// Allow all methods in the service.
67    Any,
68}
69
70impl MethodSelector {
71    /// Check if this selector matches the given service and method.
72    pub fn matches(&self, service: &str, method: &str) -> bool {
73        let full_name = format!("{service}.{method}");
74        match self {
75            MethodSelector::Exact(s) => s == method || s == &full_name,
76            MethodSelector::Prefix(prefix) => {
77                method.starts_with(prefix) || full_name.starts_with(prefix)
78            }
79            MethodSelector::Any => true,
80        }
81    }
82}
83
84/// Quotas applicable to a method.
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct QuotaSet {
87    /// Optional bytes/sec rate limit.
88    pub bytes_per_sec: Option<u64>,
89    /// Optional ops/sec limit.
90    pub ops_per_sec: Option<u64>,
91    /// Optional burst capacity.
92    pub burst: Option<u64>,
93}
94
95impl QuotaSet {
96    /// Compute the effective burst capacity for a bytes/sec token bucket.
97    ///
98    /// If `burst` is not specified, this defaults to allowing a 1-second burst
99    /// at the configured rate.
100    pub fn effective_burst_bytes(&self) -> Option<u64> {
101        let Some(rate) = self.bytes_per_sec else {
102            return None;
103        };
104        // Reason for fallback: unconfigured burst capacity defaults to 1-second burst at target rate per docblock
105        Some(self.burst.unwrap_or(rate))
106    }
107
108    /// Compute the effective burst capacity for an ops/sec token bucket.
109    ///
110    /// If `burst` is not specified, this defaults to allowing a 1-second burst
111    /// at the configured rate.
112    pub fn effective_burst_ops(&self) -> Option<u64> {
113        let Some(rate) = self.ops_per_sec else {
114            return None;
115        };
116        // Reason for fallback: unconfigured burst capacity defaults to 1-second burst at target rate per docblock
117        Some(self.burst.unwrap_or(rate))
118    }
119}
120
121/// Global limits across the connection/process.
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct GlobalLimits {
124    pub max_concurrent_requests: Option<u32>,
125    pub max_streams: Option<u32>,
126    pub max_blob_bytes: Option<u64>,
127}
128
129impl GlobalLimits {
130    /// Whether this set contains any configured limits.
131    pub fn is_empty(&self) -> bool {
132        self.max_concurrent_requests.is_none()
133            && self.max_streams.is_none()
134            && self.max_blob_bytes.is_none()
135    }
136}
137
138/// A capability bundle given to the workspace to spawn a child process.
139/// Includes both a token and a capability set.
140#[derive(Debug, Clone, Serialize, Deserialize, Default)]
141pub struct CapabilityBundle {
142    /// Initial capability token to authenticate the child’s control connection.
143    pub token: CapabilityToken,
144    /// Initial capability set bound to the connection.
145    pub capabilities: CapabilitySet,
146}
147
148/// Validates a capability token and derives a bound `CapabilitySet`.
149/// Implementations should avoid panics and return errors for invalid tokens.
150pub trait TokenValidator: Send + Sync + std::fmt::Debug {
151    /// Validate a token, producing a `CapabilitySet` on success.
152    fn validate(
153        &self,
154        token: &CapabilityToken,
155    ) -> Result<CapabilitySet, anyhow::Error>;
156}
157
158/// A simple in-memory token validator that stores tokens and their associated
159/// capability sets.
160///
161/// This is useful for examples and tests. For production use, consider a more
162/// sophisticated implementation (e.g., database-backed, time-limited tokens).
163///
164/// # Example
165///
166/// ```
167/// use ctb_workspace_ipc::auth::capability::{
168///     InMemoryTokenValidator, CapabilitySet, CapabilityToken, TokenValidator,
169/// };
170///
171/// let validator = InMemoryTokenValidator::new();
172/// validator.register_token("my-token", CapabilitySet::default());
173///
174/// let caps = validator.validate(&CapabilityToken("my-token".into())).unwrap();
175/// ```
176#[derive(Debug, Default)]
177pub struct InMemoryTokenValidator {
178    tokens: std::sync::RwLock<HashMap<String, CapabilitySet>>,
179}
180
181impl InMemoryTokenValidator {
182    /// Create a new empty validator.
183    pub fn new() -> Self {
184        Self {
185            tokens: std::sync::RwLock::new(HashMap::new()),
186        }
187    }
188
189    /// Register a token with its associated capability set.
190    ///
191    /// If the token already exists, its capability set is replaced.
192    pub fn register_token(&self, token: &str, caps: CapabilitySet) {
193        if let Ok(mut guard) = self.tokens.write() {
194            guard.insert(token.to_string(), caps);
195        }
196    }
197
198    /// Remove a registered token.
199    ///
200    /// Returns the capability set if the token was present.
201    pub fn revoke_token(&self, token: &str) -> Option<CapabilitySet> {
202        if let Ok(mut guard) = self.tokens.write() {
203            guard.remove(token)
204        } else {
205            None
206        }
207    }
208
209    /// Check if a token is registered.
210    pub fn has_token(&self, token: &str) -> bool {
211        if let Ok(guard) = self.tokens.read() {
212            guard.contains_key(token)
213        } else {
214            false
215        }
216    }
217}
218
219impl TokenValidator for InMemoryTokenValidator {
220    fn validate(
221        &self,
222        token: &CapabilityToken,
223    ) -> Result<CapabilitySet, anyhow::Error> {
224        let guard = self
225            .tokens
226            .read()
227            .map_err(|e| anyhow::anyhow!("lock poisoned: {e}"))?;
228        guard
229            .get(&token.0)
230            .cloned()
231            .ok_or_else(|| anyhow::anyhow!("invalid token: {}", token.0))
232    }
233}
234
235/// Provides default capabilities for singleton services.
236///
237/// These are minimal capabilities that allow services to perform basic
238/// operations like shutting down their own process tree.
239pub fn default_service_capabilities(kind: ChildKind) -> CapabilitySet {
240    use crate::auth::capability::{MethodRule, MethodSelector, ServiceName};
241    use crate::services::process::SERVICE_NAME as PROCESS_SERVICE_NAME;
242    use std::collections::HashMap;
243
244    let mut allowed: HashMap<ServiceName, Vec<MethodRule>> = HashMap::new();
245
246    // All services can shut down their own process tree
247    allowed.insert(
248        ServiceName(PROCESS_SERVICE_NAME.to_string()),
249        vec![MethodRule {
250            method: MethodSelector::Exact("shutdown_own_tree".into()),
251            quotas: None,
252        }],
253    );
254
255    // All services can query environment from workspace
256    allowed.insert(
257        ServiceName("workspace".to_string()),
258        vec![
259            MethodRule {
260                method: MethodSelector::Exact("capture".into()),
261                quotas: None,
262            },
263            MethodRule {
264                method: MethodSelector::Exact("capture_quick".into()),
265                quotas: None,
266            },
267            MethodRule {
268                method: MethodSelector::Exact("env_cache_reset".into()),
269                quotas: None,
270            },
271        ],
272    );
273
274    // Service-specific capabilities can be added here
275    match kind {
276        ChildKind::Network | ChildKind::Io | ChildKind::Storage => {
277            // Use the common capabilities defined above
278        }
279        _ => {
280            // Non-service processes don't get capabilities via this function
281        }
282    }
283
284    CapabilitySet {
285        allowed,
286        global_limits: None,
287    }
288}
289
290/// Capabilities used to authorize requests arriving from the workspace.
291///
292/// In the current IPC topology, a child process only accepts inbound IPC
293/// requests from its parent workspace process over its single control
294/// connection. The parent workspace is trusted to call into the child’s
295/// locally-hosted services (e.g., `process`, `network`, `renderer`).
296///
297/// This capability set is used on the child side for authorizing *incoming*
298/// requests. It is intentionally distinct from the capability set issued by
299/// the workspace during handshake, which represents what the child is allowed
300/// to call on the workspace.
301pub fn trusted_workspace_capabilities() -> CapabilitySet {
302    use crate::auth::capability::{MethodRule, MethodSelector, ServiceName};
303    use crate::services::formats::SERVICE_NAME as FORMATS_SERVICE_NAME;
304    use crate::services::io::SERVICE_NAME as IO_SERVICE_NAME;
305    use crate::services::network::SERVICE_NAME as NETWORK_SERVICE_NAME;
306    use crate::services::parent::SERVICE_NAME as PARENT_SERVICE_NAME;
307    use crate::services::process::SERVICE_NAME as PROCESS_SERVICE_NAME;
308    use crate::services::renderer::SERVICE_NAME as RENDERER_SERVICE_NAME;
309    use crate::services::runtime::SERVICE_NAME as RUNTIME_SERVICE_NAME;
310    use crate::services::storage::SERVICE_NAME as STORAGE_SERVICE_NAME;
311    use std::collections::HashMap;
312
313    let mut allowed: HashMap<ServiceName, Vec<MethodRule>> = HashMap::new();
314
315    for service in [
316        PROCESS_SERVICE_NAME,
317        FORMATS_SERVICE_NAME,
318        IO_SERVICE_NAME,
319        NETWORK_SERVICE_NAME,
320        RENDERER_SERVICE_NAME,
321        RUNTIME_SERVICE_NAME,
322        PARENT_SERVICE_NAME,
323        STORAGE_SERVICE_NAME,
324    ] {
325        allowed.insert(
326            ServiceName(service.to_string()),
327            vec![MethodRule {
328                method: MethodSelector::Any,
329                quotas: None,
330            }],
331        );
332    }
333
334    CapabilitySet {
335        allowed,
336        global_limits: None,
337    }
338}
339
340#[cfg(test)]
341#[allow(
342    clippy::panic,
343    clippy::expect_used,
344    clippy::unwrap_used,
345    clippy::unwrap_in_result,
346    clippy::panic_in_result_fn,
347    clippy::indexing_slicing,
348    clippy::arithmetic_side_effects,
349    reason = "Standard repository test boilerplate"
350)]
351mod tests {
352    use super::*;
353    use anyhow::Result;
354
355    /// A simple fake validator for tests. Accepts "ok", rejects others.
356    #[derive(Debug)]
357    struct FakeTokenValidator;
358
359    impl TokenValidator for FakeTokenValidator {
360        fn validate(
361            &self,
362            token: &CapabilityToken,
363        ) -> Result<CapabilitySet, anyhow::Error> {
364            if token.0 == "ok" {
365                Ok(CapabilitySet::default())
366            } else {
367                Err(anyhow::anyhow!("invalid token"))
368            }
369        }
370    }
371
372    #[crate::ctb_test]
373    fn fake_validator_ok() -> Result<()> {
374        let v = FakeTokenValidator;
375        let set = v.validate(&CapabilityToken("ok".into()))?;
376        let _ = set; // success
377        Ok(())
378    }
379
380    #[crate::ctb_test]
381    fn fake_validator_err() -> Result<()> {
382        let v = FakeTokenValidator;
383        let res = v.validate(&CapabilityToken("bad".into()));
384        res.unwrap_err();
385        Ok(())
386    }
387
388    #[crate::ctb_test]
389    fn in_memory_validator_register_and_validate() -> Result<()> {
390        let v = InMemoryTokenValidator::new();
391        v.register_token("test-token", CapabilitySet::default());
392
393        assert!(v.has_token("test-token"));
394        assert!(!v.has_token("other-token"));
395
396        let caps = v.validate(&CapabilityToken("test-token".into()))?;
397        assert!(caps.allowed.is_empty());
398
399        Ok(())
400    }
401
402    #[crate::ctb_test]
403    fn in_memory_validator_revoke() -> Result<()> {
404        let v = InMemoryTokenValidator::new();
405        v.register_token("test-token", CapabilitySet::default());
406        assert!(v.has_token("test-token"));
407
408        let revoked = v.revoke_token("test-token");
409        assert!(revoked.is_some());
410        assert!(!v.has_token("test-token"));
411
412        let res = v.validate(&CapabilityToken("test-token".into()));
413        res.unwrap_err();
414
415        Ok(())
416    }
417
418    #[crate::ctb_test]
419    fn in_memory_validator_invalid_token() -> Result<()> {
420        let v = InMemoryTokenValidator::new();
421        let res = v.validate(&CapabilityToken("nonexistent".into()));
422        res.unwrap_err();
423        Ok(())
424    }
425}