1#[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#[derive(
35 Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default,
36)]
37pub struct CapabilityToken(pub String);
38
39#[derive(Debug, Clone, Serialize, Deserialize, Default)]
41pub struct CapabilitySet {
42 pub allowed: HashMap<ServiceName, Vec<MethodRule>>,
44 pub global_limits: Option<GlobalLimits>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
50pub struct ServiceName(pub String);
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct MethodRule {
55 pub method: MethodSelector,
56 pub quotas: Option<QuotaSet>,
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize)]
61pub enum MethodSelector {
62 Exact(String),
64 Prefix(String),
66 Any,
68}
69
70impl MethodSelector {
71 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#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct QuotaSet {
87 pub bytes_per_sec: Option<u64>,
89 pub ops_per_sec: Option<u64>,
91 pub burst: Option<u64>,
93}
94
95impl QuotaSet {
96 pub fn effective_burst_bytes(&self) -> Option<u64> {
101 let Some(rate) = self.bytes_per_sec else {
102 return None;
103 };
104 Some(self.burst.unwrap_or(rate))
106 }
107
108 pub fn effective_burst_ops(&self) -> Option<u64> {
113 let Some(rate) = self.ops_per_sec else {
114 return None;
115 };
116 Some(self.burst.unwrap_or(rate))
118 }
119}
120
121#[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 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#[derive(Debug, Clone, Serialize, Deserialize, Default)]
141pub struct CapabilityBundle {
142 pub token: CapabilityToken,
144 pub capabilities: CapabilitySet,
146}
147
148pub trait TokenValidator: Send + Sync + std::fmt::Debug {
151 fn validate(
153 &self,
154 token: &CapabilityToken,
155 ) -> Result<CapabilitySet, anyhow::Error>;
156}
157
158#[derive(Debug, Default)]
177pub struct InMemoryTokenValidator {
178 tokens: std::sync::RwLock<HashMap<String, CapabilitySet>>,
179}
180
181impl InMemoryTokenValidator {
182 pub fn new() -> Self {
184 Self {
185 tokens: std::sync::RwLock::new(HashMap::new()),
186 }
187 }
188
189 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 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 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
235pub 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 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 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 match kind {
276 ChildKind::Network | ChildKind::Io | ChildKind::Storage => {
277 }
279 _ => {
280 }
282 }
283
284 CapabilitySet {
285 allowed,
286 global_limits: None,
287 }
288}
289
290pub 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 #[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; 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}