Skip to main content

alien_core/
sandbox_capability.rs

1//! Sandbox capabilities: what the manager mints and the agent verifies.
2//!
3//! Lives here because both sides need identical rules, and a mismatch between minting and
4//! verification is a security bug that only shows up as "it works" until it does not.
5//!
6//! A capability is scoped to **one sandbox and one operation class**. Provider ids and hostnames
7//! are guessable, so neither is authorisation.
8
9use serde::{Deserialize, Serialize};
10
11use crate::error::{ErrorData, Result};
12use alien_error::AlienError;
13
14/// What a capability permits. Deliberately coarse: a class, not a method list, so adding a
15/// method cannot silently widen an already-minted capability.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
17#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
18#[serde(rename_all = "camelCase")]
19pub enum SandboxOperationClass {
20    /// Running commands and moving files inside an existing sandbox
21    Execute,
22    /// Creating and terminating sandboxes
23    Manage,
24    /// Reaching one declared port of the sandbox over HTTP. Neither Execute nor Manage permits
25    /// it, and it permits neither: a capability for a web server is not a shell.
26    Preview,
27}
28
29/// The claims an agent checks before doing anything.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
32#[serde(rename_all = "camelCase")]
33pub struct SandboxCapabilityClaims {
34    /// Sandbox this capability addresses
35    pub session_id: String,
36    /// Operation class permitted
37    pub operation: SandboxOperationClass,
38    /// Lifecycle generation the sandbox started under
39    pub generation: u64,
40    /// Unix seconds after which the capability is void
41    pub expires_at: i64,
42    /// Key that signed it, so rotation can retain an overlapping ring
43    pub key_id: String,
44    /// The one port a `preview` capability admits. Absent on every other class, where a port
45    /// would mean nothing.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub port: Option<u16>,
48}
49
50/// What the agent knows about itself, established at sandbox start.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct SandboxSessionIdentity {
53    /// The sandbox this agent serves
54    pub session_id: String,
55    /// The generation it started under
56    pub generation: u64,
57}
58
59impl SandboxCapabilityClaims {
60    /// Verifies claims against the agent's own identity and the current time.
61    ///
62    /// Signature checking happens before this — an unsigned claim never reaches here. What this
63    /// enforces is everything a valid signature does *not* prove: that the capability is for
64    /// this sandbox, this generation, this operation, and still in date.
65    pub fn verify(
66        &self,
67        identity: &SandboxSessionIdentity,
68        required: SandboxOperationClass,
69        now_unix: i64,
70    ) -> Result<()> {
71        // Sandbox first: a capability for another sandbox is the case that matters most, and
72        // reporting expiry for it would tell an attacker the wrong thing.
73        if self.session_id != identity.session_id {
74            return Err(refused("this capability addresses a different sandbox"));
75        }
76
77        // A running agent cannot observe a generation changed outside it, so terminate fences
78        // ingress and this check catches anything that slipped through before the fence closed.
79        if self.generation != identity.generation {
80            return Err(refused(
81                "this capability was issued for a previous lifecycle generation",
82            ));
83        }
84
85        if self.expires_at <= now_unix {
86            return Err(refused("this capability has expired"));
87        }
88
89        // Execute does not imply Manage. Manage does not imply Execute either: the whole point
90        // of the split is that an app which only runs code cannot terminate sandboxes.
91        if self.operation != required {
92            return Err(refused(
93                "this capability does not permit this operation class",
94            ));
95        }
96
97        Ok(())
98    }
99
100    /// Whether this capability admits `port`. A preview capability admits only the port it was
101    /// minted for; any other class admits none, so a shell capability cannot reach a web port.
102    pub fn admits_port(&self, port: u16) -> bool {
103        self.operation == SandboxOperationClass::Preview && self.port == Some(port)
104    }
105}
106
107fn refused(reason: &str) -> AlienError<ErrorData> {
108    AlienError::new(ErrorData::SandboxCapabilityRefused {
109        reason: reason.to_string(),
110    })
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    const NOW: i64 = 1_000_000;
118
119    fn identity() -> SandboxSessionIdentity {
120        SandboxSessionIdentity {
121            session_id: "s1".to_string(),
122            generation: 2,
123        }
124    }
125
126    fn claims() -> SandboxCapabilityClaims {
127        SandboxCapabilityClaims {
128            session_id: "s1".to_string(),
129            operation: SandboxOperationClass::Execute,
130            generation: 2,
131            expires_at: NOW + 300,
132            key_id: "k1".to_string(),
133            port: None,
134        }
135    }
136
137    #[test]
138    fn a_preview_capability_admits_only_its_port_and_no_other_class() {
139        let mut preview = claims();
140        preview.operation = SandboxOperationClass::Preview;
141        preview.port = Some(8080);
142        assert!(preview.admits_port(8080));
143        assert!(!preview.admits_port(8971));
144        preview
145            .verify(&identity(), SandboxOperationClass::Execute, NOW)
146            .expect_err("a preview capability does not run commands");
147        let mut execute = claims();
148        execute.port = Some(8080);
149        assert!(
150            !execute.admits_port(8080),
151            "only a preview capability admits a port"
152        );
153    }
154
155    #[test]
156    fn a_matching_capability_is_accepted() {
157        claims()
158            .verify(&identity(), SandboxOperationClass::Execute, NOW)
159            .expect("a capability for this sandbox, generation and class is valid");
160    }
161
162    /// The case that matters most: provider ids are guessable, so a capability
163    /// minted for one sandbox must be useless against another.
164    #[test]
165    fn a_capability_for_another_session_is_refused() {
166        let mut other = claims();
167        other.session_id = "s2".to_string();
168
169        let error = other
170            .verify(&identity(), SandboxOperationClass::Execute, NOW)
171            .expect_err("sandbox B must not accept sandbox A's capability");
172        assert!(error.to_string().contains("different sandbox"));
173    }
174
175    /// Terminate bumps the generation; anything minted before is void even if
176    /// its signature and expiry are still good.
177    #[test]
178    fn a_capability_from_a_previous_generation_is_refused() {
179        let mut stale = claims();
180        stale.generation = 1;
181
182        let error = stale
183            .verify(&identity(), SandboxOperationClass::Execute, NOW)
184            .expect_err("a previous generation must be refused");
185        assert!(error.to_string().contains("generation"));
186    }
187
188    #[test]
189    fn an_expired_capability_is_refused() {
190        let mut expired = claims();
191        expired.expires_at = NOW;
192
193        expired
194            .verify(&identity(), SandboxOperationClass::Execute, NOW)
195            .expect_err("expiry is inclusive: a capability expiring now is already void");
196    }
197
198    /// The split only means something if it holds in both directions. An execute-only app must
199    /// not terminate sandboxes, and a manage-only component must not read sandbox contents.
200    #[test]
201    fn operation_classes_do_not_imply_each_other() {
202        claims()
203            .verify(&identity(), SandboxOperationClass::Manage, NOW)
204            .expect_err("execute must not permit manage");
205
206        let mut manage = claims();
207        manage.operation = SandboxOperationClass::Manage;
208        manage
209            .verify(&identity(), SandboxOperationClass::Execute, NOW)
210            .expect_err("manage must not permit execute");
211    }
212
213    /// Checked before expiry on purpose: telling a caller "expired" for a capability that was
214    /// never theirs leaks which sandboxes exist.
215    #[test]
216    fn a_wrong_session_is_reported_as_wrong_session_even_when_also_expired() {
217        let mut wrong = claims();
218        wrong.session_id = "s2".to_string();
219        wrong.expires_at = NOW - 1;
220
221        let error = wrong
222            .verify(&identity(), SandboxOperationClass::Execute, NOW)
223            .expect_err("refused");
224        assert!(
225            error.to_string().contains("different sandbox"),
226            "the reason must not reveal that some other sandbox's capability had expired"
227        );
228    }
229
230    #[test]
231    fn claims_round_trip_so_minting_and_verification_cannot_drift() {
232        let json = serde_json::to_string(&claims()).expect("serializes");
233        let restored: SandboxCapabilityClaims = serde_json::from_str(&json).expect("deserializes");
234        assert_eq!(claims(), restored);
235    }
236}