Skip to main content

ciab_gateway/proxy/
mod.rs

1use uuid::Uuid;
2
3use crate::types::TokenScope;
4
5/// Extract sandbox ID from a path-based proxy URL (`/sandbox/<id>/...`).
6pub fn extract_sandbox_id_from_path(path: &str) -> Option<Uuid> {
7    let parts: Vec<&str> = path.trim_start_matches('/').splitn(3, '/').collect();
8    if parts.len() >= 2 && parts[0] == "sandbox" {
9        Uuid::parse_str(parts[1]).ok()
10    } else {
11        None
12    }
13}
14
15/// Strip the `/sandbox/<id>` prefix from a path, returning the remainder.
16pub fn strip_sandbox_prefix(path: &str) -> String {
17    let parts: Vec<&str> = path.trim_start_matches('/').splitn(3, '/').collect();
18    if parts.len() >= 3 && parts[0] == "sandbox" {
19        format!("/{}", parts[2])
20    } else if parts.len() == 2 && parts[0] == "sandbox" {
21        "/".to_string()
22    } else {
23        path.to_string()
24    }
25}
26
27/// Check if a set of scopes allows access to a sandbox.
28pub fn check_sandbox_access(scopes: &[TokenScope], sandbox_id: &Uuid) -> bool {
29    scopes.iter().any(|s| s.allows_sandbox(sandbox_id))
30}
31
32/// Check if a set of scopes allows write access.
33pub fn check_write_access(scopes: &[TokenScope]) -> bool {
34    scopes.iter().any(|s| s.allows_write())
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn test_extract_sandbox_id() {
43        let id = Uuid::new_v4();
44        let path = format!("/sandbox/{}/api/v1/sessions", id);
45        assert_eq!(extract_sandbox_id_from_path(&path), Some(id));
46    }
47
48    #[test]
49    fn test_strip_prefix() {
50        let id = Uuid::new_v4();
51        let path = format!("/sandbox/{}/api/v1/sessions", id);
52        assert_eq!(strip_sandbox_prefix(&path), "/api/v1/sessions");
53    }
54
55    #[test]
56    fn test_strip_prefix_no_trailing() {
57        let id = Uuid::new_v4();
58        let path = format!("/sandbox/{}", id);
59        assert_eq!(strip_sandbox_prefix(&path), "/");
60    }
61
62    #[test]
63    fn test_no_sandbox_prefix() {
64        assert_eq!(extract_sandbox_id_from_path("/api/v1/health"), None);
65    }
66}