// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Client for the HashiCorp Vault HTTP API. //! //! This client handles the parts every Vault call needs: authenticating with //! a token, issuing requests against `/v1/...`, and translating Vault's status //! codes and JSON error envelope into Zig errors. Secret-engine specific //! helpers live alongside it in `kv2.zig` and `kv1.zig`. //! //! ```zig //! var client: vault.Client = try .initFromEnv(io, gpa, env_map, .{}); //! defer client.deinit(); //! //! var secret = try vault.kv2.read(&client, "myapp/config", .{}); //! defer secret.deinit(); //! //! const password = secret.getString("password") orelse return error.MissingField; //! ``` const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const Uri = std.Uri; const http = std.http; const Client = @This(); /// Where the Vault CLI looks when `VAULT_ADDR` is unset. pub const default_address = "https://127.0.0.1:8200"; /// File under `$HOME` that the CLI writes on login. OpenBao's `bao` uses the /// same name as HashiCorp's `vault`, so one fallback serves both. /// /// `BAO_TOKEN_PATH` overrides the whole path, not just the directory. pub const token_file_name = ".vault-token"; io: Io, gpa: Allocator, http_client: http.Client, /// Scheme, authority and any path prefix of the Vault server. Its components /// point into `address_buf`. base: Uri, address_buf: []u8, /// Percent-decoded path prefix from the address, without a trailing slash. /// Usually empty; non-empty when Vault sits behind a reverse proxy subpath. prefix: []u8, /// Sent as `X-Vault-Token` on every request. token: ?[]u8, /// Sent as `X-Vault-Namespace`. Vault Enterprise and HCP Vault only. namespace: ?[]u8, /// Server-supplied text for the most recent failed request, joined with "; ". /// Owned by the client and replaced on every request, so copy it if it needs /// to outlive the next call. last_error: ?[]u8, /// Responses larger than this are rejected with `error.ResponseTooLarge`. max_response_bytes: usize, pub const Error = error{ /// No token is configured, `VAULT_TOKEN` is unset, and no token helper /// file was found. MissingToken, /// The configured address is not a usable absolute URL. InvalidAddress, /// 400 — Vault rejected the request as malformed. InvalidRequest, /// 403 — the token is missing, expired, or has no policy granting this /// path. PermissionDenied, /// 404 — nothing is mounted or stored at this path. Vault also answers /// 404 for paths the token is not allowed to know about, so this does not /// prove the secret is absent. SecretNotFound, /// 405 — the mount does not support this operation. UnsupportedOperation, /// 412 — a standby node has not replicated the requested data yet; /// retrying usually succeeds. NotYetReplicated, /// 429 — the node is a standby that cannot serve this request, or the /// request was rate limited. Unavailable, /// 473 — a performance standby could not forward the request. PerformanceStandby, /// 500 — internal Vault error. InternalError, /// 502 — Vault could not reach a backing service. BadGateway, /// 503 — Vault is sealed or otherwise in maintenance. Sealed, /// 3xx — the address points at a node that is redirecting elsewhere, /// typically a standby pointing at the active node. `last_error` names /// the target. Redirects are never followed, because doing so would send /// the token to a host the response chose. Redirected, /// A non-2xx status Vault does not document for the API. UnexpectedStatus, /// The response body exceeded `max_response_bytes`. ResponseTooLarge, /// The response was not the JSON shape the endpoint promises. MalformedResponse, }; pub const Options = struct { /// Base URL of the Vault server, e.g. `https://vault.example.com:8200`. address: []const u8 = default_address, /// Vault token. Without one, every request but the unauthenticated /// health endpoints will be denied. token: ?[]const u8 = null, /// Vault Enterprise / HCP namespace, e.g. `admin/team-a`. namespace: ?[]const u8 = null, max_response_bytes: usize = 4 << 20, /// PEM bundle trusted in addition to the system roots. Mirrors /// `VAULT_CACERT`; needed for the self-signed certificates that private /// Vault clusters usually present. ca_file: ?[]const u8 = null, /// Directory of PEM files, trusted in addition to the system roots. /// Mirrors `VAULT_CAPATH`. ca_dir: ?[]const u8 = null, }; pub const InitError = Error || Allocator.Error || error{ /// A CA file or directory was configured but could not be loaded. CertificateBundleLoadFailure, }; pub const CredentialError = error{ /// `$CREDENTIALS_DIRECTORY` is not set, so nothing passed credentials to /// this process. Either it was not started by systemd, or its unit has no /// `LoadCredential=`, `SetCredential=` or `ImportCredential=`. NoCredentialsDirectory, /// Credentials were passed, but none by that name. Usually a typo in the /// unit, or a name that differs from the one the program asks for. CredentialNotFound, /// The credential exists but could not be read. CredentialUnreadable, /// systemd credential names are single path components. A name with a /// slash in it is rejected rather than followed out of the directory. InvalidCredentialName, }; /// Largest credential this client will read. systemd's own limit is larger; /// this is a guard against being pointed at the wrong file, since an address /// and a token are both tiny. pub const max_credential_bytes = 64 * 1024; pub fn init(io: Io, gpa: Allocator, options: Options) InitError!Client { const address_buf = try gpa.dupe(u8, std.mem.trimEnd(u8, options.address, "/")); errdefer gpa.free(address_buf); var base = Uri.parse(address_buf) catch return error.InvalidAddress; if (base.host == null) return error.InvalidAddress; switch (base.scheme.len) { 4, 5 => if (!std.mem.eql(u8, base.scheme, "http") and !std.mem.eql(u8, base.scheme, "https")) return error.InvalidAddress, else => return error.InvalidAddress, } const prefix = try rawComponentAlloc(gpa, base.path); errdefer gpa.free(prefix); base.path = .empty; base.query = null; base.fragment = null; const token = try dupeOptional(gpa, options.token); errdefer if (token) |t| gpa.free(t); const namespace = try dupeOptional(gpa, options.namespace); errdefer if (namespace) |n| gpa.free(n); var client: Client = .{ .io = io, .gpa = gpa, .http_client = .{ .allocator = gpa, .io = io }, .base = base, .address_buf = address_buf, .prefix = prefix, .token = token, .namespace = namespace, .last_error = null, .max_response_bytes = options.max_response_bytes, }; errdefer client.http_client.deinit(); if (options.ca_file != null or options.ca_dir != null) { try client.loadCaBundle(options.ca_file, options.ca_dir); } return client; } pub const EnvOptions = struct { /// Overrides the environment when non-null. address: ?[]const u8 = null, /// Overrides `VAULT_TOKEN` and the token helper file when non-null. token: ?[]const u8 = null, /// Overrides `VAULT_NAMESPACE` when non-null. namespace: ?[]const u8 = null, max_response_bytes: usize = 4 << 20, /// Fall back to `$HOME/.vault-token` when no token variable is set. This /// is the file `vault login` and `bao login` write. read_token_file: bool = true, }; /// Configures a client the way the `vault` CLI does: `VAULT_ADDR`, /// `VAULT_TOKEN` (falling back to `$HOME/.vault-token`), `VAULT_NAMESPACE`, /// `VAULT_CACERT` and `VAULT_CAPATH`. /// /// OpenBao spells the same settings `BAO_ADDR`, `BAO_TOKEN`, `BAO_NAMESPACE`, /// `BAO_CACERT` and `BAO_CAPATH`, and those are consulted after the `VAULT_` /// ones. A shell that sets both — which is what happens on a machine talking /// to both implementations — keeps the `VAULT_` values, so adding OpenBao /// support cannot change where an existing setup points. /// /// `BAO_TOKEN_PATH` moves the token helper file, which has no `VAULT_` /// counterpart. Left unset, both CLIs write `$HOME/.vault-token`. /// /// A missing token is not an error here — requests will simply be denied — /// so that unauthenticated endpoints remain reachable. pub fn initFromEnv( io: Io, gpa: Allocator, env: *const std.process.Environ.Map, options: EnvOptions, ) InitError!Client { var token_from_file: ?[]u8 = null; defer if (token_from_file) |t| gpa.free(t); const token: ?[]const u8 = options.token orelse firstSet(env, &.{ "VAULT_TOKEN", "BAO_TOKEN" }) orelse blk: { if (!options.read_token_file) break :blk null; token_from_file = tokenFromFile(io, gpa, env); break :blk token_from_file; }; return init(io, gpa, .{ .address = options.address orelse firstSet(env, &.{ "VAULT_ADDR", "BAO_ADDR" }) orelse default_address, .token = token, .namespace = options.namespace orelse firstSet(env, &.{ "VAULT_NAMESPACE", "BAO_NAMESPACE" }), .max_response_bytes = options.max_response_bytes, .ca_file = firstSet(env, &.{ "VAULT_CACERT", "BAO_CACERT" }), .ca_dir = firstSet(env, &.{ "VAULT_CAPATH", "BAO_CAPATH" }), }); } pub const CredentialOptions = struct { /// Credential holding the base URL, spelled as in the unit's /// `LoadCredential=`. Null skips it, leaving `address`. address_credential: ?[]const u8 = "vault-address", /// Credential holding the token. Null skips it, leaving `token`. token_credential: ?[]const u8 = "vault-token", /// Used when `address_credential` is null. address: []const u8 = default_address, /// Used when `token_credential` is null. token: ?[]const u8 = null, /// These have no credential of their own; pass them directly, or read /// them yourself with `readCredential`. namespace: ?[]const u8 = null, max_response_bytes: usize = 4 << 20, ca_file: ?[]const u8 = null, ca_dir: ?[]const u8 = null, }; /// Configures a client from credentials passed by systemd, by default the /// ones named `vault-address` and `vault-token`. /// /// This is the right way to hand a token to a service. An environment /// variable is visible in `/proc//environ` to anyone who can see the /// process and is inherited by every child it spawns; a credential is a file /// in a per-service tmpfs that only that service's user can read. A unit /// gets one with: /// /// ``` /// [Service] /// LoadCredential=vault-token:/etc/myapp/vault-token /// SetCredential=vault-address:https://vault.example.com:8200 /// ``` /// /// A named credential that is not there is an error rather than a silent /// fallback, so a unit with a typo in it fails at startup instead of at the /// first request. To take only the token from a credential, set /// `address_credential` to null and pass `address`. pub fn initFromCredentials( io: Io, gpa: Allocator, env: *const std.process.Environ.Map, options: CredentialOptions, ) (InitError || CredentialError)!Client { var address_bytes: ?[]u8 = null; defer if (address_bytes) |bytes| gpa.free(bytes); var token_bytes: ?[]u8 = null; defer if (token_bytes) |bytes| { std.crypto.secureZero(u8, bytes); gpa.free(bytes); }; if (options.address_credential) |name| { address_bytes = try readCredential(io, gpa, env, name); } if (options.token_credential) |name| { token_bytes = try readCredential(io, gpa, env, name); } const token: ?[]const u8 = if (token_bytes) |bytes| bytes else options.token; return init(io, gpa, .{ .address = if (address_bytes) |bytes| bytes else options.address, .token = token, .namespace = options.namespace, .max_response_bytes = options.max_response_bytes, .ca_file = options.ca_file, .ca_dir = options.ca_dir, }); } /// Reads one credential passed by systemd. The caller owns the result. /// /// Each credential named by the unit lands in its own file under /// `$CREDENTIALS_DIRECTORY`. Surrounding whitespace is trimmed, because /// `LoadCredential=` copies a file verbatim and such files usually end with a /// newline; neither an address nor a token can contain leading or trailing /// whitespace, so nothing is lost. /// /// The bytes read are zeroed before the buffer holding them is freed, so a /// credential does not linger in freed memory. pub fn readCredential( io: Io, gpa: Allocator, env: *const std.process.Environ.Map, name: []const u8, ) (CredentialError || Allocator.Error)![]u8 { const directory = nonEmpty(env.get("CREDENTIALS_DIRECTORY")) orelse return error.NoCredentialsDirectory; if (!isValidCredentialName(name)) return error.InvalidCredentialName; const path = try std.fs.path.join(gpa, &.{ directory, name }); defer gpa.free(path); const contents = Io.Dir.cwd().readFileAlloc( io, path, gpa, .limited(max_credential_bytes), ) catch |err| switch (err) { error.FileNotFound => return error.CredentialNotFound, error.OutOfMemory => |e| return e, else => return error.CredentialUnreadable, }; defer { std.crypto.secureZero(u8, contents); gpa.free(contents); } return gpa.dupe(u8, std.mem.trim(u8, contents, " \t\r\n")); } /// systemd credential names are single path components, so anything that /// could walk out of the credentials directory is refused. fn isValidCredentialName(name: []const u8) bool { if (name.len == 0) return false; if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) return false; return std.mem.findScalar(u8, name, '/') == null; } pub fn deinit(client: *Client) void { const gpa = client.gpa; client.http_client.deinit(); gpa.free(client.address_buf); gpa.free(client.prefix); if (client.token) |t| { std.crypto.secureZero(u8, t); gpa.free(t); } if (client.namespace) |n| gpa.free(n); if (client.last_error) |e| gpa.free(e); client.* = undefined; } /// The server address this client resolved to, with any trailing slash /// removed. Worth asking for after `initFromEnv`, which picks between several /// environment variables and a default. pub fn address(client: *const Client) []const u8 { return client.address_buf; } /// Replaces the token used for subsequent requests. The previous token is /// zeroed before being freed. pub fn setToken(client: *Client, token: ?[]const u8) Allocator.Error!void { const new = try dupeOptional(client.gpa, token); if (client.token) |old| { std.crypto.secureZero(u8, old); client.gpa.free(old); } client.token = new; } /// A response body plus the status it came with. Callers that only want the /// happy path should prefer `readJson`, which checks the status for them. pub const Response = struct { gpa: Allocator, status: http.Status, /// Raw response body; empty for 204 responses. body: []u8, pub fn deinit(response: *Response) void { response.gpa.free(response.body); response.* = undefined; } }; pub const RequestOptions = struct { method: http.Method = .GET, /// API path relative to `/v1/`, e.g. `secret/data/myapp`. A leading slash /// is ignored. Characters that are not legal in a URL path are /// percent-encoded automatically. path: []const u8, /// Raw query string without the leading `?`, e.g. `version=3`. query: ?[]const u8 = null, /// Request body. Sent as `application/json` unless `content_type` says /// otherwise. body: ?[]const u8 = null, /// Overrides the media type of the body. Vault's JSON merge patch /// endpoints require `application/merge-patch+json`. content_type: []const u8 = "application/json", }; pub const RequestError = Error || Allocator.Error || http.Client.RequestError || http.Client.Request.ReceiveHeadError || error{ WriteFailed, ReadFailed, UnsupportedCompressionMethod }; /// Issues a request and returns the body regardless of status. The caller owns /// the result and must call `deinit` on it. pub fn request(client: *Client, options: RequestOptions) RequestError!Response { const gpa = client.gpa; client.clearLastError(); const path = try buildPath(gpa, client.prefix, options.path); defer gpa.free(path); var uri = client.base; uri.path = .{ .raw = path }; if (options.query) |q| uri.query = .{ .raw = q }; var header_storage: [2]http.Header = undefined; var header_count: usize = 0; if (client.token) |t| { header_storage[header_count] = .{ .name = "x-vault-token", .value = t }; header_count += 1; } if (client.namespace) |n| { header_storage[header_count] = .{ .name = "x-vault-namespace", .value = n }; header_count += 1; } var req = try client.http_client.request(options.method, uri, .{ .headers = .{ .content_type = if (options.body != null) .{ .override = options.content_type } else .default, }, // Redirects are surfaced rather than followed. Every request carries // the token, and following a `Location` would hand it to whatever // host the response names. A Vault standby answers 307 with the // active node's address, so `error.Redirected` plus that address in // `last_error` is the useful outcome. .redirect_behavior = .unhandled, .extra_headers = header_storage[0..header_count], }); defer req.deinit(); if (options.body) |body| { req.transfer_encoding = .{ .content_length = body.len }; var body_writer = try req.sendBodyUnflushed(&.{}); try body_writer.writer.writeAll(body); try body_writer.end(); try req.connection.?.flush(); } else { try req.sendBodiless(); } var response = try req.receiveHead(&.{}); // `Response.reader` invalidates the head's string fields, so anything // needed from them has to be copied first. const redirect_location: ?[]u8 = if (isRedirect(response.head.status)) if (response.head.location) |location| try gpa.dupe(u8, location) else null else null; defer if (redirect_location) |location| gpa.free(location); // RFC 9110 §6.4.1: a 1xx, 204 or 304 response carries no body, and neither // does any response to HEAD, whatever the headers say. `std.http` frames // the body from the headers alone, so a 204 that omits content-length — // which is exactly what Vault and OpenBao send for a successful write — // would otherwise be read as "body until the connection closes" and block // until the server hangs up. Rewriting the framing to an explicit zero // length also leaves the connection reusable. if (!statusHasBody(response.head.status) or !options.method.responseHasBody()) { response.head.content_length = 0; response.head.transfer_encoding = .none; response.head.content_encoding = .identity; } const decompress_buffer: []u8 = switch (response.head.content_encoding) { .identity => &.{}, .zstd => try gpa.alloc(u8, std.compress.zstd.default_window_len), .deflate, .gzip => try gpa.alloc(u8, std.compress.flate.max_window_len), .compress => return error.UnsupportedCompressionMethod, }; defer gpa.free(decompress_buffer); var transfer_buffer: [4096]u8 = undefined; var decompress: http.Decompress = undefined; const reader = response.readerDecompressing(&transfer_buffer, &decompress, decompress_buffer); const body = reader.allocRemaining(gpa, .limited(client.max_response_bytes)) catch |err| switch (err) { error.StreamTooLong => return error.ResponseTooLarge, error.ReadFailed => |e| return e, error.OutOfMemory => |e| return e, }; errdefer gpa.free(body); if (@intFromEnum(response.head.status) >= 300) { client.last_error = if (redirect_location) |location| std.fmt.allocPrint(gpa, "redirected to {s}", .{location}) catch null else extractErrors(gpa, body) catch null; } return .{ .gpa = gpa, .status = response.head.status, .body = body }; } /// Issues a request, turns a non-2xx status into a Zig error, and returns the /// body. On error, `client.last_error` holds Vault's explanation if it sent /// one. The caller owns the result and must call `deinit` on it. pub fn requestChecked(client: *Client, options: RequestOptions) RequestError!Response { var response = try client.request(options); errdefer response.deinit(); try statusToError(response.status); return response; } /// `GET /v1/{path}`, parsed into `T`. Unknown fields are ignored, so `T` only /// needs to name the parts of the response the caller cares about. pub fn readAs( client: *Client, comptime T: type, path: []const u8, query: ?[]const u8, ) (RequestError || std.json.ParseError(std.json.Scanner))!std.json.Parsed(T) { var response = try client.requestChecked(.{ .path = path, .query = query }); defer response.deinit(); return std.json.parseFromSlice(T, client.gpa, response.body, .{ .ignore_unknown_fields = true, // The response body is freed as this function returns, so the parsed // value must own its strings rather than point into it. .allocate = .alloc_always, }); } /// `GET /v1/{path}`, parsed as untyped JSON. Useful for endpoints without a /// helper in this library. pub fn read( client: *Client, path: []const u8, query: ?[]const u8, ) (RequestError || std.json.ParseError(std.json.Scanner))!std.json.Parsed(std.json.Value) { return client.readAs(std.json.Value, path, query); } /// Vault's `LIST` verb, expressed as `GET ?list=true` so that it travels /// through proxies that only understand standard HTTP methods. pub fn listAs( client: *Client, comptime T: type, path: []const u8, ) (RequestError || std.json.ParseError(std.json.Scanner))!std.json.Parsed(T) { return client.readAs(T, path, "list=true"); } /// `POST /v1/{path}` with `body` as the payload. The caller owns the result /// and must call `deinit` on it. Vault answers many write endpoints with 204 /// and an empty body, so do not assume the result parses as JSON. pub fn write(client: *Client, path: []const u8, body: []const u8) RequestError!Response { return client.requestChecked(.{ .method = .POST, .path = path, .body = body }); } /// `POST /v1/{path}`, with the response parsed into `T`. Only for endpoints /// that answer 200 with a body; a 204 yields `error.UnexpectedEndOfInput`. pub fn writeAs( client: *Client, comptime T: type, path: []const u8, body: []const u8, ) (RequestError || std.json.ParseError(std.json.Scanner))!std.json.Parsed(T) { var response = try client.write(path, body); defer response.deinit(); return std.json.parseFromSlice(T, client.gpa, response.body, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }); } /// `POST /v1/{path}`, discarding the response body. pub fn writeDiscard(client: *Client, path: []const u8, body: []const u8) RequestError!void { var response = try client.write(path, body); response.deinit(); } /// `DELETE /v1/{path}`, discarding the response body. pub fn delete(client: *Client, path: []const u8) RequestError!void { var response = try client.requestChecked(.{ .method = .DELETE, .path = path }); response.deinit(); } /// Encodes `value` as a JSON payload. Accepts anything `std.json` can /// stringify: a struct literal such as `.{ .password = "hunter2" }`, a /// `std.json.Value`, a map, or a slice of them. The caller owns the result. pub fn encodeJson(gpa: Allocator, value: anytype) Allocator.Error![]u8 { return std.json.Stringify.valueAlloc(gpa, value, .{}); } /// True when the server answers `/v1/sys/health` as an initialized, unsealed, /// active node. Does not require a token. pub fn healthy(client: *Client) RequestError!bool { var response = try client.request(.{ .path = "sys/health" }); defer response.deinit(); return response.status == .ok; } fn loadCaBundle(client: *Client, ca_file: ?[]const u8, ca_dir: ?[]const u8) InitError!void { const gpa = client.gpa; const io = client.io; const now = Io.Clock.real.now(io); var bundle: std.crypto.Certificate.Bundle = .empty; errdefer bundle.deinit(gpa); bundle.rescan(gpa, io, now) catch return error.CertificateBundleLoadFailure; if (ca_file) |file| { bundle.addCertsFromFilePath(gpa, io, now, .cwd(), file) catch return error.CertificateBundleLoadFailure; } if (ca_dir) |dir| { var iterable = Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch return error.CertificateBundleLoadFailure; defer iterable.close(io); bundle.addCertsFromDir(gpa, io, now, iterable) catch return error.CertificateBundleLoadFailure; } client.http_client.ca_bundle.deinit(gpa); client.http_client.ca_bundle = bundle; // Non-null `now` tells `http.Client` the bundle is already populated and // must not be replaced by a system rescan on the first HTTPS request. client.http_client.now = now; } /// Drops the message from the previous failure. Useful before a sequence of /// calls whose errors are deliberately ignored, so that a later report cannot /// quote an unrelated one. pub fn clearLastError(client: *Client) void { if (client.last_error) |e| client.gpa.free(e); client.last_error = null; } fn buildPath(gpa: Allocator, prefix: []const u8, path: []const u8) Allocator.Error![]u8 { const trimmed = std.mem.trimStart(u8, path, "/"); return std.fmt.allocPrint(gpa, "{s}/v1/{s}", .{ prefix, trimmed }); } /// Vault reports failures as `{"errors": ["...", "..."]}`. Warnings and other /// shapes are ignored; a body that is not that envelope yields null. fn extractErrors(gpa: Allocator, body: []const u8) !?[]u8 { const Envelope = struct { errors: []const []const u8 = &.{} }; const parsed = std.json.parseFromSlice(Envelope, gpa, body, .{ .ignore_unknown_fields = true, }) catch return null; defer parsed.deinit(); if (parsed.value.errors.len == 0) return null; var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); // Vault wraps messages as "1 error occurred:\n\t* permission denied\n"; // the surrounding whitespace only makes the output ragged. for (parsed.value.errors, 0..) |message, i| { if (i != 0) out.writer.writeAll("; ") catch return error.OutOfMemory; out.writer.writeAll(std.mem.trim(u8, message, " \t\r\n")) catch return error.OutOfMemory; } return try out.toOwnedSlice(); } pub fn statusToError(status: http.Status) Error!void { return switch (@intFromEnum(status)) { 200...299 => {}, 300...399 => error.Redirected, 400 => error.InvalidRequest, 403 => error.PermissionDenied, 404 => error.SecretNotFound, 405 => error.UnsupportedOperation, 412 => error.NotYetReplicated, 429 => error.Unavailable, 473 => error.PerformanceStandby, 500 => error.InternalError, 502 => error.BadGateway, 503 => error.Sealed, else => error.UnexpectedStatus, }; } /// Reads the token helper file, or returns null when there is none to read. /// A file that is missing, unreadable or empty is not an error: the caller /// simply ends up with no token, and Vault will say so on the first request. fn tokenFromFile(io: Io, gpa: Allocator, env: *const std.process.Environ.Map) ?[]u8 { // OpenBao's BAO_TOKEN_PATH names the file itself, not its directory. if (firstSet(env, &.{"BAO_TOKEN_PATH"})) |path| { return readTokenFile(io, gpa, path) catch null; } const home = nonEmpty(env.get("HOME")) orelse return null; const path = std.fs.path.join(gpa, &.{ home, token_file_name }) catch return null; defer gpa.free(path); return readTokenFile(io, gpa, path) catch null; } fn readTokenFile(io: Io, gpa: Allocator, path: []const u8) ![]u8 { const contents = try Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(64 * 1024)); defer gpa.free(contents); const trimmed = std.mem.trim(u8, contents, " \t\r\n"); if (trimmed.len == 0) return error.EmptyTokenFile; return gpa.dupe(u8, trimmed); } /// Whether a response with this status is allowed to carry a body at all. fn statusHasBody(status: http.Status) bool { return switch (@intFromEnum(status)) { 100...199, 204, 304 => false, else => true, }; } fn isRedirect(status: http.Status) bool { const code = @intFromEnum(status); return code >= 300 and code < 400; } /// Value of the first variable in `names` that is set and not empty. The /// order of `names` is the precedence. fn firstSet(env: *const std.process.Environ.Map, names: []const []const u8) ?[]const u8 { for (names) |name| { if (nonEmpty(env.get(name))) |value| return value; } return null; } fn nonEmpty(value: ?[]const u8) ?[]const u8 { const v = value orelse return null; return if (v.len == 0) null else v; } fn dupeOptional(gpa: Allocator, value: ?[]const u8) Allocator.Error!?[]u8 { return if (value) |v| try gpa.dupe(u8, v) else null; } /// Percent-decodes a URI component into freshly allocated memory. fn rawComponentAlloc(gpa: Allocator, component: Uri.Component) Allocator.Error![]u8 { var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); component.formatRaw(&out.writer) catch return error.OutOfMemory; const slice = try out.toOwnedSlice(); if (slice.len > 0 and slice[slice.len - 1] == '/') { return gpa.realloc(slice, slice.len - 1) catch slice[0 .. slice.len - 1]; } return slice; } test "buildPath joins the /v1 prefix and tolerates a leading slash" { const gpa = std.testing.allocator; const a = try buildPath(gpa, "", "secret/data/app"); defer gpa.free(a); try std.testing.expectEqualStrings("/v1/secret/data/app", a); const b = try buildPath(gpa, "", "/sys/health"); defer gpa.free(b); try std.testing.expectEqualStrings("/v1/sys/health", b); } test "buildPath keeps a reverse-proxy subpath" { const gpa = std.testing.allocator; const path = try buildPath(gpa, "/vault", "secret/data/app"); defer gpa.free(path); try std.testing.expectEqualStrings("/vault/v1/secret/data/app", path); } test "init rejects addresses that are not absolute http(s) URLs" { const gpa = std.testing.allocator; const io = std.Io.Threaded.global_single_threaded.io(); for ([_][]const u8{ "vault.example.com:8200", "ftp://vault.example.com", "" }) |bad| { try std.testing.expectError(error.InvalidAddress, init(io, gpa, .{ .address = bad })); } } test "init normalizes the address into a base URI and path prefix" { const gpa = std.testing.allocator; var client = try init(std.Io.Threaded.global_single_threaded.io(), gpa, .{ .address = "https://vault.example.com:8200/vault/" }); defer client.deinit(); try std.testing.expectEqualStrings("https", client.base.scheme); try std.testing.expectEqual(@as(?u16, 8200), client.base.port); try std.testing.expectEqualStrings("/vault", client.prefix); } test "extractErrors joins Vault's error envelope" { const gpa = std.testing.allocator; const joined = (try extractErrors(gpa, \\{"errors":["permission denied","token expired"]} )).?; defer gpa.free(joined); try std.testing.expectEqualStrings("permission denied; token expired", joined); // Vault's real wire format wraps the message in whitespace. const wrapped = (try extractErrors(gpa, \\{"errors":["1 error occurred:\n\t* permission denied\n"]} )).?; defer gpa.free(wrapped); try std.testing.expectEqualStrings("1 error occurred:\n\t* permission denied", wrapped); try std.testing.expectEqual(@as(?[]u8, null), try extractErrors(gpa, "{\"errors\":[]}")); try std.testing.expectEqual(@as(?[]u8, null), try extractErrors(gpa, "not json")); } test "statusHasBody follows RFC 9110 on bodiless statuses" { try std.testing.expect(!statusHasBody(@enumFromInt(204))); try std.testing.expect(!statusHasBody(@enumFromInt(304))); try std.testing.expect(!statusHasBody(@enumFromInt(100))); try std.testing.expect(statusHasBody(@enumFromInt(200))); try std.testing.expect(statusHasBody(@enumFromInt(403))); } test "statusToError maps the statuses Vault documents" { try statusToError(@enumFromInt(200)); try statusToError(@enumFromInt(204)); try std.testing.expectError(error.PermissionDenied, statusToError(@enumFromInt(403))); try std.testing.expectError(error.SecretNotFound, statusToError(@enumFromInt(404))); try std.testing.expectError(error.Sealed, statusToError(@enumFromInt(503))); try std.testing.expectError(error.Redirected, statusToError(@enumFromInt(307))); try std.testing.expectError(error.UnexpectedStatus, statusToError(@enumFromInt(418))); } test "initFromEnv accepts the BAO_ names OpenBao uses" { const gpa = std.testing.allocator; const io = std.Io.Threaded.global_single_threaded.io(); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try env.put("BAO_ADDR", "http://openbao.example.com:8200"); try env.put("BAO_TOKEN", "bao-token"); var client = try initFromEnv(io, gpa, &env, .{ .read_token_file = false }); defer client.deinit(); try std.testing.expectEqualStrings("openbao.example.com", client.base.host.?.percent_encoded); try std.testing.expectEqualStrings("bao-token", client.token.?); } test "the VAULT_ names win when both are set" { const gpa = std.testing.allocator; const io = std.Io.Threaded.global_single_threaded.io(); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try env.put("VAULT_ADDR", "http://vault.example.com:8200"); try env.put("VAULT_TOKEN", "vault-token"); try env.put("BAO_ADDR", "http://openbao.example.com:8200"); try env.put("BAO_TOKEN", "bao-token"); var client = try initFromEnv(io, gpa, &env, .{ .read_token_file = false }); defer client.deinit(); // Adding OpenBao support must not move an existing setup's target. try std.testing.expectEqualStrings("vault.example.com", client.base.host.?.percent_encoded); try std.testing.expectEqualStrings("vault-token", client.token.?); } test "an empty variable does not shadow the next one" { const gpa = std.testing.allocator; const io = std.Io.Threaded.global_single_threaded.io(); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); // `export VAULT_ADDR=` is a common way to mean "unset", so it must fall // through rather than be taken as an address. try env.put("VAULT_ADDR", ""); try env.put("VAULT_TOKEN", ""); try env.put("BAO_ADDR", "http://openbao.example.com:8200"); try env.put("BAO_TOKEN", "bao-token"); var client = try initFromEnv(io, gpa, &env, .{ .read_token_file = false }); defer client.deinit(); try std.testing.expectEqualStrings("openbao.example.com", client.base.host.?.percent_encoded); try std.testing.expectEqualStrings("bao-token", client.token.?); } test "with nothing set, the address falls back to the documented default" { const gpa = std.testing.allocator; const io = std.Io.Threaded.global_single_threaded.io(); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); var client = try initFromEnv(io, gpa, &env, .{ .read_token_file = false }); defer client.deinit(); try std.testing.expectEqualStrings("127.0.0.1", client.base.host.?.percent_encoded); try std.testing.expectEqualStrings("https", client.base.scheme); try std.testing.expectEqual(@as(?[]u8, null), client.token); } test "firstSet returns the earliest name that has a non-empty value" { const gpa = std.testing.allocator; var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try env.put("SECOND", "b"); try std.testing.expectEqualStrings("b", firstSet(&env, &.{ "FIRST", "SECOND" }).?); try env.put("FIRST", "a"); try std.testing.expectEqualStrings("a", firstSet(&env, &.{ "FIRST", "SECOND" }).?); // An empty value counts as unset, so it does not shadow what follows. try env.put("FIRST", ""); try std.testing.expectEqualStrings("b", firstSet(&env, &.{ "FIRST", "SECOND" }).?); try std.testing.expectEqual(@as(?[]const u8, null), firstSet(&env, &.{"ABSENT"})); } test "the namespace falls back to BAO_NAMESPACE" { const gpa = std.testing.allocator; const io = std.Io.Threaded.global_single_threaded.io(); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try env.put("BAO_NAMESPACE", "team-a"); { var client = try initFromEnv(io, gpa, &env, .{ .read_token_file = false }); defer client.deinit(); try std.testing.expectEqualStrings("team-a", client.namespace.?); } try env.put("VAULT_NAMESPACE", "admin/team-b"); var client = try initFromEnv(io, gpa, &env, .{ .read_token_file = false }); defer client.deinit(); try std.testing.expectEqualStrings("admin/team-b", client.namespace.?); } test "the CA settings fall back to the BAO_ names" { const gpa = std.testing.allocator; const io = std.Io.Threaded.global_single_threaded.io(); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); // With nothing set the trust store is left alone and init succeeds. { var client = try initFromEnv(io, gpa, &env, .{ .read_token_file = false }); client.deinit(); } // Setting it makes the bundle load, and a path that does not exist makes // that fail — which is how we can tell the variable was consulted at all. try env.put("BAO_CACERT", "/nonexistent/ca.pem"); try std.testing.expectError( error.CertificateBundleLoadFailure, initFromEnv(io, gpa, &env, .{ .read_token_file = false }), ); var dir_env: std.process.Environ.Map = .init(gpa); defer dir_env.deinit(); try dir_env.put("BAO_CAPATH", "/nonexistent/ca.d"); try std.testing.expectError( error.CertificateBundleLoadFailure, initFromEnv(io, gpa, &dir_env, .{ .read_token_file = false }), ); } test "BAO_TOKEN_PATH names the token file itself" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); // Surrounding whitespace is what a shell redirect leaves behind, and the // token has to come back without it. try tmp.dir.writeFile(io, .{ .sub_path = "helper-token", .data = " s.from-a-custom-path\n" }); const path = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/helper-token", .{tmp.sub_path}); defer gpa.free(path); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try env.put("BAO_TOKEN_PATH", path); // The custom path wins over $HOME, which is where the file would be // looked for otherwise. try env.put("HOME", "/nonexistent"); var client = try initFromEnv(io, gpa, &env, .{}); defer client.deinit(); try std.testing.expectEqualStrings("s.from-a-custom-path", client.token.?); } test "an explicit token still beats the token file" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(io, .{ .sub_path = "helper-token", .data = "from-file" }); const path = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/helper-token", .{tmp.sub_path}); defer gpa.free(path); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try env.put("BAO_TOKEN_PATH", path); try env.put("BAO_TOKEN", "from-the-environment"); var client = try initFromEnv(io, gpa, &env, .{}); defer client.deinit(); try std.testing.expectEqualStrings("from-the-environment", client.token.?); } /// Builds a stand-in for the directory systemd populates, so the credential /// tests exercise the real file reading. fn testCredentialsDir( gpa: Allocator, env: *std.process.Environ.Map, tmp: *std.testing.TmpDir, ) Allocator.Error!void { const path = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{tmp.sub_path}); defer gpa.free(path); try env.put("CREDENTIALS_DIRECTORY", path); } test "initFromCredentials takes the address and token from systemd credentials" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(io, .{ .sub_path = "vault-address", .data = "http://vault.example.com:8200" }); try tmp.dir.writeFile(io, .{ .sub_path = "vault-token", .data = "s.from-a-credential" }); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try testCredentialsDir(gpa, &env, &tmp); var client = try initFromCredentials(io, gpa, &env, .{}); defer client.deinit(); try std.testing.expectEqualStrings("vault.example.com", client.base.host.?.percent_encoded); try std.testing.expectEqualStrings("s.from-a-credential", client.token.?); } test "a credential written by LoadCredential keeps its trailing newline out of the value" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); // `LoadCredential=` copies the source file verbatim, and a file written by // a shell redirect ends with a newline. try tmp.dir.writeFile(io, .{ .sub_path = "vault-address", .data = "http://vault.example.com:8200\n" }); try tmp.dir.writeFile(io, .{ .sub_path = "vault-token", .data = " s.padded\n" }); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try testCredentialsDir(gpa, &env, &tmp); var client = try initFromCredentials(io, gpa, &env, .{}); defer client.deinit(); try std.testing.expectEqualStrings("vault.example.com", client.base.host.?.percent_encoded); try std.testing.expectEqualStrings("s.padded", client.token.?); } test "credential names can be changed, and skipped one at a time" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(io, .{ .sub_path = "prod-token", .data = "s.prod" }); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try testCredentialsDir(gpa, &env, &tmp); // Only the token comes from a credential; the address is passed directly. var client = try initFromCredentials(io, gpa, &env, .{ .address_credential = null, .address = "http://vault.example.com:8200", .token_credential = "prod-token", }); defer client.deinit(); try std.testing.expectEqualStrings("vault.example.com", client.base.host.?.percent_encoded); try std.testing.expectEqualStrings("s.prod", client.token.?); } test "a missing credential fails loudly instead of falling back" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(io, .{ .sub_path = "vault-address", .data = "http://vault.example.com:8200" }); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try testCredentialsDir(gpa, &env, &tmp); // A unit that names a credential it does not pass is misconfigured, and // should say so at startup rather than at the first denied request. try std.testing.expectError( error.CredentialNotFound, initFromCredentials(io, gpa, &env, .{}), ); } test "without a credentials directory the error names the cause" { const gpa = std.testing.allocator; const io = std.testing.io; var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try std.testing.expectError( error.NoCredentialsDirectory, initFromCredentials(io, gpa, &env, .{}), ); // An empty value is as good as unset. try env.put("CREDENTIALS_DIRECTORY", ""); try std.testing.expectError( error.NoCredentialsDirectory, initFromCredentials(io, gpa, &env, .{}), ); } test "credential names that could escape the directory are refused" { try std.testing.expect(isValidCredentialName("vault-token")); try std.testing.expect(isValidCredentialName("..vault")); try std.testing.expect(!isValidCredentialName("")); try std.testing.expect(!isValidCredentialName(".")); try std.testing.expect(!isValidCredentialName("..")); try std.testing.expect(!isValidCredentialName("../../etc/shadow")); try std.testing.expect(!isValidCredentialName("sub/token")); } test "readCredential reads any credential, not just the two init uses" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(io, .{ .sub_path = "vault-namespace", .data = "admin/team-a\n" }); var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try testCredentialsDir(gpa, &env, &tmp); const namespace = try readCredential(io, gpa, &env, "vault-namespace"); defer gpa.free(namespace); try std.testing.expectEqualStrings("admin/team-a", namespace); try std.testing.expectError( error.InvalidCredentialName, readCredential(io, gpa, &env, "../escape"), ); }