fix(codex): sync temp file before close and rename in WriteJSONFileAtomic

- Sync the temporary credential file after writing JSON data and before closing and renaming it onto the target path, closing and removing the temp file if sync fails.
- Remove the unused strconv import and dead strconv.IntSize placeholder in SaveTokenToFile.
- Add regression tests verifying sync ordering before close/rename and temp file cleanup with existing credential preservation on sync error.

Closes: #7718
This commit is contained in:
Luis Pater
2026-11-21 10:28:31 +08:00
parent 5dff8b6728
commit 6d703fdf48
2 changed files with 147 additions and 2 deletions

View File

@@ -7,7 +7,6 @@ import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
@@ -59,6 +58,10 @@ func WithFileLock(authFilePath string, fn func() error) error {
return fn()
}
var syncTempCredentialFile = func(tmpFile *os.File) error {
return tmpFile.Sync()
}
// WriteJSONFileAtomic writes data as JSON to authFilePath atomically via a temporary file in the same directory.
func WriteJSONFileAtomic(authFilePath string, data map[string]any) error {
dir := filepath.Dir(authFilePath)
@@ -87,6 +90,12 @@ func WriteJSONFileAtomic(authFilePath string, data map[string]any) error {
_ = tmpFile.Close()
return fmt.Errorf("failed to write token to temp file: %w", errWrite)
}
if errSync := syncTempCredentialFile(tmpFile); errSync != nil {
if errClose := tmpFile.Close(); errClose != nil {
log.Errorf("codex token storage: close temp token file after sync error: %v", errClose)
}
return fmt.Errorf("failed to sync temp credential file: %w", errSync)
}
if errClose := tmpFile.Close(); errClose != nil {
log.Errorf("codex token storage: close temp token file error: %v", errClose)
return fmt.Errorf("failed to close temp credential file: %w", errClose)
@@ -271,7 +280,6 @@ func (ts *CodexTokenStorage) SetMetadata(meta map[string]any) {
func (ts *CodexTokenStorage) SaveTokenToFile(authFilePath string) error {
misc.LogSavingCredentials(authFilePath)
ts.Type = "codex"
_ = strconv.IntSize
return WithFileLock(authFilePath, func() error {
data, errMerge := misc.MergeMetadata(ts, ts.Metadata)

View File

@@ -1,8 +1,10 @@
package codex
import (
"errors"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/MoeForge/moego/json"
@@ -76,3 +78,138 @@ func TestSaveTokenToFile_PreservesCustomMetadata(t *testing.T) {
t.Errorf("weight = %v, want 42", saved["weight"])
}
}
func TestWriteJSONFileAtomic_SyncsTempFileBeforeCloseAndRename(t *testing.T) {
tempDir := t.TempDir()
authFilePath := filepath.Join(tempDir, "codex-auth.json")
initialRaw := []byte(`{"refresh_token":"old-refresh"}`)
if errWrite := os.WriteFile(authFilePath, initialRaw, 0o600); errWrite != nil {
t.Fatalf("os.WriteFile() error = %v", errWrite)
}
origSync := syncTempCredentialFile
t.Cleanup(func() {
syncTempCredentialFile = origSync
})
syncCalls := 0
syncTempCredentialFile = func(tmpFile *os.File) error {
syncCalls++
// Target file must still hold the previous contents when Sync runs (before Rename).
currentTarget, errReadTarget := os.ReadFile(authFilePath)
if errReadTarget != nil {
t.Errorf("os.ReadFile(target) during sync error = %v", errReadTarget)
} else if string(currentTarget) != string(initialRaw) {
t.Errorf("target content during sync = %s, want %s", currentTarget, initialRaw)
}
// Temp file must already hold the marshaled payload when Sync runs (after Write).
tmpRaw, errReadTmp := os.ReadFile(tmpFile.Name())
if errReadTmp != nil {
t.Errorf("os.ReadFile(tmp) during sync error = %v", errReadTmp)
} else {
var pending map[string]any
if errUnmarshal := json.Unmarshal(tmpRaw, &pending); errUnmarshal != nil {
t.Errorf("json.Unmarshal(tmp) during sync error = %v", errUnmarshal)
} else if pending["refresh_token"] != "new-refresh" || pending["access_token"] != "new-access" {
t.Errorf("temp payload during sync = %v, want new-refresh/new-access", pending)
}
}
// Delegate to the real os.File.Sync to confirm the file handle is still open (before Close).
return origSync(tmpFile)
}
if errWrite := WriteJSONFileAtomic(authFilePath, map[string]any{
"refresh_token": "new-refresh",
"access_token": "new-access",
}); errWrite != nil {
t.Fatalf("WriteJSONFileAtomic() error = %v", errWrite)
}
if syncCalls != 1 {
t.Fatalf("sync call count = %d, want 1", syncCalls)
}
savedRaw, errRead := os.ReadFile(authFilePath)
if errRead != nil {
t.Fatalf("os.ReadFile() error = %v", errRead)
}
var saved map[string]any
if errUnmarshal := json.Unmarshal(savedRaw, &saved); errUnmarshal != nil {
t.Fatalf("json.Unmarshal() error = %v", errUnmarshal)
}
if saved["refresh_token"] != "new-refresh" || saved["access_token"] != "new-access" {
t.Fatalf("saved payload = %v, want new-refresh/new-access", saved)
}
if runtime.GOOS != "windows" {
info, errStat := os.Stat(authFilePath)
if errStat != nil {
t.Fatalf("os.Stat() error = %v", errStat)
}
if perm := info.Mode().Perm(); perm != 0o600 {
t.Fatalf("file permissions = %o, want 600", perm)
}
}
entries, errEntries := os.ReadDir(tempDir)
if errEntries != nil {
t.Fatalf("os.ReadDir() error = %v", errEntries)
}
if len(entries) != 1 || entries[0].Name() != "codex-auth.json" {
t.Fatalf("unexpected leftover files in dir: %v", entries)
}
}
func TestWriteJSONFileAtomic_SyncErrorCleansUpTempFileAndPreservesExisting(t *testing.T) {
tempDir := t.TempDir()
authFilePath := filepath.Join(tempDir, "codex-auth.json")
initialRaw := []byte(`{"refresh_token":"old-refresh"}`)
if errWrite := os.WriteFile(authFilePath, initialRaw, 0o600); errWrite != nil {
t.Fatalf("os.WriteFile() error = %v", errWrite)
}
origSync := syncTempCredentialFile
t.Cleanup(func() {
syncTempCredentialFile = origSync
})
errSyncBoom := errors.New("injected sync failure")
var syncedFile *os.File
syncTempCredentialFile = func(tmpFile *os.File) error {
syncedFile = tmpFile
return errSyncBoom
}
errWrite := WriteJSONFileAtomic(authFilePath, map[string]any{
"refresh_token": "rotated-refresh",
})
if !errors.Is(errWrite, errSyncBoom) {
t.Fatalf("WriteJSONFileAtomic() error = %v, want wrapped %v", errWrite, errSyncBoom)
}
if syncedFile == nil {
t.Fatal("expected sync hook to receive temp file handle")
}
if errCloseAgain := syncedFile.Close(); !errors.Is(errCloseAgain, os.ErrClosed) {
t.Fatalf("temp file handle was not closed after sync failure: second Close() error = %v", errCloseAgain)
}
preservedRaw, errRead := os.ReadFile(authFilePath)
if errRead != nil {
t.Fatalf("os.ReadFile() error = %v", errRead)
}
if string(preservedRaw) != string(initialRaw) {
t.Fatalf("existing credential file modified on sync failure: got %s, want %s", preservedRaw, initialRaw)
}
entries, errEntries := os.ReadDir(tempDir)
if errEntries != nil {
t.Fatalf("os.ReadDir() error = %v", errEntries)
}
if len(entries) != 1 || entries[0].Name() != "codex-auth.json" {
t.Fatalf("temp file not cleaned up after sync failure; dir entries: %v", entries)
}
}