Skip to main content

cts_common/
workspace.rs

1use crate::{AsCrn, Crn, Region};
2use arrayvec::ArrayString;
3#[cfg(feature = "server")]
4use http::HeaderValue;
5use miette::Diagnostic;
6use serde::{Deserialize, Deserializer, Serialize};
7use std::{fmt::Display, str::FromStr};
8use thiserror::Error;
9use utoipa::ToSchema;
10use vitaminc::encrypt::{Aad, IntoAad};
11use vitaminc::random::{Generatable, SafeRand};
12
13const WORKSPACE_ID_BYTE_LEN: usize = 10;
14const WORKSPACE_ID_ENCODED_LEN: usize = 16;
15const ALPHABET: base32::Alphabet = base32::Alphabet::Rfc4648 { padding: false };
16
17type WorkspaceIdArrayString = ArrayString<WORKSPACE_ID_ENCODED_LEN>;
18
19#[derive(Error, Debug, Diagnostic)]
20#[error("Invalid workspace ID: {0}")]
21#[diagnostic(help = "Workspace IDs are 10-byte random strings formatted in base32.")]
22pub struct InvalidWorkspaceId(String);
23
24#[derive(Error, Debug)]
25#[error("Failed to generate workspace ID")]
26pub struct WorkspaceIdGenerationError(#[from] vitaminc::random::RandomError);
27
28/// Defines a workspace.
29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
30pub struct Workspace {
31    id: WorkspaceId,
32    region: Region,
33    #[serde(default = "default_workspace_name")]
34    #[serde(deserialize_with = "deserialize_workspace_name")]
35    name: String,
36}
37
38impl AsCrn for Workspace {
39    fn as_crn(&self) -> crate::Crn {
40        Crn::new(self.region, self.id)
41    }
42}
43
44fn deserialize_workspace_name<'d, D>(deserializer: D) -> Result<String, D::Error>
45where
46    D: Deserializer<'d>,
47{
48    let opt = Option::deserialize(deserializer)?;
49    Ok(opt.unwrap_or("unnamed workspace".to_string()))
50}
51
52impl Workspace {
53    pub fn new(id: WorkspaceId, region: Region, name: impl Into<String>) -> Self {
54        Self {
55            id,
56            region,
57            name: name.into(),
58        }
59    }
60
61    /// The unique identifier of the workspace.
62    /// See [WorkspaceId] for more information.
63    pub fn id(&self) -> WorkspaceId {
64        self.id
65    }
66
67    pub fn crn(&self) -> Crn {
68        Crn::new(self.region, self.id)
69    }
70
71    pub fn name(&self) -> &str {
72        self.name.as_str()
73    }
74
75    pub fn region(&self) -> Region {
76        self.region
77    }
78}
79
80fn default_workspace_name() -> String {
81    "Default".to_string()
82}
83
84/// A unique identifier for a workspace.
85/// Workspace IDs are 10-byte random strings formatted in base32.
86///
87/// Internally, the workspace ID is stored as an [ArrayString] with a maximum length of 20 characters.
88/// This means that values work entirely on the stack and implement the `Copy` trait.
89///
90/// # Example
91///
92/// ```
93/// use cts_common::WorkspaceId;
94///
95/// let workspace_id = WorkspaceId::generate().unwrap();
96/// println!("Workspace ID: {}", workspace_id);
97/// ```
98///
99/// A [WorkspaceId] can be converted from a string but will fail if the string is not a valid workspace ID.
100///
101/// ```
102/// use cts_common::WorkspaceId;
103/// let workspace_id = WorkspaceId::try_from("JBSWY3DPEHPK3PXP").unwrap();
104///
105/// // This will fail because the string is not a valid workspace ID
106/// let workspace_id = WorkspaceId::try_from("invalid-id").unwrap_err();
107/// ```
108///
109/// ## Comparison
110///
111/// Workspace IDs can be compared to strings.
112///
113/// ```
114/// use cts_common::WorkspaceId;
115/// let workspace_id = WorkspaceId::try_from("E4UMRN47WJNSMAKR").unwrap();
116/// assert_eq!(workspace_id, "E4UMRN47WJNSMAKR");
117/// ```
118///
119/// ## Use with Diesel
120///
121/// When the `server` feature is enabled, [WorkspaceId] can be used with Diesel in models and queries.
122/// The underlying data type is a `Text` column in the database.
123///
124#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
125#[serde(transparent)]
126#[cfg_attr(
127    feature = "server",
128    derive(diesel::expression::AsExpression, diesel::deserialize::FromSqlRow)
129)]
130#[schema(value_type = String, example = "JBSWY3DPEHPK3PXP")]
131#[cfg_attr(feature = "server", diesel(sql_type = diesel::sql_types::Text))]
132pub struct WorkspaceId(WorkspaceIdArrayString);
133
134impl WorkspaceId {
135    /// Generate a new workspace ID with an entropy source.
136    /// To use a [SafeRand] instance, use the [`Generatable::random`] method instead.
137    pub fn generate() -> Result<Self, WorkspaceIdGenerationError> {
138        let mut rng = SafeRand::from_entropy()?;
139        Ok(Self::random(&mut rng)?)
140    }
141
142    pub fn as_str(&self) -> &str {
143        self.0.as_str()
144    }
145}
146
147/// Allows `WorkspaceId` to be used directly as additional authenticated data (AAD) in
148/// AES-256-GCM-SIV encryption via the [`vitaminc`] crate.
149///
150/// This is used by the refresh token envelope to bind the workspace_id to the ciphertext
151/// so that tampering with the workspace_id causes decryption to fail. Because `WorkspaceId`
152/// is `Copy` (stack-allocated `ArrayString`), it can be passed by value into composite AAD
153/// tuples — e.g. `(extra_aad, workspace_id)` — without allocation or lifetime concerns.
154impl<'a> IntoAad<'a> for WorkspaceId {
155    fn into_aad(self) -> Aad<'a> {
156        Aad::new_owned(self.as_str().bytes())
157    }
158}
159
160impl PartialEq<&str> for WorkspaceId {
161    fn eq(&self, other: &&str) -> bool {
162        self.0.as_str() == *other
163    }
164}
165
166impl PartialEq<String> for WorkspaceId {
167    fn eq(&self, other: &String) -> bool {
168        self.0.as_str() == other.as_str()
169    }
170}
171
172impl TryFrom<String> for WorkspaceId {
173    type Error = InvalidWorkspaceId;
174
175    fn try_from(value: String) -> Result<Self, Self::Error> {
176        value.as_str().try_into()
177    }
178}
179
180impl TryFrom<&str> for WorkspaceId {
181    type Error = InvalidWorkspaceId;
182
183    fn try_from(value: &str) -> Result<Self, Self::Error> {
184        if is_valid_workspace_id(value) {
185            let mut array_str = WorkspaceIdArrayString::new();
186            array_str.push_str(value);
187            Ok(Self(array_str))
188        } else {
189            Err(InvalidWorkspaceId(value.to_string()))
190        }
191    }
192}
193
194impl FromStr for WorkspaceId {
195    type Err = InvalidWorkspaceId;
196
197    fn from_str(value: &str) -> Result<Self, Self::Err> {
198        Self::try_from(value)
199    }
200}
201
202impl From<WorkspaceId> for String {
203    fn from(value: WorkspaceId) -> Self {
204        value.0.to_string()
205    }
206}
207
208impl Generatable for WorkspaceId {
209    fn random(rng: &mut vitaminc::random::SafeRand) -> Result<Self, vitaminc::random::RandomError> {
210        let buf: [u8; WORKSPACE_ID_BYTE_LEN] = Generatable::random(rng)?;
211        let id = base32::encode(ALPHABET, &buf);
212        let mut array_str = WorkspaceIdArrayString::new();
213        array_str.push_str(&id);
214        Ok(Self(array_str))
215    }
216}
217
218impl Display for WorkspaceId {
219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        write!(f, "{}", self.0)
221    }
222}
223
224/// Workspace IDs can be converted into HTTP header values.
225#[cfg(feature = "server")]
226impl TryInto<HeaderValue> for WorkspaceId {
227    type Error = http::header::InvalidHeaderValue;
228
229    fn try_into(self) -> Result<HeaderValue, Self::Error> {
230        HeaderValue::from_str(self.0.as_str())
231    }
232}
233
234/// Check if a workspace ID is valid.
235/// A valid workspace ID is a base32 encoded string with a length of 10 bytes.
236fn is_valid_workspace_id(workspace_id: &str) -> bool {
237    if let Some(bytes) = base32::decode(ALPHABET, workspace_id) {
238        bytes.len() == WORKSPACE_ID_BYTE_LEN
239    } else {
240        false
241    }
242}
243
244#[cfg(feature = "test_utils")]
245mod testing {
246    use super::*;
247    use fake::Faker;
248    use rand::Rng;
249
250    impl fake::Dummy<Faker> for WorkspaceId {
251        fn dummy_with_rng<R: Rng + ?Sized>(_: &Faker, _: &mut R) -> Self {
252            WorkspaceId::generate().unwrap()
253        }
254    }
255}
256
257#[cfg(feature = "server")]
258mod sql_types {
259    use super::WorkspaceId;
260    use diesel::{
261        backend::Backend,
262        deserialize::{self, FromSql},
263        serialize::{self, Output, ToSql},
264        sql_types::Text,
265    };
266
267    impl<DB> ToSql<Text, DB> for WorkspaceId
268    where
269        DB: Backend,
270        str: ToSql<Text, DB>,
271    {
272        fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
273            self.0.to_sql(out)
274        }
275    }
276
277    impl<DB> FromSql<Text, DB> for WorkspaceId
278    where
279        DB: Backend,
280        String: FromSql<Text, DB>,
281    {
282        fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
283            let raw = String::from_sql(bytes)?;
284            let workspace_id = WorkspaceId::try_from(raw)?;
285
286            Ok(workspace_id)
287        }
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    mod workspace_id {
296        use super::*;
297
298        #[test]
299        fn generation_is_valid() {
300            let mut rng = vitaminc::random::SafeRand::from_entropy().unwrap();
301            let id = WorkspaceId::random(&mut rng).unwrap();
302            assert!(WorkspaceId::try_from(id.to_string()).is_ok());
303        }
304
305        #[test]
306        fn invalid_id() {
307            assert!(WorkspaceId::try_from("invalid-id").is_err());
308        }
309    }
310
311    mod workspace {
312        use super::*;
313
314        #[test]
315        fn serialize() -> anyhow::Result<()> {
316            let workspace = Workspace {
317                id: WorkspaceId::generate()?,
318                region: Region::new("us-west-1.aws")?,
319                name: "test-workspace".to_string(),
320            };
321
322            let serialized = serde_json::to_string(&workspace)?;
323            assert_eq!(
324                serialized,
325                format!(
326                    "{{\"id\":\"{}\",\"region\":\"us-west-1.aws\",\"name\":\"test-workspace\"}}",
327                    workspace.id
328                )
329            );
330
331            Ok(())
332        }
333
334        #[test]
335        fn desirialise_with_null_workspace_name() {
336            let mut rng = vitaminc::random::SafeRand::from_entropy().unwrap();
337            let id = WorkspaceId::random(&mut rng).unwrap();
338            let serialised =
339                format!("{{\"id\":\"{id}\",\"region\":\"us-west-1.aws\",\"name\":null}}",);
340
341            let deserialized: Workspace = serde_json::from_str(&serialised).unwrap();
342            assert_eq!("unnamed workspace".to_string(), deserialized.name,);
343        }
344    }
345}