cipherstash-client 0.34.1-alpha.1

The official CipherStash SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use serde::{Deserialize, Serialize};
use stack_profile::{ProfileData, ProfileError, ProfileStore};
use uuid::Uuid;
use vitaminc::protected::OpaqueDebug;
use zeroize::{Zeroize, ZeroizeOnDrop};
use zerokms_protocol::ViturKeyMaterial;

use super::{ClientKey, KeyProvider, KeyProviderError};

/// A device-scoped client key, stored in `secretkey.json` within the profile directory.
///
/// The key material is zeroized on drop and hidden from debug output.
///
/// # Example
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use cipherstash_client::zerokms::{SecretKey, KeyProvider};
/// use zerokms_protocol::ViturKeyMaterial;
/// use uuid::Uuid;
///
/// let key_material: ViturKeyMaterial = vec![/* key bytes */].into();
/// let secret_key = SecretKey::new(
///     Uuid::new_v4(),
///     key_material,
/// );
///
/// // SecretKey implements KeyProvider
/// let client_key = secret_key.client_key().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Serialize, Deserialize, Zeroize, ZeroizeOnDrop, OpaqueDebug)]
pub struct SecretKey {
    /// The client ID returned by ZeroKMS when creating a device keyset.
    #[zeroize(skip)]
    client_id: Uuid,
    /// The client key material for this device.
    client_key: ViturKeyMaterial,
}

impl SecretKey {
    /// Create a new [`SecretKey`] from the given client ID and key material.
    pub fn new(client_id: Uuid, client_key: ViturKeyMaterial) -> Self {
        Self {
            client_id,
            client_key,
        }
    }

    /// Create a [`SecretKey`] from string representations of the client ID and hex-encoded key material.
    ///
    /// This is a convenience constructor for FFI boundaries where the client ID and key material
    /// arrive as strings.
    ///
    /// # Errors
    ///
    /// Returns [`KeyProviderError::InvalidKey`] if:
    /// - `client_id` is not a valid UUID
    /// - `client_key_hex` is not valid hex
    pub fn from_hex(
        client_id: String,
        mut client_key_hex: String,
    ) -> Result<Self, KeyProviderError> {
        let uuid = Uuid::parse_str(&client_id)
            .map_err(|e| KeyProviderError::InvalidKey(format!("invalid client_id: {e}")))?;

        let result = base16ct::mixed::decode_vec(&client_key_hex);
        client_key_hex.zeroize();

        let bytes = result
            .map_err(|e| KeyProviderError::InvalidKey(format!("invalid client_key hex: {e}")))?;

        Ok(Self::new(uuid, ViturKeyMaterial::from(bytes)))
    }

    /// Load a [`SecretKey`] from the `CS_CLIENT_ID` and `CS_CLIENT_KEY` environment variables.
    ///
    /// Returns `Ok(None)` if neither or only one variable is set, allowing callers to
    /// fall back to another source. Returns `Err` if both variables are present but
    /// the values are invalid (bad UUID or bad hex).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use cipherstash_client::zerokms::SecretKey;
    ///
    /// let key = SecretKey::from_env().expect("invalid key material in env");
    /// // key is Option<SecretKey> — None means "not configured via env"
    /// ```
    pub fn from_env() -> Result<Option<Self>, KeyProviderError> {
        use crate::config::vars::{CS_CLIENT_ID, CS_CLIENT_KEY};

        match (std::env::var(CS_CLIENT_ID), std::env::var(CS_CLIENT_KEY)) {
            (Ok(id), Ok(key)) => {
                tracing::debug!("both {CS_CLIENT_ID} and {CS_CLIENT_KEY} set, loading secret key");
                Self::from_hex(id, key).map(Some)
            }
            (Ok(_), Err(_)) => {
                tracing::debug!("{CS_CLIENT_ID} set but {CS_CLIENT_KEY} missing, skipping");
                Ok(None)
            }
            (Err(_), Ok(_)) => {
                tracing::debug!("{CS_CLIENT_KEY} set but {CS_CLIENT_ID} missing, skipping");
                Ok(None)
            }
            (Err(_), Err(_)) => {
                tracing::debug!("neither {CS_CLIENT_ID} nor {CS_CLIENT_KEY} set");
                Ok(None)
            }
        }
    }
}

/// Implement [ProfileData] for [SecretKey] to enable loading/saving from the profile directory.
impl ProfileData for SecretKey {
    const FILENAME: &'static str = "secretkey.json";
    const MODE: Option<u32> = Some(0o600);
}

/// Implement [KeyProvider] for [SecretKey] to allow it to be used directly as a key source when initializing with a [super::ZeroKMSBuilder].
impl KeyProvider for SecretKey {
    async fn client_key(&self) -> Result<ClientKey, KeyProviderError> {
        ClientKey::from_bytes(self.client_id, &self.client_key)
            .map_err(|e| KeyProviderError::InvalidKey(e.to_string()))
    }
}

impl KeyProvider for ProfileStore {
    async fn client_key(&self) -> Result<ClientKey, KeyProviderError> {
        let ws_store = self.current_workspace_store().map_err(|e| match e {
            ProfileError::NoCurrentWorkspace => KeyProviderError::NotConfigured(e.to_string()),
            _ => KeyProviderError::LoadError(e.to_string()),
        })?;
        let secret_key: SecretKey = ws_store.load_profile().map_err(|e| match e {
            ProfileError::NotFound { .. } => KeyProviderError::NotConfigured(e.to_string()),
            _ => KeyProviderError::LoadError(e.to_string()),
        })?;
        secret_key.client_key().await
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use recipher::keyset::{EncryptionKeySet, ProxyKeySet};
    use tempfile::TempDir;

    /// Build a random `SecretKey` and return it alongside the `client_id` and raw keyset bytes.
    fn random_secret_key() -> (SecretKey, Uuid, Vec<u8>) {
        let client_id = Uuid::new_v4();
        let ek_a = EncryptionKeySet::generate().unwrap();
        let ek_b = EncryptionKeySet::generate().unwrap();
        let keyset = ProxyKeySet::generate(&ek_a, &ek_b);
        let bytes = keyset.to_bytes().unwrap();

        let secret_key = SecretKey::new(client_id, ViturKeyMaterial::from(bytes.clone()));

        (secret_key, client_id, bytes)
    }

    mod secret_key_provider {
        use super::*;

        #[tokio::test]
        async fn returns_client_key_with_matching_id() {
            let (secret_key, client_id, _) = random_secret_key();

            let result = secret_key.client_key().await.unwrap();

            assert_eq!(
                result.key_id, client_id,
                "client_key should preserve the client_id"
            );
        }

        #[tokio::test]
        async fn returns_client_key_with_correct_key_material() {
            let (secret_key, _, bytes) = random_secret_key();

            let result = secret_key.client_key().await.unwrap();

            let expected_hex = base16ct::lower::encode_string(&bytes);
            let actual_hex = result.to_hex_v1().unwrap();
            assert_eq!(
                actual_hex, expected_hex,
                "client_key should preserve the key material"
            );
        }

        #[tokio::test]
        async fn returns_invalid_key_for_bad_material() {
            let secret_key =
                SecretKey::new(Uuid::new_v4(), ViturKeyMaterial::from(vec![0xDE, 0xAD]));

            let err = secret_key.client_key().await.unwrap_err();

            assert!(
                matches!(err, KeyProviderError::InvalidKey(_)),
                "expected InvalidKey for garbage bytes, got: {err:?}"
            );
        }
    }

    mod from_hex {
        use super::*;

        #[tokio::test]
        async fn round_trips_through_key_provider() {
            let (original, client_id, bytes) = random_secret_key();
            let hex = base16ct::lower::encode_string(&bytes);

            let from_hex = SecretKey::from_hex(client_id.to_string(), hex).unwrap();

            let original_key = original.client_key().await.unwrap();
            let from_hex_key = from_hex.client_key().await.unwrap();

            assert_eq!(
                original_key.key_id, from_hex_key.key_id,
                "from_hex should produce the same client_id"
            );
            assert_eq!(
                original_key.to_hex_v1().unwrap(),
                from_hex_key.to_hex_v1().unwrap(),
                "from_hex should produce the same key material"
            );
        }

        #[test]
        fn returns_invalid_key_for_bad_uuid() {
            let err = SecretKey::from_hex("not-a-uuid".into(), "deadbeef".into()).unwrap_err();

            assert!(
                matches!(err, KeyProviderError::InvalidKey(_)),
                "expected InvalidKey for bad UUID, got: {err:?}"
            );
        }

        #[test]
        fn returns_invalid_key_for_bad_hex() {
            let uuid = Uuid::new_v4();
            let err = SecretKey::from_hex(uuid.to_string(), "not-valid-hex!!".into()).unwrap_err();

            assert!(
                matches!(err, KeyProviderError::InvalidKey(_)),
                "expected InvalidKey for bad hex, got: {err:?}"
            );
        }
    }

    mod from_env {
        use super::*;
        use crate::config::vars::{CS_CLIENT_ID, CS_CLIENT_KEY};

        #[test]
        fn returns_some_when_both_vars_set_with_valid_values() {
            let (_, client_id, bytes) = random_secret_key();
            let hex = base16ct::lower::encode_string(&bytes);

            unsafe {
                std::env::set_var(CS_CLIENT_ID, client_id.to_string());
                std::env::set_var(CS_CLIENT_KEY, &hex);
            }

            let result = SecretKey::from_env().unwrap();
            assert!(result.is_some(), "expected Some when both vars are set");
            assert_eq!(result.unwrap().client_id, client_id);

            unsafe {
                std::env::remove_var(CS_CLIENT_ID);
                std::env::remove_var(CS_CLIENT_KEY);
            }
        }

        #[test]
        fn returns_none_when_neither_var_set() {
            unsafe {
                std::env::remove_var(CS_CLIENT_ID);
                std::env::remove_var(CS_CLIENT_KEY);
            }

            let result = SecretKey::from_env().unwrap();
            assert!(result.is_none(), "expected None when neither var is set");
        }

        #[test]
        fn returns_none_when_only_client_id_set() {
            unsafe {
                std::env::set_var(CS_CLIENT_ID, Uuid::new_v4().to_string());
                std::env::remove_var(CS_CLIENT_KEY);
            }

            let result = SecretKey::from_env().unwrap();
            assert!(
                result.is_none(),
                "expected None when only CS_CLIENT_ID is set"
            );

            unsafe {
                std::env::remove_var(CS_CLIENT_ID);
            }
        }

        #[test]
        fn returns_none_when_only_client_key_set() {
            unsafe {
                std::env::remove_var(CS_CLIENT_ID);
                std::env::set_var(CS_CLIENT_KEY, "deadbeef");
            }

            let result = SecretKey::from_env().unwrap();
            assert!(
                result.is_none(),
                "expected None when only CS_CLIENT_KEY is set"
            );

            unsafe {
                std::env::remove_var(CS_CLIENT_KEY);
            }
        }

        #[test]
        fn returns_err_when_both_set_but_invalid_uuid() {
            unsafe {
                std::env::set_var(CS_CLIENT_ID, "not-a-uuid");
                std::env::set_var(CS_CLIENT_KEY, "deadbeef");
            }

            let err = SecretKey::from_env().unwrap_err();
            assert!(
                matches!(err, KeyProviderError::InvalidKey(_)),
                "expected InvalidKey for bad UUID, got: {err:?}"
            );

            unsafe {
                std::env::remove_var(CS_CLIENT_ID);
                std::env::remove_var(CS_CLIENT_KEY);
            }
        }
    }

    mod profile_store_provider {
        use super::*;

        const TEST_WORKSPACE_ID: &str = "ZVATKW3VHMFG27DY";

        #[tokio::test]
        async fn loads_secret_key_from_disk() {
            let dir = TempDir::new().unwrap();
            let store = ProfileStore::new(dir.path());
            store.init_workspace(TEST_WORKSPACE_ID).unwrap();

            let (secret_key, client_id, bytes) = random_secret_key();
            let ws_store = store.current_workspace_store().unwrap();
            ws_store.save_profile(&secret_key).unwrap();

            let result = store.client_key().await.unwrap();

            assert_eq!(
                result.key_id, client_id,
                "should load and convert the stored SecretKey"
            );

            let expected_hex = base16ct::lower::encode_string(&bytes);
            let actual_hex = result.to_hex_v1().unwrap();
            assert_eq!(
                actual_hex, expected_hex,
                "should preserve the key material after round-tripping through disk"
            );
        }

        #[tokio::test]
        async fn returns_not_configured_when_no_workspace_set() {
            let dir = TempDir::new().unwrap();
            let store = ProfileStore::new(dir.path());

            let err = store.client_key().await.unwrap_err();

            assert!(
                matches!(err, KeyProviderError::NotConfigured(_)),
                "expected NotConfigured when no workspace is set, got: {err:?}"
            );
        }

        #[tokio::test]
        async fn returns_not_configured_when_file_missing() {
            let dir = TempDir::new().unwrap();
            let store = ProfileStore::new(dir.path());
            store.init_workspace(TEST_WORKSPACE_ID).unwrap();

            let err = store.client_key().await.unwrap_err();

            assert!(
                matches!(err, KeyProviderError::NotConfigured(_)),
                "expected NotConfigured for missing file, got: {err:?}"
            );

            let msg = err.to_string();
            assert!(
                msg.contains("Profile not found"),
                "error should explain the profile is missing, got: {msg}"
            );
        }

        #[tokio::test]
        async fn returns_load_error_for_invalid_json() {
            let dir = TempDir::new().unwrap();
            let store = ProfileStore::new(dir.path());
            store.init_workspace(TEST_WORKSPACE_ID).unwrap();

            // Write invalid JSON to the workspace-scoped file path
            let ws_dir = dir.path().join("workspaces").join(TEST_WORKSPACE_ID);
            std::fs::create_dir_all(&ws_dir).unwrap();
            std::fs::write(ws_dir.join(SecretKey::FILENAME), "not json").unwrap();

            let err = store.client_key().await.unwrap_err();

            assert!(
                matches!(err, KeyProviderError::LoadError(_)),
                "expected LoadError for corrupt file, got: {err:?}"
            );

            let msg = err.to_string();
            assert!(
                msg.contains("JSON error"),
                "error should mention the JSON parse failure, got: {msg}"
            );
        }
    }
}