graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(credentials): write atomically through symlinks (#685)
yxlyx72e9a008f788
diff --git a/src/credential_store.zig b/src/credential_store.zigindex 7a73e44b..a9c5d03b 100644--- a/src/credential_store.zig+++ b/src/credential_store.zig@@ -23,15 +23,79 @@ const Allocator = std.mem.Allocator;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;+const max_symlink_hops = 40;++fn windowsRootedTarget(allocator: Allocator, parent_absolute: []const u8, target: []const u8) ![]u8 {+ const parent = std.fs.path.parsePathWindows(u8, parent_absolute);+ const root = switch (parent.kind) {+ .drive_absolute, .unc_absolute => parent.root,+ else => return error.BadPathName,+ };+ const target_root = std.fs.path.parsePathWindows(u8, target).root;+ const tail = target[target_root.len..];+ const separator = if (root.len > 0 and root[root.len - 1] != '\\' and root[root.len - 1] != '/' and tail.len > 0) "\\" else "";+ return std.fmt.allocPrint(allocator, "{s}{s}{s}", .{ root, separator, tail });+}++/// Return the path an ordinary write through `sub_path` would reach. Atomic+/// rename does not follow the final symlink, so resolve only that link (and any+/// chain it names) before staging the replacement. Relative link targets are+/// relative to the link's directory, not to `dir` or the process cwd.+fn writeDestination(io: Io, dir: Io.Dir, sub_path: []const u8, allocator: Allocator) ![]const u8 {+ var current = sub_path;+ var hops: usize = 0;+ var target_buf: [std.fs.max_path_bytes]u8 = undefined;+ while (true) {+ const target_len = dir.readLink(io, current, &target_buf) catch |err| switch (err) {+ error.NotLink, error.FileNotFound => return current,+ else => return err,+ };+ if (hops == max_symlink_hops) return error.SymLinkLoop;+ hops += 1;+ const target = target_buf[0..target_len];+ if (builtin.os.tag == .windows) switch (std.fs.path.parsePathWindows(u8, target).kind) {+ .rooted => {+ // `\foo` is rooted on the link's volume, not the process CWD's+ // volume. Turn it into an unambiguous drive/UNC path first.+ const parent = std.fs.path.dirname(current) orelse ".";+ var parent_buf: [std.fs.max_path_bytes]u8 = undefined;+ const parent_len = try dir.realPathFile(io, parent, &parent_buf);+ current = try windowsRootedTarget(allocator, parent_buf[0..parent_len], target);+ continue;+ },+ .drive_relative => {+ // `C:foo` is relative to drive C's working directory, never to+ // the link's parent. Native Windows link creation normally+ // expands this form to absolute, but preserve it if encountered.+ current = try allocator.dupe(u8, target);+ continue;+ },+ else => {},+ };+ current = if (std.fs.path.isAbsolute(target))+ try allocator.dupe(u8, target)+ else if (std.fs.path.dirname(current)) |parent|+ // Deliberately do not normalize `..`: if `parent` is itself a+ // symlink, the kernel must traverse it before interpreting `..`.+ try std.fs.path.join(allocator, &.{ parent, target })+ else+ try allocator.dupe(u8, target);+ }+}+/// 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.+/// own directory, so the rename never crosses a filesystem. If `sub_path` is a+/// symlink, preserve it and atomically replace its referent instead.////// `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 });+ var path_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);+ defer path_arena.deinit();+ const dest = try writeDestination(io, dir, sub_path, path_arena.allocator());+ var atomic = try dir.createFileAtomic(io, dest, .{ .permissions = permissions, .replace = true });defer atomic.deinit(io);if (Io.File.Permissions.has_executable_bit) {if (permissions != .default_file) {@@ -41,7 +105,7 @@ pub fn replaceFile(io: Io, dir: Io.Dir, sub_path: []const u8, bytes: []const u8,// 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| {+ } else if (dir.statFile(io, dest, .{})) |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@@ -168,6 +232,131 @@ test "replaceFile: .default_file keeps umask in charge and never widens an existtry std.testing.expectEqual(@as(std.posix.mode_t, 0o600), (try tmp.dir.statFile(io, "settings.json", .{})).permissions.toMode() & 0o777);}+test "#405: Windows rooted targets retain the link parent volume" {+ const gpa = std.testing.allocator;+ const drive = try windowsRootedTarget(gpa, "C:\\users\\me", "\\vault\\auth.json");+ defer gpa.free(drive);+ try std.testing.expectEqualStrings("C:\\vault\\auth.json", drive);+ const unc = try windowsRootedTarget(gpa, "\\\\server\\share\\users\\me", "\\vault\\auth.json");+ defer gpa.free(unc);+ try std.testing.expectEqualStrings("\\\\server\\share\\vault\\auth.json", unc);+ try std.testing.expectError(error.BadPathName, windowsRootedTarget(gpa, "relative\\parent", "\\vault\\auth.json"));+}++fn expectLinkTarget(io: Io, dir: Io.Dir, path: []const u8, expected: []const u8) !void {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = try dir.readLink(io, path, &buf);+ try std.testing.expectEqualStrings(expected, buf[0..n]);+}++test "#405: replaceFile preserves a relative symlink and atomically replaces its 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.createDir(io, "nested", .default_dir);+ try tmp.dir.writeFile(io, .{ .sub_path = "nested/real.json", .data = "old" });+ try tmp.dir.setFilePermissions(io, "nested/real.json", private_file, .{});+ try tmp.dir.symLink(io, "real.json", "nested/settings.json", .{});++ // Holding the referent's original inode proves the through-link write is+ // still a rename, not a truncate hidden behind correct final contents.+ const original = try tmp.dir.openFile(io, "nested/real.json", .{});+ defer original.close(io);+ try replaceFile(io, tmp.dir, "nested/settings.json", "new", .default_file);++ try expectLinkTarget(io, tmp.dir, "nested/settings.json", "real.json");+ const after = try tmp.dir.readFileAlloc(io, "nested/settings.json", gpa, .limited(64));+ defer gpa.free(after);+ try std.testing.expectEqualStrings("new", after);+ var read_buf: [16]u8 = undefined;+ var reader = original.reader(io, &read_buf);+ const before = try reader.interface.allocRemaining(gpa, .limited(64));+ defer gpa.free(before);+ try std.testing.expectEqualStrings("old", before);+ try std.testing.expectEqual(@as(u32, 0o600), (try tmp.dir.statFile(io, "nested/real.json", .{})).permissions.toMode() & 0o777);+ const nested = try tmp.dir.openDir(io, "nested", .{ .iterate = true });+ defer nested.close(io);+ try std.testing.expectEqual(@as(usize, 2), try entryCount(io, nested));+}++test "#405: replaceFile follows absolute and relative symlink chains" {+ 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;+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];+ const absolute_middle = try std.fmt.allocPrint(gpa, "{s}/middle", .{base});+ defer gpa.free(absolute_middle);+ try tmp.dir.writeFile(io, .{ .sub_path = "real.json", .data = "old" });+ try tmp.dir.symLink(io, "real.json", "middle", .{});+ try tmp.dir.symLink(io, absolute_middle, "settings.json", .{});++ try replaceFile(io, tmp.dir, "settings.json", "new", private_file);++ try expectLinkTarget(io, tmp.dir, "settings.json", absolute_middle);+ try expectLinkTarget(io, tmp.dir, "middle", "real.json");+ const after = try tmp.dir.readFileAlloc(io, "real.json", gpa, .limited(64));+ defer gpa.free(after);+ try std.testing.expectEqualStrings("new", after);+}++test "#405: replaceFile preserves a dangling symlink and creates its 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.createDir(io, "nested", .default_dir);+ try tmp.dir.symLink(io, "created.json", "nested/settings.json", .{});++ try replaceFile(io, tmp.dir, "nested/settings.json", "created", private_file);++ try expectLinkTarget(io, tmp.dir, "nested/settings.json", "created.json");+ const after = try tmp.dir.readFileAlloc(io, "nested/created.json", gpa, .limited(64));+ defer gpa.free(after);+ try std.testing.expectEqualStrings("created", after);+}++test "#405: relative dot-dot keeps symlinked parent traversal semantics" {+ 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.createDir(io, "real", .default_dir);+ try tmp.dir.createDir(io, "real/nested", .default_dir);+ try tmp.dir.writeFile(io, .{ .sub_path = "real/target.json", .data = "old" });+ try tmp.dir.symLink(io, "real/nested", "alias", .{});+ try tmp.dir.symLink(io, "../target.json", "real/nested/settings.json", .{});++ try replaceFile(io, tmp.dir, "alias/settings.json", "new", private_file);++ try expectLinkTarget(io, tmp.dir, "real/nested/settings.json", "../target.json");+ const after = try tmp.dir.readFileAlloc(io, "real/target.json", gpa, .limited(64));+ defer gpa.free(after);+ try std.testing.expectEqualStrings("new", after);+ try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "target.json", .{}));+}++test "#405: replaceFile rejects a symlink cycle without replacing either link" {+ if (builtin.os.tag == .windows) return;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ try tmp.dir.symLink(io, "second", "first", .{});+ try tmp.dir.symLink(io, "first", "second", .{});++ try std.testing.expectError(error.SymLinkLoop, replaceFile(io, tmp.dir, "first", "new", private_file));++ try expectLinkTarget(io, tmp.dir, "first", "second");+ try expectLinkTarget(io, tmp.dir, "second", "first");+ try std.testing.expectEqual(@as(usize, 2), try entryCount(io, tmp.dir));+}+test "writeOAuth: the credential file is 0600 inside 0700 directories" {if (builtin.os.tag == .windows) return;const io = std.testing.io;