zlayer-secrets 0.12.5

Secure secrets management for ZLayer container workloads
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Credential store for API authentication.
//!
//! Built on top of [`PersistentSecretsStore`], this module provides API-key
//! based authentication with Argon2id password hashing.
//!
//! Credentials are stored in the `credentials` scope of the secrets store.
//! Each credential is a JSON object containing the argon2id hash of the
//! API secret and an array of roles.
//!
//! # Example
//!
//! ```rust,ignore
//! use zlayer_secrets::credentials::CredentialStore;
//! use zlayer_secrets::{EncryptionKey, PersistentSecretsStore};
//!
//! # async fn example() -> zlayer_secrets::Result<()> {
//! let key = EncryptionKey::generate();
//! let secrets_dir = zlayer_paths::ZLayerDirs::system_default().secrets();
//! let store = PersistentSecretsStore::open(&secrets_dir, key).await?;
//! let cred_store = CredentialStore::new(store);
//!
//! // Create an API key
//! cred_store.create_api_key("admin", "super-secret-password", &["admin"]).await?;
//!
//! // Validate credentials
//! let roles = cred_store.validate("admin", "super-secret-password").await?;
//! assert!(roles.is_some());
//! # Ok(())
//! # }
//! ```

use argon2::{
    password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
    Argon2,
};
use serde::{Deserialize, Serialize};
use tracing::{debug, info};

use crate::{Result, Secret, SecretsError, SecretsStore};

/// The scope used for storing API credentials in the secrets store.
const CREDENTIALS_SCOPE: &str = "credentials";

/// Stored credential record (JSON-serialised inside the encrypted secret).
#[derive(Debug, Clone, Serialize, Deserialize)]
struct StoredCredential {
    /// Argon2id hash of the API secret / password.
    hash: String,
    /// Roles assigned to this credential (e.g. `["admin"]`).
    roles: Vec<String>,
}

/// Credential store for API key authentication.
///
/// Wraps a [`SecretsStore`] implementation and stores credentials as encrypted
/// JSON blobs keyed by API key name under the `credentials` scope.
pub struct CredentialStore<S: SecretsStore> {
    store: S,
}

impl<S: SecretsStore> std::fmt::Debug for CredentialStore<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CredentialStore")
            .field("store", &"<secrets store>")
            .finish()
    }
}

impl<S: SecretsStore> CredentialStore<S> {
    /// Create a new credential store backed by the provided secrets store.
    pub fn new(store: S) -> Self {
        Self { store }
    }

    /// Borrow the underlying secrets store.
    ///
    /// Useful for constructing sibling typed stores (e.g.
    /// [`crate::RegistryCredentialStore`] / [`crate::GitCredentialStore`]) that
    /// share the same concrete backing store without re-opening it. When `S` is
    /// an `Arc<_>` (the common case), call `.clone()` on the returned reference
    /// for a cheap refcount bump.
    #[must_use]
    pub fn store(&self) -> &S {
        &self.store
    }

    /// Validate an API key and secret pair.
    ///
    /// Returns `Some(roles)` if the credentials are valid, `None` if invalid.
    ///
    /// # Arguments
    /// * `api_key` - The API key (used as the secret name in the store)
    /// * `api_secret` - The password/secret to verify against the stored hash
    ///
    /// # Errors
    /// Returns a `SecretsError` if there is a storage or decryption error
    /// (NOT for invalid credentials -- that returns `Ok(None)`).
    pub async fn validate(&self, api_key: &str, api_secret: &str) -> Result<Option<Vec<String>>> {
        // Look up the credential by API key
        let secret = match self.store.get_secret(CREDENTIALS_SCOPE, api_key).await {
            Ok(s) => s,
            Err(SecretsError::NotFound { .. }) => {
                debug!(api_key = %api_key, "Credential not found");
                return Ok(None);
            }
            Err(e) => return Err(e),
        };

        // Deserialise the stored credential
        let stored: StoredCredential = serde_json::from_str(secret.expose()).map_err(|e| {
            SecretsError::Storage(format!("corrupt credential record for '{api_key}': {e}"))
        })?;

        // Verify the password against the stored argon2id hash
        let parsed_hash = PasswordHash::new(&stored.hash).map_err(|e| {
            SecretsError::Storage(format!("invalid password hash for '{api_key}': {e}"))
        })?;

        let argon2 = Argon2::default();
        if argon2
            .verify_password(api_secret.as_bytes(), &parsed_hash)
            .is_ok()
        {
            debug!(api_key = %api_key, "Credential validated successfully");
            Ok(Some(stored.roles))
        } else {
            debug!(api_key = %api_key, "Invalid password");
            Ok(None)
        }
    }

    /// Create a new API key credential.
    ///
    /// The password is hashed with Argon2id before storage. If a credential
    /// with the same key already exists, it will be overwritten.
    ///
    /// # Arguments
    /// * `api_key` - The API key identifier
    /// * `password` - The password/secret to hash and store
    /// * `roles` - Roles assigned to this credential
    ///
    /// # Errors
    /// Returns a `SecretsError` if hashing or storage fails.
    pub async fn create_api_key(
        &self,
        api_key: &str,
        password: &str,
        roles: &[&str],
    ) -> Result<()> {
        // Hash the password with Argon2id
        let salt = SaltString::generate(&mut OsRng);
        let argon2 = Argon2::default();
        let hash = argon2
            .hash_password(password.as_bytes(), &salt)
            .map_err(|e| SecretsError::Encryption(format!("failed to hash password: {e}")))?
            .to_string();

        let credential = StoredCredential {
            hash,
            roles: roles.iter().map(|r| (*r).to_string()).collect(),
        };

        let json = serde_json::to_string(&credential)
            .map_err(|e| SecretsError::Storage(format!("failed to serialise credential: {e}")))?;

        self.store
            .set_secret(CREDENTIALS_SCOPE, api_key, &Secret::new(json))
            .await?;

        info!(api_key = %api_key, roles = ?roles, "Created API key credential");
        Ok(())
    }

    /// Delete an API key credential.
    ///
    /// # Arguments
    /// * `api_key` - The API key to delete
    ///
    /// # Errors
    /// Returns `SecretsError::NotFound` if the credential doesn't exist.
    pub async fn delete_api_key(&self, api_key: &str) -> Result<()> {
        self.store.delete_secret(CREDENTIALS_SCOPE, api_key).await?;
        info!(api_key = %api_key, "Deleted API key credential");
        Ok(())
    }

    /// Check if an API key credential exists.
    ///
    /// # Errors
    /// Returns a `SecretsError` if there is a storage or decryption error.
    pub async fn exists(&self, api_key: &str) -> Result<bool> {
        self.store.exists(CREDENTIALS_SCOPE, api_key).await
    }

    /// Overwrite the roles array on an existing credential, preserving the
    /// password hash. Use this to keep credential roles in sync with the
    /// authoritative user-store role when an admin changes a user's role.
    ///
    /// # Arguments
    /// * `api_key` - The API key whose roles should be updated
    /// * `roles` - The new role list (replaces existing)
    ///
    /// # Errors
    /// Returns `SecretsError::NotFound` if the credential doesn't exist, or a
    /// `SecretsError` if the storage or (de)serialisation fails.
    pub async fn set_roles(&self, api_key: &str, roles: &[&str]) -> Result<()> {
        let secret = self.store.get_secret(CREDENTIALS_SCOPE, api_key).await?;
        let mut stored: StoredCredential = serde_json::from_str(secret.expose()).map_err(|e| {
            SecretsError::Storage(format!("corrupt credential record for '{api_key}': {e}"))
        })?;

        stored.roles = roles.iter().map(|r| (*r).to_string()).collect();

        let json = serde_json::to_string(&stored)
            .map_err(|e| SecretsError::Storage(format!("failed to serialise credential: {e}")))?;

        self.store
            .set_secret(CREDENTIALS_SCOPE, api_key, &Secret::new(json))
            .await?;

        info!(api_key = %api_key, roles = ?roles, "Updated credential roles");
        Ok(())
    }

    /// Ensure a default admin credential exists.
    ///
    /// If no credential with the given `api_key` exists, one is created with
    /// the provided password and `["admin"]` role. Returns the password that
    /// was set (either the provided one or the existing one if already present).
    ///
    /// # Arguments
    /// * `api_key` - The admin API key name (e.g. "admin")
    /// * `password` - The password to use if the credential doesn't exist
    ///
    /// # Returns
    /// `true` if a new credential was created, `false` if one already existed.
    ///
    /// # Errors
    /// Returns a `SecretsError` if hashing or storage fails during creation.
    pub async fn ensure_admin(&self, api_key: &str, password: &str) -> Result<bool> {
        if self.exists(api_key).await? {
            debug!(api_key = %api_key, "Admin credential already exists");
            return Ok(false);
        }

        self.create_api_key(api_key, password, &["admin"]).await?;
        Ok(true)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{EncryptionKey, PersistentSecretsStore};
    use zlayer_paths::ZLayerDirs;

    async fn create_test_store() -> (PersistentSecretsStore, zlayer_types::Scratch) {
        let temp_dir = ZLayerDirs::system_default()
            .scratch_dir("create-test-store-")
            .unwrap();
        let db_path = temp_dir.path().join("test_creds.sqlite");
        let key = EncryptionKey::generate();
        let store = PersistentSecretsStore::open(&db_path, key).await.unwrap();
        (store, temp_dir)
    }

    #[tokio::test]
    async fn test_create_and_validate() {
        let (store, _temp) = create_test_store().await;
        let cred_store = CredentialStore::new(store);

        cred_store
            .create_api_key("test-key", "test-secret", &["admin", "reader"])
            .await
            .unwrap();

        // Valid credentials
        let roles = cred_store
            .validate("test-key", "test-secret")
            .await
            .unwrap();
        assert!(roles.is_some());
        let roles = roles.unwrap();
        assert!(roles.contains(&"admin".to_string()));
        assert!(roles.contains(&"reader".to_string()));
    }

    #[tokio::test]
    async fn test_validate_wrong_password() {
        let (store, _temp) = create_test_store().await;
        let cred_store = CredentialStore::new(store);

        cred_store
            .create_api_key("test-key", "correct-password", &["admin"])
            .await
            .unwrap();

        let roles = cred_store
            .validate("test-key", "wrong-password")
            .await
            .unwrap();
        assert!(roles.is_none());
    }

    #[tokio::test]
    async fn test_validate_nonexistent_key() {
        let (store, _temp) = create_test_store().await;
        let cred_store = CredentialStore::new(store);

        let roles = cred_store
            .validate("nonexistent", "password")
            .await
            .unwrap();
        assert!(roles.is_none());
    }

    #[tokio::test]
    async fn test_exists() {
        let (store, _temp) = create_test_store().await;
        let cred_store = CredentialStore::new(store);

        assert!(!cred_store.exists("test-key").await.unwrap());

        cred_store
            .create_api_key("test-key", "password", &["admin"])
            .await
            .unwrap();

        assert!(cred_store.exists("test-key").await.unwrap());
    }

    #[tokio::test]
    async fn test_delete_api_key() {
        let (store, _temp) = create_test_store().await;
        let cred_store = CredentialStore::new(store);

        cred_store
            .create_api_key("delete-me", "password", &["admin"])
            .await
            .unwrap();
        assert!(cred_store.exists("delete-me").await.unwrap());

        cred_store.delete_api_key("delete-me").await.unwrap();
        assert!(!cred_store.exists("delete-me").await.unwrap());
    }

    #[tokio::test]
    async fn test_set_roles_preserves_hash() {
        let (store, _temp) = create_test_store().await;
        let cred_store = CredentialStore::new(store);

        cred_store
            .create_api_key("alice@example.com", "hunter2hunter2", &["user"])
            .await
            .unwrap();

        cred_store
            .set_roles("alice@example.com", &["admin"])
            .await
            .unwrap();

        // Old password still works (hash preserved)
        let roles = cred_store
            .validate("alice@example.com", "hunter2hunter2")
            .await
            .unwrap()
            .expect("should validate");
        assert_eq!(roles, vec!["admin".to_string()]);
    }

    #[tokio::test]
    async fn test_set_roles_missing_errors() {
        let (store, _temp) = create_test_store().await;
        let cred_store = CredentialStore::new(store);

        let err = cred_store
            .set_roles("nonexistent", &["admin"])
            .await
            .unwrap_err();
        assert!(
            matches!(err, SecretsError::NotFound { .. }),
            "unexpected: {err}"
        );
    }

    #[tokio::test]
    async fn test_ensure_admin_creates() {
        let (store, _temp) = create_test_store().await;
        let cred_store = CredentialStore::new(store);

        let created = cred_store
            .ensure_admin("admin", "admin-password")
            .await
            .unwrap();
        assert!(created);

        // Should be able to validate
        let roles = cred_store
            .validate("admin", "admin-password")
            .await
            .unwrap();
        assert!(roles.is_some());
        assert!(roles.unwrap().contains(&"admin".to_string()));
    }

    #[tokio::test]
    async fn test_ensure_admin_skips_existing() {
        let (store, _temp) = create_test_store().await;
        let cred_store = CredentialStore::new(store);

        // Create first
        cred_store
            .create_api_key("admin", "original-password", &["admin"])
            .await
            .unwrap();

        // ensure_admin should not overwrite
        let created = cred_store
            .ensure_admin("admin", "new-password")
            .await
            .unwrap();
        assert!(!created);

        // Original password should still work
        let roles = cred_store
            .validate("admin", "original-password")
            .await
            .unwrap();
        assert!(roles.is_some());

        // New password should NOT work
        let roles = cred_store.validate("admin", "new-password").await.unwrap();
        assert!(roles.is_none());
    }

    #[tokio::test]
    async fn test_overwrite_credential() {
        let (store, _temp) = create_test_store().await;
        let cred_store = CredentialStore::new(store);

        cred_store
            .create_api_key("key", "password1", &["reader"])
            .await
            .unwrap();

        // Overwrite with new password and roles
        cred_store
            .create_api_key("key", "password2", &["admin"])
            .await
            .unwrap();

        // Old password should NOT work
        let roles = cred_store.validate("key", "password1").await.unwrap();
        assert!(roles.is_none());

        // New password should work with new roles
        let roles = cred_store.validate("key", "password2").await.unwrap();
        assert!(roles.is_some());
        let roles = roles.unwrap();
        assert!(roles.contains(&"admin".to_string()));
        assert!(!roles.contains(&"reader".to_string()));
    }
}