car-ffi-common 0.50.0

Shared logic for FFI bindings (NAPI, PyO3) — JSON wrappers for verify, multi-agent, scheduler
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
//! Shared JSON wrapper for `car-secrets` operations, consumed by the CLI,
//! NAPI + PyO3 bindings, and the WebSocket server.
//!
//! Each typed `SecretError` variant maps to a stable machine-readable
//! `code` so callers can branch programmatically instead of parsing
//! message strings. The error JSON shape is:
//!
//! ```json
//! {
//!   "code": "not_found | unavailable | access_denied | user_cancelled | helper_timed_out | backend | invalid_json",
//!   "message": "...",
//!   "context": {"service": "...", "key": "..."}
//! }
//! ```
//!
//! FFI surfaces (NAPI, PyO3, JSON-RPC) surface this as the error message
//! body — consumers parse the JSON to read `code` programmatically.

use car_secrets::{SecretError, SecretRef, SecretStatus, SecretStore, DEFAULT_SERVICE};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::path::PathBuf;

fn make_ref(service: Option<&str>, key: &str) -> SecretRef {
    SecretRef::new(service.unwrap_or(DEFAULT_SERVICE), key)
}

fn reject_daemon_private(service: Option<&str>, key: &str) -> Result<(), String> {
    if car_secrets::is_daemon_private_secret(service.unwrap_or(DEFAULT_SERVICE), key) {
        Err("reserved_private_secret: this daemon-owned credential metadata is available only through its dedicated connection surface".to_string())
    } else {
        Ok(())
    }
}

// ---- Secret name index ------------------------------------------------------
//
// The OS keychain backend is stateless round-trips with no portable
// enumeration (macOS `security` can't list a service's keys without
// prompt/value exposure, and the `keyring` crate has no cross-platform list).
// To give CarHost's Secrets pane (car#366) a "List" without keychain
// enumeration, every secret written THROUGH this module records its
// `(service, key)` — NAMES ONLY, never the value — in `secret_index.json` under
// the CAR state root (`$CAR_HOME` when set, otherwise `~/.car`), so a relocated
// install keeps its own index rather than sharing the default one.
// `delete` forgets it, and `list` reads the index and joins a live existence
// check so a name whose keychain item was removed out-of-band is flagged.
//
// Deliberately scoped to secrets written through the FFI/CLI/WS surface: CAR's
// own internal secrets (connector OAuth tokens, browser session refs) go
// straight to `car_secrets::SecretStore`, bypass this module, and are correctly
// absent from the user-facing Secrets pane.

/// File name under the CAR state root. Holds secret NAMES only — no values ever
/// touch it.
const INDEX_FILE: &str = "secret_index.json";

#[derive(Debug, Default, Serialize, Deserialize)]
struct SecretIndex {
    #[serde(default)]
    entries: Vec<IndexEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct IndexEntry {
    service: String,
    key: String,
}

/// `secret_index.json` under the CAR state root — `$CAR_HOME` when set,
/// otherwise `~/.car`. `None` when neither the override nor a home directory
/// resolves (the index is then simply unavailable — put/delete still succeed
/// against the keychain, list just can't enumerate).
fn index_path() -> Option<PathBuf> {
    Some(car_home::root()?.join(INDEX_FILE))
}

fn load_index() -> SecretIndex {
    match index_path() {
        Some(path) => load_index_at(&path),
        None => SecretIndex::default(),
    }
}

fn load_index_at(path: &std::path::Path) -> SecretIndex {
    match std::fs::read_to_string(path) {
        Ok(s) => serde_json::from_str(&s).unwrap_or_default(),
        Err(_) => SecretIndex::default(), // missing/unreadable → empty
    }
}

fn save_index_at(path: &std::path::Path, idx: &SecretIndex) {
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let Ok(s) = serde_json::to_string_pretty(idx) else {
        return;
    };
    // Write to a sibling temp file then atomically rename, so a concurrent
    // `list`/`load_index` never observes a half-written or truncated file (the
    // index is best-effort, but a torn read would transiently blank the pane).
    // Temp is in the same directory to keep the rename on one filesystem.
    let tmp = path.with_extension("json.tmp");
    if std::fs::write(&tmp, s).is_ok() && std::fs::rename(&tmp, path).is_err() {
        let _ = std::fs::remove_file(&tmp); // don't leave a stray temp behind
    }
}

/// Record a `(service, key)` in the index (idempotent — no duplicates).
/// Best-effort: index failures must never fail the keychain write itself.
fn index_record(service: &str, key: &str) {
    if let Some(path) = index_path() {
        index_record_at(&path, service, key);
    }
}

fn index_record_at(path: &std::path::Path, service: &str, key: &str) {
    let mut idx = load_index_at(path);
    if !idx
        .entries
        .iter()
        .any(|e| e.service == service && e.key == key)
    {
        idx.entries.push(IndexEntry {
            service: service.to_string(),
            key: key.to_string(),
        });
        save_index_at(path, &idx);
    }
}

/// Forget a `(service, key)` from the index. Best-effort.
fn index_forget(service: &str, key: &str) {
    if let Some(path) = index_path() {
        index_forget_at(&path, service, key);
    }
}

fn index_forget_at(path: &std::path::Path, service: &str, key: &str) {
    let mut idx = load_index_at(path);
    let before = idx.entries.len();
    idx.entries
        .retain(|e| !(e.service == service && e.key == key));
    if idx.entries.len() != before {
        save_index_at(path, &idx);
    }
}

/// Stable error codes the FFI surface exposes.
fn code_for(e: &SecretError) -> &'static str {
    match e {
        SecretError::NotFound { .. } => "not_found",
        SecretError::Unavailable(_) => "unavailable",
        SecretError::AccessDenied { .. } => "access_denied",
        SecretError::UserCancelled { .. } => "user_cancelled",
        SecretError::HelperTimedOut { .. } => "helper_timed_out",
        SecretError::Backend(_) => "backend",
        SecretError::InvalidJson(_) => "invalid_json",
    }
}

fn json_err(e: SecretError) -> String {
    let message = match &e {
        SecretError::AccessDenied { .. } => "secret store access denied".to_string(),
        SecretError::UserCancelled { .. } => "secret store access cancelled".to_string(),
        SecretError::HelperTimedOut { .. } => "secret store helper timed out".to_string(),
        _ => e.to_string(),
    };
    let mut body = json!({
        "code": code_for(&e),
        "message": message,
    });
    if let SecretError::NotFound { service, key } = &e {
        body["context"] = json!({"service": service, "key": key});
    }
    body.to_string()
}

pub fn put(service: Option<&str>, key: &str, value: &str) -> Result<Value, String> {
    reject_daemon_private(service, key)?;
    let store = SecretStore::new();
    let svc = service.unwrap_or(DEFAULT_SERVICE);
    store
        .put(&make_ref(service, key), value)
        .map_err(json_err)?;
    // Record the NAME (never the value) so the Secrets pane can list it (#366).
    index_record(svc, key);
    Ok(json!({"service": svc, "key": key, "stored": true}))
}

pub fn get(service: Option<&str>, key: &str) -> Result<Value, String> {
    reject_daemon_private(service, key)?;
    let store = SecretStore::new();
    let v = store.get(&make_ref(service, key)).map_err(json_err)?;
    Ok(json!({"service": service.unwrap_or(DEFAULT_SERVICE), "key": key, "value": v}))
}

pub fn delete(service: Option<&str>, key: &str) -> Result<Value, String> {
    reject_daemon_private(service, key)?;
    let store = SecretStore::new();
    let svc = service.unwrap_or(DEFAULT_SERVICE);
    store.delete(&make_ref(service, key)).map_err(json_err)?;
    index_forget(svc, key);
    Ok(json!({"service": svc, "key": key, "deleted": true}))
}

/// List the names of secrets stored through this surface — `(service, key)`
/// plus a live `exists` flag, NEVER the values (#366). Backed by the
/// `~/.car/secret_index.json` name index, since the OS keychain has no portable
/// enumeration. Each indexed name is joined with a `status` existence check so a
/// secret removed out-of-band (e.g. via `security delete-generic-password`)
/// surfaces as `exists: false` rather than a phantom entry. Sorted by
/// `(service, key)` for a stable display order.
pub fn list() -> Result<Value, String> {
    let store = SecretStore::new();
    let mut idx = load_index();
    idx.entries
        .sort_by(|a, b| a.service.cmp(&b.service).then_with(|| a.key.cmp(&b.key)));
    let secrets: Vec<Value> = idx
        .entries
        .iter()
        .map(|e| {
            // Existence is best-effort: a backend error (e.g. locked keychain)
            // is reported as `unknown` rather than a false `exists: false`.
            let exists = store
                .status(&SecretRef::new(e.service.clone(), e.key.clone()))
                .map(|st| Value::Bool(st.exists))
                .unwrap_or(Value::Null);
            json!({"service": e.service, "key": e.key, "exists": exists})
        })
        .collect();
    Ok(json!({"secrets": secrets}))
}

pub fn status(service: Option<&str>, key: &str) -> Result<Value, String> {
    reject_daemon_private(service, key)?;
    let store = SecretStore::new();
    let st: SecretStatus = store.status(&make_ref(service, key)).map_err(json_err)?;
    serde_json::to_value(&st)
        .map_err(|e| json!({"code": "backend", "message": e.to_string()}).to_string())
}

pub fn is_available() -> Value {
    let check = SecretStore::new().availability();
    serde_json::to_value(&check).unwrap_or_else(|_| json!({"available": check.available}))
}

/// Guarded internal accessor for user-supplied secret references such as the
/// browser `session_ref` path. Daemon-private roots and their platform-derived
/// chunks remain available only to dedicated internal connection surfaces.
pub fn read_raw(service: Option<&str>, key: &str) -> Result<String, String> {
    reject_daemon_private(service, key)?;
    SecretStore::new()
        .get(&make_ref(service, key))
        .map_err(json_err)
}

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

    fn tmp_index() -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(".car").join(INDEX_FILE);
        (dir, path)
    }

    #[test]
    fn index_records_dedups_and_forgets() {
        let (_d, path) = tmp_index();
        // Missing file → empty.
        assert!(load_index_at(&path).entries.is_empty());

        index_record_at(&path, "car", "FRED_API_KEY");
        index_record_at(&path, "car", "FRED_API_KEY"); // idempotent
        index_record_at(&path, "providers", "OPENAI_API_KEY");
        let idx = load_index_at(&path);
        assert_eq!(idx.entries.len(), 2, "dedup on (service,key)");

        index_forget_at(&path, "car", "FRED_API_KEY");
        let idx = load_index_at(&path);
        assert_eq!(idx.entries.len(), 1);
        assert_eq!(idx.entries[0].key, "OPENAI_API_KEY");

        // Forgetting an absent entry is a no-op (no panic, no spurious write).
        index_forget_at(&path, "car", "nope");
        assert_eq!(load_index_at(&path).entries.len(), 1);
    }

    #[test]
    fn index_never_holds_values() {
        // The index type has no value field; serializing it can't leak a secret
        // value even if a caller mistakenly passed one as a key.
        let (_d, path) = tmp_index();
        index_record_at(&path, "car", "API_KEY");
        let raw = std::fs::read_to_string(&path).unwrap();
        assert!(raw.contains("API_KEY"));
        assert!(raw.contains("service"));
        assert!(
            !raw.contains("value"),
            "index must never serialize a value field"
        );
    }

    #[test]
    fn corrupt_index_degrades_to_empty() {
        let (_d, path) = tmp_index();
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "not json {{{").unwrap();
        assert!(
            load_index_at(&path).entries.is_empty(),
            "corrupt → empty, no panic"
        );
        // A subsequent record overwrites the corrupt file cleanly.
        index_record_at(&path, "car", "K");
        assert_eq!(load_index_at(&path).entries.len(), 1);
    }

    #[test]
    fn daemon_private_slots_fail_closed_across_generic_value_operations() {
        for key in [
            car_secrets::OPENROUTER_OAUTH_KEY,
            car_secrets::PARSLEE_ACCESS_TOKEN_KEY,
            car_secrets::PARSLEE_REFRESH_TOKEN_KEY,
            car_secrets::PARSLEE_EXPIRES_AT_KEY,
            car_secrets::PARSLEE_API_BASE_KEY,
            car_secrets::PARSLEE_ACCOUNTS_KEY,
            "PARSLEE_TOKENS_account-1",
            car_secrets::PARSLEE_AUTH_GENERATION_KEY,
            car_secrets::PARSLEE_AUTH_COMPLETION_KEY,
            car_secrets::PARSLEE_ACTIVE_ACCOUNT_ID_KEY,
            car_secrets::PARSLEE_AUTH_STATE_V2_KEY,
            "PARSLEE_AUTH_STATE_V2#chunk0",
            "PARSLEE_AUTH_STATE_V2#chunkv2#nonce-1#0",
        ] {
            for service in [None, Some(DEFAULT_SERVICE)] {
                let error = reject_daemon_private(service, key).unwrap_err();
                assert!(error.contains("reserved_private_secret"));
                for operation_error in [
                    put(service, key, "must-not-write").unwrap_err(),
                    get(service, key).unwrap_err(),
                    delete(service, key).unwrap_err(),
                    status(service, key).unwrap_err(),
                    read_raw(service, key).unwrap_err(),
                ] {
                    assert!(
                        operation_error.contains("reserved_private_secret"),
                        "{key}: {operation_error}"
                    );
                    assert!(!operation_error.contains("must-not-write"));
                }
            }
            assert!(reject_daemon_private(Some("other"), key).is_ok());
        }
        assert!(reject_daemon_private(None, "OPENROUTER_API_KEY").is_ok());
    }

    #[test]
    fn typed_helper_failures_have_stable_secret_free_ffi_errors() {
        let cases = [
            (
                SecretError::AccessDenied {
                    message: "PRIVATE_STDERR /tmp/private-keychain secret-service secret-key"
                        .to_string(),
                },
                "access_denied",
                "secret store access denied",
            ),
            (
                SecretError::UserCancelled {
                    message: "PRIVATE_CANCEL_DETAILS secret-service secret-key".to_string(),
                },
                "user_cancelled",
                "secret store access cancelled",
            ),
            (
                SecretError::HelperTimedOut {
                    operation: "PRIVATE_OPERATION secret-service/secret-key".to_string(),
                },
                "helper_timed_out",
                "secret store helper timed out",
            ),
        ];

        for (error, expected_code, expected_message) in cases {
            let body: Value = serde_json::from_str(&json_err(error)).unwrap();
            assert_eq!(body["code"], expected_code);
            assert_eq!(body["message"], expected_message);
            assert_eq!(body.as_object().unwrap().len(), 2);
            let rendered = body.to_string();
            for sensitive in [
                "PRIVATE_STDERR",
                "PRIVATE_CANCEL_DETAILS",
                "PRIVATE_OPERATION",
                "/tmp/private-keychain",
                "secret-service",
                "secret-key",
            ] {
                assert!(
                    !rendered.contains(sensitive),
                    "leaked {sensitive}: {rendered}"
                );
            }
        }
    }
}