// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Fills an empty Vaultwarden with what bwgpg needs, for the end-to-end //! tests: an account, a personal API key, and a Secure Note holding an //! OpenPGP secret key. Then writes a bwgpg config pointing at all of it. //! //! It does what a Bitwarden client does on registration -- derive the master //! key, make a user key and wrap it, hash the password for the server -- with //! bwgpg's own crypto, so a round trip through the server also checks that //! bwgpg encrypts the way it decrypts. The key note is stored with an item //! key of its own, which current clients make for every new item, and beside //! it an ordinary note that bwgpg has to pass over. //! //! usage: bwgpg-fixture //! [pbkdf2|argon2id] const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const bwgpg = @import("bwgpg"); const crypto = bwgpg.bw.crypto; const json = bwgpg.bw.json_util; fn fail(comptime fmt: []const u8, args: anytype) noreturn { std.debug.print("bwgpg-fixture: " ++ fmt ++ "\n", args); std.process.exit(1); } const Http = struct { gpa: Allocator, client: std.http.Client, fn call(h: *Http, method: std.http.Method, url: []const u8, body: ?[]const u8, content_type: []const u8, bearer: ?[]const u8) !std.json.Parsed(std.json.Value) { var out: Io.Writer.Allocating = .init(h.gpa); defer out.deinit(); var auth_buf: [4096]u8 = undefined; const res = try h.client.fetch(.{ .location = .{ .url = url }, .method = method, .payload = body, .headers = .{ .content_type = .{ .override = content_type }, .authorization = if (bearer) |b| .{ .override = try std.fmt.bufPrint(&auth_buf, "Bearer {s}", .{b}) } else .default, }, .extra_headers = &.{ .{ .name = "Device-Type", .value = "25" }, .{ .name = "Bitwarden-Client-Name", .value = "cli" }, .{ .name = "Bitwarden-Client-Version", .value = "2025.1.0" }, }, .response_writer = &out.writer, }); if (res.status.class() != .success) { fail("{s} {s}: {d} {s}", .{ @tagName(method), url, @backingInt(res.status), out.written() }); } const text = if (out.written().len == 0) "{}" else out.written(); return std.json.parseFromSlice(std.json.Value, h.gpa, text, .{}); } }; fn b64(gpa: Allocator, bytes: []const u8) ![]u8 { const enc = std.base64.standard.Encoder; const out = try gpa.alloc(u8, enc.calcSize(bytes.len)); return @constCast(enc.encode(out, bytes)); } fn uuid(gpa: Allocator, io: Io) ![]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] }); } fn formEncode(gpa: Allocator, fields: []const [2][]const u8) ![]u8 { var out: Io.Writer.Allocating = .init(gpa); for (fields, 0..) |f, i| { if (i > 0) try out.writer.writeByte('&'); try out.writer.writeAll(f[0]); try out.writer.writeByte('='); try std.Uri.Component.percentEncode(&out.writer, f[1], struct { fn ok(c: u8) bool { return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; } }.ok); } return out.toOwnedSlice(); } pub fn main(init: std.process.Init) !void { var arena_state: std.heap.ArenaAllocator = .init(init.gpa); defer arena_state.deinit(); const gpa = arena_state.allocator(); const io = init.io; const args = try init.minimal.args.toSlice(gpa); if (args.len < 7) fail("usage: bwgpg-fixture [pbkdf2|argon2id]", .{}); const server = std.mem.trimEnd(u8, args[1], "/"); const email = args[2]; const password = args[3]; const key_text = try Io.Dir.cwd().readFileAlloc(io, args[4], gpa, .limited(1 << 20)); const config_path = args[5]; const pinentry = args[6]; const use_argon2 = args.len > 7 and std.mem.eql(u8, args[7], "argon2id"); const kdf: crypto.Kdf = if (use_argon2) .{ .argon2id = .{ .iterations = 3, .memory_mib = 64, .parallelism = 4 } } else .{ .pbkdf2 = .{ .iterations = 600000 } }; // What a client does on registration. const master = try crypto.masterKey(gpa, io, password, email, kdf); const stretched = crypto.stretch(master); var user_key_bytes: [64]u8 = undefined; io.random(&user_key_bytes); const user_key = try crypto.SymmetricKey.fromBytes(&user_key_bytes); var iv: [16]u8 = undefined; io.random(&iv); const protected = try crypto.encrypt(gpa, &stretched, iv, &user_key_bytes); var hash: [32]u8 = undefined; try std.crypto.pwhash.pbkdf2(&hash, &master, password, 1, std.crypto.auth.hmac.sha2.HmacSha256); const password_hash = try b64(gpa, &hash); var http: Http = .{ .gpa = gpa, .client = .{ .allocator = gpa, .io = io } }; const kdf_type: u8, const iterations: u32, const memory: ?u32, const parallelism: ?u32 = switch (kdf) { .pbkdf2 => |p| .{ 0, p.iterations, null, null }, .argon2id => |a| .{ 1, a.iterations, a.memory_mib, a.parallelism }, }; const register_body = try std.json.Stringify.valueAlloc(gpa, .{ .email = email, .name = "bwgpg test", .masterPasswordHash = password_hash, .masterPasswordHint = @as(?[]const u8, null), .key = protected, .kdf = kdf_type, .kdfIterations = iterations, .kdfMemory = memory, .kdfParallelism = parallelism, }, .{}); _ = try http.call(.POST, try std.fmt.allocPrint(gpa, "{s}/identity/accounts/register", .{server}), register_body, "application/json", null); // Log in with the password, as the web vault would, to make an API key. const device = try uuid(gpa, io); const form = try formEncode(gpa, &.{ .{ "grant_type", "password" }, .{ "username", email }, .{ "password", password_hash }, .{ "scope", "api offline_access" }, .{ "client_id", "web" }, .{ "deviceType", "25" }, .{ "deviceIdentifier", device }, .{ "deviceName", "bwgpg-fixture" }, }); const token = try http.call(.POST, try std.fmt.allocPrint(gpa, "{s}/identity/connect/token", .{server}), form, "application/x-www-form-urlencoded", null); const access = json.getString(token.value, "access_token") orelse fail("no access token", .{}); const profile = try http.call(.GET, try std.fmt.allocPrint(gpa, "{s}/api/accounts/profile", .{server}), null, "application/json", access); const user_id = json.getString(profile.value, "id") orelse fail("no user id", .{}); const api_key_body = try std.json.Stringify.valueAlloc(gpa, .{ .masterPasswordHash = password_hash }, .{}); const api_key = try http.call(.POST, try std.fmt.allocPrint(gpa, "{s}/api/accounts/api-key", .{server}), api_key_body, "application/json", access); const client_secret = json.getString(api_key.value, "apiKey") orelse fail("no api key", .{}); // The key note, under an item key of its own. var item_key_bytes: [64]u8 = undefined; io.random(&item_key_bytes); const item_key = try crypto.SymmetricKey.fromBytes(&item_key_bytes); io.random(&iv); const wrapped_item_key = try crypto.encrypt(gpa, &user_key, iv, &item_key_bytes); io.random(&iv); const name = try crypto.encrypt(gpa, &item_key, iv, "OpenPGP signing key"); io.random(&iv); const notes = try crypto.encrypt(gpa, &item_key, iv, key_text); const ciphers_url = try std.fmt.allocPrint(gpa, "{s}/api/ciphers", .{server}); _ = try http.call(.POST, ciphers_url, try std.json.Stringify.valueAlloc(gpa, .{ .type = 2, .key = wrapped_item_key, .name = name, .notes = notes, .secureNote = .{ .type = 0 }, .favorite = false, .reprompt = 0, }, .{}), "application/json", access); // And an ordinary note, under the user key, to be passed over. io.random(&iv); const other_name = try crypto.encrypt(gpa, &user_key, iv, "wifi password"); io.random(&iv); const other_notes = try crypto.encrypt(gpa, &user_key, iv, "hunter2"); _ = try http.call(.POST, ciphers_url, try std.json.Stringify.valueAlloc(gpa, .{ .type = 2, .name = other_name, .notes = other_notes, .secureNote = .{ .type = 0 }, .favorite = false, .reprompt = 0, }, .{}), "application/json", access); try bwgpg.config.save(gpa, io, config_path, .{ .base_url = server, .email = email, .client_id = try std.fmt.allocPrint(gpa, "user.{s}", .{user_id}), .client_secret = client_secret, .device_id = try uuid(gpa, io), .pinentry = pinentry, .allow_insecure_http = true, }); std.debug.print("bwgpg-fixture: {s} registered, key stored, config at {s}\n", .{ email, config_path }); }