synaps-core 0.6.1

Foundation types, config, session, auth, protocol — leaf crate for agent-runtime
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
use std::path::PathBuf;

use super::{AuthFile, OAuthCredentials};

/// Get the path to auth.json (~/.synaps-cli/auth.json).
pub fn auth_file_path() -> PathBuf {
    crate::config::resolve_read_path("auth.json")
}

/// Load credentials from auth.json.
pub fn load_auth() -> std::result::Result<Option<AuthFile>, String> {
    let path = auth_file_path();
    if !path.exists() {
        return Ok(None);
    }
    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
    let auth: AuthFile = serde_json::from_str(&content)
        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
    Ok(Some(auth))
}

/// Load one provider's OAuth credential from auth.json.
pub fn load_provider_auth(provider: &str) -> std::result::Result<Option<OAuthCredentials>, String> {
    let path = auth_file_path();
    if !path.exists() {
        return Ok(None);
    }
    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
    let value: serde_json::Value = serde_json::from_str(&content)
        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
    let Some(raw) = value.get(provider) else {
        return Ok(None);
    };
    let creds: OAuthCredentials = serde_json::from_value(raw.clone())
        .map_err(|e| format!("Failed to parse {} credential: {}", provider, e))?;
    Ok(Some(creds))
}

/// Save credentials to auth.json.
pub fn save_auth(creds: &OAuthCredentials) -> std::result::Result<(), String> {
    save_provider_auth("anthropic", creds)
}

/// Save one provider credential while preserving other auth.json entries.
pub fn save_provider_auth(provider: &str, creds: &OAuthCredentials) -> std::result::Result<(), String> {
    let path = crate::config::resolve_write_path("auth.json");
    save_provider_auth_at(&path, provider, creds)
}

/// Path-explicit variant of `save_provider_auth`. Splits out the I/O so
/// the corrupt-file fallback path can be unit-tested without touching the
/// user's real `~/.synaps-cli/auth.json`.
fn save_provider_auth_at(
    path: &std::path::Path,
    provider: &str,
    creds: &OAuthCredentials,
) -> std::result::Result<(), String> {
    use fs4::fs_std::FileExt;

    // Ensure parent directory exists
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("Failed to create {}: {}", parent.display(), e))?;
    }

    // Hold an exclusive lock for the entire read-modify-write cycle.
    // Without this, two concurrent `synaps login` processes can race:
    // both read the same file, each adds their provider, second write
    // silently drops the first's credential.
    let lock_path = path.with_extension("json.lock");
    let lock_file = std::fs::OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(&lock_path)
        .map_err(|e| format!("Failed to open lock file {}: {}", lock_path.display(), e))?;
    FileExt::lock_exclusive(&lock_file)
        .map_err(|e| format!("Failed to lock {}: {}", lock_path.display(), e))?;

    let mut root = if path.exists() {
        let content = std::fs::read_to_string(path)
            .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
        // Corrupt-file recovery: if the existing auth.json is not a JSON
        // object (truncated write, manual edit error, swap-file detritus),
        // log a warning and start fresh rather than refusing to save the
        // new credential. The alternative is permanently locking the user
        // out of `synaps login`.
        match serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&content) {
            Ok(map) => map,
            Err(e) => {
                tracing::warn!(
                    path = %path.display(),
                    error = %e,
                    "auth.json could not be parsed as a JSON object; replacing with a fresh structure"
                );
                // Back up the corrupt file so credentials are potentially recoverable.
                let ts = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                let backup = path.with_extension(format!("json.corrupt.{}", ts));
                match std::fs::copy(path, &backup) {
                    Ok(_) => {
                        eprintln!(
                            "[warn] auth.json was corrupt and has been reset. Backup saved to: {}",
                            backup.display()
                        );
                    }
                    Err(copy_err) => {
                        eprintln!(
                            "[warn] auth.json was corrupt and has been reset, but backup failed: {}",
                            copy_err
                        );
                    }
                }
                serde_json::Map::new()
            }
        }
    } else {
        serde_json::Map::new()
    };

    root.insert(
        provider.to_string(),
        serde_json::to_value(creds).map_err(|e| format!("Failed to serialize auth: {}", e))?,
    );

    let json = serde_json::to_string_pretty(&root)
        .map_err(|e| format!("Failed to serialize auth: {}", e))?;

    // Atomic write: write to .tmp then rename. rename(2) is atomic on POSIX.
    // This prevents a crash/kill between truncate and write from zeroing auth.json.
    // Create with restrictive permissions from the start so credentials are never
    // world-readable, even briefly.
    let tmp_path = path.with_extension("json.tmp");
    {
        use std::io::Write;
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&tmp_path)
            .map_err(|e| format!("Failed to create {}: {}", tmp_path.display(), e))?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::Permissions::from_mode(0o600);
            file.set_permissions(perms)
                .map_err(|e| format!("Failed to set permissions on {}: {}", tmp_path.display(), e))?;
        }

        file.write_all(json.as_bytes())
            .map_err(|e| format!("Failed to write {}: {}", tmp_path.display(), e))?;
        file.sync_all()
            .map_err(|e| format!("Failed to fsync {}: {}", tmp_path.display(), e))?;
    }

    std::fs::rename(&tmp_path, path)
        .map_err(|e| format!("Failed to atomically replace {}: {}", path.display(), e))?;

    Ok(())
}

/// Test-only re-export of `save_provider_auth_at` so that `token::tests`
/// can exercise the same function `ensure_fresh_token` now delegates to,
/// without making the path-explicit variant part of the public API.
#[cfg(test)]
pub(super) fn save_provider_auth_at_test_hook(
    path: &std::path::Path,
    provider: &str,
    creds: &OAuthCredentials,
) -> std::result::Result<(), String> {
    save_provider_auth_at(path, provider, creds)
}

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

    fn fresh_creds() -> OAuthCredentials {
        OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "r".to_string(),
            access: "a".to_string(),
            expires: 1,
            account_id: None,
        }
    }

    #[test]
    fn save_provider_auth_at_creates_file_when_absent() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        save_provider_auth_at(&path, "openai-codex", &fresh_creds()).expect("save");
        assert!(path.exists());
        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert!(parsed.get("openai-codex").is_some());
    }

    #[test]
    fn save_provider_auth_at_preserves_other_providers() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        std::fs::write(
            &path,
            r#"{"anthropic":{"type":"oauth","refresh":"r2","access":"a2","expires":2}}"#,
        )
        .unwrap();
        save_provider_auth_at(&path, "openai-codex", &fresh_creds()).expect("save");
        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert!(parsed.get("anthropic").is_some(), "must keep anthropic entry");
        assert!(parsed.get("openai-codex").is_some());
    }

    #[test]
    fn save_provider_auth_at_recovers_from_corrupt_file() {
        // Pre-fix: a corrupt auth.json would lock the user out of
        // `synaps login` entirely because save_provider_auth would fail
        // to parse and bail. After fix: corrupt content is replaced with
        // a fresh structure containing the new credential.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        std::fs::write(&path, "this is not json {{{").unwrap();
        save_provider_auth_at(&path, "openai-codex", &fresh_creds())
            .expect("save must succeed even on corrupt input");
        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content)
            .expect("file must now contain valid JSON");
        assert!(parsed.get("openai-codex").is_some());
        assert!(
            parsed.get("anthropic").is_none(),
            "corrupt fallback discards old (unrecoverable) entries"
        );
    }

    #[test]
    fn save_provider_auth_at_recovers_from_array_root() {
        // auth.json was a JSON array (perhaps from a botched migration).
        // Treat it as corrupt — same recovery as garbage input.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        std::fs::write(&path, "[1, 2, 3]").unwrap();
        save_provider_auth_at(&path, "openai-codex", &fresh_creds())
            .expect("save must succeed against non-object root");
        let parsed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert!(parsed.is_object());
        assert!(parsed.get("openai-codex").is_some());
    }

    // ── Bug #159 regression suite ────────────────────────────────────────────
    //
    // Repro: `synaps login --provider openai-codex` (saves "openai-codex"),
    // then `synaps login` (Anthropic OAuth, saves "anthropic") → the first
    // provider's credential was wiped because save_auth() rebuilt AuthFile
    // with only the new entry and did a whole-file overwrite.
    //
    // Root cause (pre-fix): src/core/auth/storage.rs @ 90f8f71 — save_auth()
    // constructed `AuthFile { anthropic: creds }` (no read of existing file)
    // then called `fs::write(path, json)`, discarding every other provider.
    //
    // All three multi-provider tests below would FAIL against that code.

    /// Primary repro (bug #159): save openai-codex, then save anthropic via
    /// the same write path `synaps login` (Anthropic OAuth) takes.
    /// openai-codex MUST survive the second login.
    #[test]
    fn bug159_anthropic_login_preserves_existing_openai_codex() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");

        // Step 1: user runs `synaps login --provider openai-codex`
        let codex_creds = OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "codex-refresh".to_string(),
            access: "codex-access".to_string(),
            expires: 9_999_999_999_000,
            account_id: Some("acct_codex_123".to_string()),
        };
        save_provider_auth_at(&path, "openai-codex", &codex_creds)
            .expect("save openai-codex");

        // Step 2: user then runs `synaps login` (Anthropic Claude OAuth)
        let anthropic_creds = OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "anth-refresh".to_string(),
            access: "anth-access".to_string(),
            expires: 9_999_999_999_000,
            account_id: None,
        };
        save_provider_auth_at(&path, "anthropic", &anthropic_creds)
            .expect("save anthropic");

        // Both providers must be present — bug #159 would wipe openai-codex here
        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();

        assert!(
            parsed.get("anthropic").is_some(),
            "anthropic credential must be present after login"
        );
        assert!(
            parsed.get("openai-codex").is_some(),
            "bug #159: openai-codex credential must NOT be wiped when logging in as anthropic"
        );
        assert_eq!(
            parsed["openai-codex"]["refresh"].as_str(),
            Some("codex-refresh"),
            "openai-codex refresh token must be unchanged"
        );
        assert_eq!(
            parsed["anthropic"]["refresh"].as_str(),
            Some("anth-refresh"),
            "anthropic refresh token must be correctly saved"
        );
    }

    /// Reverse of primary repro: anthropic first, then openai-codex login.
    /// anthropic MUST survive.
    #[test]
    fn bug159_openai_codex_login_preserves_existing_anthropic() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");

        // Step 1: anthropic already logged in
        let anthropic_creds = OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "anth-refresh-first".to_string(),
            access: "anth-access-first".to_string(),
            expires: 9_999_999_999_000,
            account_id: None,
        };
        save_provider_auth_at(&path, "anthropic", &anthropic_creds)
            .expect("save anthropic");

        // Step 2: user runs `synaps login --provider openai-codex`
        let codex_creds = OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "codex-refresh-second".to_string(),
            access: "codex-access-second".to_string(),
            expires: 9_999_999_999_000,
            account_id: Some("acct_456".to_string()),
        };
        save_provider_auth_at(&path, "openai-codex", &codex_creds)
            .expect("save openai-codex");

        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();

        assert!(
            parsed.get("anthropic").is_some(),
            "anthropic credential must survive openai-codex login"
        );
        assert!(
            parsed.get("openai-codex").is_some(),
            "openai-codex credential must be present"
        );
        assert_eq!(
            parsed["anthropic"]["refresh"].as_str(),
            Some("anth-refresh-first"),
            "anthropic refresh token must be unchanged"
        );
    }

    /// Three-provider scenario: saving a third provider preserves the first two.
    /// Guards against regressions if/when more OAuth providers are added.
    #[test]
    fn bug159_third_provider_login_preserves_both_existing_providers() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");

        save_provider_auth_at(&path, "anthropic", &OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "anth-r".to_string(),
            access: "anth-a".to_string(),
            expires: 1,
            account_id: None,
        }).expect("save anthropic");

        save_provider_auth_at(&path, "openai-codex", &OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "codex-r".to_string(),
            access: "codex-a".to_string(),
            expires: 1,
            account_id: Some("acct_codex".to_string()),
        }).expect("save openai-codex");

        save_provider_auth_at(&path, "future-provider", &OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "future-r".to_string(),
            access: "future-a".to_string(),
            expires: 1,
            account_id: None,
        }).expect("save future-provider");

        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();

        assert!(parsed.get("anthropic").is_some(), "anthropic must survive");
        assert!(parsed.get("openai-codex").is_some(), "openai-codex must survive");
        assert!(parsed.get("future-provider").is_some(), "future-provider must be present");
    }

    /// Upsert: saving the same provider twice updates the credential in place
    /// without duplicating or corrupting the entry.
    #[test]
    fn bug159_same_provider_login_upserts_in_place() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");

        save_provider_auth_at(&path, "anthropic", &OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "old-refresh".to_string(),
            access: "old-access".to_string(),
            expires: 1,
            account_id: None,
        }).expect("initial save");

        save_provider_auth_at(&path, "anthropic", &OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "new-refresh".to_string(),
            access: "new-access".to_string(),
            expires: 2,
            account_id: None,
        }).expect("upsert save");

        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let obj = parsed.as_object().unwrap();

        assert_eq!(obj.len(), 1, "only one anthropic entry — no duplicates");
        assert_eq!(
            parsed["anthropic"]["refresh"].as_str(),
            Some("new-refresh"),
            "credential must be updated to latest value"
        );
    }
}