Skip to content

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

Python

Refresh synced rotating logins under the vault lease

justrach9ba9207e813a
diff --git a/src/additional_tests.zig b/src/additional_tests.zig
index 102208bf..3a38e4da 100644
--- a/src/additional_tests.zig
+++ b/src/additional_tests.zig
@@ -14,6 +14,7 @@ test {
_ = @import("vault_client.zig");
_ = @import("vault_sync.zig");
_ = @import("keys_vault_cli.zig");
+ _ = @import("vault_refresh.zig");
_ = @import("peer_cli.zig");
}
diff --git a/src/vault_refresh.zig b/src/vault_refresh.zig
new file mode 100644
index 00000000..cb9b6be3
--- /dev/null
+++ b/src/vault_refresh.zig
@@ -0,0 +1,108 @@
+//! Refreshing a synced rotating login without racing other devices
+//! (harness ADR 0005 decision 7). A single-use refresh token may have only
+//! one refresher, so a device that wants to refresh first checks the vault:
+//! a newer version is adopted instead; otherwise it takes the 60 s lease,
+//! refreshes, writes the next version, and releases. When the provider
+//! rejects the refresh token, the vault is pulled before giving up.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const sync = @import("vault_sync.zig");
+const credential_store = @import("credential_store.zig");
+
+const versions_file = ".graff/vault-versions.json";
+
+pub const Plan = union(enum) {
+ /// The vault had a newer login; it is now in the local file. Use it.
+ adopted: u64,
+ /// This device holds the lease. Refresh, then call `commit`.
+ refresh: u64,
+ /// Another device is refreshing. Use the current token; try again later.
+ wait,
+};
+
+/// Which vault version each local credential file was last synced from.
+pub const Versions = struct {
+ io: Io,
+ arena: Allocator,
+ path: []const u8,
+
+ pub fn at(io: Io, arena: Allocator, home: []const u8) !Versions {
+ return .{ .io = io, .arena = arena, .path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ home, versions_file }) };
+ }
+
+ pub fn get(v: Versions, slot: []const u8) u64 {
+ const data = Io.Dir.cwd().readFileAlloc(v.io, v.path, v.arena, .limited(64 * 1024)) catch return 0;
+ const parsed = std.json.parseFromSliceLeaky(std.json.Value, v.arena, data, .{}) catch return 0;
+ if (parsed != .object) return 0;
+ const n = parsed.object.get(slot) orelse return 0;
+ return if (n == .integer and n.integer > 0) @intCast(n.integer) else 0;
+ }
+
+ pub fn set(v: Versions, slot: []const u8, version: u64) !void {
+ var obj: std.json.ObjectMap = .empty;
+ if (Io.Dir.cwd().readFileAlloc(v.io, v.path, v.arena, .limited(64 * 1024))) |data| {
+ if (std.json.parseFromSliceLeaky(std.json.Value, v.arena, data, .{})) |p| {
+ if (p == .object) obj = p.object;
+ } else |_| {}
+ } else |_| {}
+ try obj.put(v.arena, slot, .{ .integer = @intCast(version) });
+ var aw: Io.Writer.Allocating = .init(v.arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.write(std.json.Value{ .object = obj });
+ if (std.fs.path.dirname(v.path)) |dir| Io.Dir.cwd().createDirPath(v.io, dir) catch {};
+ try credential_store.replaceFile(v.io, Io.Dir.cwd(), v.path, aw.writer.buffered(), credential_store.private_file);
+ }
+};
+
+fn adopt(s: *sync.Session, versions: Versions, slot: []const u8, file: []const u8) !?u64 {
+ const got = (try s.pull("graff", slot)) orelse return null;
+ try credential_store.replaceFile(s.io, Io.Dir.cwd(), file, got.bytes, credential_store.private_file);
+ try versions.set(slot, got.version);
+ return got.version;
+}
+
+pub fn plan(s: *sync.Session, versions: Versions, slot: []const u8, file: []const u8) !Plan {
+ const local = versions.get(slot);
+ const current: u64 = if (try s.c.getItem("graff", slot)) |it| it.version else 0;
+ if (current > local) {
+ if (try adopt(s, versions, slot, file)) |v| return .{ .adopted = v };
+ }
+ if (!try s.c.lease("graff", slot, 60)) return .wait;
+ return .{ .refresh = current };
+}
+
+/// After a refresh under the lease: write the new login as the next version.
+/// If the vault moved anyway, the vault wins and the local result is
+/// discarded (its refresh token was already spent elsewhere).
+pub fn commit(s: *sync.Session, versions: Versions, slot: []const u8, file: []const u8, base: u64) !u64 {
+ defer s.c.release("graff", slot) catch {};
+ const bytes = try Io.Dir.cwd().readFileAlloc(s.io, file, s.arena, .limited(1 << 20));
+ switch (try s.putAt("graff", slot, "rotating", base, bytes)) {
+ .ok => |v| {
+ try versions.set(slot, v);
+ return v;
+ },
+ .conflict, .lease_held => return (try adopt(s, versions, slot, file)) orelse error.Conflict,
+ }
+}
+
+pub const Rejected = union(enum) { adopted: u64, needs_signin };
+
+/// The provider rejected the refresh token (invalid_grant, 401/403 on
+/// refresh). Another device may already hold a newer one; otherwise every
+/// device should show "sign in again".
+pub fn rejected(s: *sync.Session, versions: Versions, slot: []const u8, file: []const u8) !Rejected {
+ const local = versions.get(slot);
+ const item = (try s.c.getItem("graff", slot)) orelse return .needs_signin;
+ if (item.version > local) {
+ if (try adopt(s, versions, slot, file)) |v| return .{ .adopted = v };
+ }
+ s.c.setStatus("graff", slot, "needs_signin", item.version) catch {};
+ return .needs_signin;
+}
+
+test {
+ _ = @import("vault_refresh_tests.zig");
+}
diff --git a/src/vault_refresh_tests.zig b/src/vault_refresh_tests.zig
new file mode 100644
index 00000000..329485c1
--- /dev/null
+++ b/src/vault_refresh_tests.zig
@@ -0,0 +1,102 @@
+//! Refresh under lease across two devices against the in-memory edge.
+
+const std = @import("std");
+const testing = std.testing;
+const Io = std.Io;
+const crypto = @import("vault_crypto.zig");
+const client = @import("vault_client.zig");
+const sync = @import("vault_sync.zig");
+const refresh = @import("vault_refresh.zig");
+const MockEdge = @import("vault_mock_edge.zig").MockEdge;
+
+const Dev = struct {
+ c: client.Client,
+ s: sync.Session,
+ home: []const u8,
+ file: []const u8,
+ versions: refresh.Versions,
+
+ fn init(d: *Dev, arena: std.mem.Allocator, edge: *MockEdge, id: []const u8, home: []const u8) !void {
+ d.c = .{ .io = testing.io, .arena = arena, .transport = edge.transport(), .bearer = "user-7", .device_id = id, .keys = crypto.DeviceKeys.generate(testing.io), .now_ms = 1 };
+ d.s = try sync.Session.open(testing.io, arena, &d.c);
+ d.home = home;
+ d.file = try std.fmt.allocPrint(arena, "{s}/xai.json", .{home});
+ d.versions = try refresh.Versions.at(testing.io, arena, home);
+ }
+
+ fn write(d: *Dev, bytes: []const u8) !void {
+ try Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = d.file, .data = bytes });
+ }
+
+ fn read(d: *Dev, arena: std.mem.Allocator) ![]const u8 {
+ return Io.Dir.cwd().readFileAlloc(testing.io, d.file, arena, .limited(4096));
+ }
+};
+
+fn tmpPath(arena: std.mem.Allocator, tmp: *testing.TmpDir, sub: []const u8) ![]const u8 {
+ try tmp.dir.createDirPath(testing.io, sub);
+ return std.fmt.allocPrint(arena, ".zig-cache/tmp/{s}/{s}", .{ tmp.sub_path, sub });
+}
+
+test "one refresher at a time: the other device adopts the committed version instead of refreshing" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var edge = MockEdge.init(testing.allocator);
+ defer edge.deinit();
+ var a: Dev = undefined;
+ try a.init(arena, &edge, "dev-a", try tmpPath(arena, &tmp, "a"));
+ var b: Dev = undefined;
+ try b.init(arena, &edge, "dev-b", try tmpPath(arena, &tmp, "b"));
+ _ = try a.s.enable("laptop");
+ _ = try b.s.enable("vps");
+ try a.s.approve("dev-b");
+ try a.write("token-v1");
+ const v1 = try a.s.push("graff", "xai", "rotating", "token-v1");
+ try a.versions.set("xai", v1);
+
+ // Both devices hit expiry. A plans first and gets the lease.
+ const pa = try refresh.plan(&a.s, a.versions, "xai", a.file);
+ try testing.expect(pa == .refresh);
+ // B has never synced: it adopts v1 rather than refreshing blind…
+ const pb = try refresh.plan(&b.s, b.versions, "xai", b.file);
+ try testing.expectEqual(refresh.Plan{ .adopted = v1 }, pb);
+ // …and once caught up, it must wait while A holds the lease.
+ try testing.expect((try refresh.plan(&b.s, b.versions, "xai", b.file)) == .wait);
+
+ // A refreshes and commits the rotated token.
+ try a.write("token-v2");
+ const v2 = try refresh.commit(&a.s, a.versions, "xai", a.file, pa.refresh);
+ try testing.expectEqual(v1 + 1, v2);
+ // B's next plan adopts v2 without ever spending the refresh token.
+ try testing.expectEqual(refresh.Plan{ .adopted = v2 }, try refresh.plan(&b.s, b.versions, "xai", b.file));
+ try testing.expectEqualStrings("token-v2", try b.read(arena));
+}
+
+test "a rejected refresh adopts a newer vault login, else marks needs_signin" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var edge = MockEdge.init(testing.allocator);
+ defer edge.deinit();
+ var a: Dev = undefined;
+ try a.init(arena, &edge, "dev-a", try tmpPath(arena, &tmp, "a"));
+ var b: Dev = undefined;
+ try b.init(arena, &edge, "dev-b", try tmpPath(arena, &tmp, "b"));
+ _ = try a.s.enable("laptop");
+ _ = try b.s.enable("vps");
+ try a.s.approve("dev-b");
+ try b.write("stale");
+ _ = try a.s.push("graff", "xai", "rotating", "fresh-from-a");
+ // B's refresh token was spent by A: invalid_grant → B adopts A's version.
+ const r1 = try refresh.rejected(&b.s, b.versions, "xai", b.file);
+ try testing.expect(r1 == .adopted);
+ try testing.expectEqualStrings("fresh-from-a", try b.read(arena));
+ // Nothing newer anywhere: every device should ask the person to sign in.
+ try testing.expect((try refresh.rejected(&b.s, b.versions, "xai", b.file)) == .needs_signin);
+ try testing.expectEqualStrings("needs_signin", (try a.c.getItem("graff", "xai")).?.status);
+}