graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Add the vault edge client and sync operations
justracha3a4e01e1112
diff --git a/src/additional_tests.zig b/src/additional_tests.zigindex ed36fba8..e1611d6f 100644--- a/src/additional_tests.zig+++ b/src/additional_tests.zig@@ -11,6 +11,8 @@ test {_ = @import("agent_responses.zig");_ = @import("session_branch.zig");_ = @import("vault_crypto.zig");+ _ = @import("vault_client.zig");+ _ = @import("vault_sync.zig");_ = @import("peer_cli.zig");}diff --git a/src/vault_client.zig b/src/vault_client.zignew file mode 100644index 00000000..09c1695a--- /dev/null+++ b/src/vault_client.zig@@ -0,0 +1,241 @@+//! HTTP client for the Harness edge vault (contract v1.1). Every request+//! carries the Harness bearer and X-Vault-Device; mutating requests are also+//! signed with the device's Ed25519 key. The transport is an interface so+//! tests run against an in-memory edge.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const crypto = @import("vault_crypto.zig");++pub const default_edge = "https://edge.codegraff.com";++pub const Response = struct { status: u16, body: []const u8 };++pub const Transport = struct {+ ctx: *anyopaque,+ callFn: *const fn (ctx: *anyopaque, arena: Allocator, method: []const u8, path: []const u8, headers: []const std.http.Header, body: []const u8) anyerror!Response,+};++pub const Client = struct {+ io: Io,+ arena: Allocator,+ transport: Transport,+ bearer: []const u8,+ device_id: []const u8,+ keys: crypto.DeviceKeys,+ /// Test hook: fixed clock for signatures.+ now_ms: ?i64 = null,++ fn call(c: *Client, method: []const u8, path: []const u8, body: []const u8, signed: bool, extra: []const std.http.Header) !Response {+ var headers: std.ArrayList(std.http.Header) = .empty;+ try headers.append(c.arena, .{ .name = "Authorization", .value = try std.fmt.allocPrint(c.arena, "Bearer {s}", .{c.bearer}) });+ try headers.append(c.arena, .{ .name = "X-Vault-Device", .value = c.device_id });+ if (body.len > 0) try headers.append(c.arena, .{ .name = "Content-Type", .value = "application/json" });+ if (signed) {+ const ts = c.now_ms orelse @import("util.zig").unixMs(c.io);+ try headers.append(c.arena, .{ .name = "X-Vault-Timestamp", .value = try std.fmt.allocPrint(c.arena, "{d}", .{ts}) });+ try headers.append(c.arena, .{ .name = "X-Vault-Signature", .value = try crypto.signRequest(c.arena, c.keys, method, path, body, ts, c.device_id) });+ }+ try headers.appendSlice(c.arena, extra);+ return c.transport.callFn(c.transport.ctx, c.arena, method, path, headers.items, body);+ }++ fn json(c: *Client, value: anytype) ![]const u8 {+ var aw: Io.Writer.Allocating = .init(c.arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(value);+ return aw.writer.buffered();+ }++ fn itemPath(c: *Client, agent: []const u8, slot: []const u8, suffix: []const u8) ![]const u8 {+ return std.fmt.allocPrint(c.arena, "/vault/items/{s}/{s}{s}", .{ agent, slot, suffix });+ }++ pub fn getVault(c: *Client) !Vault {+ const r = try c.call("GET", "/vault", "", false, &.{});+ if (r.status != 200) return statusError(r.status);+ return std.json.parseFromSliceLeaky(Vault, c.arena, r.body, .{ .ignore_unknown_fields = true, .allocate = .alloc_always });+ }++ pub fn getItem(c: *Client, agent: []const u8, slot: []const u8) !?Item {+ const r = try c.call("GET", try c.itemPath(agent, slot, ""), "", false, &.{});+ if (r.status == 404) return null;+ if (r.status != 200) return statusError(r.status);+ return try std.json.parseFromSliceLeaky(Item, c.arena, r.body, .{ .ignore_unknown_fields = true, .allocate = .alloc_always });+ }++ pub fn putItem(c: *Client, agent: []const u8, slot: []const u8, if_match: u64, body: PutBody) !PutResult {+ const payload = try c.json(body);+ const etag = try std.fmt.allocPrint(c.arena, "{d}", .{if_match});+ const r = try c.call("PUT", try c.itemPath(agent, slot, ""), payload, true, &.{.{ .name = "If-Match", .value = etag }});+ return switch (r.status) {+ 200, 201 => .{ .ok = (try parseField(c.arena, r.body, "version")) orelse if_match + 1 },+ 412 => .{ .conflict = (try parseField(c.arena, r.body, "currentVersion")) orelse 0 },+ 409 => if (std.mem.indexOf(u8, r.body, "stale_epoch") != null) .stale_epoch else .lease_held,+ else => statusError(r.status),+ };+ }++ /// true = lease granted, false = another device holds it.+ pub fn lease(c: *Client, agent: []const u8, slot: []const u8, ttl_s: u32) !bool {+ const r = try c.call("POST", try c.itemPath(agent, slot, "/lease"), try c.json(.{ .ttlSeconds = @min(ttl_s, 60) }), true, &.{});+ return switch (r.status) {+ 200 => true,+ 409 => false,+ else => statusError(r.status),+ };+ }++ pub fn release(c: *Client, agent: []const u8, slot: []const u8) !void {+ const r = try c.call("DELETE", try c.itemPath(agent, slot, "/lease"), "", true, &.{});+ if (r.status != 200 and r.status != 204 and r.status != 404) return statusError(r.status);+ }++ pub fn setStatus(c: *Client, agent: []const u8, slot: []const u8, status: []const u8, if_version: u64) !void {+ const r = try c.call("POST", try c.itemPath(agent, slot, "/status"), try c.json(.{ .status = status, .ifVersion = if_version }), true, &.{});+ if (r.status != 200 and r.status != 412) return statusError(r.status);+ }++ pub fn registerDevice(c: *Client, name: []const u8, wrapped_key: ?[]const u8) ![]const u8 {+ const body = try c.json(.{+ .deviceId = c.device_id,+ .name = name,+ .publicKey = try crypto.encode(c.arena, &c.keys.box.public_key),+ .signingKey = try crypto.encode(c.arena, &c.keys.sign.public_key.toBytes()),+ .wrappedKey = wrapped_key,+ });+ const r = try c.call("POST", "/vault/devices", body, false, &.{});+ if (r.status != 200 and r.status != 201) return statusError(r.status);+ return (try parseStringField(c.arena, r.body, "status")) orelse "pending";+ }++ pub fn approve(c: *Client, device_id: []const u8, wrapped_key: []const u8) !void {+ const path = try std.fmt.allocPrint(c.arena, "/vault/devices/{s}/approve", .{device_id});+ const r = try c.call("POST", path, try c.json(.{ .wrappedKey = wrapped_key }), true, &.{});+ if (r.status != 200) return statusError(r.status);+ }++ pub fn deleteDevice(c: *Client, device_id: []const u8) !void {+ const path = try std.fmt.allocPrint(c.arena, "/vault/devices/{s}", .{device_id});+ const r = try c.call("DELETE", path, "", true, &.{});+ if (r.status != 200 and r.status != 204) return statusError(r.status);+ }++ pub fn rotate(c: *Client, key_epoch: u64, wrapped: std.json.ObjectMap) !void {+ const r = try c.call("POST", "/vault/rotate", try c.json(.{ .keyEpoch = key_epoch, .wrappedKeys = std.json.Value{ .object = wrapped } }), true, &.{});+ if (r.status != 200) return statusError(r.status);+ }+};++pub const Device = struct {+ deviceId: []const u8 = "",+ name: []const u8 = "",+ publicKey: []const u8 = "",+ signingKey: []const u8 = "",+ status: []const u8 = "",+};++pub const ItemHeader = struct {+ agent: []const u8 = "",+ slot: []const u8 = "",+ version: u64 = 0,+ keyEpoch: u64 = 0,+ kind: []const u8 = "static",+ status: []const u8 = "ok",+ holder: ?[]const u8 = null,+ leaseHolder: ?[]const u8 = null,+ leaseUntil: ?i64 = null,+ updatedAt: ?i64 = null,+ updatedBy: ?[]const u8 = null,+};++pub const Vault = struct {+ /// The verified user id. Older edges omit it; callers then fall back to+ /// the bearer's `sub`.+ userId: ?[]const u8 = null,+ devices: []const Device = &.{},+ wrappedKey: ?[]const u8 = null,+ keyEpoch: u64 = 0,+ items: []const ItemHeader = &.{},+};++pub const Item = struct {+ agent: []const u8 = "",+ slot: []const u8 = "",+ version: u64 = 0,+ keyEpoch: u64 = 0,+ kind: []const u8 = "static",+ status: []const u8 = "ok",+ nonce: []const u8 = "",+ ciphertext: []const u8 = "",+};++pub const PutBody = struct {+ kind: []const u8,+ status: []const u8 = "ok",+ keyEpoch: u64,+ nonce: []const u8,+ ciphertext: []const u8,+};++pub const PutResult = union(enum) {+ ok: u64,+ conflict: u64,+ lease_held,+ stale_epoch,+};++fn statusError(status: u16) error{ Unauthorized, Forbidden, NotFound, EdgeError } {+ return switch (status) {+ 401 => error.Unauthorized,+ 403 => error.Forbidden,+ 404 => error.NotFound,+ else => error.EdgeError,+ };+}++fn parseField(arena: Allocator, body: []const u8, name: []const u8) !?u64 {+ const v = std.json.parseFromSliceLeaky(std.json.Value, arena, body, .{}) catch return null;+ if (v != .object) return null;+ const f = v.object.get(name) orelse return null;+ return if (f == .integer and f.integer >= 0) @intCast(f.integer) else null;+}++fn parseStringField(arena: Allocator, body: []const u8, name: []const u8) !?[]const u8 {+ const v = std.json.parseFromSliceLeaky(std.json.Value, arena, body, .{ .allocate = .alloc_always }) catch return null;+ if (v != .object) return null;+ const f = v.object.get(name) orelse return null;+ return if (f == .string) f.string else null;+}++/// Real transport: std.http against the edge base URL.+pub const Http = struct {+ io: Io,+ gpa: Allocator,+ base: []const u8 = default_edge,++ pub fn transport(h: *Http) Transport {+ return .{ .ctx = h, .callFn = callHttp };+ }++ fn callHttp(ctx: *anyopaque, arena: Allocator, method: []const u8, path: []const u8, headers: []const std.http.Header, body: []const u8) anyerror!Response {+ const h: *Http = @ptrCast(@alignCast(ctx));+ var client: std.http.Client = .{ .allocator = h.gpa, .io = h.io };+ defer client.deinit();+ var aw: Io.Writer.Allocating = .init(arena);+ const m = std.meta.stringToEnum(std.http.Method, method) orelse return error.BadMethod;+ const res = try client.fetch(.{+ .location = .{ .url = try std.fmt.allocPrint(arena, "{s}{s}", .{ h.base, path }) },+ .method = m,+ .payload = if (body.len > 0 or m == .POST or m == .PUT) body else null,+ .response_writer = &aw.writer,+ .extra_headers = headers,+ });+ return .{ .status = @intFromEnum(res.status), .body = aw.writer.buffered() };+ }+};++test {+ _ = @import("vault_client_tests.zig");+}diff --git a/src/vault_client_tests.zig b/src/vault_client_tests.zignew file mode 100644index 00000000..2d8838c1--- /dev/null+++ b/src/vault_client_tests.zig@@ -0,0 +1 @@+//! vault_client unit tests live in vault_sync_tests.zig (they need the mock edge).diff --git a/src/vault_crypto.zig b/src/vault_crypto.zigindex 0b89765d..b713fab9 100644--- a/src/vault_crypto.zig+++ b/src/vault_crypto.zig@@ -147,17 +147,13 @@ pub fn open(arena: Allocator, vault_key: VaultKey, r: ItemRef, nonce: []const u8return out;}-/// The string a mutating request signs. An empty body contributes an empty-/// hash field.+/// The string a mutating request signs. The body hash is always sha256 hex,+/// including for an empty body.pub fn signingString(arena: Allocator, method: []const u8, path: []const u8, body: []const u8, ts_ms: i64, device_id: []const u8) ![]const u8 {- var hex: [2 * Sha256.digest_length]u8 = undefined;- const hash: []const u8 = if (body.len == 0) "" else blk: {- var d: [Sha256.digest_length]u8 = undefined;- Sha256.hash(body, &d, .{});- hex = std.fmt.bytesToHex(d, .lower);- break :blk &hex;- };- return std.fmt.allocPrint(arena, "{s}|{s}|{s}|{d}|{s}", .{ method, path, hash, ts_ms, device_id });+ var d: [Sha256.digest_length]u8 = undefined;+ Sha256.hash(body, &d, .{});+ const hex = std.fmt.bytesToHex(d, .lower);+ return std.fmt.allocPrint(arena, "{s}|{s}|{s}|{d}|{s}", .{ method, path, &hex, ts_ms, device_id });}/// base64url Ed25519 signature for X-Vault-Signature.@@ -246,7 +242,7 @@ test "device secret survives encode/decode and request signatures verify" {const sig = Ed25519.Signature.fromBytes((try decode(arena, sig_b64))[0..64].*);try sig.verify(try signingString(arena, "PUT", "/vault/items/graff/codex", "{}", 1700000000000, "dev-a"), k.sign.public_key);try std.testing.expectError(error.SignatureVerificationFailed, sig.verify(try signingString(arena, "PUT", "/vault/items/graff/kimi", "{}", 1700000000000, "dev-a"), k.sign.public_key));- try std.testing.expectEqualStrings("GET|/vault||5|d", try signingString(arena, "GET", "/vault", "", 5, "d"));+ try std.testing.expectEqualStrings("DELETE|/vault/devices/x|e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855|5|d", try signingString(arena, "DELETE", "/vault/devices/x", "", 5, "d"));}test "userIdFromBearer reads the JWT sub and the dev forms" {diff --git a/src/vault_mock_edge.zig b/src/vault_mock_edge.zignew file mode 100644index 00000000..42a02bb3--- /dev/null+++ b/src/vault_mock_edge.zig@@ -0,0 +1,203 @@+//! In-memory Harness edge vault for tests (contract v1.1): device+//! enrollment, per-device wrapped keys, compare-and-swap items, leases,+//! key epochs, rotation, and Ed25519 request-signature checks.++const std = @import("std");+const Allocator = std.mem.Allocator;+const crypto = @import("vault_crypto.zig");+const client = @import("vault_client.zig");+const Ed25519 = std.crypto.sign.Ed25519;++const Device = struct {+ id: []const u8,+ name: []const u8,+ public_key: []const u8,+ signing_key: []const u8,+ enrolled: bool,+ wrapped: ?[]const u8 = null,+};++const Item = struct {+ version: u64 = 0,+ key_epoch: u64 = 0,+ kind: []const u8 = "static",+ status: []const u8 = "ok",+ nonce: []const u8 = "",+ ciphertext: []const u8 = "",+ lease_holder: ?[]const u8 = null,+};++pub const MockEdge = struct {+ gpa: Allocator,+ arena: std.heap.ArenaAllocator,+ devices: std.ArrayList(Device) = .empty,+ items: std.StringHashMapUnmanaged(Item) = .empty,+ key_epoch: u64 = 1,+ /// Count of rejected signatures, so tests can prove the checks ran.+ bad_signatures: usize = 0,+ requests: usize = 0,++ pub fn init(gpa: Allocator) MockEdge {+ return .{ .gpa = gpa, .arena = .init(gpa) };+ }++ pub fn deinit(m: *MockEdge) void {+ m.arena.deinit();+ }++ pub fn transport(m: *MockEdge) client.Transport {+ return .{ .ctx = m, .callFn = handle };+ }++ fn header(headers: []const std.http.Header, name: []const u8) ?[]const u8 {+ for (headers) |h| if (std.ascii.eqlIgnoreCase(h.name, name)) return h.value;+ return null;+ }++ fn find(m: *MockEdge, id: []const u8) ?*Device {+ for (m.devices.items) |*d| if (std.mem.eql(u8, d.id, id)) return d;+ return null;+ }++ fn resp(arena: Allocator, status: u16, value: anytype) !client.Response {+ var aw: std.Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(value);+ return .{ .status = status, .body = aw.writer.buffered() };+ }++ fn verified(m: *MockEdge, arena: Allocator, method: []const u8, path: []const u8, headers: []const std.http.Header, body: []const u8) bool {+ const dev_id = header(headers, "X-Vault-Device") orelse return false;+ const d = m.find(dev_id) orelse return false;+ if (!d.enrolled) return false;+ const ts = std.fmt.parseInt(i64, header(headers, "X-Vault-Timestamp") orelse return false, 10) catch return false;+ const sig_raw = crypto.decode(arena, header(headers, "X-Vault-Signature") orelse return false) catch return false;+ const key_raw = crypto.decode(arena, d.signing_key) catch return false;+ if (sig_raw.len != 64 or key_raw.len != 32) return false;+ const pk = Ed25519.PublicKey.fromBytes(key_raw[0..32].*) catch return false;+ const msg = crypto.signingString(arena, method, path, body, ts, dev_id) catch return false;+ Ed25519.Signature.fromBytes(sig_raw[0..64].*).verify(msg, pk) catch return false;+ return true;+ }++ fn handle(ctx: *anyopaque, arena: Allocator, method: []const u8, path: []const u8, headers: []const std.http.Header, body: []const u8) anyerror!client.Response {+ const m: *MockEdge = @ptrCast(@alignCast(ctx));+ m.requests += 1;+ const a = m.arena.allocator();+ if (header(headers, "Authorization") == null) return .{ .status = 401, .body = "{}" };+ const caller = header(headers, "X-Vault-Device") orelse "";+ const is_get = std.mem.eql(u8, method, "GET");+ const registering = std.mem.eql(u8, method, "POST") and std.mem.eql(u8, path, "/vault/devices");+ if (!is_get and !registering and !m.verified(arena, method, path, headers, body)) {+ m.bad_signatures += 1;+ return .{ .status = 401, .body = "{\"error\":\"bad_signature\"}" };+ }+ const parsed: std.json.Value = if (body.len > 0) try std.json.parseFromSliceLeaky(std.json.Value, arena, body, .{}) else .null;++ if (is_get and std.mem.eql(u8, path, "/vault")) {+ var devs: std.ArrayList(client.Device) = .empty;+ for (m.devices.items) |d| try devs.append(arena, .{ .deviceId = d.id, .name = d.name, .publicKey = d.public_key, .signingKey = d.signing_key, .status = if (d.enrolled) "enrolled" else "pending" });+ var heads: std.ArrayList(client.ItemHeader) = .empty;+ var it = m.items.iterator();+ while (it.next()) |e| {+ const slash = std.mem.indexOfScalar(u8, e.key_ptr.*, '/').?;+ try heads.append(arena, .{ .agent = e.key_ptr.*[0..slash], .slot = e.key_ptr.*[slash + 1 ..], .version = e.value_ptr.version, .keyEpoch = e.value_ptr.key_epoch, .kind = e.value_ptr.kind, .status = e.value_ptr.status, .leaseHolder = e.value_ptr.lease_holder });+ }+ const wrapped = if (m.find(caller)) |d| d.wrapped else null;+ return resp(arena, 200, client.Vault{ .userId = "user-7", .devices = devs.items, .wrappedKey = wrapped, .keyEpoch = m.key_epoch, .items = heads.items });+ }+ if (registering) {+ const o = parsed.object;+ var any_enrolled = false;+ for (m.devices.items) |d| any_enrolled = any_enrolled or d.enrolled;+ const wrapped = if (o.get("wrappedKey")) |w| (if (w == .string) w.string else null) else null;+ const bootstrap = !any_enrolled and wrapped != null;+ try m.devices.append(a, .{+ .id = try a.dupe(u8, o.get("deviceId").?.string),+ .name = try a.dupe(u8, o.get("name").?.string),+ .public_key = try a.dupe(u8, o.get("publicKey").?.string),+ .signing_key = try a.dupe(u8, o.get("signingKey").?.string),+ .enrolled = bootstrap,+ .wrapped = if (bootstrap) try a.dupe(u8, wrapped.?) else null,+ });+ return resp(arena, 200, .{ .status = if (bootstrap) "enrolled" else "pending" });+ }+ if (std.mem.startsWith(u8, path, "/vault/devices/")) {+ const rest = path["/vault/devices/".len..];+ if (std.mem.endsWith(u8, rest, "/approve")) {+ const d = m.find(rest[0 .. rest.len - "/approve".len]) orelse return .{ .status = 404, .body = "{}" };+ d.enrolled = true;+ d.wrapped = try a.dupe(u8, parsed.object.get("wrappedKey").?.string);+ return resp(arena, 200, .{ .status = "enrolled" });+ }+ for (m.devices.items, 0..) |d, i| if (std.mem.eql(u8, d.id, rest)) {+ _ = m.devices.orderedRemove(i);+ return .{ .status = 204, .body = "" };+ };+ return .{ .status = 404, .body = "{}" };+ }+ if (std.mem.eql(u8, path, "/vault/rotate")) {+ const o = parsed.object;+ const epoch: u64 = @intCast(o.get("keyEpoch").?.integer);+ if (epoch != m.key_epoch + 1) return .{ .status = 409, .body = "{\"error\":\"stale_epoch\"}" };+ const wk = o.get("wrappedKeys").?.object;+ var enrolled: usize = 0;+ for (m.devices.items) |d| if (d.enrolled) {+ enrolled += 1;+ if (wk.get(d.id) == null) return .{ .status = 400, .body = "{\"error\":\"missing_device\"}" };+ };+ if (wk.count() != enrolled) return .{ .status = 400, .body = "{\"error\":\"extra_device\"}" };+ for (m.devices.items) |*d| if (d.enrolled) {+ d.wrapped = try a.dupe(u8, wk.get(d.id).?.string);+ };+ m.key_epoch = epoch;+ return resp(arena, 200, .{ .keyEpoch = epoch });+ }+ if (std.mem.startsWith(u8, path, "/vault/items/")) {+ var rest = path["/vault/items/".len..];+ var action: []const u8 = "";+ for ([_][]const u8{ "/lease", "/status", "/hold" }) |suf| if (std.mem.endsWith(u8, rest, suf)) {+ action = suf;+ rest = rest[0 .. rest.len - suf.len];+ };+ const gop = try m.items.getOrPut(a, try a.dupe(u8, rest));+ if (!gop.found_existing) gop.value_ptr.* = .{};+ const item = gop.value_ptr;+ if (std.mem.eql(u8, action, "/lease")) {+ if (std.mem.eql(u8, method, "DELETE")) {+ if (item.lease_holder) |h| if (std.mem.eql(u8, h, caller)) {+ item.lease_holder = null;+ };+ return .{ .status = 204, .body = "" };+ }+ if (item.lease_holder) |h| if (!std.mem.eql(u8, h, caller)) return .{ .status = 409, .body = "{\"error\":\"lease_held\"}" };+ item.lease_holder = try a.dupe(u8, caller);+ return resp(arena, 200, .{ .leaseHolder = caller });+ }+ if (std.mem.eql(u8, action, "/status")) {+ item.status = try a.dupe(u8, parsed.object.get("status").?.string);+ return resp(arena, 200, .{ .status = item.status });+ }+ if (is_get) {+ if (item.version == 0) return .{ .status = 404, .body = "{}" };+ const slash = std.mem.indexOfScalar(u8, rest, '/').?;+ return resp(arena, 200, client.Item{ .agent = rest[0..slash], .slot = rest[slash + 1 ..], .version = item.version, .keyEpoch = item.key_epoch, .kind = item.kind, .status = item.status, .nonce = item.nonce, .ciphertext = item.ciphertext });+ }+ if (std.mem.eql(u8, method, "PUT")) {+ if (item.lease_holder) |h| if (!std.mem.eql(u8, h, caller)) return .{ .status = 409, .body = "{\"error\":\"lease_held\"}" };+ const o = parsed.object;+ if (@as(u64, @intCast(o.get("keyEpoch").?.integer)) != m.key_epoch) return .{ .status = 409, .body = "{\"error\":\"stale_epoch\"}" };+ const if_match = std.fmt.parseInt(u64, header(headers, "If-Match") orelse "", 10) catch return .{ .status = 428, .body = "{}" };+ if (if_match != item.version) return resp(arena, 412, .{ .currentVersion = item.version });+ item.version += 1;+ item.key_epoch = m.key_epoch;+ item.kind = try a.dupe(u8, o.get("kind").?.string);+ item.status = try a.dupe(u8, o.get("status").?.string);+ item.nonce = try a.dupe(u8, o.get("nonce").?.string);+ item.ciphertext = try a.dupe(u8, o.get("ciphertext").?.string);+ return resp(arena, 200, .{ .version = item.version });+ }+ }+ return .{ .status = 404, .body = "{}" };+ }+};diff --git a/src/vault_sync.zig b/src/vault_sync.zignew file mode 100644index 00000000..391a7988--- /dev/null+++ b/src/vault_sync.zig@@ -0,0 +1,168 @@+//! Vault operations on top of the edge client (harness ADR 0005, contract+//! v1.1): enroll this device, push/pull opaque credential bytes, approve a+//! new device, and remove one with a key rotation. Only graff holds the vault+//! key; the edge stores ciphertext.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const crypto = @import("vault_crypto.zig");+const client = @import("vault_client.zig");++pub const Session = struct {+ io: Io,+ arena: Allocator,+ c: *client.Client,+ user_id: []const u8,++ /// A session for `c`. The user id comes from the edge (GET /vault) and+ /// falls back to the bearer's `sub` on edges that do not return it.+ pub fn open(io: Io, arena: Allocator, c: *client.Client) !Session {+ const v = try c.getVault();+ const user = v.userId orelse try crypto.userIdFromBearer(arena, c.bearer);+ return .{ .io = io, .arena = arena, .c = c, .user_id = user };+ }++ pub const Enrolled = enum { enrolled, pending };++ /// Register this device. The first device creates the vault key and+ /// enrolls itself; later devices wait for `approve` on an enrolled one.+ pub fn enable(s: *Session, name: []const u8) !Enrolled {+ const v = try s.c.getVault();+ var any_enrolled = false;+ for (v.devices) |d| {+ if (std.mem.eql(u8, d.deviceId, s.c.device_id)) return if (std.mem.eql(u8, d.status, "enrolled")) .enrolled else .pending;+ any_enrolled = any_enrolled or std.mem.eql(u8, d.status, "enrolled");+ }+ var wrapped: ?[]const u8 = null;+ if (!any_enrolled) {+ var vk: crypto.VaultKey = undefined;+ s.io.random(&vk);+ const w = try crypto.wrap(s.io, vk, s.c.keys.box.public_key, s.user_id, s.c.device_id);+ wrapped = try crypto.encode(s.arena, &w);+ }+ const status = try s.c.registerDevice(name, wrapped);+ return if (std.mem.eql(u8, status, "enrolled")) .enrolled else .pending;+ }++ pub const Key = struct { key: crypto.VaultKey, epoch: u64 };++ pub fn vaultKey(s: *Session) !Key {+ const v = try s.c.getVault();+ const wrapped = v.wrappedKey orelse return error.NotEnrolled;+ const raw = try crypto.decode(s.arena, wrapped);+ return .{ .key = try crypto.unwrap(s.c.keys, raw, s.user_id, s.c.device_id), .epoch = v.keyEpoch };+ }++ pub const Pulled = struct { bytes: []u8, version: u64, kind: []const u8, status: []const u8 };++ pub fn pull(s: *Session, agent: []const u8, slot: []const u8) !?Pulled {+ const item = (try s.c.getItem(agent, slot)) orelse return null;+ const k = try s.vaultKey();+ if (item.keyEpoch != k.epoch) return error.StaleItemEpoch;+ const bytes = try crypto.open(s.arena, k.key, .{ .user_id = s.user_id, .agent = agent, .slot = slot, .version = item.version, .key_epoch = item.keyEpoch }, try crypto.decode(s.arena, item.nonce), try crypto.decode(s.arena, item.ciphertext));+ return .{ .bytes = bytes, .version = item.version, .kind = item.kind, .status = item.status };+ }++ pub const Put = union(enum) { ok: u64, conflict: u64, lease_held };++ /// One compare-and-swap write at `if_match` (0 = create). A stale key+ /// epoch re-reads the vault key and retries once.+ pub fn putAt(s: *Session, agent: []const u8, slot: []const u8, kind: []const u8, if_match: u64, plaintext: []const u8) !Put {+ var attempt: usize = 0;+ while (attempt < 2) : (attempt += 1) {+ const k = try s.vaultKey();+ const sealed = try crypto.seal(s.io, s.arena, k.key, .{ .user_id = s.user_id, .agent = agent, .slot = slot, .version = if_match + 1, .key_epoch = k.epoch }, plaintext);+ const r = try s.c.putItem(agent, slot, if_match, .{+ .kind = kind,+ .keyEpoch = k.epoch,+ .nonce = try crypto.encode(s.arena, &sealed.nonce),+ .ciphertext = try crypto.encode(s.arena, sealed.body),+ });+ switch (r) {+ .ok => |v| return .{ .ok = v },+ .conflict => |v| return .{ .conflict = v },+ .lease_held => return .lease_held,+ .stale_epoch => continue,+ }+ }+ return error.StaleEpoch;+ }++ /// `graff keys push`: write the current bytes as the next version,+ /// whatever version the vault holds now.+ pub fn push(s: *Session, agent: []const u8, slot: []const u8, kind: []const u8, plaintext: []const u8) !u64 {+ var current: u64 = if (try s.c.getItem(agent, slot)) |it| it.version else 0;+ var attempt: usize = 0;+ while (attempt < 3) : (attempt += 1) {+ switch (try s.putAt(agent, slot, kind, current, plaintext)) {+ .ok => |v| return v,+ .conflict => |v| current = v,+ .lease_held => return error.LeaseHeld,+ }+ }+ return error.Conflict;+ }++ pub fn findDevice(v: client.Vault, id: []const u8) ?client.Device {+ for (v.devices) |d| if (std.mem.eql(u8, d.deviceId, id)) return d;+ return null;+ }++ pub fn deviceFingerprint(s: *Session, d: client.Device) ![8]u8 {+ const raw = try crypto.decode(s.arena, d.publicKey);+ if (raw.len != 32) return error.BadPublicKey;+ return crypto.fingerprint(raw[0..32].*);+ }++ /// Wrap the vault key to a pending device and approve it.+ pub fn approve(s: *Session, device_id: []const u8) !void {+ const v = try s.c.getVault();+ const d = findDevice(v, device_id) orelse return error.NoSuchDevice;+ const pub_raw = try crypto.decode(s.arena, d.publicKey);+ if (pub_raw.len != 32) return error.BadPublicKey;+ const k = try s.vaultKey();+ const w = try crypto.wrap(s.io, k.key, pub_raw[0..32].*, s.user_id, device_id);+ try s.c.approve(device_id, try crypto.encode(s.arena, &w));+ }++ /// Remove a device and rotate: new vault key wrapped to every remaining+ /// enrolled device, then every item re-encrypted under the new epoch+ /// (rotating items under their lease).+ pub fn remove(s: *Session, device_id: []const u8) !void {+ const old = try s.vaultKey();+ const before = try s.c.getVault();+ const Plain = struct { agent: []const u8, slot: []const u8, kind: []const u8, version: u64, bytes: []u8, leased: bool };+ var plains: std.ArrayList(Plain) = .empty;+ for (before.items) |h| {+ const rotating = std.mem.eql(u8, h.kind, "rotating");+ if (rotating and !try s.c.lease(h.agent, h.slot, 60)) return error.LeaseHeld;+ const p = (try s.pull(h.agent, h.slot)) orelse continue;+ try plains.append(s.arena, .{ .agent = h.agent, .slot = h.slot, .kind = h.kind, .version = p.version, .bytes = p.bytes, .leased = rotating });+ }+ try s.c.deleteDevice(device_id);+ const after = try s.c.getVault();+ var new_key: crypto.VaultKey = undefined;+ s.io.random(&new_key);+ var wrapped: std.json.ObjectMap = .empty;+ for (after.devices) |d| {+ if (!std.mem.eql(u8, d.status, "enrolled")) continue;+ const pub_raw = try crypto.decode(s.arena, d.publicKey);+ if (pub_raw.len != 32) return error.BadPublicKey;+ const w = try crypto.wrap(s.io, new_key, pub_raw[0..32].*, s.user_id, d.deviceId);+ try wrapped.put(s.arena, d.deviceId, .{ .string = try crypto.encode(s.arena, &w) });+ }+ try s.c.rotate(old.epoch + 1, wrapped);+ for (plains.items) |p| {+ defer if (p.leased) s.c.release(p.agent, p.slot) catch {};+ switch (try s.putAt(p.agent, p.slot, p.kind, p.version, p.bytes)) {+ .ok => {},+ .conflict, .lease_held => return error.Conflict,+ }+ }+ }+};++test {+ _ = @import("vault_sync_tests.zig");+}diff --git a/src/vault_sync_tests.zig b/src/vault_sync_tests.zignew file mode 100644index 00000000..8e958eeb--- /dev/null+++ b/src/vault_sync_tests.zig@@ -0,0 +1,127 @@+//! vault_sync against the in-memory edge: enrollment, round trips, CAS,+//! leases, signature enforcement, and rotation on removal.++const std = @import("std");+const testing = std.testing;+const crypto = @import("vault_crypto.zig");+const client = @import("vault_client.zig");+const sync = @import("vault_sync.zig");+const MockEdge = @import("vault_mock_edge.zig").MockEdge;++const Dev = struct {+ c: client.Client,+ s: sync.Session,++ fn init(d: *Dev, arena: std.mem.Allocator, edge: *MockEdge, id: []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_700_000_000_000 };+ d.s = sync.Session.open(testing.io, arena, &d.c) catch unreachable;+ }+};++test "first device bootstraps, pushes, and pulls its own bytes back" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var edge = MockEdge.init(testing.allocator);+ defer edge.deinit();+ var a: Dev = undefined;+ a.init(arena, &edge, "dev-a");+ try testing.expectEqual(sync.Session.Enrolled.enrolled, try a.s.enable("laptop"));+ try testing.expectEqual(@as(u64, 1), try a.s.push("graff", "codex", "rotating", "{\"t\":1}"));+ const got = (try a.s.pull("graff", "codex")).?;+ try testing.expectEqualStrings("{\"t\":1}", got.bytes);+ try testing.expectEqual(@as(u64, 1), got.version);+ try testing.expectEqual(@as(usize, 0), edge.bad_signatures);+}++test "a second device waits for approval, then reads what the first wrote" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var edge = MockEdge.init(testing.allocator);+ defer edge.deinit();+ var a: Dev = undefined;+ a.init(arena, &edge, "dev-a");+ var b: Dev = undefined;+ b.init(arena, &edge, "dev-b");+ _ = try a.s.enable("laptop");+ _ = try a.s.push("graff", "xai", "rotating", "secret-xai");+ try testing.expectEqual(sync.Session.Enrolled.pending, try b.s.enable("vps"));+ try testing.expectError(error.NotEnrolled, b.s.pull("graff", "xai"));+ const v = try a.c.getVault();+ const pending = sync.Session.findDevice(v, "dev-b").?;+ try testing.expectEqualSlices(u8, &crypto.fingerprint(b.c.keys.box.public_key), &(try a.s.deviceFingerprint(pending)));+ try a.s.approve("dev-b");+ try testing.expectEqualStrings("secret-xai", (try b.s.pull("graff", "xai")).?.bytes);+}++test "compare-and-swap: a stale If-Match gets 412, and a lease blocks other writers" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var edge = MockEdge.init(testing.allocator);+ defer edge.deinit();+ var a: Dev = undefined;+ a.init(arena, &edge, "dev-a");+ var b: Dev = undefined;+ b.init(arena, &edge, "dev-b");+ _ = try a.s.enable("laptop");+ _ = try b.s.enable("vps");+ try a.s.approve("dev-b");+ _ = try a.s.push("graff", "kimi", "rotating", "v1");+ // b refreshes from a stale version: the edge refuses and names the current one.+ switch (try b.s.putAt("graff", "kimi", "rotating", 0, "b-local")) {+ .conflict => |cur| try testing.expectEqual(@as(u64, 1), cur),+ else => return error.ExpectedConflict,+ }+ try testing.expect(try a.c.lease("graff", "kimi", 60));+ try testing.expect(!try b.c.lease("graff", "kimi", 60));+ try testing.expect((try b.s.putAt("graff", "kimi", "rotating", 1, "b-refresh")) == .lease_held);+ try testing.expect((try a.s.putAt("graff", "kimi", "rotating", 1, "a-refresh")) == .ok);+ try a.c.release("graff", "kimi");+ try testing.expectEqualStrings("a-refresh", (try b.s.pull("graff", "kimi")).?.bytes);+}++test "unsigned or forged mutations are rejected by the edge" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var edge = MockEdge.init(testing.allocator);+ defer edge.deinit();+ var a: Dev = undefined;+ a.init(arena, &edge, "dev-a");+ _ = try a.s.enable("laptop");+ // Same device id, different signing key: an attacker holding only the bearer.+ var forged = a.c;+ forged.keys = crypto.DeviceKeys.generate(testing.io);+ try testing.expectError(error.Unauthorized, forged.lease("graff", "codex", 60));+ try testing.expectEqual(@as(usize, 1), edge.bad_signatures);+}++test "removing a device rotates the key; the survivor still reads, the removed one cannot" {+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var edge = MockEdge.init(testing.allocator);+ defer edge.deinit();+ var a: Dev = undefined;+ a.init(arena, &edge, "dev-a");+ var b: Dev = undefined;+ b.init(arena, &edge, "dev-b");+ _ = try a.s.enable("laptop");+ _ = try b.s.enable("old-vps");+ try a.s.approve("dev-b");+ _ = try a.s.push("graff", "codex", "rotating", "codex-login");+ _ = try a.s.push("graff", "zai", "static", "zai-key");+ const before = try a.s.vaultKey();+ try a.s.remove("dev-b");+ const after = try a.s.vaultKey();+ try testing.expectEqual(before.epoch + 1, after.epoch);+ try testing.expect(!std.mem.eql(u8, &before.key, &after.key));+ try testing.expectEqualStrings("codex-login", (try a.s.pull("graff", "codex")).?.bytes);+ try testing.expectEqualStrings("zai-key", (try a.s.pull("graff", "zai")).?.bytes);+ // The removed device has no wrapped key any more and its signatures fail.+ try testing.expectError(error.NotEnrolled, b.s.pull("graff", "codex"));+ // Leases taken for the rotation were released.+ try testing.expect(try a.c.lease("graff", "codex", 60));+}