openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! OS keychain credential store via the `keyring` crate (per D-01).
//!
//! All keyring calls are wrapped in `tokio::task::spawn_blocking` to prevent
//! async runtime deadlock on Linux (per D-07, CRED-06).

use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};

use secrecy::{ExposeSecret, SecretString};

use crate::error::OlError;

use super::{
    CredentialStore, ERR_KEYCHAIN_PERMISSION, ERR_KEYCHAIN_UNAVAILABLE, ERR_NO_CREDENTIALS,
};

/// The one service name every OpenLatch keychain entry lives under.
pub const SERVICE_NAME: &str = "openlatch";
const USERNAME: &str = "api-key";

/// Username prefix for a proxy password — one entry per proxy authority.
///
/// The API key is `api-key`; a proxy password is `proxy:<authority>`. Different usernames
/// under the same service, so neither can overwrite the other, and a changed authority
/// resolves to a different entry that inherits nothing from the old one (D-19).
pub const PROXY_USERNAME_PREFIX: &str = "proxy:";

/// Test-only seam: when `OPENLATCH_SKIP_KEYRING` is set to a truthy value,
/// the keyring store behaves as if the OS keychain is unavailable. Used by the
/// E2E credentials suite so tests can exercise the `OPENLATCH_API_KEY` env-var
/// fallback path on a developer machine whose real keyring already holds a
/// credential. Truthy values: any non-empty string other than `0` / `false` /
/// `no` / `off` (case-insensitive).
const SKIP_KEYRING_ENV: &str = "OPENLATCH_SKIP_KEYRING";

fn keyring_disabled_by_env() -> bool {
    match std::env::var(SKIP_KEYRING_ENV) {
        Ok(v) => {
            let v = v.trim().to_ascii_lowercase();
            !matches!(v.as_str(), "" | "0" | "false" | "no" | "off")
        }
        Err(_) => false,
    }
}

/// Process-wide memo of the first keychain read.
///
/// macOS binds a keychain item's ACL to the code identity of the binary that
/// created it, so any read from a different binary — including a rebuilt one,
/// since unsigned/ad-hoc builds get a fresh identity every compile — raises a
/// blocking authorization dialog. The dialogs are per *read*, not per process:
/// a single `openlatch status` resolves the credential twice (the
/// cloud-configured check and the live cloud probe), `doctor` adds more, and
/// the daemon's policy poller and cloud worker re-resolve on their loops.
///
/// Nothing outside this store mutates the entry during a process's lifetime,
/// so the first answer is reused for the rest of it. Failures are memoized
/// too — a denied dialog must not re-prompt on the next call. `store` and
/// `delete` invalidate the memo.
///
/// **Keyed by `(service, username)`, and that is a correctness requirement, not a
/// refinement.** The memo held a single unkeyed slot while `api-key` was the only identity
/// in the process. The moment a second one exists — a proxy password under
/// `proxy:<authority>` — an unkeyed slot would hand whichever read happened first back to
/// the other: an API key returned as a proxy password, or the reverse. Both are silent, and
/// one of them puts the platform credential on the wire to a proxy.
static READ_MEMO: OnceLock<Mutex<ReadMemo>> = OnceLock::new();

/// `(service, username)` to the memoized outcome of reading that entry.
type MemoKey = (String, String);
type ReadMemo = HashMap<MemoKey, Result<String, OlError>>;

fn read_memo() -> &'static Mutex<ReadMemo> {
    READ_MEMO.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Drop one identity's memoized read so its next retrieve sees the keychain's new state.
///
/// Only the entry that was written or deleted is dropped: a `proxy set` must not cost the
/// API key a fresh macOS authorization dialog.
fn invalidate_read_memo(service: &str, username: &str) {
    if let Ok(mut memo) = read_memo().lock() {
        memo.remove(&(service.to_string(), username.to_string()));
    }
}

/// Read through the memo for one identity, calling `read` at most once per process.
///
/// Split out from [`CredentialStore::retrieve`] so the keying can be unit-tested without an
/// OS keychain: the tests below drive this with an in-memory reader, which is the only way
/// to prove the isolation on a machine where `OPENLATCH_SKIP_KEYRING=1` short-circuits
/// `retrieve` before it ever reaches the memo.
fn memoized_read<F>(key: MemoKey, read: F) -> Result<String, OlError>
where
    F: FnOnce() -> Result<String, OlError>,
{
    if let Ok(memo) = read_memo().lock() {
        if let Some(memoized) = memo.get(&key) {
            return memoized.clone();
        }
    }

    let result = read();

    if let Ok(mut memo) = read_memo().lock() {
        memo.insert(key, result.clone());
    }

    result
}

fn skipped_no_entry_error() -> OlError {
    OlError::new(
        ERR_NO_CREDENTIALS,
        "OS keychain disabled via OPENLATCH_SKIP_KEYRING",
    )
    .with_suggestion("Unset OPENLATCH_SKIP_KEYRING to use the OS keychain.")
}

fn skipped_unavailable_error() -> OlError {
    OlError::new(
        ERR_KEYCHAIN_UNAVAILABLE,
        "OS keychain disabled via OPENLATCH_SKIP_KEYRING",
    )
    .with_suggestion("Unset OPENLATCH_SKIP_KEYRING to use the OS keychain.")
}

/// OS keychain credential store.
///
/// Uses `keyring` crate v3.6.x with platform-native backends:
/// - macOS: Keychain
/// - Windows: Credential Manager
/// - Linux: Secret Service (GNOME Keyring / KWallet)
///
/// All blocking operations MUST be called via `spawn_blocking` in async contexts (per D-07).
pub struct KeyringCredentialStore {
    service: String,
    username: String,
}

impl KeyringCredentialStore {
    pub fn new() -> Self {
        Self {
            service: SERVICE_NAME.to_string(),
            username: USERNAME.to_string(),
        }
    }

    /// A store for one named identity under an arbitrary service.
    ///
    /// [`new`](Self::new) is the API-key singleton (`openlatch`/`api-key`); this is how a
    /// second identity — a proxy password under `openlatch`/`proxy:<authority>` — gets its
    /// own entry and its own memo slot.
    pub fn for_identity(service: &str, username: &str) -> Self {
        Self {
            service: service.to_string(),
            username: username.to_string(),
        }
    }
}

impl Default for KeyringCredentialStore {
    fn default() -> Self {
        Self::new()
    }
}

/// Map a keyring error to an OlError with appropriate code.
///
/// `username` selects the remedy: a missing API key and a missing proxy password are the
/// same keyring error and two entirely different things for the operator to do about it.
fn map_keyring_error(e: keyring::Error, username: &str) -> OlError {
    match e {
        keyring::Error::NoEntry if username.starts_with(PROXY_USERNAME_PREFIX) => {
            let authority = username
                .strip_prefix(PROXY_USERNAME_PREFIX)
                .unwrap_or(username);
            OlError::new(
                ERR_NO_CREDENTIALS,
                format!("No proxy password found in OS keychain for {authority}"),
            )
            .with_suggestion("Run 'openlatch proxy set' to store the proxy password.")
        }
        keyring::Error::NoEntry => {
            OlError::new(ERR_NO_CREDENTIALS, "No API key found in OS keychain")
                .with_suggestion("Run 'openlatch auth login' to authenticate.")
        }

        keyring::Error::NoStorageAccess(_) | keyring::Error::PlatformFailure(_) => OlError::new(
            ERR_KEYCHAIN_UNAVAILABLE,
            format!("OS keychain is not available: {e}"),
        )
        .with_suggestion(crate::error::keychain_suggestion()),

        keyring::Error::Ambiguous(_) => OlError::new(
            ERR_KEYCHAIN_PERMISSION,
            format!("OS keychain access denied: {e}"),
        )
        .with_suggestion(crate::error::keychain_suggestion()),

        other => OlError::new(ERR_KEYCHAIN_UNAVAILABLE, format!("Keychain error: {other}"))
            .with_suggestion(crate::error::keychain_suggestion()),
    }
}

impl KeyringCredentialStore {
    /// One unmemoized read of the backing keychain entry.
    ///
    /// Returns the raw secret rather than a `SecretString` so the result can be
    /// memoized: `SecretString` is `SecretBox<str>`, which is not `Clone`.
    fn read_entry(&self) -> Result<String, OlError> {
        let entry = keyring::Entry::new(&self.service, &self.username)
            .map_err(|e| map_keyring_error(e, &self.username))?;
        entry
            .get_password()
            .map_err(|e| map_keyring_error(e, &self.username))
    }

    /// This store's memo key.
    fn memo_key(&self) -> MemoKey {
        (self.service.clone(), self.username.clone())
    }

    /// Store API key in OS keychain. Wrapped in spawn_blocking for async safety (per D-07).
    pub async fn store_async(&self, key: SecretString) -> Result<(), OlError> {
        if keyring_disabled_by_env() {
            return Err(skipped_unavailable_error());
        }
        invalidate_read_memo(&self.service, &self.username);
        let service = self.service.clone();
        let username = self.username.clone();
        let secret_val = key.expose_secret().to_string();
        tokio::task::spawn_blocking(move || {
            let entry = keyring::Entry::new(&service, &username)
                .map_err(|e| map_keyring_error(e, &username))?;
            entry
                .set_password(&secret_val)
                .map_err(|e| map_keyring_error(e, &username))
        })
        .await
        .map_err(|e| {
            OlError::new(
                ERR_KEYCHAIN_UNAVAILABLE,
                format!("Keychain task panicked: {e}"),
            )
        })?
    }

    /// Retrieve API key from OS keychain. Wrapped in spawn_blocking (per D-07).
    pub async fn retrieve_async(&self) -> Result<SecretString, OlError> {
        if keyring_disabled_by_env() {
            return Err(skipped_no_entry_error());
        }
        // Delegates to the sync impl so both entry points share one memo
        // (and therefore raise at most one macOS authorization dialog).
        let store = Self {
            service: self.service.clone(),
            username: self.username.clone(),
        };
        tokio::task::spawn_blocking(move || CredentialStore::retrieve(&store))
            .await
            .map_err(|e| {
                OlError::new(
                    ERR_KEYCHAIN_UNAVAILABLE,
                    format!("Keychain task panicked: {e}"),
                )
            })?
    }

    /// Delete API key from OS keychain. Wrapped in spawn_blocking (per D-07).
    pub async fn delete_async(&self) -> Result<(), OlError> {
        if keyring_disabled_by_env() {
            return Err(skipped_unavailable_error());
        }
        invalidate_read_memo(&self.service, &self.username);
        let service = self.service.clone();
        let username = self.username.clone();
        tokio::task::spawn_blocking(move || {
            let entry = keyring::Entry::new(&service, &username)
                .map_err(|e| map_keyring_error(e, &username))?;
            match entry.delete_credential() {
                Ok(()) => Ok(()),
                Err(keyring::Error::NoEntry) => Ok(()), // Already gone, no-op
                Err(e) => Err(map_keyring_error(e, &username)),
            }
        })
        .await
        .map_err(|e| {
            OlError::new(
                ERR_KEYCHAIN_UNAVAILABLE,
                format!("Keychain task panicked: {e}"),
            )
        })?
    }
}

/// Synchronous `CredentialStore` impl for `KeyringCredentialStore`.
///
/// These methods block the current thread. They exist to satisfy the `CredentialStore`
/// trait which is sync. Callers in async context MUST use the `_async` methods directly,
/// or wrap these calls in `spawn_blocking` at the call site (per D-07, CRED-06).
impl CredentialStore for KeyringCredentialStore {
    fn store(&self, key: SecretString) -> Result<(), OlError> {
        if keyring_disabled_by_env() {
            return Err(skipped_unavailable_error());
        }
        invalidate_read_memo(&self.service, &self.username);
        let entry = keyring::Entry::new(&self.service, &self.username)
            .map_err(|e| map_keyring_error(e, &self.username))?;
        entry
            .set_password(key.expose_secret())
            .map_err(|e| map_keyring_error(e, &self.username))
    }

    /// Retrieve the API key, reading the OS keychain at most once per process.
    ///
    /// See [`READ_MEMO`] for why repeat reads are worth avoiding.
    fn retrieve(&self) -> Result<SecretString, OlError> {
        if keyring_disabled_by_env() {
            return Err(skipped_no_entry_error());
        }

        memoized_read(self.memo_key(), || self.read_entry()).map(SecretString::from)
    }

    fn delete(&self) -> Result<(), OlError> {
        if keyring_disabled_by_env() {
            return Err(skipped_unavailable_error());
        }
        invalidate_read_memo(&self.service, &self.username);
        let entry = keyring::Entry::new(&self.service, &self.username)
            .map_err(|e| map_keyring_error(e, &self.username))?;
        match entry.delete_credential() {
            Ok(()) => Ok(()),
            Err(keyring::Error::NoEntry) => Ok(()),
            Err(e) => Err(map_keyring_error(e, &self.username)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::{ERR_KEYCHAIN_UNAVAILABLE, ERR_NO_CREDENTIALS};

    #[test]
    fn test_keyring_credential_store_new_creates_instance() {
        let store = KeyringCredentialStore::new();
        assert_eq!(store.service, "openlatch");
        assert_eq!(store.username, "api-key");
    }

    #[test]
    fn test_keyring_default_creates_instance_with_correct_fields() {
        let store = KeyringCredentialStore::default();
        assert_eq!(store.service, "openlatch");
        assert_eq!(store.username, "api-key");
    }

    #[test]
    fn test_map_keyring_error_no_entry_maps_to_ol_1600() {
        let err = map_keyring_error(keyring::Error::NoEntry, USERNAME);
        assert_eq!(err.code, ERR_NO_CREDENTIALS);
        assert!(err.suggestion.is_some());
        assert!(
            err.suggestion
                .as_deref()
                .is_some_and(|s| s.contains("auth login")),
            "the API-key remedy must stay the API-key remedy"
        );
    }

    #[test]
    fn test_map_keyring_error_no_entry_for_a_proxy_names_the_proxy_remedy() {
        // Same keyring error, entirely different thing to do about it: telling an operator
        // with an unauthenticated proxy to run `auth login` sends them to the wrong screen.
        let err = map_keyring_error(keyring::Error::NoEntry, "proxy:proxy.corp.example:8080");
        assert_eq!(err.code, ERR_NO_CREDENTIALS);
        let suggestion = err.suggestion.as_deref().unwrap_or_default();
        assert!(
            suggestion.contains("proxy set"),
            "expected the proxy remedy, got: {suggestion}"
        );
        assert!(
            err.message.contains("proxy.corp.example:8080"),
            "the message must name the authority: {}",
            err.message
        );
    }

    #[test]
    fn test_map_keyring_error_platform_failure_maps_to_ol_1602() {
        let boxed: Box<dyn std::error::Error + Send + Sync> = "test failure".to_string().into();
        let err = map_keyring_error(keyring::Error::PlatformFailure(boxed), USERNAME);
        assert_eq!(err.code, ERR_KEYCHAIN_UNAVAILABLE);
        assert!(err.suggestion.is_some());
    }

    #[test]
    fn test_map_keyring_error_no_storage_access_maps_to_ol_1602() {
        let boxed: Box<dyn std::error::Error + Send + Sync> = "no access".to_string().into();
        let err = map_keyring_error(keyring::Error::NoStorageAccess(boxed), USERNAME);
        assert_eq!(err.code, ERR_KEYCHAIN_UNAVAILABLE);
    }

    #[test]
    fn test_for_identity_addresses_a_second_entry_under_the_same_service() {
        let store = KeyringCredentialStore::for_identity(SERVICE_NAME, "proxy:proxy.test:8080");
        assert_eq!(store.service, "openlatch");
        assert_eq!(store.username, "proxy:proxy.test:8080");
        // The API-key singleton is a *different username*, which is what makes it
        // unoverwritable by construction rather than by convention.
        assert_ne!(store.username, KeyringCredentialStore::new().username);
    }

    /// The E-12 regression trap: an unkeyed memo returns the first identity's secret to
    /// every later identity. Reading the proxy password first and then the API key must
    /// yield the API key — not the proxy password that happened to be read first.
    ///
    /// Driven through `memoized_read` with in-memory readers rather than a real store: the
    /// automated suites run with `OPENLATCH_SKIP_KEYRING=1`, under which `retrieve` returns
    /// before the memo is ever consulted, so a store-level test here would assert nothing.
    #[test]
    fn test_read_memo_is_keyed_per_identity() {
        let service = "openlatch-memo-isolation-test";
        let api = (service.to_string(), "api-key".to_string());
        let proxy = (service.to_string(), "proxy:proxy.test:8080".to_string());

        let first =
            memoized_read(proxy.clone(), || Ok("proxy-password".to_string())).expect("proxy read");
        assert_eq!(first, "proxy-password");

        let second =
            memoized_read(api.clone(), || Ok("the-api-key".to_string())).expect("api read");
        assert_eq!(
            second, "the-api-key",
            "a keyed memo must not serve the proxy password as the API key"
        );

        // Both are now memoized, independently: a second reader returning a different
        // value proves the answer came from the memo rather than from a fresh read.
        assert_eq!(
            memoized_read(proxy, || Ok("never-read-again".to_string())).expect("memoized"),
            "proxy-password"
        );
        assert_eq!(
            memoized_read(api, || Ok("never-read-again".to_string())).expect("memoized"),
            "the-api-key"
        );
    }

    /// Invalidation is per entry: storing a proxy password must not force a fresh keychain
    /// read — and on macOS a fresh authorization dialog — for the API key.
    #[test]
    fn test_invalidation_drops_only_its_own_entry() {
        let service = "openlatch-memo-invalidation-test";
        let api = (service.to_string(), "api-key".to_string());
        let proxy = (service.to_string(), "proxy:proxy.test:8080".to_string());

        memoized_read(api.clone(), || Ok("the-api-key".to_string())).expect("seed api");
        memoized_read(proxy.clone(), || Ok("v1".to_string())).expect("seed proxy");

        invalidate_read_memo(service, "proxy:proxy.test:8080");

        assert_eq!(
            memoized_read(proxy, || Ok("v2".to_string())).expect("re-read"),
            "v2",
            "the invalidated entry must be re-read"
        );
        assert_eq!(
            memoized_read(api, || Ok("re-read".to_string())).expect("memoized"),
            "the-api-key",
            "the untouched entry must still be memoized"
        );
    }

    /// A failure is memoized too — a denied macOS dialog must not re-prompt — and that
    /// memoization is also per identity.
    #[test]
    fn test_failures_are_memoized_per_identity() {
        let service = "openlatch-memo-failure-test";
        let key = (service.to_string(), "api-key".to_string());
        let err = || Err(OlError::new(ERR_NO_CREDENTIALS, "denied"));

        assert!(memoized_read(key.clone(), err).is_err());
        assert!(
            memoized_read(key, || Ok("would-have-prompted".to_string())).is_err(),
            "a memoized failure must not fall through to a second read"
        );
    }

    #[test]
    #[ignore] // Mutates a process-wide env var — not safe to run in parallel.
              // Run with: cargo test test_keyring_skip_env -- --ignored --test-threads=1
    fn test_keyring_skip_env_disables_retrieve() {
        let key = "OPENLATCH_SKIP_KEYRING";
        std::env::remove_var(key);
        assert!(!keyring_disabled_by_env());

        for truthy in ["1", "true", "TRUE", "yes", "on"] {
            std::env::set_var(key, truthy);
            assert!(keyring_disabled_by_env(), "{truthy:?} should be truthy");
        }
        for falsy in ["", "0", "false", "no", "off"] {
            std::env::set_var(key, falsy);
            assert!(!keyring_disabled_by_env(), "{falsy:?} should be falsy");
        }

        std::env::set_var(key, "1");
        let result = KeyringCredentialStore::new().retrieve();
        std::env::remove_var(key);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code, ERR_NO_CREDENTIALS);
    }

    #[tokio::test]
    #[ignore] // Requires real OS keychain — fails on headless CI without Secret Service
    async fn test_keyring_async_methods_compile_and_run_in_tokio_context() {
        // Verify the async methods can be called without panicking in a tokio runtime.
        // The keychain may not have a credential, so we only check that the call completes.
        let store = KeyringCredentialStore::new();
        // delete_async is idempotent (no-op when no entry exists), so it's safe to call.
        // This verifies spawn_blocking works correctly in the tokio context.
        let result = store.delete_async().await;
        assert!(
            result.is_ok(),
            "delete_async should succeed even when no entry exists"
        );
    }

    #[tokio::test]
    #[ignore] // Requires real OS keychain — run manually with: cargo test keyring -- --ignored
    async fn test_keyring_store_retrieve_delete_round_trip() {
        let store = KeyringCredentialStore::new();
        let key = SecretString::from("test-api-key-12345".to_string());
        store.store_async(key).await.unwrap();
        let retrieved = store.retrieve_async().await.unwrap();
        use secrecy::ExposeSecret;
        assert_eq!(retrieved.expose_secret(), "test-api-key-12345");
        store.delete_async().await.unwrap();
        assert!(store.retrieve_async().await.is_err());
    }
}