Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(oauth): write credentials atomically and lock down the xAI token file

Rach Pradhana862b46aa30f
diff --git a/src/credential_store.zig b/src/credential_store.zig
new file mode 100644
index 00000000..f55804c8
--- /dev/null
+++ b/src/credential_store.zig
@@ -0,0 +1,130 @@
+//! Atomic, owner-only writes for credential and cache files.
+//!
+//! Truncate-in-place (createFile + write) leaves a half-written file behind
+//! when the process dies, the disk fills, or a second graff writes the same
+//! path. For an OAuth credential that is fatal: the file holds the only copy of
+//! the refresh token, so a truncated write reads back as "not logged in" — a
+//! silent logout with nothing left to recover from. Write a per-writer-unique
+//! temp file in the target's own directory, fsync it, then rename over the
+//! target, so a reader sees either the whole old file or the whole new one.
+//! Same shape as learn_store.writeAtomicReplace / eval_memory.writeNotes.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+/// 0600 / 0700 on platforms that have permission bits at all.
+pub const private_file: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o600) else .default_file;
+pub const private_dir: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o700) else .default_dir;
+
+/// Replace `dir`/`sub_path` with `bytes` atomically. `sub_path` may carry
+/// directory components; createFileAtomic keeps the temp file in the target's
+/// own directory, so the rename never crosses a filesystem.
+pub fn replaceFile(io: Io, dir: Io.Dir, sub_path: []const u8, bytes: []const u8, permissions: Io.File.Permissions) !void {
+ var atomic = try dir.createFileAtomic(io, sub_path, .{ .permissions = permissions, .replace = true });
+ defer atomic.deinit(io);
+ // The create mode is masked by umask; chmod is not, so an unusual umask
+ // cannot narrow the file out from under the caller that asked for 0600.
+ if (builtin.os.tag != .windows) atomic.file.setPermissions(io, permissions) catch {};
+ try atomic.file.writeStreamingAll(io, bytes);
+ try atomic.file.sync(io);
+ try atomic.replace(io);
+}
+
+/// `<home>/<provider_dir>/credentials/graff-oauth.json` — where the kimi and
+/// xai device-code logins keep their access/refresh pair.
+pub fn oauthPath(arena: Allocator, home: []const u8, provider_dir: []const u8) []const u8 {
+ return std.fmt.allocPrint(arena, "{s}/{s}/credentials/graff-oauth.json", .{ home, provider_dir }) catch "";
+}
+
+/// Store an access/refresh/expiry triple at `oauthPath`, 0600 inside 0700 dirs.
+pub fn writeOAuth(io: Io, arena: Allocator, home: []const u8, provider_dir: []const u8, access: []const u8, refresh: []const u8, expires_at: i64) !void {
+ // createDir is one level, so make <home>/<provider_dir> then its credentials/.
+ const base = try std.fmt.allocPrint(arena, "{s}/{s}", .{ home, provider_dir });
+ const credentials = try std.fmt.allocPrint(arena, "{s}/credentials", .{base});
+ for ([_][]const u8{ base, credentials }) |path| {
+ Io.Dir.cwd().createDir(io, path, private_dir) catch {};
+ // iterate=true: see kimi_catalog.secureDir — a default openDir can be
+ // O_PATH on Linux, where fchmod panics EBADF instead of erroring.
+ const dir = Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch continue;
+ defer dir.close(io);
+ dir.setPermissions(io, private_dir) catch {};
+ }
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(arena, "access_token", .{ .string = access });
+ try obj.put(arena, "refresh_token", .{ .string = refresh });
+ try obj.put(arena, "expires_at", .{ .integer = expires_at });
+ var aw: Io.Writer.Allocating = .init(arena);
+ var stringify: std.json.Stringify = .{ .writer = &aw.writer };
+ try stringify.write(Value{ .object = obj });
+ try replaceFile(io, Io.Dir.cwd(), oauthPath(arena, home, provider_dir), aw.writer.buffered(), private_file);
+}
+
+fn entryCount(io: Io, dir: Io.Dir) !usize {
+ var it = dir.iterate();
+ var n: usize = 0;
+ while (try it.next(io)) |_| n += 1;
+ return n;
+}
+
+test "replaceFile: renames a whole new file into place, never truncating the target" {
+ if (builtin.os.tag == .windows) return;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{ .iterate = true });
+ defer tmp.cleanup();
+ const gpa = std.testing.allocator;
+ try tmp.dir.writeFile(io, .{ .sub_path = "cred.json", .data = "{\"refresh_token\":\"old\"}" });
+
+ // Hold the ORIGINAL inode open: a truncate-in-place writer changes what this
+ // handle sees, a temp-file+rename writer cannot touch it. That is exactly
+ // the property that keeps a crashed write from eating the refresh token.
+ const original = try tmp.dir.openFile(io, "cred.json", .{});
+ defer original.close(io);
+
+ try replaceFile(io, tmp.dir, "cred.json", "{\"refresh_token\":\"new\"}", private_file);
+
+ var read_buffer: [64]u8 = undefined;
+ var reader = original.reader(io, &read_buffer);
+ const before = try reader.interface.allocRemaining(gpa, .limited(1024));
+ defer gpa.free(before);
+ try std.testing.expectEqualStrings("{\"refresh_token\":\"old\"}", before);
+
+ const after = try tmp.dir.readFileAlloc(io, "cred.json", gpa, .limited(1024));
+ defer gpa.free(after);
+ try std.testing.expectEqualStrings("{\"refresh_token\":\"new\"}", after);
+
+ // The temp file was consumed by the rename, not left in the directory.
+ try std.testing.expectEqual(@as(usize, 1), try entryCount(io, tmp.dir));
+}
+
+test "writeOAuth: the credential file is 0600 inside 0700 directories (#xai parity)" {
+ if (builtin.os.tag == .windows) return;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{ .iterate = true });
+ defer tmp.cleanup();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const home = try std.fmt.allocPrint(arena, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+
+ try writeOAuth(io, arena, home, ".xai", "access-1", "refresh-1", 1234);
+
+ const base = try tmp.dir.openDir(io, ".xai", .{});
+ defer base.close(io);
+ const credentials = try base.openDir(io, "credentials", .{});
+ defer credentials.close(io);
+ try std.testing.expectEqual(@as(u32, 0o700), (try base.stat(io)).permissions.toMode() & 0o777);
+ try std.testing.expectEqual(@as(u32, 0o700), (try credentials.stat(io)).permissions.toMode() & 0o777);
+ const file = try credentials.openFile(io, "graff-oauth.json", .{});
+ defer file.close(io);
+ try std.testing.expectEqual(@as(u32, 0o600), (try file.stat(io)).permissions.toMode() & 0o777);
+
+ // The loader reads back what the writer stored, at the path it advertises.
+ const data = try Io.Dir.cwd().readFileAlloc(io, oauthPath(arena, home, ".xai"), arena, .limited(4096));
+ const parsed = try std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always });
+ try std.testing.expectEqualStrings("access-1", parsed.object.get("access_token").?.string);
+ try std.testing.expectEqualStrings("refresh-1", parsed.object.get("refresh_token").?.string);
+ try std.testing.expectEqual(@as(i64, 1234), parsed.object.get("expires_at").?.integer);
+}
diff --git a/src/fallback_config.zig b/src/fallback_config.zig
index 764fb62d..f39db955 100644
--- a/src/fallback_config.zig
+++ b/src/fallback_config.zig
@@ -7,6 +7,8 @@ const Io = std.Io;
const Allocator = std.mem.Allocator;
const Value = std.json.Value;
+const credential_store = @import("credential_store.zig");
+
const settings_dir = ".harness";
const settings_path = ".harness/settings.json";
const field = "fallback_providers";
@@ -52,13 +54,8 @@ pub fn save(io: Io, gpa: Allocator, providers: []const []const u8) bool {
defer aw.deinit();
var stringify: std.json.Stringify = .{ .writer = &aw.writer, .options = .{ .whitespace = .indent_2 } };
stringify.write(Value{ .object = root }) catch return false;
- const file = Io.Dir.cwd().createFile(io, settings_path, .{}) catch return false;
- defer file.close(io);
- var buf: [4096]u8 = undefined;
- var writer = file.writer(io, &buf);
- writer.interface.writeAll(aw.writer.buffered()) catch return false;
- writer.interface.writeByte('\n') catch return false;
- writer.interface.flush() catch return false;
+ aw.writer.writeByte('\n') catch return false;
+ credential_store.replaceFile(io, Io.Dir.cwd(), settings_path, aw.writer.buffered(), .default_file) catch return false;
return true;
}
diff --git a/src/models_cache.zig b/src/models_cache.zig
index de0a3db7..10fd65b9 100644
--- a/src/models_cache.zig
+++ b/src/models_cache.zig
@@ -17,6 +17,7 @@ const strFieldObj = util.strFieldObj;
const provider = @import("provider.zig"); // g_codex_url_override: keep /models discovery on the same origin as the overridden responses endpoint
const kimi_catalog = @import("kimi_catalog.zig");
const cache_tests = @import("models_cache_tests.zig");
+const credential_store = @import("credential_store.zig");
const models_dev_url = "https://models.dev/api.json";
const codex_models_url = "https://chatgpt.com/backend-api/codex/models";
@@ -262,12 +263,7 @@ fn writeCodexCache(io: Io, arena: Allocator, home: []const u8, version: []const
aw.writer.writeAll("]}\n") catch return;
for ([_][]const u8{ codexDirPath(arena, home), codexFlatPath(arena, home) }) |path| {
if (path.len == 0) continue;
- const f = Io.Dir.cwd().createFile(io, path, .{}) catch continue;
- defer f.close(io);
- var wbuf: [4096]u8 = undefined;
- var fw = f.writer(io, &wbuf);
- fw.interface.writeAll(aw.writer.buffered()) catch continue;
- fw.interface.flush() catch continue;
+ credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), .default_file) catch continue;
return;
}
}
@@ -418,12 +414,7 @@ fn writeCache(io: Io, arena: Allocator, home: []const u8, metas: []const Meta) ?
const bytes = aw.writer.buffered();
for ([_][]const u8{ dirPath(arena, home), flatPath(arena, home) }) |path| {
if (path.len == 0) continue;
- const f = Io.Dir.cwd().createFile(io, path, .{}) catch continue;
- defer f.close(io);
- var wbuf: [4096]u8 = undefined;
- var fw = f.writer(io, &wbuf);
- fw.interface.writeAll(bytes) catch continue;
- fw.interface.flush() catch continue;
+ credential_store.replaceFile(io, Io.Dir.cwd(), path, bytes, .default_file) catch continue;
return path;
}
return null;
diff --git a/src/oauth.zig b/src/oauth.zig
index c19545b9..3ee2afdf 100644
--- a/src/oauth.zig
+++ b/src/oauth.zig
@@ -31,6 +31,7 @@ const unixMs = util.unixMs;
const kimi_catalog = @import("kimi_catalog.zig");
const pricing = @import("pricing.zig");
const codegraff = @import("oauth_codegraff.zig");
+const credential_store = @import("credential_store.zig");
pub const CodexAuth = struct { token: []const u8, account: []const u8 };
@@ -230,38 +231,11 @@ fn kimiOAuthPost(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, url
}
fn kimiAuthPath(arena: Allocator, home: []const u8) []const u8 {
- return std.fmt.allocPrint(arena, "{s}/.kimi/credentials/graff-oauth.json", .{home}) catch "";
+ return credential_store.oauthPath(arena, home, ".kimi");
}
fn writeKimiAuth(io: Io, arena: Allocator, home: []const u8, access: []const u8, refresh: []const u8, expires_at: i64) !void {
- const private_file_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o600) else .default_file;
- const private_dir_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o700) else .default_dir;
- // createDir is one level, so make ~/.kimi then ~/.kimi/credentials.
- const kimi_dir = try std.fmt.allocPrint(arena, "{s}/.kimi", .{home});
- const credentials_dir = try std.fmt.allocPrint(arena, "{s}/.kimi/credentials", .{home});
- Io.Dir.cwd().createDir(io, kimi_dir, private_dir_permissions) catch {};
- Io.Dir.cwd().createDir(io, credentials_dir, private_dir_permissions) catch {};
- for ([_][]const u8{ kimi_dir, credentials_dir }) |path| {
- // iterate=true: see kimi_catalog.secureDir — a default openDir can be
- // O_PATH on Linux, where fchmod panics EBADF instead of erroring.
- const dir = Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch continue;
- defer dir.close(io);
- dir.setPermissions(io, private_dir_permissions) catch {};
- }
- var obj: std.json.ObjectMap = .empty;
- try obj.put(arena, "access_token", .{ .string = access });
- try obj.put(arena, "refresh_token", .{ .string = refresh });
- try obj.put(arena, "expires_at", .{ .integer = expires_at });
- var aw: Io.Writer.Allocating = .init(arena);
- var s: std.json.Stringify = .{ .writer = &aw.writer };
- try s.write(Value{ .object = obj });
- const f = try Io.Dir.cwd().createFile(io, kimiAuthPath(arena, home), .{ .permissions = private_file_permissions });
- defer f.close(io);
- f.setPermissions(io, private_file_permissions) catch {};
- var wbuf: [4096]u8 = undefined;
- var fw = f.writer(io, &wbuf);
- try fw.interface.writeAll(aw.writer.buffered());
- try fw.interface.flush();
+ return credential_store.writeOAuth(io, arena, home, ".kimi", access, refresh, expires_at);
}
/// `graff login kimi`: Kimi Code device-code OAuth. Prints a verification URL +
@@ -428,25 +402,11 @@ fn xaiOAuthPost(io: Io, gpa: Allocator, arena: Allocator, url: []const u8, body:
}
fn xaiAuthPath(arena: Allocator, home: []const u8) []const u8 {
- return std.fmt.allocPrint(arena, "{s}/.xai/credentials/graff-oauth.json", .{home}) catch "";
+ return credential_store.oauthPath(arena, home, ".xai");
}
fn writeXaiAuth(io: Io, arena: Allocator, home: []const u8, access: []const u8, refresh: []const u8, expires_at: i64) !void {
- Io.Dir.cwd().createDir(io, try std.fmt.allocPrint(arena, "{s}/.xai", .{home}), .default_dir) catch {};
- Io.Dir.cwd().createDir(io, try std.fmt.allocPrint(arena, "{s}/.xai/credentials", .{home}), .default_dir) catch {};
- var obj: std.json.ObjectMap = .empty;
- try obj.put(arena, "access_token", .{ .string = access });
- try obj.put(arena, "refresh_token", .{ .string = refresh });
- try obj.put(arena, "expires_at", .{ .integer = expires_at });
- var aw: Io.Writer.Allocating = .init(arena);
- var st: std.json.Stringify = .{ .writer = &aw.writer };
- try st.write(Value{ .object = obj });
- const f = try Io.Dir.cwd().createFile(io, xaiAuthPath(arena, home), .{});
- defer f.close(io);
- var wbuf: [4096]u8 = undefined;
- var fw = f.writer(io, &wbuf);
- try fw.interface.writeAll(aw.writer.buffered());
- try fw.interface.flush();
+ return credential_store.writeOAuth(io, arena, home, ".xai", access, refresh, expires_at);
}
/// `graff login xai`: xAI/Grok device-code OAuth. Prints a verification URL +
diff --git a/src/oauth_codegraff.zig b/src/oauth_codegraff.zig
index e7ad5713..7e68ba44 100644
--- a/src/oauth_codegraff.zig
+++ b/src/oauth_codegraff.zig
@@ -10,6 +10,7 @@ const util = @import("util.zig");
const strFieldObj = util.strFieldObj;
const intFieldObj = util.intFieldObj;
const openBrowser = @import("oauth_helpers.zig").openBrowser;
+const credential_store = @import("credential_store.zig");
const codegraff_device_base = @import("main.zig").codegraff_device_base;
const key_file = ".simple-harness-codegraff.json";
@@ -92,12 +93,7 @@ fn writeKey(io: Io, arena: Allocator, home: []const u8, key: []const u8) !void {
var aw: Io.Writer.Allocating = .init(arena);
var stringify: std.json.Stringify = .{ .writer = &aw.writer };
try stringify.write(Value{ .object = obj });
- const file = try Io.Dir.cwd().createFile(io, path, .{});
- defer file.close(io);
- var wbuf: [4096]u8 = undefined;
- var writer = file.writer(io, &wbuf);
- try writer.interface.writeAll(aw.writer.buffered());
- try writer.interface.flush();
+ try credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), .default_file);
}
/// Load the harness login file first, then graff's credential store.
diff --git a/src/oauth_helpers.zig b/src/oauth_helpers.zig
index 9dad99c8..9a0d215d 100644
--- a/src/oauth_helpers.zig
+++ b/src/oauth_helpers.zig
@@ -7,6 +7,8 @@ const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
+const credential_store = @import("credential_store.zig");
+
pub fn b64url(arena: Allocator, bytes: []const u8) []const u8 {
const enc = std.base64.url_safe_no_pad.Encoder;
const buf = arena.alloc(u8, enc.calcSize(bytes.len)) catch return "";
@@ -44,12 +46,7 @@ pub fn writeCodexAuth(io: Io, arena: Allocator, home: []const u8, id_token: []co
var aw: Io.Writer.Allocating = .init(arena);
var stringify: std.json.Stringify = .{ .writer = &aw.writer };
try stringify.write(Value{ .object = object });
- const file = try Io.Dir.cwd().createFile(io, path, .{});
- defer file.close(io);
- var write_buffer: [4096]u8 = undefined;
- var writer = file.writer(io, &write_buffer);
- try writer.interface.writeAll(aw.writer.buffered());
- try writer.interface.flush();
+ try credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), .default_file);
}
/// The page the Codex OAuth callback tab lands on after a successful login.
diff --git a/src/router_catalog.zig b/src/router_catalog.zig
index 49e89a45..f7444132 100644
--- a/src/router_catalog.zig
+++ b/src/router_catalog.zig
@@ -9,6 +9,7 @@ const Allocator = std.mem.Allocator;
const Value = std.json.Value;
const catalog_selection = @import("catalog_selection.zig");
+const credential_store = @import("credential_store.zig");
const pricing = @import("pricing.zig");
const provider = @import("provider.zig");
const serde = @import("serde.zig");
@@ -160,12 +161,7 @@ fn writeCache(io: Io, arena: Allocator, home: []const u8, spec: provider.Provide
const document = cacheDocument(io, arena, spec, models) orelse return;
for ([_][]const u8{ dirPath(arena, home, spec), flatPath(arena, home, spec) }) |path| {
if (path.len == 0) continue;
- const file = Io.Dir.cwd().createFile(io, path, .{}) catch continue;
- defer file.close(io);
- var buffer: [4096]u8 = undefined;
- var writer = file.writer(io, &buffer);
- writer.interface.writeAll(document) catch continue;
- writer.interface.flush() catch continue;
+ credential_store.replaceFile(io, Io.Dir.cwd(), path, document, .default_file) catch continue;
return;
}
}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 81575dc3..2055f90c 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -111,6 +111,10 @@ const workflow_pipeline = @import("workflow_pipeline.zig");
// is contingent on those call sites staying — pinned here instead.
const shutdown_trace = @import("shutdown_trace.zig");
+// Atomic + owner-only credential writes. Production reaches it only through
+// calls from oauth.zig and the catalog writers, so its own tests need the hook.
+const credential_store = @import("credential_store.zig");
+
test {
_ = learn_holdout;
_ = learn_receipt;
@@ -147,6 +151,7 @@ test {
_ = playbook_glue;
_ = playbook_reflect;
_ = shutdown_trace;
+ _ = credential_store;
_ = escalation;
_ = escalation_tests;
_ = edit_contract;