secretx-keyring 0.5.1

Linux kernel keyring backend for secretx.
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
//! Linux kernel keyring backend for secretx.
//!
//! # Integration test status
//!
//! Unit tests (URI parsing, error mapping) pass without credentials.
//! The integration test (`SECRETX_KEYRING_INTEGRATION_TESTS=1`) uses the Linux
//! kernel keyring directly (no daemon required). Run with:
//!
//! ```sh
//! SECRETX_KEYRING_INTEGRATION_TESTS=1 cargo test -p secretx-keyring
//! ```
//!
//! On Linux, secrets are stored via the kernel
//! [persistent keyring](https://www.man7.org/linux/man-pages/man7/persistent-keyring.7.html),
//! which survives across logout/login sessions for a configurable window
//! (default: a few days, set by `/proc/sys/kernel/keys/persistent_keyring_expiry`).
//! Secrets do **not** survive reboots.
//!
//! See [`keyutils(7)`](https://www.man7.org/linux/man-pages/man7/keyutils.7.html)
//! for the kernel keyutils subsystem overview.
//!
//! **Persistent keyring probe**: `get` and `put` probe `keyctl_get_persistent`
//! before each operation. If the kernel does not support
//! `CONFIG_PERSISTENT_KEYRINGS` (e.g. some containers, restricted namespaces,
//! or hardened kernels), [`SecretError::Unavailable`] is returned rather than
//! silently falling back to the session keyring (which expires when the process
//! exits).
//!
//! **Integration-tested 2026-04-28**: Linux headless (kernel persistent keyring,
//! no daemon).
//!
//! URI: `secretx:keyring:<service>/<account>`
//!
//! ```rust,no_run
//! # async fn example() -> Result<(), secretx_core::SecretError> {
//! use secretx_keyring::KeyringBackend;
//! use secretx_core::{SecretStore, SecretValue, WritableSecretStore};
//!
//! // Read
//! let store = KeyringBackend::from_uri("secretx:keyring:my-app/api-key")?;
//! let value = store.get().await?;
//!
//! // Write (requires WritableSecretStore in scope)
//! store.put(SecretValue::new(b"new-secret".to_vec())).await?;
//! # Ok(())
//! # }
//! ```

use std::sync::Arc;

use secretx_core::{SecretError, SecretStore, SecretUri, SecretValue, WritableSecretStore};
use zeroize::Zeroizing;

const BACKEND: &str = "keyring";

/// Map a `keyring::Error` into the appropriate `SecretError` variant.
///
/// - `NoEntry` → `NotFound` (expected on `get`, should not occur on `put`).
/// - `NoStorageAccess` → `Unavailable` (transient; the inner platform error
///   is forwarded directly).
/// - Everything else → `Backend` (permanent).
fn map_keyring_error(e: keyring::Error) -> SecretError {
    match e {
        keyring::Error::NoEntry => SecretError::NotFound,
        keyring::Error::NoStorageAccess(inner) => SecretError::Unavailable {
            backend: BACKEND,
            source: inner,
        },
        other => SecretError::Backend {
            backend: BACKEND,
            source: other.into(),
        },
    }
}

/// Map a `tokio::task::JoinError` into `SecretError::Backend`.
fn map_join_error(e: tokio::task::JoinError) -> SecretError {
    SecretError::Backend {
        backend: BACKEND,
        source: e.into(),
    }
}

/// Probe that the kernel persistent keyring is reachable.
///
/// Returns `Ok(())` if `keyctl_get_persistent` succeeds, or
/// [`SecretError::Unavailable`] if the kernel does not support
/// `CONFIG_PERSISTENT_KEYRINGS` (containers, restricted namespaces, etc.).
///
/// Without this check, the `keyring` crate silently falls back to the session
/// keyring, which expires when the process exits — a much weaker durability
/// guarantee than the persistent keyring's multi-day window.
#[cfg(target_os = "linux")]
fn require_persistent_keyring() -> Result<(), SecretError> {
    use linux_keyutils::{KeyRing, KeyRingIdentifier};
    KeyRing::get_persistent(KeyRingIdentifier::Session).map_err(|e| SecretError::Unavailable {
        backend: BACKEND,
        source: format!(
            "persistent keyring unavailable (kernel CONFIG_PERSISTENT_KEYRINGS \
             may be disabled, or this environment restricts keyctl): {e}"
        )
        .into(),
    })?;
    Ok(())
}

/// Backend that reads and writes secrets via the Linux kernel keyring.
///
/// On Linux, `get` and `put` probe for persistent keyring availability and
/// return [`SecretError::Unavailable`] if it is not present, rather than
/// silently falling back to the session keyring.
///
/// The URI path encodes both a service name and an account name separated by
/// the first `/`:
///
/// ```text
/// secretx:keyring:<service>/<account>
/// ```
///
/// `get` and `refresh` retrieve the stored password string.
/// `put` writes a new password string; the value must be valid UTF-8 and
/// non-empty (the kernel keyutils subsystem rejects empty secrets).
#[derive(Debug)]
pub struct KeyringBackend {
    service: Arc<str>,
    account: Arc<str>,
}

impl KeyringBackend {
    /// Construct from a `secretx:keyring:<service>/<account>` URI.
    ///
    /// Does not open the keychain — construction only.
    ///
    /// # Errors
    ///
    /// Returns [`SecretError::InvalidUri`] if the backend is not `keyring`,
    /// the path is empty, or the path contains no `/` separator (both
    /// `service` and `account` must be non-empty).
    pub fn from_uri(uri: &str) -> Result<Self, SecretError> {
        Self::from_parsed_uri(&SecretUri::parse(uri)?)
    }

    /// Construct from a pre-parsed [`SecretUri`].
    pub fn from_parsed_uri(parsed: &SecretUri) -> Result<Self, SecretError> {
        if parsed.backend() != BACKEND {
            return Err(SecretError::InvalidUri(format!(
                "expected backend `keyring`, got `{}`",
                parsed.backend()
            )));
        }
        // path must be "<service>/<account>" — split on the first '/'.
        // account may itself contain slashes (e.g. "svc/user/sub").
        let (service, account) = parsed.path().split_once('/').ok_or_else(|| {
            SecretError::InvalidUri(
                "keyring URI requires `secretx:keyring:<service>/<account>`".into(),
            )
        })?;
        if service.is_empty() {
            return Err(SecretError::InvalidUri(
                "keyring URI: service name must not be empty".into(),
            ));
        }
        if account.is_empty() {
            return Err(SecretError::InvalidUri(
                "keyring URI: account name must not be empty".into(),
            ));
        }
        // Keyring values are opaque byte strings stored by the OS keychain;
        // ?field= JSON extraction is not supported and would silently return
        // the full stored value, which is confusing.  Reject early.
        if parsed.param("field").is_some() {
            return Err(SecretError::InvalidUri(
                "keyring does not support ?field= (kernel keyring values are opaque strings, not JSON \
                 objects); remove ?field= or use a backend that supports JSON field extraction \
                 (e.g. aws-sm)"
                    .into(),
            ));
        }
        Ok(Self {
            service: Arc::from(service),
            account: Arc::from(account),
        })
    }
}

#[async_trait::async_trait]
impl SecretStore for KeyringBackend {
    async fn get(&self) -> Result<SecretValue, SecretError> {
        let service = self.service.clone();
        let account = self.account.clone();
        // Kernel keyring calls (keyctl syscalls) are synchronous.
        // Run them on a blocking thread to avoid stalling the async executor.
        tokio::task::spawn_blocking(move || {
            #[cfg(not(target_os = "linux"))]
            return Err(SecretError::Unavailable {
                backend: BACKEND,
                source: "secretx-keyring requires Linux (kernel persistent keyring); \
                         not implemented on this platform"
                    .into(),
            });
            #[cfg(target_os = "linux")]
            require_persistent_keyring()?;
            let entry =
                keyring::Entry::new(&service, &account).map_err(map_keyring_error)?;
            // ZEROIZATION GAP: keyring crate returns plain String from the OS
            // keychain.  `pw.into_bytes()` is zero-copy (reuses the same heap
            // allocation), so the buffer enters Zeroizing immediately.  The
            // keychain's own internal copy is outside our control.
            entry
                .get_password()
                .map(|pw| SecretValue::new(pw.into_bytes()))
                .map_err(map_keyring_error)
        })
        .await
        .map_err(map_join_error)?
    }

    async fn refresh(&self) -> Result<SecretValue, SecretError> {
        self.get().await
    }
}

#[async_trait::async_trait]
impl WritableSecretStore for KeyringBackend {
    async fn put(&self, value: SecretValue) -> Result<(), SecretError> {
        // Decode to UTF-8 before entering spawn_blocking (no I/O needed here).
        // Wrap in Zeroizing so the plaintext copy is zeroed when the closure returns.
        let password = Zeroizing::new(
            std::str::from_utf8(value.as_bytes())
                .map_err(|_| {
                    SecretError::DecodeFailed("keyring backend requires UTF-8 secret values".into())
                })?
                .to_owned(),
        );
        let service = self.service.clone();
        let account = self.account.clone();
        tokio::task::spawn_blocking(move || {
            #[cfg(not(target_os = "linux"))]
            {
                let _ = (&service, &account, &password);
                return Err(SecretError::Unavailable {
                    backend: BACKEND,
                    source: "secretx-keyring requires Linux (kernel persistent keyring); \
                             not implemented on this platform"
                        .into(),
                });
            }
            #[cfg(target_os = "linux")]
            require_persistent_keyring()?;
            let entry =
                keyring::Entry::new(&service, &account).map_err(map_keyring_error)?;
            entry.set_password(&password).map_err(map_keyring_error)
        })
        .await
        .map_err(map_join_error)?
    }
}

#[cfg(target_os = "linux")]
inventory::submit!(secretx_core::BackendRegistration::new(
    "keyring",
    |uri: &secretx_core::SecretUri| {
        let b = KeyringBackend::from_parsed_uri(uri)?;
        Ok(Arc::new(b) as Arc<dyn secretx_core::SecretStore>)
    },
));

#[cfg(target_os = "linux")]
inventory::submit!(secretx_core::WritableBackendRegistration::new(
    "keyring",
    |uri: &secretx_core::SecretUri| {
        let b = KeyringBackend::from_parsed_uri(uri)?;
        Ok(Arc::new(b) as Arc<dyn secretx_core::WritableSecretStore>)
    },
));

#[cfg(test)]
mod tests {
    use super::*;

    const _: () = {
        const fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<KeyringBackend>();
    };

    // ── URI parsing tests (no OS keychain required) ───────────────────────────

    #[test]
    fn from_uri_ok() {
        let b = KeyringBackend::from_uri("secretx:keyring:my-app/api-key").unwrap();
        assert_eq!(&*b.service, "my-app");
        assert_eq!(&*b.account, "api-key");
    }

    #[test]
    fn from_uri_ok_nested_account() {
        // account portion may contain slashes; only the first '/' is the separator.
        let b = KeyringBackend::from_uri("secretx:keyring:svc/user/sub").unwrap();
        assert_eq!(&*b.service, "svc");
        assert_eq!(&*b.account, "user/sub");
    }

    #[test]
    fn from_uri_empty_service() {
        assert!(matches!(
            KeyringBackend::from_uri("secretx:keyring:/account"),
            Err(SecretError::InvalidUri(_))
        ));
    }

    #[test]
    fn from_uri_wrong_backend() {
        assert!(matches!(
            KeyringBackend::from_uri("secretx:env:MY_VAR"),
            Err(SecretError::InvalidUri(_))
        ));
    }

    #[test]
    fn from_uri_missing_slash() {
        // path has no '/' so account is absent
        assert!(matches!(
            KeyringBackend::from_uri("secretx:keyring:onlyone"),
            Err(SecretError::InvalidUri(_))
        ));
    }

    #[test]
    fn from_uri_empty_account() {
        // trailing slash means account is empty
        assert!(matches!(
            KeyringBackend::from_uri("secretx:keyring:svc/"),
            Err(SecretError::InvalidUri(_))
        ));
    }

    #[test]
    fn from_uri_empty_path() {
        // no path component at all
        assert!(matches!(
            KeyringBackend::from_uri("secretx:keyring"),
            Err(SecretError::InvalidUri(_))
        ));
    }

    #[test]
    fn from_uri_field_selector_rejected() {
        // Keyring values are opaque strings; ?field= is not supported and must
        // be rejected at construction time.
        let Err(SecretError::InvalidUri(msg)) =
            KeyringBackend::from_uri("secretx:keyring:my-app/api-key?field=token")
        else {
            panic!("expected InvalidUri");
        };
        assert!(
            msg.contains("keyring does not support ?field="),
            "error must mention the limitation, got: {msg}"
        );
    }

    // ── Integration tests (require OS keychain) ───────────────────────────────
    //
    // Gated behind SECRETX_KEYRING_INTEGRATION_TESTS=1.  No daemon required —
    // uses the kernel persistent keyring directly.

    /// Returns true if the kernel keyring is unavailable (e.g. running in a
    /// container that restricts keyrings, or the keyutils subsystem is absent).
    fn is_kernel_keyring_unavailable(e: &SecretError) -> bool {
        matches!(e, SecretError::Unavailable { .. })
    }

    /// Drop guard that deletes a keyring entry on drop, ensuring cleanup
    /// even if an assertion panics mid-test.
    struct KeyringCleanup {
        svc: &'static str,
        acct: &'static str,
    }
    impl Drop for KeyringCleanup {
        fn drop(&mut self) {
            if let Ok(entry) = keyring::Entry::new(self.svc, self.acct) {
                let _ = entry.delete_credential();
            }
        }
    }

    #[tokio::test]
    async fn integration_roundtrip() {
        if std::env::var("SECRETX_KEYRING_INTEGRATION_TESTS").as_deref() != Ok("1") {
            eprintln!("skipped: set SECRETX_KEYRING_INTEGRATION_TESTS=1 to run");
            return;
        }

        let svc = "secretx-test";
        let acct = "roundtrip";
        let uri = format!("secretx:keyring:{svc}/{acct}");

        let backend = KeyringBackend::from_uri(&uri).unwrap();

        // Clean up any leftover entry from a previous run, and install a
        // drop guard so cleanup happens even if assertions panic.
        let _cleanup = KeyringCleanup { svc, acct };
        if let Ok(entry) = keyring::Entry::new(svc, acct) {
            let _ = entry.delete_credential();
        }

        // Write.
        let put_result = backend
            .put(SecretValue::new(b"test-secret-value".to_vec()))
            .await;
        match put_result {
            Ok(()) => {}
            Err(ref e) if is_kernel_keyring_unavailable(e) => {
                eprintln!("keyring: kernel keyring unavailable, skipping integration test");
                return;
            }
            Err(e) => panic!("put failed: {e}"),
        }

        // Read back.
        let got = backend.get().await.expect("get after put failed");
        assert_eq!(got.as_bytes(), b"test-secret-value");

        // Refresh should also work.
        let refreshed = backend.refresh().await.expect("refresh failed");
        assert_eq!(refreshed.as_bytes(), b"test-secret-value");

        // Drop guard handles cleanup. Verify post-deletion state.
        drop(_cleanup);
        let after = backend.get().await;
        assert!(
            matches!(after, Err(SecretError::NotFound)),
            "expected NotFound after delete"
        );
    }

    /// Empty secrets are rejected by the kernel keyutils subsystem.
    #[tokio::test]
    async fn integration_empty_secret_rejected() {
        if std::env::var("SECRETX_KEYRING_INTEGRATION_TESTS").as_deref() != Ok("1") {
            eprintln!("skipped: set SECRETX_KEYRING_INTEGRATION_TESTS=1 to run");
            return;
        }
        let backend =
            KeyringBackend::from_uri("secretx:keyring:secretx-test/empty-reject").unwrap();
        let result = backend.put(SecretValue::new(Vec::new())).await;
        assert!(
            result.is_err(),
            "empty secret should be rejected, got Ok"
        );
    }
}