Skip to content

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

Python

fix: address review findings — .default_file no longer chmods to 0o666, mode carry-forward, mcp_oauth + keys_cli atomic, real-writer tests

Rach Pradhan4c22bba053f0
diff --git a/src/credential_store.zig b/src/credential_store.zig
index f55804c8..b6186a9e 100644
--- a/src/credential_store.zig
+++ b/src/credential_store.zig
@@ -7,7 +7,11 @@
//! 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.
+//!
+//! The guarantee is against a crashed process, not against power loss: the temp
+//! file is fsynced but the containing directory is not, so some filesystems can
+//! still lose the rename across a hard power cut. Same shape — and same limit —
+//! as learn_store.writeAtomicReplace / eval_memory.writeNotes.
const std = @import("std");
const builtin = @import("builtin");
@@ -22,12 +26,29 @@ pub const private_dir: Io.File.Permissions = if (Io.File.Permissions.has_executa
/// 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.
+///
+/// `permissions` is the mode for a file that does not exist yet. Pass
+/// `private_file` for anything holding a secret; pass `.default_file` to keep
+/// the ordinary umask-governed behaviour of a plain `createFile`.
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 {};
+ if (Io.File.Permissions.has_executable_bit) {
+ if (permissions != .default_file) {
+ // An explicit mode is a requirement, not a hint: the create mode is
+ // masked by umask and chmod is not, so re-apply it and an unusual
+ // umask cannot widen the file out from under a caller asking for
+ // 0600. NEVER do this for .default_file — that constant is 0o666,
+ // and chmodding to it publishes a world-writable credential file.
+ atomic.file.setPermissions(io, permissions) catch {};
+ } else if (dir.statFile(io, sub_path, .{})) |existing| {
+ // Rename-into-place discards the old inode, so without this a mode
+ // the user set by hand (`chmod 600 ~/.codex/auth.json`) would be
+ // silently re-widened on every save. Nothing to carry for a new
+ // file, and then umask governs exactly as createFile did.
+ atomic.file.setPermissions(io, Io.File.Permissions.fromMode(existing.permissions.toMode() & 0o7777)) catch {};
+ } else |_| {}
+ }
try atomic.file.writeStreamingAll(io, bytes);
try atomic.file.sync(io);
try atomic.replace(io);
@@ -99,7 +120,32 @@ test "replaceFile: renames a whole new file into place, never truncating the tar
try std.testing.expectEqual(@as(usize, 1), try entryCount(io, tmp.dir));
}
-test "writeOAuth: the credential file is 0600 inside 0700 directories (#xai parity)" {
+test "replaceFile: .default_file keeps umask in charge and never widens an existing mode" {
+ if (builtin.os.tag == .windows) return;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{ .iterate = true });
+ defer tmp.cleanup();
+
+ // A NEW file must land on exactly the mode the plain `createFile` these call
+ // sites used to do produces: 0o666 masked by the process umask. Chmodding to
+ // the requested `.default_file` instead would publish 0o666 — world-WRITABLE
+ // ~/.codex/auth.json and ~/.simple-harness-codegraff.json.
+ (try tmp.dir.createFile(io, "reference", .{})).close(io);
+ const reference_mode = (try tmp.dir.statFile(io, "reference", .{})).permissions.toMode() & 0o777;
+ try replaceFile(io, tmp.dir, "settings.json", "{}", .default_file);
+ // (Comparing against a live reference rather than a hard 0o644 keeps this
+ // umask-agnostic; the umask-independent guard is the second half below.)
+ try std.testing.expectEqual(reference_mode, (try tmp.dir.statFile(io, "settings.json", .{})).permissions.toMode() & 0o777);
+
+ // An EXISTING file's mode survives the rewrite. Rename-into-place discards
+ // the old inode, so a user's manual `chmod 600` has to be carried forward by
+ // hand or every save silently re-widens the file.
+ try tmp.dir.setFilePermissions(io, "settings.json", private_file, .{});
+ try replaceFile(io, tmp.dir, "settings.json", "{\"fallback_providers\":[]}", .default_file);
+ try std.testing.expectEqual(@as(std.posix.mode_t, 0o600), (try tmp.dir.statFile(io, "settings.json", .{})).permissions.toMode() & 0o777);
+}
+
+test "writeOAuth: the credential file is 0600 inside 0700 directories" {
if (builtin.os.tag == .windows) return;
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{ .iterate = true });
diff --git a/src/keys_cli.zig b/src/keys_cli.zig
index 54f7dcff..30eca996 100644
--- a/src/keys_cli.zig
+++ b/src/keys_cli.zig
@@ -18,6 +18,7 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
+const credential_store = @import("credential_store.zig");
const main_mod = @import("main.zig");
const provider_mod = @import("provider.zig");
const provider_specs = provider_mod.provider_specs;
@@ -121,12 +122,11 @@ pub fn storeKey(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, prov
var aw: Io.Writer.Allocating = .init(arena);
var s: std.json.Stringify = .{ .writer = &aw.writer };
s.write(Value{ .object = obj }) catch return false;
- const f = Io.Dir.cwd().createFile(io, path, .{}) catch return false;
- defer f.close(io);
- var wbuf: [4096]u8 = undefined;
- var fw = f.writer(io, &wbuf);
- fw.interface.writeAll(aw.writer.buffered()) catch return false;
- fw.interface.flush() catch return false;
+ // Atomic + 0600: this is a read-modify-write of EVERY provider's key, so a
+ // truncate-in-place that dies mid-write does not lose one key, it loses all
+ // of them at once. 0600 also makes the "0600 JSON file" above true: the old
+ // createFile took the umask default, i.e. world-readable API keys.
+ credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), credential_store.private_file) catch return false;
return true;
}
diff --git a/src/mcp_oauth.zig b/src/mcp_oauth.zig
index cda0d787..75f85e4e 100644
--- a/src/mcp_oauth.zig
+++ b/src/mcp_oauth.zig
@@ -5,6 +5,7 @@ const std = @import("std");
const builtin = @import("builtin");
const util = @import("util.zig");
const discovery = @import("mcp_oauth_discovery.zig");
+const credential_store = @import("credential_store.zig");
const Io = std.Io;
const Allocator = std.mem.Allocator;
@@ -369,14 +370,10 @@ fn writeCredentials(io: Io, arena: Allocator, home: []const u8, resource_url: []
var stringify: std.json.Stringify = .{ .writer = &aw.writer };
try stringify.write(Value{ .object = obj });
const user_only: Io.Dir.Permissions = @enumFromInt(0o600);
- {
- const file = try Io.Dir.cwd().createFile(io, path, .{ .permissions = user_only });
- defer file.close(io);
- var buffer: [4096]u8 = undefined;
- var fw = file.writer(io, &buffer);
- try fw.interface.writeAll(aw.writer.buffered());
- try fw.interface.flush();
- }
+ // Atomic: this file is the only copy of the client_secret + refresh token,
+ // so a truncate-in-place that dies mid-write logs the user out of the MCP
+ // server with nothing left to recover from.
+ try credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), user_only);
if (builtin.os.tag == .windows)
try secureWindowsCredentials(io, dir, path)
else
@@ -542,6 +539,37 @@ test "supported scopes are joined for authorization requests" {
try std.testing.expectEqualStrings("openid docs:read offline_access", try supportedScopes(arena, metadata));
}
+test "writeCredentials: 0600, and a rewrite cannot truncate the live token file" {
+ 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});
+ const resource = "https://mcp.example/api";
+ const endpoints: EndpointSet = .{ .issuer = "https://idp.example", .authorization = "https://idp.example/a", .token = "https://idp.example/t", .registration = "https://idp.example/r" };
+
+ try writeCredentials(io, arena, home, resource, endpoints, .{ .id = "c1", .secret = "s1" }, .{ .access = "a1", .refresh = "refresh-1", .expires_at_ms = 1 });
+ const path = try credentialPath(arena, home, resource);
+ try std.testing.expectEqual(@as(std.posix.mode_t, 0o600), (try Io.Dir.cwd().statFile(io, path, .{})).permissions.toMode() & 0o777);
+
+ // Hold the first inode open across a re-login. A truncate-in-place writer
+ // blanks it out from under this handle; only a rename leaves it whole, which
+ // is what keeps a crashed rewrite from eating the client_secret + refresh.
+ const first = try Io.Dir.cwd().openFile(io, path, .{});
+ defer first.close(io);
+ try writeCredentials(io, arena, home, resource, endpoints, .{ .id = "c2", .secret = "s2" }, .{ .access = "a2", .refresh = "refresh-2", .expires_at_ms = 2 });
+
+ var read_buffer: [512]u8 = undefined;
+ var reader = first.reader(io, &read_buffer);
+ const kept = try reader.interface.allocRemaining(arena, .limited(64 * 1024));
+ try std.testing.expect(std.mem.indexOf(u8, kept, "refresh-1") != null);
+ const current = try Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 * 1024));
+ try std.testing.expect(std.mem.indexOf(u8, current, "refresh-2") != null);
+}
+
test "credential path is stable and resource-specific" {
const path = try credentialPath(std.testing.allocator, "/home/alice", "https://mcp.example/api");
defer std.testing.allocator.free(path);
diff --git a/src/oauth.zig b/src/oauth.zig
index 3ee2afdf..06cab2ad 100644
--- a/src/oauth.zig
+++ b/src/oauth.zig
@@ -8,6 +8,7 @@
//! codegraff gateway base) back-imported from main.
const std = @import("std");
+const builtin = @import("builtin");
const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
@@ -549,3 +550,35 @@ test "supersededToken (#245): a concurrent refresher's token is adopted, not re-
try std.testing.expect(!supersededToken(true, replaced, null));
try std.testing.expect(!supersededToken(false, replaced, null));
}
+
+test "writeKimiAuth/writeXaiAuth: both real writers store 0600 in 0700 dirs, loadable" {
+ 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});
+ const far_future = 4102444800; // year 2100: the loaders must not try to refresh
+
+ // Drive the two production writers, not a shared helper: xAI used to open its
+ // token file with a bare createFile (0644, no 0700 dirs) while kimi hardened
+ // its own, and only pinning both functions keeps that from coming back.
+ try writeKimiAuth(io, arena, home, "kimi-access", "kimi-refresh", far_future);
+ try writeXaiAuth(io, arena, home, "xai-access", "xai-refresh", far_future);
+
+ for ([_][]const u8{ ".kimi", ".xai" }) |provider_dir| {
+ const base = try tmp.dir.openDir(io, provider_dir, .{});
+ defer base.close(io);
+ const credentials = try base.openDir(io, "credentials", .{});
+ defer credentials.close(io);
+ try std.testing.expectEqual(@as(std.posix.mode_t, 0o700), (try base.stat(io)).permissions.toMode() & 0o777);
+ try std.testing.expectEqual(@as(std.posix.mode_t, 0o700), (try credentials.stat(io)).permissions.toMode() & 0o777);
+ try std.testing.expectEqual(@as(std.posix.mode_t, 0o600), (try credentials.statFile(io, "graff-oauth.json", .{})).permissions.toMode() & 0o777);
+ }
+
+ // …and the real loaders find what the real writers wrote, at their own paths.
+ try std.testing.expectEqualStrings("kimi-access", loadKimiOAuth(io, std.testing.allocator, arena, home, false, null).?);
+ try std.testing.expectEqualStrings("xai-access", loadXaiOAuth(io, std.testing.allocator, arena, home, false, null).?);
+}
diff --git a/src/oauth_codegraff.zig b/src/oauth_codegraff.zig
index 7e68ba44..c8f78e49 100644
--- a/src/oauth_codegraff.zig
+++ b/src/oauth_codegraff.zig
@@ -93,7 +93,9 @@ 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 });
- try credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), .default_file);
+ // 0600: the file is a bearer cg_sk_ API key, same posture as the kimi/xai
+ // credential stores.
+ try credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), credential_store.private_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 9a0d215d..a6f2b492 100644
--- a/src/oauth_helpers.zig
+++ b/src/oauth_helpers.zig
@@ -46,7 +46,10 @@ 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 });
- try credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), .default_file);
+ // 0600: this holds the id/access/refresh triple. ~/.codex/auth.json is
+ // co-owned with the openai/codex CLI, which writes it 0600 itself, so the
+ // tighter mode is what the other writer already expects.
+ try credential_store.replaceFile(io, Io.Dir.cwd(), path, aw.writer.buffered(), credential_store.private_file);
}
/// The page the Codex OAuth callback tab lands on after a successful login.