// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Where bwgpg keeps things, and its configuration file. //! //! | | Linux | Windows | //! |---|---|---| //! | config | `$XDG_CONFIG_HOME/bwgpg/config.json`, else `~/.config/…` | `%APPDATA%\bwgpg\config.json` | //! | agent socket | `$XDG_RUNTIME_DIR/bwgpg/agent.sock` | `%LOCALAPPDATA%\bwgpg\agent.sock` | //! | state (`device_id`) | `$XDG_STATE_HOME/bwgpg/`, else `~/.local/state/…` | `%LOCALAPPDATA%\bwgpg\` | //! //! The base directories come from known-folders, which on Windows asks the //! shell for them rather than trusting the environment. Two choices are //! bwgpg's own. The runtime directory on Windows is `%LOCALAPPDATA%` rather //! than known-folders' `%LOCALAPPDATA%\Temp`. The state directory is //! known-folders' `logs`, which is `XDG_STATE_HOME` on Linux, and //! `%LOCALAPPDATA%` on Windows rather than `Temp`, since a device ID has to //! outlive a cleaned-out temporary directory. //! //! On Linux there is no runtime directory without `XDG_RUNTIME_DIR`: it is a //! per-user tmpfs only its owner can enter, and `/tmp` is neither. //! //! `BWGPG_CONFIG`, `BWGPG_RUNTIME_DIR` and `BWGPG_STATE_DIR` override the //! three. That is what the tests use, and what running a second, separate //! agent takes. //! //! The API key's secret is either in the config itself, which must then be //! readable by its owner alone, or in a file of its own named by //! `client_secret_file`. The second is for a config that cannot be private: //! one Home Manager writes, which is a link into the world-readable Nix //! store, with the secret coming from sops-nix or agenix. const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const Io = std.Io; const Environ = std.process.Environ; const known_folders = @import("known-folders"); /// Field names here and in `Config` are the config file's keys, so they keep /// the names they were published with. pub const KeyMapping = struct { /// The key selectors that mean this Secure Note: fingerprints, key IDs, /// emails, as `-u` would be given them. match: []const []const u8, /// The Secure Note's name or ID. item: []const u8, }; pub const Config = struct { /// A self-hosted server's base URL, under which `/identity` and `/api` /// both live. base_url: []const u8, /// Overrides for a server that splits them, as Bitwarden's cloud does. identity_url: ?[]const u8 = null, api_url: ?[]const u8 = null, email: []const u8, client_id: []const u8, /// The API key's secret. Either this or `client_secret_file`. client_secret: ?[]const u8 = null, /// A file holding the API key's secret, which must be readable by its /// owner alone. client_secret_file: ?[]const u8 = null, /// A UUID naming this installation to the server. When not set, one is /// made once and kept in the state directory. device_id: ?[]const u8 = null, /// Optional: pins key selectors to particular Secure Notes. Without it, /// every Secure Note holding a key is searched. keys: []const KeyMapping = &.{}, /// The key selector used when gpg is given no `-u`, as `default-key` in /// gpg.conf is. default_key: ?[]const u8 = null, /// The pinentry program; found on PATH when not set. pinentry: ?[]const u8 = null, /// The real gpg, for passthrough of everything bwgpg does not do itself; /// found on PATH when not set. gpg: ?[]const u8 = null, /// Seconds of disuse after which the agent locks. lock_timeout_secs: u32 = 3600, /// Whether a remote signature, by either route, is confirmed on this /// machine first. `bwgpg remote allow` stops the confirmations for one /// SSH session; this stops them for all. remote_confirm: bool = true, /// The TCP port an agent bwgpg starts itself listens on over the /// tailnet, for remote signing during an SSH session; see /// `agent/tailnet.zig`. Off when not set. Under systemd, /// `bwgpg-agent-tailnet.socket` listens instead, and this, or 7743 when /// it is not set, is the port `bwgpg remote pair` tells the remote /// machine. tailnet_port: ?u16 = null, /// Permits a plain `http://` server, which the tests need and nothing /// else should. allow_insecure_http: bool = false, }; pub const Error = error{ /// There is no environment variable to put the directory under. NoHomeDirectory, /// No config file: `bwgpg login` has not been run. NotConfigured, /// The config file is readable by others (Linux). InsecurePermissions, /// The config file is not valid. InvalidConfig, /// Neither `client_secret` nor `client_secret_file` is set, or the file /// cannot be read or is empty. NoClientSecret, }; const is_windows = builtin.os.tag == .windows; /// `/bwgpg/`, where `base` is the known folder. fn under( gpa: Allocator, io: Io, env: *const Environ.Map, folder: known_folders.KnownFolder, leaf: ?[]const u8, ) (Error || Allocator.Error)![]u8 { const base = known_folders.getPath(io, gpa, env, folder) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.Canceled => return error.NoHomeDirectory, } orelse return error.NoHomeDirectory; defer gpa.free(base); return if (leaf) |l| std.fs.path.join(gpa, &.{ base, "bwgpg", l }) else std.fs.path.join(gpa, &.{ base, "bwgpg" }); } /// The path of the config file. pub fn configPath(gpa: Allocator, io: Io, env: *const Environ.Map) (Error || Allocator.Error)![]u8 { if (env.get("BWGPG_CONFIG")) |p| return gpa.dupe(u8, p); return under(gpa, io, env, .roaming_configuration, "config.json"); } /// The directory holding the agent's socket. pub fn runtimeDir(gpa: Allocator, io: Io, env: *const Environ.Map) (Error || Allocator.Error)![]u8 { if (env.get("BWGPG_RUNTIME_DIR")) |p| return gpa.dupe(u8, p); return under(gpa, io, env, if (is_windows) .local_configuration else .runtime, null); } /// The directory for what bwgpg keeps between runs: the device ID. pub fn stateDir(gpa: Allocator, io: Io, env: *const Environ.Map) (Error || Allocator.Error)![]u8 { if (env.get("BWGPG_STATE_DIR")) |p| return gpa.dupe(u8, p); return under(gpa, io, env, if (is_windows) .local_configuration else .logs, null); } pub fn socketPath(gpa: Allocator, io: Io, env: *const Environ.Map) (Error || Allocator.Error)![]u8 { const dir = try runtimeDir(gpa, io, env); defer gpa.free(dir); return std.fs.path.join(gpa, &.{ dir, "agent.sock" }); } /// Creates `path` and its parents, the last one readable only by its owner. pub fn makePrivateDir(io: Io, path: []const u8) !void { const cwd = Io.Dir.cwd(); if (std.fs.path.dirname(path)) |parent| try cwd.createDirPath(io, parent); cwd.createDir(io, path, privateDirPermissions()) catch |err| switch (err) { error.PathAlreadyExists => {}, else => return err, }; if (!is_windows) { // An existing directory may have been made with a looser mode. Opened // for iteration because the default is an O_PATH handle, which // fchmod refuses. var dir = try cwd.openDir(io, path, .{ .iterate = true }); defer dir.close(io); try dir.setPermissions(io, privateDirPermissions()); } } fn privateDirPermissions() Io.File.Permissions { return if (is_windows) .default_dir else .fromMode(0o700); } fn privateFilePermissions() Io.File.Permissions { return if (is_windows) .default_file else .fromMode(0o600); } /// Whether `path` can be read by anyone but its owner. Always false on /// Windows, where the directories bwgpg uses are private already. pub fn readableByOthers(io: Io, path: []const u8) error{NotFound}!bool { if (is_windows) return false; const stat = Io.Dir.cwd().statFile(io, path, .{}) catch return error.NotFound; return stat.permissions.toMode() & 0o077 != 0; } /// Loads the config. It must be private if it holds the secret itself; one /// that names a secret file need not be. pub fn load(gpa: Allocator, io: Io, path: []const u8) (Error || Allocator.Error)!std.json.Parsed(Config) { const cwd = Io.Dir.cwd(); const public = readableByOthers(io, path) catch return error.NotConfigured; const text = cwd.readFileAlloc(io, path, gpa, .limited(1 << 20)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return error.NotConfigured, }; defer { std.crypto.secureZero(u8, text); gpa.free(text); } const parsed = std.json.parseFromSlice(Config, gpa, text, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }) catch |err| return switch (err) { error.OutOfMemory => error.OutOfMemory, else => error.InvalidConfig, }; if (public and parsed.value.client_secret != null) { parsed.deinit(); return error.InsecurePermissions; } return parsed; } /// The API key's secret, from the config or from its file. The caller wipes /// and frees it. pub fn clientSecret(gpa: Allocator, io: Io, config: *const Config) (Error || Allocator.Error)![]u8 { if (config.client_secret) |s| return gpa.dupe(u8, s); const path = config.client_secret_file orelse return error.NoClientSecret; if (readableByOthers(io, path) catch return error.NoClientSecret) return error.InsecurePermissions; const text = Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(4096)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return error.NoClientSecret, }; defer { std.crypto.secureZero(u8, text); gpa.free(text); } const secret = std.mem.trim(u8, text, " \t\r\n"); if (secret.len == 0) return error.NoClientSecret; return gpa.dupe(u8, secret); } /// The device ID: the config's, or the one kept in the state directory, /// made the first time it is asked for. pub fn deviceId(gpa: Allocator, io: Io, env: *const Environ.Map, config: *const Config) ![]u8 { if (config.device_id) |d| return gpa.dupe(u8, d); const dir = try stateDir(gpa, io, env); defer gpa.free(dir); const path = try std.fs.path.join(gpa, &.{ dir, "device_id" }); defer gpa.free(path); const cwd = Io.Dir.cwd(); if (cwd.readFileAlloc(io, path, gpa, .limited(256))) |text| { defer gpa.free(text); const id = std.mem.trim(u8, text, " \t\r\n"); if (id.len > 0) return gpa.dupe(u8, id); } else |_| {} const id = try newUuid(gpa, io); errdefer gpa.free(id); try makePrivateDir(io, dir); var file = try cwd.createFile(io, path, .{}); defer file.close(io); var w = file.writer(io, &.{}); try w.interface.print("{s}\n", .{id}); return id; } /// A random (version 4) UUID. pub fn newUuid(gpa: Allocator, io: Io) Allocator.Error![]u8 { var b: [16]u8 = undefined; io.random(&b); b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80; const h = std.fmt.bytesToHex(b, .lower); return std.fmt.allocPrint(gpa, "{s}-{s}-{s}-{s}-{s}", .{ h[0..8], h[8..12], h[12..16], h[16..20], h[20..32] }); } pub fn save(gpa: Allocator, io: Io, path: []const u8, config: Config) !void { try savePrivate(gpa, io, path, config); } /// Writes `value` to `path` as JSON, readable by its owner alone, making /// its directory if need be. The text is wiped once written, since it may /// hold a secret. pub fn savePrivate(gpa: Allocator, io: Io, path: []const u8, value: anytype) !void { if (std.fs.path.dirname(path)) |dir| try makePrivateDir(io, dir); const text = try std.json.Stringify.valueAlloc(gpa, value, .{ .whitespace = .indent_2 }); defer { std.crypto.secureZero(u8, text); gpa.free(text); } var file = try Io.Dir.cwd().createFile(io, path, .{ .permissions = privateFilePermissions() }); defer file.close(io); if (!is_windows) try file.setPermissions(io, privateFilePermissions()); var buf: [1024]u8 = undefined; var w = file.writer(io, &buf); try w.interface.writeAll(text); try w.interface.writeByte('\n'); try w.interface.flush(); } /// Whether `a` and `b` name the same key: equal ignoring case, a leading /// `0x` and a trailing `!`. pub fn sameSelector(a: []const u8, b: []const u8) bool { return std.ascii.eqlIgnoreCase(normalize(a), normalize(b)); } fn normalize(s: []const u8) []const u8 { var r = std.mem.trim(u8, s, " \t"); if (std.mem.endsWith(u8, r, "!")) r = r[0 .. r.len - 1]; if (std.ascii.startsWithIgnoreCase(r, "0x")) r = r[2..]; return r; } /// The Secure Note the config pins the key selector `selector` to, if any. pub fn noteFor(config: *const Config, selector: ?[]const u8) ?[]const u8 { const sel = selector orelse return null; for (config.keys) |mapping| { for (mapping.match) |m| { if (sameSelector(m, sel)) return mapping.item; } } return null; } test "key selectors compare the way gpg reads them" { try std.testing.expect(sameSelector("0xABCDEF0123456789", "abcdef0123456789!")); try std.testing.expect(!sameSelector("ABCD", "ABCE")); const config: Config = .{ .base_url = "", .email = "", .client_id = "", .client_secret = "", .device_id = "", .keys = &.{.{ .match = &.{ "jeff@example.org", "0x1BB9EB7EA602265B" }, .item = "gpg key" }}, }; try std.testing.expectEqualStrings("gpg key", noteFor(&config, "1bb9eb7ea602265b").?); try std.testing.expectEqual(@as(?[]const u8, null), noteFor(&config, "other")); try std.testing.expectEqual(@as(?[]const u8, null), noteFor(&config, null)); } test "a config round trips through a private file" { const io = std.testing.io; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const base = try tmp.dir.realPathFileAlloc(io, ".", gpa); defer gpa.free(base); const path = try std.fs.path.join(gpa, &.{ base, "sub", "config.json" }); defer gpa.free(path); try save(gpa, io, path, .{ .base_url = "https://vault.example.org", .email = "a@example.org", .client_id = "user.x", .client_secret = "s", .device_id = "d", .default_key = "ABCD", }); const loaded = try load(gpa, io, path); defer loaded.deinit(); try std.testing.expectEqualStrings("https://vault.example.org", loaded.value.base_url); try std.testing.expectEqualStrings("ABCD", loaded.value.default_key.?); try std.testing.expectEqual(@as(u32, 3600), loaded.value.lock_timeout_secs); if (!is_windows) { var file = try Io.Dir.cwd().openFile(io, path, .{}); try file.setPermissions(io, .fromMode(0o644)); file.close(io); try std.testing.expectError(error.InsecurePermissions, load(gpa, io, path)); } } test "the secret from a file, a public config, and a kept device ID" { const io = std.testing.io; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const base = try tmp.dir.realPathFileAlloc(io, ".", gpa); defer gpa.free(base); const secret_path = try std.fs.path.join(gpa, &.{ base, "secret" }); defer gpa.free(secret_path); { var f = try Io.Dir.cwd().createFile(io, secret_path, .{ .permissions = privateFilePermissions() }); defer f.close(io); var w = f.writer(io, &.{}); try w.interface.writeAll(" s3cret\n"); } // A config naming the file may be readable by anyone, as a link into // the Nix store is. const path = try std.fs.path.join(gpa, &.{ base, "config.json" }); defer gpa.free(path); { var f = try Io.Dir.cwd().createFile(io, path, .{}); defer f.close(io); var w = f.writer(io, &.{}); // Through the JSON encoder: a Windows path is full of backslashes. try w.interface.print( \\{{"base_url":"https://v.example","email":"a@b","client_id":"user.x","client_secret_file":{f}}} , .{std.json.fmt(secret_path, .{})}); if (!is_windows) try f.setPermissions(io, .fromMode(0o644)); } const loaded = try load(gpa, io, path); defer loaded.deinit(); const secret = try clientSecret(gpa, io, &loaded.value); defer gpa.free(secret); try std.testing.expectEqualStrings("s3cret", secret); // The secret file itself has to be private. if (!is_windows) { var f = try Io.Dir.cwd().openFile(io, secret_path, .{}); try f.setPermissions(io, .fromMode(0o644)); f.close(io); try std.testing.expectError(error.InsecurePermissions, clientSecret(gpa, io, &loaded.value)); } // The device ID is made once, then read back. var env: Environ.Map = .init(gpa); defer env.deinit(); try env.put("BWGPG_STATE_DIR", base); const first = try deviceId(gpa, io, &env, &loaded.value); defer gpa.free(first); const second = try deviceId(gpa, io, &env, &loaded.value); defer gpa.free(second); try std.testing.expectEqual(@as(usize, 36), first.len); try std.testing.expectEqualStrings(first, second); } test "directories come from known-folders, under bwgpg" { if (is_windows) return error.SkipZigTest; const io = std.testing.io; const gpa = std.testing.allocator; var env: Environ.Map = .init(gpa); defer env.deinit(); try env.put("HOME", "/home/alice"); // The XDG defaults, and no runtime directory without XDG_RUNTIME_DIR. const config = try configPath(gpa, io, &env); defer gpa.free(config); try std.testing.expectEqualStrings("/home/alice/.config/bwgpg/config.json", config); const state = try stateDir(gpa, io, &env); defer gpa.free(state); try std.testing.expectEqualStrings("/home/alice/.local/state/bwgpg", state); try std.testing.expectError(error.NoHomeDirectory, runtimeDir(gpa, io, &env)); // The XDG variables, when set. try env.put("XDG_CONFIG_HOME", "/cfg"); try env.put("XDG_STATE_HOME", "/state"); try env.put("XDG_RUNTIME_DIR", "/run/user/1000"); const config2 = try configPath(gpa, io, &env); defer gpa.free(config2); try std.testing.expectEqualStrings("/cfg/bwgpg/config.json", config2); const state2 = try stateDir(gpa, io, &env); defer gpa.free(state2); try std.testing.expectEqualStrings("/state/bwgpg", state2); const socket = try socketPath(gpa, io, &env); defer gpa.free(socket); try std.testing.expectEqualStrings("/run/user/1000/bwgpg/agent.sock", socket); // And bwgpg's own overrides above them all. try env.put("BWGPG_CONFIG", "/tmp/c.json"); const config3 = try configPath(gpa, io, &env); defer gpa.free(config3); try std.testing.expectEqualStrings("/tmp/c.json", config3); }