Skip to main content

synaps_cli/core/auth/
storage.rs

1use std::path::PathBuf;
2
3use super::{AuthFile, OAuthCredentials};
4
5/// Get the path to auth.json (~/.synaps-cli/auth.json).
6pub fn auth_file_path() -> PathBuf {
7    crate::config::resolve_read_path("auth.json")
8}
9
10/// Load credentials from auth.json.
11pub fn load_auth() -> std::result::Result<Option<AuthFile>, String> {
12    let path = auth_file_path();
13    if !path.exists() {
14        return Ok(None);
15    }
16    let content = std::fs::read_to_string(&path)
17        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
18    let auth: AuthFile = serde_json::from_str(&content)
19        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
20    Ok(Some(auth))
21}
22
23/// Load one provider's OAuth credential from auth.json.
24pub fn load_provider_auth(provider: &str) -> std::result::Result<Option<OAuthCredentials>, String> {
25    let path = auth_file_path();
26    if !path.exists() {
27        return Ok(None);
28    }
29    let content = std::fs::read_to_string(&path)
30        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
31    let value: serde_json::Value = serde_json::from_str(&content)
32        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
33    let Some(raw) = value.get(provider) else {
34        return Ok(None);
35    };
36    let creds: OAuthCredentials = serde_json::from_value(raw.clone())
37        .map_err(|e| format!("Failed to parse {} credential: {}", provider, e))?;
38    Ok(Some(creds))
39}
40
41/// Save credentials to auth.json.
42pub fn save_auth(creds: &OAuthCredentials) -> std::result::Result<(), String> {
43    save_provider_auth("anthropic", creds)
44}
45
46/// Save one provider credential while preserving other auth.json entries.
47pub fn save_provider_auth(provider: &str, creds: &OAuthCredentials) -> std::result::Result<(), String> {
48    let path = crate::config::resolve_write_path("auth.json");
49    save_provider_auth_at(&path, provider, creds)
50}
51
52/// Path-explicit variant of `save_provider_auth`. Splits out the I/O so
53/// the corrupt-file fallback path can be unit-tested without touching the
54/// user's real `~/.synaps-cli/auth.json`.
55fn save_provider_auth_at(
56    path: &std::path::Path,
57    provider: &str,
58    creds: &OAuthCredentials,
59) -> std::result::Result<(), String> {
60    use fs4::fs_std::FileExt;
61
62    // Ensure parent directory exists
63    if let Some(parent) = path.parent() {
64        std::fs::create_dir_all(parent)
65            .map_err(|e| format!("Failed to create {}: {}", parent.display(), e))?;
66    }
67
68    // Hold an exclusive lock for the entire read-modify-write cycle.
69    // Without this, two concurrent `synaps login` processes can race:
70    // both read the same file, each adds their provider, second write
71    // silently drops the first's credential.
72    let lock_path = path.with_extension("json.lock");
73    let lock_file = std::fs::OpenOptions::new()
74        .create(true)
75        .write(true)
76        .open(&lock_path)
77        .map_err(|e| format!("Failed to open lock file {}: {}", lock_path.display(), e))?;
78    FileExt::lock_exclusive(&lock_file)
79        .map_err(|e| format!("Failed to lock {}: {}", lock_path.display(), e))?;
80
81    let mut root = if path.exists() {
82        let content = std::fs::read_to_string(path)
83            .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
84        // Corrupt-file recovery: if the existing auth.json is not a JSON
85        // object (truncated write, manual edit error, swap-file detritus),
86        // log a warning and start fresh rather than refusing to save the
87        // new credential. The alternative is permanently locking the user
88        // out of `synaps login`.
89        match serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&content) {
90            Ok(map) => map,
91            Err(e) => {
92                tracing::warn!(
93                    path = %path.display(),
94                    error = %e,
95                    "auth.json could not be parsed as a JSON object; replacing with a fresh structure"
96                );
97                // Back up the corrupt file so credentials are potentially recoverable.
98                let ts = std::time::SystemTime::now()
99                    .duration_since(std::time::UNIX_EPOCH)
100                    .map(|d| d.as_secs())
101                    .unwrap_or(0);
102                let backup = path.with_extension(format!("json.corrupt.{}", ts));
103                match std::fs::copy(path, &backup) {
104                    Ok(_) => {
105                        eprintln!(
106                            "[warn] auth.json was corrupt and has been reset. Backup saved to: {}",
107                            backup.display()
108                        );
109                    }
110                    Err(copy_err) => {
111                        eprintln!(
112                            "[warn] auth.json was corrupt and has been reset, but backup failed: {}",
113                            copy_err
114                        );
115                    }
116                }
117                serde_json::Map::new()
118            }
119        }
120    } else {
121        serde_json::Map::new()
122    };
123
124    root.insert(
125        provider.to_string(),
126        serde_json::to_value(creds).map_err(|e| format!("Failed to serialize auth: {}", e))?,
127    );
128
129    let json = serde_json::to_string_pretty(&root)
130        .map_err(|e| format!("Failed to serialize auth: {}", e))?;
131
132    // Atomic write: write to .tmp then rename. rename(2) is atomic on POSIX.
133    // This prevents a crash/kill between truncate and write from zeroing auth.json.
134    // Create with restrictive permissions from the start so credentials are never
135    // world-readable, even briefly.
136    let tmp_path = path.with_extension("json.tmp");
137    {
138        use std::io::Write;
139        let mut file = std::fs::OpenOptions::new()
140            .write(true)
141            .create(true)
142            .truncate(true)
143            .open(&tmp_path)
144            .map_err(|e| format!("Failed to create {}: {}", tmp_path.display(), e))?;
145
146        #[cfg(unix)]
147        {
148            use std::os::unix::fs::PermissionsExt;
149            let perms = std::fs::Permissions::from_mode(0o600);
150            file.set_permissions(perms)
151                .map_err(|e| format!("Failed to set permissions on {}: {}", tmp_path.display(), e))?;
152        }
153
154        file.write_all(json.as_bytes())
155            .map_err(|e| format!("Failed to write {}: {}", tmp_path.display(), e))?;
156        file.sync_all()
157            .map_err(|e| format!("Failed to fsync {}: {}", tmp_path.display(), e))?;
158    }
159
160    std::fs::rename(&tmp_path, path)
161        .map_err(|e| format!("Failed to atomically replace {}: {}", path.display(), e))?;
162
163    Ok(())
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    fn fresh_creds() -> OAuthCredentials {
171        OAuthCredentials {
172            auth_type: "oauth".to_string(),
173            refresh: "r".to_string(),
174            access: "a".to_string(),
175            expires: 1,
176            account_id: None,
177        }
178    }
179
180    #[test]
181    fn save_provider_auth_at_creates_file_when_absent() {
182        let dir = tempfile::tempdir().expect("tempdir");
183        let path = dir.path().join("auth.json");
184        save_provider_auth_at(&path, "openai-codex", &fresh_creds()).expect("save");
185        assert!(path.exists());
186        let content = std::fs::read_to_string(&path).unwrap();
187        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
188        assert!(parsed.get("openai-codex").is_some());
189    }
190
191    #[test]
192    fn save_provider_auth_at_preserves_other_providers() {
193        let dir = tempfile::tempdir().expect("tempdir");
194        let path = dir.path().join("auth.json");
195        std::fs::write(
196            &path,
197            r#"{"anthropic":{"type":"oauth","refresh":"r2","access":"a2","expires":2}}"#,
198        )
199        .unwrap();
200        save_provider_auth_at(&path, "openai-codex", &fresh_creds()).expect("save");
201        let content = std::fs::read_to_string(&path).unwrap();
202        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
203        assert!(parsed.get("anthropic").is_some(), "must keep anthropic entry");
204        assert!(parsed.get("openai-codex").is_some());
205    }
206
207    #[test]
208    fn save_provider_auth_at_recovers_from_corrupt_file() {
209        // Pre-fix: a corrupt auth.json would lock the user out of
210        // `synaps login` entirely because save_provider_auth would fail
211        // to parse and bail. After fix: corrupt content is replaced with
212        // a fresh structure containing the new credential.
213        let dir = tempfile::tempdir().expect("tempdir");
214        let path = dir.path().join("auth.json");
215        std::fs::write(&path, "this is not json {{{").unwrap();
216        save_provider_auth_at(&path, "openai-codex", &fresh_creds())
217            .expect("save must succeed even on corrupt input");
218        let content = std::fs::read_to_string(&path).unwrap();
219        let parsed: serde_json::Value = serde_json::from_str(&content)
220            .expect("file must now contain valid JSON");
221        assert!(parsed.get("openai-codex").is_some());
222        assert!(
223            parsed.get("anthropic").is_none(),
224            "corrupt fallback discards old (unrecoverable) entries"
225        );
226    }
227
228    #[test]
229    fn save_provider_auth_at_recovers_from_array_root() {
230        // auth.json was a JSON array (perhaps from a botched migration).
231        // Treat it as corrupt — same recovery as garbage input.
232        let dir = tempfile::tempdir().expect("tempdir");
233        let path = dir.path().join("auth.json");
234        std::fs::write(&path, "[1, 2, 3]").unwrap();
235        save_provider_auth_at(&path, "openai-codex", &fresh_creds())
236            .expect("save must succeed against non-object root");
237        let parsed: serde_json::Value =
238            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
239        assert!(parsed.is_object());
240        assert!(parsed.get("openai-codex").is_some());
241    }
242}