Skip to main content

capsid_protocol/
workspace.rs

1use serde::{Deserialize, Serialize};
2use uuid::Uuid;
3
4use crate::{
5    AttemptId, Error, InstanceId, Result, WorkspaceAttachmentId, WorkspaceGrantId, WorkspaceId,
6};
7
8pub const MAX_MOUNTS: usize = 64;
9
10pub const MAX_WORKSPACES: usize = 512;
11
12pub const MAX_SESSIONS: usize = 128;
13
14pub const MAX_NEW_GRANTS: usize = 4096;
15
16pub const MAX_GRANTS: usize = 2 * MAX_NEW_GRANTS;
17
18pub const GUEST_ROOT: &str = "/workspaces";
19
20pub const MIN_STORAGE_UID: u32 = 1_000_000;
21
22pub const MAX_STORAGE_UID: u32 = i32::MAX as u32;
23
24pub fn is_storage_uid(uid: u32) -> bool {
25    (MIN_STORAGE_UID..=MAX_STORAGE_UID).contains(&uid)
26}
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct RequiredMount {
31    pub attachment: WorkspaceAttachmentId,
32
33    pub target: String,
34
35    pub access: Access,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(deny_unknown_fields)]
40pub struct Mount {
41    pub attachment: WorkspaceAttachmentId,
42
43    pub grant: WorkspaceGrantId,
44
45    pub generation: u64,
46
47    pub target: String,
48
49    pub access: Access,
50
51    pub user: String,
52}
53
54#[derive(Debug, Serialize, Deserialize)]
55#[serde(deny_unknown_fields)]
56pub struct ClientRequest {
57    pub version: u32,
58
59    pub attachment: WorkspaceAttachmentId,
60
61    pub grant: WorkspaceGrantId,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(rename_all = "snake_case")]
66pub enum MountState {
67    Mounting,
68
69    Mounted,
70
71    Busy,
72
73    Detaching,
74
75    Failed,
76
77    Detached,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(deny_unknown_fields)]
82pub struct MountStatus {
83    pub binding: Mount,
84
85    pub state: MountState,
86
87    pub message: Option<String>,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(deny_unknown_fields)]
92pub struct GrantSpec {
93    pub workspace: WorkspaceId,
94
95    pub attachment: WorkspaceAttachmentId,
96
97    pub id: WorkspaceGrantId,
98
99    pub generation: u64,
100
101    pub instance: InstanceId,
102
103    pub attempt: AttemptId,
104
105    pub storage_attempt: AttemptId,
106
107    pub access: Access,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
112pub enum StorageAction {
113    Hello,
114
115    Create {
116        workspace: WorkspaceId,
117
118        uid: u32,
119
120        quota: Quota,
121    },
122
123    Inspect {
124        workspace: WorkspaceId,
125    },
126
127    Delete {
128        workspace: WorkspaceId,
129
130        uid: u32,
131
132        quota: Quota,
133    },
134
135    Grant {
136        grant: GrantSpec,
137    },
138
139    Revoke {
140        grant: GrantSpec,
141    },
142
143    GrantStatus {
144        grant: WorkspaceGrantId,
145    },
146}
147
148#[derive(Debug, Clone, Serialize, Deserialize)]
149#[serde(deny_unknown_fields)]
150pub struct StorageRequest {
151    pub version: u32,
152
153    pub storage_attempt: AttemptId,
154
155    pub action: StorageAction,
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(rename_all = "snake_case")]
160pub enum StorageState {
161    Creating,
162
163    Ready,
164
165    Deleting,
166
167    Removed,
168}
169
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(rename_all = "snake_case")]
172pub enum StorageGrantState {
173    Active,
174
175    Revoking,
176
177    Revoked,
178}
179
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181#[serde(deny_unknown_fields)]
182pub struct GrantStatus {
183    pub spec: GrantSpec,
184
185    pub state: StorageGrantState,
186}
187
188#[derive(Debug, Serialize, Deserialize)]
189#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
190pub enum StorageResult {
191    Hello {
192        boot: Uuid,
193
194        capacity_bytes: u64,
195    },
196
197    Workspace {
198        workspace: WorkspaceId,
199
200        uid: u32,
201
202        quota: Quota,
203
204        state: StorageState,
205
206        bytes: u64,
207
208        inodes: u64,
209    },
210
211    Grant {
212        grant: GrantStatus,
213    },
214
215    Error {
216        message: String,
217    },
218}
219
220#[derive(Debug, Serialize, Deserialize)]
221#[serde(deny_unknown_fields)]
222pub struct StorageResponse {
223    pub version: u32,
224
225    pub storage_attempt: AttemptId,
226
227    pub result: StorageResult,
228}
229
230#[derive(Debug, Serialize, Deserialize)]
231#[serde(deny_unknown_fields)]
232pub struct DataRequest {
233    pub version: u32,
234
235    pub storage_attempt: AttemptId,
236
237    pub grant: WorkspaceGrantId,
238
239    pub attempt: AttemptId,
240}
241
242#[derive(Debug, Serialize, Deserialize)]
243#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
244pub enum DataResponse {
245    Connected { grant: WorkspaceGrantId },
246
247    Error { message: String },
248}
249
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(rename_all = "snake_case")]
252pub enum Access {
253    ReadOnly,
254
255    ReadWrite,
256}
257
258#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(deny_unknown_fields)]
260pub struct Quota {
261    pub bytes: u64,
262
263    pub inodes: u64,
264}
265
266impl Quota {
267    pub fn validate(&self) -> Result<()> {
268        if !(64 * 1024..=256 * 1024 * 1024).contains(&self.bytes)
269            || !self.bytes.is_multiple_of(4096)
270            || !(16..=65536).contains(&self.inodes)
271        {
272            return Err(Error::Invalid(
273                "workspace quota requires 64 KiB to 256 MiB in whole 4 KiB blocks and 16 to 65536 inodes",
274            ));
275        }
276        Ok(())
277    }
278}
279
280pub fn validate_target(target: &str) -> Result<()> {
281    let valid = target_path(target).is_some_and(|tail| {
282        !tail.is_empty()
283            && tail.split('/').count() <= 8
284            && tail.split('/').all(|part| {
285                !part.is_empty()
286                    && part != "."
287                    && part != ".."
288                    && part != ".capsid"
289                    && part.len() <= 128
290                    && part
291                        .bytes()
292                        .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
293            })
294    });
295    if !valid || target.len() > 1024 {
296        return Err(Error::Invalid(
297            "workspace target must be a normal path below /workspaces with at most eight components",
298        ));
299    }
300    Ok(())
301}
302
303pub fn target_path(target: &str) -> Option<&str> {
304    target
305        .strip_prefix(GUEST_ROOT)
306        .and_then(|tail| tail.strip_prefix('/'))
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    #[test]
314    fn test_targets_stay_below_the_reserved_directory() {
315        for target in [
316            "/workspaces/a",
317            "/workspaces/a/results",
318            "/workspaces/result-1",
319        ] {
320            assert!(validate_target(target).is_ok(), "{target}");
321        }
322        for target in [
323            "/workspaces",
324            "/workspaces/",
325            "/workspaces//a",
326            "/workspaces/a/../b",
327            "/workspaces/./a",
328            "/workspaces/.capsid/a",
329            "/dev/a",
330            "/workspaces/a\n",
331        ] {
332            assert!(validate_target(target).is_err(), "{target:?}");
333        }
334        assert!(crate::path::overlap(
335            "/workspaces/a",
336            "/workspaces/a/result"
337        ));
338        assert!(!crate::path::overlap("/workspaces/a", "/workspaces/ab"));
339    }
340}