// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A version 2 key/value secret engine — the default `secret/` mount on a //! `vault server -dev` instance, and the engine most deployments use. //! //! KV v2 splits the user-facing path from the API path: a secret the operator //! calls `myapp/config` on the `secret/` mount lives at //! `secret/data/myapp/config`, its directory listing lives at //! `secret/metadata/myapp`, and the version-management endpoints live under //! `secret/delete/`, `secret/undelete/` and `secret/destroy/`. These helpers //! take the user-facing path and do that rewriting, so callers pass what they //! see in the Vault UI. const std = @import("std"); const Allocator = std.mem.Allocator; const Client = @import("Client.zig"); pub const Error = Client.Error; pub const Options = struct { /// Mount point of the engine, without slashes: `secret`, `kv`, ... mount: []const u8 = "secret", }; pub const ReadOptions = struct { mount: []const u8 = "secret", /// Which version to read. Null reads the current one. Reading a specific /// version of a soft-deleted secret succeeds but yields a `Secret` whose /// `values` is null. version: ?u64 = null, }; /// One secret and the version metadata Vault returned with it. Owns the /// parsed JSON; call `deinit` when done. pub const Secret = struct { parsed: std.json.Parsed(Envelope), pub const Envelope = struct { request_id: []const u8 = "", lease_duration: u64 = 0, renewable: bool = false, data: Data, }; pub const Data = struct { /// Null when this version has been deleted but not destroyed. data: ?std.json.Value = null, metadata: Metadata = .{}, }; pub const Metadata = struct { /// RFC 3339 timestamp, e.g. `2024-05-01T12:00:00.000000Z`. created_time: []const u8 = "", /// RFC 3339 timestamp, empty unless this version is soft-deleted. deletion_time: []const u8 = "", /// True once the version's data has been permanently removed. destroyed: bool = false, version: u64 = 0, custom_metadata: ?std.json.Value = null, }; pub fn deinit(secret: *Secret) void { secret.parsed.deinit(); secret.* = undefined; } pub fn metadata(secret: Secret) Metadata { return secret.parsed.value.data.metadata; } /// The secret's key/value pairs, or null if this version was deleted. pub fn values(secret: Secret) ?std.json.ObjectMap { const data = secret.parsed.value.data.data orelse return null; return switch (data) { .object => |object| object, else => null, }; } /// Raw JSON value for `key`. KV v2 stores arbitrary JSON, so a field may /// well be a number, a bool, or a nested object. pub fn get(secret: Secret, key: []const u8) ?std.json.Value { const object = secret.values() orelse return null; return object.get(key); } /// Value for `key` when it is a JSON string. Returns null for a missing /// key and for a key whose value has any other type; use `get` to tell /// those apart. The slice is owned by the `Secret`. pub fn getString(secret: Secret, key: []const u8) ?[]const u8 { return switch (secret.get(key) orelse return null) { .string => |s| s, else => null, }; } }; pub const ReadError = Client.RequestError || std.json.ParseError(std.json.Scanner); /// Reads `mount/data/path`. /// /// `path` is the user-facing path, e.g. `myapp/config`. On /// `error.SecretNotFound` the secret may be absent, the mount may not exist, /// or the token may lack a policy for it — Vault does not distinguish. pub fn read(client: *Client, path: []const u8, options: ReadOptions) ReadError!Secret { const gpa = client.gpa; const api_path = try dataPath(gpa, options.mount, path); defer gpa.free(api_path); var query_buf: [32]u8 = undefined; const query: ?[]const u8 = if (options.version) |v| std.fmt.bufPrint(&query_buf, "version={d}", .{v}) catch unreachable else null; return .{ .parsed = try client.readAs(Secret.Envelope, api_path, query) }; } /// Reads a single field, returning a copy owned by the caller. A convenience /// for the common "I need one password" case; prefer `read` when several /// fields are wanted, so the secret is fetched once. pub fn readField( client: *Client, path: []const u8, field: []const u8, options: ReadOptions, ) (ReadError || error{FieldNotFound})![]u8 { var secret = try read(client, path, options); defer secret.deinit(); const value = secret.getString(field) orelse return error.FieldNotFound; return client.gpa.dupe(u8, value); } /// Keys directly under a path. Owns its backing memory; call `deinit`. pub const Listing = struct { parsed: std.json.Parsed(Envelope), pub const Envelope = struct { data: Data = .{}, pub const Data = struct { keys: []const []const u8 = &.{} }; }; pub fn deinit(listing: *Listing) void { listing.parsed.deinit(); listing.* = undefined; } /// Child names. Entries ending in `/` are sub-paths rather than secrets. pub fn keys(listing: Listing) []const []const u8 { return listing.parsed.value.data.keys; } }; /// Lists the keys directly under `mount/metadata/path`. /// /// An empty path lists the root of the mount. A path with no children answers /// `error.SecretNotFound`, which is Vault's way of saying "nothing here". pub fn list(client: *Client, path: []const u8, options: Options) ReadError!Listing { const gpa = client.gpa; const api_path = try metadataPath(gpa, options.mount, path); defer gpa.free(api_path); return .{ .parsed = try client.listAs(Listing.Envelope, api_path) }; } pub const WriteOptions = struct { mount: []const u8 = "secret", /// Check-and-set. When set, the write only lands if the secret's current /// version is exactly this number, and `error.CheckAndSetMismatch` is /// returned otherwise — the way to update a secret without clobbering a /// concurrent change. Zero means "only if nothing is stored here yet", /// which is how to create a secret without overwriting an existing one. /// /// Null skips the check. A mount configured with `cas_required` rejects /// such a write outright. cas: ?u64 = null, }; /// What Vault reports about the version a write created. pub const WriteResult = struct { parsed: std.json.Parsed(Envelope), pub const Envelope = struct { data: Secret.Metadata = .{} }; pub fn deinit(result: *WriteResult) void { result.parsed.deinit(); result.* = undefined; } pub fn metadata(result: WriteResult) Secret.Metadata { return result.parsed.value.data; } /// The version number the write produced. pub fn version(result: WriteResult) u64 { return result.parsed.value.data.version; } }; pub const WriteError = ReadError || error{ /// `WriteOptions.cas` did not match the secret's current version, so the /// write was refused. Re-read the secret and try again. CheckAndSetMismatch, }; /// Writes `data` to `mount/data/path`, creating a new version. /// /// Every KV v2 write replaces the whole secret: fields absent from `data` /// are gone from the new version, though earlier versions still hold them. /// Use `patch` to change some fields and leave the rest alone. /// /// `data` is anything `std.json` can stringify, so a struct literal is /// usually the most convenient form: /// /// ```zig /// var result = try kv2.write(&client, "myapp/config", .{ /// .password = "hunter2", /// .port = 5432, /// }, .{}); /// defer result.deinit(); /// ``` pub fn write( client: *Client, path: []const u8, data: anytype, options: WriteOptions, ) WriteError!WriteResult { const gpa = client.gpa; const api_path = try dataPath(gpa, options.mount, path); defer gpa.free(api_path); const body = try encodeWriteBody(gpa, data, options.cas); defer gpa.free(body); return .{ .parsed = client.writeAs(WriteResult.Envelope, api_path, body) catch |err| return translateCasError(client, err) }; } /// Merges `data` into the current version of `mount/data/path`, leaving /// fields it does not mention untouched. A null field value removes that /// field, following JSON merge patch semantics (RFC 7386). /// /// The mount must be KV v2 and the token needs the `patch` capability. /// `error.SecretNotFound` means there is no current version to merge into. pub fn patch( client: *Client, path: []const u8, data: anytype, options: WriteOptions, ) WriteError!WriteResult { const gpa = client.gpa; const api_path = try dataPath(gpa, options.mount, path); defer gpa.free(api_path); const body = try encodeWriteBody(gpa, data, options.cas); defer gpa.free(body); var response = client.requestChecked(.{ .method = .PATCH, .path = api_path, .body = body, .content_type = "application/merge-patch+json", }) catch |err| return translateCasError(client, err); defer response.deinit(); return .{ .parsed = try std.json.parseFromSlice( WriteResult.Envelope, gpa, response.body, .{ .ignore_unknown_fields = true, .allocate = .alloc_always }, ) }; } /// Soft-deletes the current version: it stops being readable, but the data /// survives and `undeleteVersions` brings it back. pub fn delete(client: *Client, path: []const u8, options: Options) WriteError!void { const gpa = client.gpa; const api_path = try dataPath(gpa, options.mount, path); defer gpa.free(api_path); return client.delete(api_path); } /// Soft-deletes specific versions. Reversible with `undeleteVersions`. pub fn deleteVersions( client: *Client, path: []const u8, versions: []const u64, options: Options, ) WriteError!void { return versionOp(client, "delete", path, versions, options); } /// Restores versions that `delete` or `deleteVersions` soft-deleted. A /// version whose data was destroyed cannot be restored. pub fn undeleteVersions( client: *Client, path: []const u8, versions: []const u64, options: Options, ) WriteError!void { return versionOp(client, "undelete", path, versions, options); } /// Permanently removes the data of specific versions. The version numbers /// remain in the metadata, marked destroyed. This cannot be undone. pub fn destroyVersions( client: *Client, path: []const u8, versions: []const u64, options: Options, ) WriteError!void { return versionOp(client, "destroy", path, versions, options); } /// Permanently removes the secret: every version, its data, and its /// metadata. This cannot be undone, and it is what `vault kv metadata delete` /// does — not what `vault kv delete` does. pub fn deleteMetadata(client: *Client, path: []const u8, options: Options) WriteError!void { const gpa = client.gpa; const api_path = try metadataPath(gpa, options.mount, path); defer gpa.free(api_path); return client.delete(api_path); } /// The three version endpoints take the same `{"versions": [...]}` body and /// differ only in the path segment. fn versionOp( client: *Client, comptime verb: []const u8, path: []const u8, versions: []const u64, options: Options, ) WriteError!void { const gpa = client.gpa; const api_path = try std.fmt.allocPrint(gpa, "{s}/" ++ verb ++ "/{s}", .{ std.mem.trim(u8, options.mount, "/"), std.mem.trimStart(u8, path, "/"), }); defer gpa.free(api_path); const body = try Client.encodeJson(gpa, .{ .versions = versions }); defer gpa.free(body); return client.writeDiscard(api_path, body); } /// Wraps `data` in the envelope KV v2 expects: `{"data": ..., "options": ...}`. fn encodeWriteBody(gpa: Allocator, data: anytype, cas: ?u64) Allocator.Error![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); var json: std.json.Stringify = .{ .writer = &out.writer }; encodeWriteBodyInner(&json, data, cas) catch return error.OutOfMemory; return out.toOwnedSlice(); } fn encodeWriteBodyInner(json: *std.json.Stringify, data: anytype, cas: ?u64) !void { try json.beginObject(); try json.objectField("data"); try json.write(data); if (cas) |version| { try json.objectField("options"); try json.beginObject(); try json.objectField("cas"); try json.write(version); try json.endObject(); } try json.endObject(); } /// Vault reports a failed check-and-set as a plain 400, distinguished only by /// its message, so the message is what has to be matched. A message that does /// not match is passed through as the original error. fn translateCasError(client: *Client, err: ReadError) WriteError { if (err != error.InvalidRequest) return err; const message = client.last_error orelse return err; if (std.mem.find(u8, message, "check-and-set") == null) return err; return error.CheckAndSetMismatch; } fn dataPath(gpa: Allocator, mount: []const u8, path: []const u8) Allocator.Error![]u8 { return std.fmt.allocPrint(gpa, "{s}/data/{s}", .{ std.mem.trim(u8, mount, "/"), std.mem.trimStart(u8, path, "/"), }); } fn metadataPath(gpa: Allocator, mount: []const u8, path: []const u8) Allocator.Error![]u8 { return std.fmt.allocPrint(gpa, "{s}/metadata/{s}", .{ std.mem.trim(u8, mount, "/"), std.mem.trimStart(u8, path, "/"), }); } const testing = std.testing; fn parseSecret(json: []const u8) !Secret { return .{ .parsed = try std.json.parseFromSlice( Secret.Envelope, testing.allocator, json, .{ .ignore_unknown_fields = true }, ) }; } test "Secret exposes values and metadata from a KV v2 response" { var secret = try parseSecret( \\{ \\ "request_id": "aa", \\ "lease_duration": 0, \\ "renewable": false, \\ "data": { \\ "data": {"password": "hunter2", "port": 5432, "tls": true}, \\ "metadata": { \\ "created_time": "2024-05-01T12:00:00Z", \\ "deletion_time": "", \\ "destroyed": false, \\ "version": 3 \\ } \\ }, \\ "warnings": null \\} ); defer secret.deinit(); try testing.expectEqualStrings("hunter2", secret.getString("password").?); try testing.expectEqual(@as(i64, 5432), secret.get("port").?.integer); try testing.expectEqual(@as(u64, 3), secret.metadata().version); try testing.expectEqual(@as(usize, 3), secret.values().?.count()); // A non-string field read as a string is null, not an error. try testing.expectEqual(@as(?[]const u8, null), secret.getString("port")); try testing.expectEqual(@as(?std.json.Value, null), secret.get("absent")); } test "a deleted version parses with no values" { var secret = try parseSecret( \\{ \\ "data": { \\ "data": null, \\ "metadata": { \\ "created_time": "2024-05-01T12:00:00Z", \\ "deletion_time": "2024-06-01T12:00:00Z", \\ "destroyed": false, \\ "version": 1 \\ } \\ } \\} ); defer secret.deinit(); try testing.expectEqual(@as(?std.json.ObjectMap, null), secret.values()); try testing.expectEqual(@as(?[]const u8, null), secret.getString("password")); try testing.expectEqualStrings("2024-06-01T12:00:00Z", secret.metadata().deletion_time); } test "Listing separates secrets from sub-paths by trailing slash" { var listing: Listing = .{ .parsed = try std.json.parseFromSlice( Listing.Envelope, testing.allocator, \\{"data": {"keys": ["config", "db/", "tls"]}} , .{ .ignore_unknown_fields = true }, ) }; defer listing.deinit(); try testing.expectEqual(@as(usize, 3), listing.keys().len); try testing.expectEqualStrings("db/", listing.keys()[1]); } test "encodeWriteBody wraps the payload in the KV v2 envelope" { const gpa = testing.allocator; const plain = try encodeWriteBody(gpa, .{ .password = "hunter2", .port = 5432 }, null); defer gpa.free(plain); try testing.expectEqualStrings( \\{"data":{"password":"hunter2","port":5432}} , plain); const with_cas = try encodeWriteBody(gpa, .{ .password = "hunter2" }, 7); defer gpa.free(with_cas); try testing.expectEqualStrings( \\{"data":{"password":"hunter2"},"options":{"cas":7}} , with_cas); // cas = 0 means "only if absent", and must survive the optional. const create_only = try encodeWriteBody(gpa, .{ .a = "b" }, 0); defer gpa.free(create_only); try testing.expectEqualStrings( \\{"data":{"a":"b"},"options":{"cas":0}} , create_only); } test "encodeWriteBody accepts a dynamic object as well as a struct" { const gpa = testing.allocator; var object: std.json.ObjectMap = .empty; defer object.deinit(gpa); try object.put(gpa, "user", .{ .string = "admin" }); const body = try encodeWriteBody(gpa, std.json.Value{ .object = object }, null); defer gpa.free(body); try testing.expectEqualStrings( \\{"data":{"user":"admin"}} , body); }