{"record":{"id":"e9ba9b0307ce9830","repo":"Hmbown/CodeWhale","slug":"refusing-to-replace-an-existing-xai-oauth-generati","errorCode":null,"errorMessage":"refusing to replace an existing xAI OAuth generation","messagePattern":"refusing to replace an existing xAI OAuth generation","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/config/src/xai_credentials.rs","lineNumber":1091,"sourceCode":"            })();\n            if let Err(error) = secured {\n                let cleanup = mark_windows_file_handle_for_deletion(&file);\n                return match cleanup {\n                    Ok(()) => Err(error),\n                    Err(cleanup) => Err(error).context(format!(\n                        \"also failed to delete the empty lifecycle lock: {cleanup:#}\"\n                    )),\n                };\n            }\n            return Ok(file);\n        }\n        bail!(\"xAI OAuth lifecycle lock changed repeatedly while opening\")\n    }\n\n    fn write_owned_file(&self, name: &str, bytes: &[u8], allow_replace: bool) -> Result<()> {\n        let path = self.directory.join(name);\n        if let Some(existing) = self.open_owned_file_for_read(name)? {\n            anyhow::ensure!(\n                allow_replace,\n                \"refusing to replace an existing xAI OAuth generation\"\n            );\n            drop(existing);\n        }\n        let mut temporary = tempfile::NamedTempFile::new_in(&self.directory)\n            .context(\"creating private xAI OAuth temporary file\")?;\n        let temporary_path = temporary.path().to_path_buf();\n        let security_handle =\n            reopen_windows_file_for_owner_security(temporary.as_file(), &temporary_path)?;\n        secure_windows_owner_only_handle(&security_handle, false)\n            .context(\"securing a new xAI OAuth temporary file before writing credentials\")?;\n        validate_owned_file_handle(&security_handle, &temporary_path)\n            .context(\"verifying a new xAI OAuth temporary file before writing credentials\")?;\n        let write_result = (|| -> Result<()> {\n            temporary\n                .write_all(bytes)\n                .context(\"writing xAI OAuth temporary file\")?;","sourceCodeStart":1073,"sourceCodeEnd":1109,"githubUrl":"https://github.com/Hmbown/CodeWhale/blob/73e0f67d83c59909b571efdfc88c4bc28c309cb1/crates/config/src/xai_credentials.rs#L1073-L1109","documentation":"write_owned_file implements create-if-absent semantics for credential generations: it first opens the target name for read, and if a generation already exists it requires the caller to explicitly pass allow_replace=true. This prevents an accidental second persist call (e.g. a concurrent login or a retry) from silently overwriting valid stored credentials.","triggerScenarios":"Calling the store's write/persist API for a generation name that already exists in the credentials directory while allow_replace is false — e.g. calling save twice, or two processes racing to write the same generation.","commonSituations":"Double-invoking the login flow; a retry after a timeout that actually succeeded; a second Codewhale instance writing tokens while one is already stored.","solutions":["Pass allow_replace=true if overwriting the existing generation is intended","Skip the write if a generation already exists (check via the store's read API first)","Use the remove/rotate API to delete the old generation, then write the new one"],"exampleFix":"// before\nstore.write_owned_file(\"auth.json\", &bytes, false)?;\n// after (replacement intended)\nstore.write_owned_file(\"auth.json\", &bytes, true)?;","handlingStrategy":"try-catch","validationCode":"fn generation_exists(store: &Store, name: &str) -> bool {\n    store.open_owned_file_for_read(name).map(|o| o.is_some()).unwrap_or(false)\n}","typeGuard":null,"tryCatchPattern":"match store.write_owned_file(\"auth.json\", &bytes, false) {\n    Err(e) if e.to_string().contains(\"refusing to replace\") => {\n        // already stored: treat as success or opt in to replace\n        store.write_owned_file(\"auth.json\", &bytes, true)?\n    }\n    r => r?,\n}","preventionTips":["Call persist once per login; make retries idempotent (check before writing)","Pass allow_replace=true explicitly when rotation is intended","Serialize writes across processes with the lifecycle lock"],"tags":["credentials","file-write","conflict"],"backgroundTag":"file-already-exists","analyzedSha":"73e0f67d83c59909b571efdfc88c4bc28c309cb1","analyzedAt":"2026-09-22T01:30:00.501Z","contentChangedAt":"2026-09-22T01:30:00.501Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}