// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The token's own lifecycle: `auth/token/lookup-self`, `renew-self` and //! `revoke-self`. //! //! A Vault token is leased. It arrives with a TTL, and unless something //! renews it before that TTL runs out the token stops working, taking every //! secret read with it. A short-lived program can ignore this; anything that //! outlives its token's TTL cannot. //! //! `Renewer` is the piece that makes that manageable. It holds the policy — //! when the next renewal is due — and performs it, so the caller only has to //! decide how to wait: //! //! ```zig //! var renewer: vault.token.Renewer = .init(&client, .{}); //! while (true) { //! switch (try renewer.renew()) { //! .renewed => |seconds| try std.Io.sleep(io, .fromSeconds(@intCast(seconds)), .awake), //! .never_expires => break, // nothing to keep alive //! .not_renewable => break, // this token cannot be extended further //! } //! } //! ``` //! //! Renewal never changes the token's id, so `client.token` stays valid //! throughout and no other part of the program needs to be told. const std = @import("std"); const Allocator = std.mem.Allocator; const Client = @import("Client.zig"); pub const Error = Client.Error; pub const RequestError = Client.RequestError || std.json.ParseError(std.json.Scanner); /// What `auth/token/lookup-self` reports about the token in use. Owns the /// parsed JSON; call `deinit`. pub const Lookup = struct { parsed: std.json.Parsed(Envelope), pub const Envelope = struct { data: Info = .{} }; pub const Info = struct { /// The token's own id. Present only for tokens allowed to see it. id: []const u8 = "", /// Stable identifier safe to log and to pass to `auth/token/revoke-accessor`. accessor: []const u8 = "", display_name: []const u8 = "", /// Seconds left before the token expires. Zero for a token that never /// expires, and also for one that just did. ttl: u64 = 0, /// The TTL the token was created with. creation_ttl: u64 = 0, /// Hard ceiling on renewal, if one was set. Zero means the mount's /// default applies instead. explicit_max_ttl: u64 = 0, /// Whether `renew-self` can extend this token at all. renewable: bool = false, /// RFC 3339 timestamp, or null for a token that never expires. expire_time: ?[]const u8 = null, issue_time: []const u8 = "", policies: []const []const u8 = &.{}, /// Remaining uses, or zero for unlimited. num_uses: u64 = 0, orphan: bool = false, /// `service`, `batch`, or `default` on older servers. Batch tokens /// cannot be renewed at all. type: []const u8 = "", path: []const u8 = "", meta: ?std.json.Value = null, }; pub fn deinit(lookup: *Lookup) void { lookup.parsed.deinit(); lookup.* = undefined; } pub fn info(lookup: Lookup) Info { return lookup.parsed.value.data; } /// True for a token with no expiry — a root token, typically. There is /// nothing to renew, and `renew-self` on one fails. pub fn neverExpires(lookup: Lookup) bool { const data = lookup.parsed.value.data; return data.expire_time == null and data.ttl == 0; } }; /// The `auth` block `auth/token/renew-self` answers with. Owns the parsed /// JSON; call `deinit`. pub const Renewal = struct { parsed: std.json.Parsed(Envelope), pub const Envelope = struct { auth: Auth = .{} }; pub const Auth = struct { /// The renewed token's id, which is the same id as before. client_token: []const u8 = "", accessor: []const u8 = "", /// Seconds the token is now good for, counted from this response. lease_duration: u64 = 0, /// Whether it can be renewed again after this. renewable: bool = false, policies: []const []const u8 = &.{}, token_type: []const u8 = "", }; pub fn deinit(renewal: *Renewal) void { renewal.parsed.deinit(); renewal.* = undefined; } pub fn auth(renewal: Renewal) Auth { return renewal.parsed.value.auth; } /// Seconds the token is now good for. pub fn ttl(renewal: Renewal) u64 { return renewal.parsed.value.auth.lease_duration; } }; /// Reads `auth/token/lookup-self`. Any valid token may call this, including /// one with no policies, which makes it the cheapest way to check that a /// token still works. pub fn lookupSelf(client: *Client) RequestError!Lookup { return .{ .parsed = try client.readAs(Lookup.Envelope, "auth/token/lookup-self", null) }; } pub const RenewOptions = struct { /// Seconds of extra life to ask for. Null asks for the token's default /// period, which is what most callers want. Vault treats this as a /// request, not an instruction: it caps the result at the token's maximum /// TTL, so the granted lease may be shorter than asked. increment_s: ?u64 = null, }; /// Extends the current token's lease via `auth/token/renew-self`. /// /// `error.InvalidRequest` here usually means the token is not renewable — a /// batch token, or a root token with no expiry — and `client.last_error` /// carries Vault's wording. Prefer `Renewer`, which checks first and reports /// those cases as values rather than errors. pub fn renewSelf(client: *Client, options: RenewOptions) RequestError!Renewal { const gpa = client.gpa; const body = if (options.increment_s) |seconds| blk: { // Vault's duration parser takes "3600s" as well as a bare number, and // the suffixed form is what the API documents. var buf: [32]u8 = undefined; const increment = std.fmt.bufPrint(&buf, "{d}s", .{seconds}) catch unreachable; break :blk try Client.encodeJson(gpa, .{ .increment = increment }); } else try gpa.dupe(u8, "{}"); defer gpa.free(body); return .{ .parsed = try client.writeAs(Renewal.Envelope, "auth/token/renew-self", body) }; } /// Revokes the current token immediately via `auth/token/revoke-self`. Every /// lease the token created is revoked with it, and the client is left holding /// a token that no longer works. pub fn revokeSelf(client: *Client) Client.RequestError!void { return client.writeDiscard("auth/token/revoke-self", "{}"); } /// Keeps a token alive. /// /// The problem this solves is not "how do I call renew-self" — that is /// `renewSelf` — but "when should I call it, and when should I stop". A /// renewal that fires too late leaves no room to retry, one that fires too /// often wastes requests, and a token that has hit its maximum TTL will keep /// answering renewals with a lease that no longer grows. /// /// `Renewer` holds that policy and performs the renewal; the caller decides /// how to wait. It does no I/O of its own beyond the requests, keeps no /// thread, and is not threadsafe. pub const Renewer = struct { client: *Client, options: Options, /// Seconds the lease was good for as of the last renewal. Zero before the /// first one. lease_s: u64 = 0, /// Whether the last response said the token can be renewed again. renewable: bool = true, pub const Options = struct { /// How much of the lease to let elapse before renewing, as a /// percentage. The default renews at the halfway mark, which leaves /// the whole second half of the lease as room for retries. renew_at_percent: u8 = 50, /// Never wait longer than this between renewals, however long the /// lease. A long lease with a distant renewal is fine until the /// process is suspended or the clock jumps. max_wait_s: u64 = 60 * 60, /// Never renew more often than this, however short the lease, so a /// pathological one-second TTL cannot turn into a request flood. min_wait_s: u64 = 1, /// Passed through to `renewSelf`. increment_s: ?u64 = null, }; /// What the caller should do next. pub const Status = union(enum) { /// The lease was extended. Renew again after this many seconds. renewed: u64, /// The token has no expiry, so there is nothing to keep alive. Stop. never_expires, /// The token cannot be extended any further and will expire when its /// current lease runs out. Whatever issued it has to issue a new one. /// The payload is the seconds left on that final lease. not_renewable: u64, }; pub const RenewError = RequestError; /// Pure; performs no I/O. The first `renew` establishes the state. pub fn init(client: *Client, options: Options) Renewer { return .{ .client = client, .options = options }; } /// Renews now and reports when to come back. /// /// The first call looks the token up first, so that a token which cannot /// be renewed is reported as `.never_expires` or `.not_renewable` rather /// than as the error `renew-self` would raise. pub fn renew(renewer: *Renewer) RenewError!Status { if (renewer.lease_s == 0) { var lookup = try lookupSelf(renewer.client); defer lookup.deinit(); if (lookup.neverExpires()) return .never_expires; const info = lookup.info(); renewer.lease_s = info.ttl; renewer.renewable = info.renewable; if (!info.renewable) return .{ .not_renewable = info.ttl }; } var renewal = try renewSelf(renewer.client, .{ .increment_s = renewer.options.increment_s }); defer renewal.deinit(); const auth = renewal.auth(); renewer.lease_s = auth.lease_duration; renewer.renewable = auth.renewable; // A token at its maximum TTL keeps answering renewals, but the lease // stops growing and eventually reaches zero. Treating that as success // would spin until the token died. if (!auth.renewable or auth.lease_duration == 0) { return .{ .not_renewable = auth.lease_duration }; } return .{ .renewed = renewer.waitSeconds() }; } /// Re-reads the token without renewing it, refreshing the internal state. /// Useful for a first look before deciding whether to run a renewal loop /// at all. pub fn refresh(renewer: *Renewer) RenewError!Status { var lookup = try lookupSelf(renewer.client); defer lookup.deinit(); if (lookup.neverExpires()) return .never_expires; const info = lookup.info(); renewer.lease_s = info.ttl; renewer.renewable = info.renewable; if (!info.renewable) return .{ .not_renewable = info.ttl }; return .{ .renewed = renewer.waitSeconds() }; } /// Seconds to wait before the next renewal, given the current lease. /// Pure, so the policy can be reasoned about without a server. pub fn waitSeconds(renewer: *const Renewer) u64 { return waitFor(renewer.lease_s, renewer.options); } }; /// The renewal policy, factored out so it can be tested directly: take /// `renew_at_percent` of the lease, then clamp into `[min_wait_s, max_wait_s]`. /// The clamp is applied after the percentage so that a lease shorter than /// `min_wait_s` still yields a wait, rather than a busy loop on zero. fn waitFor(lease_s: u64, options: Renewer.Options) u64 { const percent: u64 = @min(options.renew_at_percent, 100); const share = lease_s / 100 * percent + lease_s % 100 * percent / 100; return std.math.clamp(share, options.min_wait_s, @max(options.max_wait_s, options.min_wait_s)); } const testing = std.testing; test "waitFor renews at the halfway mark by default" { const default: Renewer.Options = .{}; try testing.expectEqual(@as(u64, 1800), waitFor(3600, default)); try testing.expectEqual(@as(u64, 30), waitFor(60, default)); } test "waitFor clamps both ends" { const options: Renewer.Options = .{ .min_wait_s = 5, .max_wait_s = 100 }; // A very short lease still yields a wait rather than a spin. try testing.expectEqual(@as(u64, 5), waitFor(2, options)); try testing.expectEqual(@as(u64, 5), waitFor(0, options)); // A very long one is capped, so the loop keeps checking in. try testing.expectEqual(@as(u64, 100), waitFor(60 * 60 * 24, options)); } test "waitFor handles a percentage of a large lease without overflow" { const options: Renewer.Options = .{ .renew_at_percent = 75, .max_wait_s = std.math.maxInt(u64) }; try testing.expectEqual(@as(u64, 300), waitFor(400, options)); // The two-part arithmetic exists so this does not wrap. try testing.expectEqual(@as(u64, 13835058055282163710), waitFor(std.math.maxInt(u64) - 1, options)); } test "waitFor treats a percentage over 100 as 100" { const options: Renewer.Options = .{ .renew_at_percent = 200, .min_wait_s = 1, .max_wait_s = 10_000 }; try testing.expectEqual(@as(u64, 3600), waitFor(3600, options)); } test "Lookup recognizes a token that never expires" { var lookup: Lookup = .{ .parsed = try std.json.parseFromSlice( Lookup.Envelope, testing.allocator, \\{"data":{"id":"hvs.root","accessor":"a1","display_name":"root", \\ "expire_time":null,"ttl":0,"renewable":false,"policies":["root"], \\ "type":"service","num_uses":0}} , .{ .ignore_unknown_fields = true, .allocate = .alloc_always }, ) }; defer lookup.deinit(); try testing.expect(lookup.neverExpires()); try testing.expectEqualStrings("root", lookup.info().policies[0]); } test "Lookup reads a leased, renewable token" { var lookup: Lookup = .{ .parsed = try std.json.parseFromSlice( Lookup.Envelope, testing.allocator, \\{"data":{"id":"hvs.abc","accessor":"a2","display_name":"token", \\ "expire_time":"2026-09-01T12:00:00Z","ttl":2764477,"creation_ttl":2764800, \\ "explicit_max_ttl":0,"renewable":true,"policies":["default","app"], \\ "type":"service","num_uses":0,"orphan":false,"meta":null}} , .{ .ignore_unknown_fields = true, .allocate = .alloc_always }, ) }; defer lookup.deinit(); try testing.expect(!lookup.neverExpires()); try testing.expect(lookup.info().renewable); try testing.expectEqual(@as(u64, 2764477), lookup.info().ttl); try testing.expectEqualStrings("2026-09-01T12:00:00Z", lookup.info().expire_time.?); } test "Renewal reads the auth block" { var renewal: Renewal = .{ .parsed = try std.json.parseFromSlice( Renewal.Envelope, testing.allocator, \\{"auth":{"client_token":"hvs.abc","accessor":"a2","policies":["default"], \\ "lease_duration":3600,"renewable":true,"token_type":"service"}} , .{ .ignore_unknown_fields = true, .allocate = .alloc_always }, ) }; defer renewal.deinit(); try testing.expectEqual(@as(u64, 3600), renewal.ttl()); try testing.expect(renewal.auth().renewable); try testing.expectEqualStrings("hvs.abc", renewal.auth().client_token); }