//! Key Pinning / TOFU (Trust On First Use) //! //! Provides security against MITM attacks by remembering peer public keys //! and detecting when they change unexpectedly. //! //! Modes: //! - TOFU: Trust the first key seen from a peer, alert on changes //! - Strict: Only allow connections to pre-configured known peers //! - Disabled: No key pinning (legacy behavior) //! //! Key changes can be legitimate (peer regenerated keys) or malicious (MITM). //! The application should handle key mismatch events appropriately. const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const Blake2b256 = std.crypto.hash.blake2.Blake2b256; const timingSafeEql = std.crypto.timing_safe.eql; /// Key pinning errors pub const Error = error{ /// Peer's key doesn't match the pinned key (potential MITM) KeyMismatch, /// Peer not in allowed list (strict mode) UnknownPeer, /// Storage is full StorageFull, /// Persistence error PersistenceError, /// Out of memory OutOfMemory, }; /// Key pinning mode pub const PinningMode = enum { /// No key pinning - accept any key disabled, /// Trust On First Use - pin first seen key, alert on changes tofu, /// Strict - only allow pre-configured known peers strict, }; /// Result of key verification pub const VerifyResult = enum { /// Key matches pinned key verified, /// First time seeing this peer (TOFU mode) first_use, /// Key changed from previously pinned key key_changed, /// Peer not in allowed list (strict mode) unknown_peer, }; /// Information about a pinned key pub const PinnedKey = struct { /// The peer's Noise public key (X25519) public_key: [32]u8, /// When the key was first seen (unix timestamp) first_seen: i64, /// When the key was last verified (unix timestamp) last_seen: i64, /// Number of successful verifications verification_count: u64, /// Optional human-readable label for this peer label: ?[]const u8, /// Whether this key was pre-configured (not learned via TOFU) preconfigured: bool, pub fn deinit(self: *PinnedKey, allocator: Allocator) void { if (self.label) |l| { allocator.free(l); } } }; /// Peer identifier for the key store (derived from public key) pub const PeerFingerprint = [32]u8; /// Compute fingerprint from public key pub fn fingerprintFromPublicKey(public_key: [32]u8) PeerFingerprint { var result: [32]u8 = undefined; Blake2b256.hash(&public_key, &result, .{}); return result; } /// Key Pin Store /// /// Thread-safe storage for pinned peer public keys. /// Supports TOFU (Trust On First Use) and strict pinning modes. pub const KeyPinStore = struct { allocator: Allocator, /// Pinned keys indexed by fingerprint keys: std.AutoHashMap(PeerFingerprint, PinnedKey), /// Mutex for thread safety mutex: std.Thread.Mutex, /// Maximum number of pinned keys (0 = unlimited) max_keys: usize, /// Current pinning mode mode: PinningMode, /// Callback for key change events on_key_change: ?*const fn (fingerprint: PeerFingerprint, old_key: [32]u8, new_key: [32]u8) void, const Self = @This(); /// Initialize key pin store pub fn init(allocator: Allocator, mode: PinningMode) Self { return Self{ .allocator = allocator, .keys = std.AutoHashMap(PeerFingerprint, PinnedKey).init(allocator), .mutex = .{}, .max_keys = 10000, // Default limit .mode = mode, .on_key_change = null, }; } /// Initialize with custom settings pub fn initWithConfig(allocator: Allocator, mode: PinningMode, max_keys: usize) Self { var store = init(allocator, mode); store.max_keys = max_keys; return store; } /// Clean up resources pub fn deinit(self: *Self) void { self.mutex.lock(); defer self.mutex.unlock(); var iter = self.keys.iterator(); while (iter.next()) |entry| { var pinned = entry.value_ptr; pinned.deinit(self.allocator); } self.keys.deinit(); } /// Verify a peer's public key /// /// Returns the verification result and optionally pins the key (TOFU mode). pub fn verifyKey(self: *Self, public_key: [32]u8) Error!VerifyResult { if (self.mode == .disabled) { return .verified; } const fingerprint = fingerprintFromPublicKey(public_key); self.mutex.lock(); defer self.mutex.unlock(); if (self.keys.get(fingerprint)) |*pinned| { // We've seen this fingerprint before // Using constant-time comparison to prevent timing side-channel attacks if (timingSafeEql([32]u8, pinned.public_key, public_key)) { // Key matches - update last seen var entry = self.keys.getPtr(fingerprint).?; entry.last_seen = std.time.timestamp(); entry.verification_count += 1; return .verified; } else { // Key mismatch! This is suspicious // Note: This shouldn't happen with fingerprint-based lookup // unless there's a hash collision (extremely unlikely) return .key_changed; } } else { // First time seeing this peer if (self.mode == .strict) { return .unknown_peer; } // TOFU mode - pin the key if (self.max_keys > 0 and self.keys.count() >= self.max_keys) { return Error.StorageFull; } const now = std.time.timestamp(); self.keys.put(fingerprint, PinnedKey{ .public_key = public_key, .first_seen = now, .last_seen = now, .verification_count = 1, .label = null, .preconfigured = false, }) catch return Error.OutOfMemory; return .first_use; } } /// Verify and handle key change scenario /// /// For peers identified by a stable ID (like network address or peer ID), /// this checks if their key has changed since last connection. pub fn verifyPeerKey(self: *Self, peer_id: [32]u8, public_key: [32]u8) Error!VerifyResult { if (self.mode == .disabled) { return .verified; } self.mutex.lock(); defer self.mutex.unlock(); // Use peer_id as the lookup key (not fingerprint of public key) // This allows detecting key changes for the same peer if (self.keys.get(peer_id)) |pinned| { // Using constant-time comparison to prevent timing side-channel attacks if (timingSafeEql([32]u8, pinned.public_key, public_key)) { // Key matches - update last seen var entry = self.keys.getPtr(peer_id).?; entry.last_seen = std.time.timestamp(); entry.verification_count += 1; return .verified; } else { // Key changed! if (self.on_key_change) |callback| { callback(peer_id, pinned.public_key, public_key); } return .key_changed; } } else { // First time seeing this peer if (self.mode == .strict) { return .unknown_peer; } // TOFU mode - pin the key if (self.max_keys > 0 and self.keys.count() >= self.max_keys) { return Error.StorageFull; } const now = std.time.timestamp(); self.keys.put(peer_id, PinnedKey{ .public_key = public_key, .first_seen = now, .last_seen = now, .verification_count = 1, .label = null, .preconfigured = false, }) catch return Error.OutOfMemory; return .first_use; } } /// Pre-configure a known peer (for strict mode or known peers) pub fn pinKey(self: *Self, peer_id: [32]u8, public_key: [32]u8, label: ?[]const u8) Error!void { self.mutex.lock(); defer self.mutex.unlock(); if (self.max_keys > 0 and self.keys.count() >= self.max_keys) { return Error.StorageFull; } var owned_label: ?[]u8 = null; if (label) |l| { owned_label = self.allocator.dupe(u8, l) catch return Error.OutOfMemory; } const now = std.time.timestamp(); self.keys.put(peer_id, PinnedKey{ .public_key = public_key, .first_seen = now, .last_seen = now, .verification_count = 0, .label = owned_label, .preconfigured = true, }) catch { if (owned_label) |l| self.allocator.free(l); return Error.OutOfMemory; }; } /// Remove a pinned key pub fn unpinKey(self: *Self, peer_id: [32]u8) bool { self.mutex.lock(); defer self.mutex.unlock(); if (self.keys.fetchRemove(peer_id)) |entry| { var pinned = entry.value; pinned.deinit(self.allocator); return true; } return false; } /// Update a peer's key (after user confirms key change is legitimate) pub fn updateKey(self: *Self, peer_id: [32]u8, new_public_key: [32]u8) Error!void { self.mutex.lock(); defer self.mutex.unlock(); if (self.keys.getPtr(peer_id)) |entry| { entry.public_key = new_public_key; entry.last_seen = std.time.timestamp(); entry.verification_count = 1; } else { return Error.UnknownPeer; } } /// Get information about a pinned key pub fn getPinnedKey(self: *Self, peer_id: [32]u8) ?PinnedKey { self.mutex.lock(); defer self.mutex.unlock(); return self.keys.get(peer_id); } /// Check if a peer is known pub fn isPeerKnown(self: *Self, peer_id: [32]u8) bool { self.mutex.lock(); defer self.mutex.unlock(); return self.keys.contains(peer_id); } /// Get the number of pinned keys pub fn count(self: *Self) usize { self.mutex.lock(); defer self.mutex.unlock(); return self.keys.count(); } /// Set key change callback pub fn setKeyChangeCallback(self: *Self, callback: *const fn (PeerFingerprint, [32]u8, [32]u8) void) void { self.mutex.lock(); defer self.mutex.unlock(); self.on_key_change = callback; } /// Export all pinned keys for persistence pub fn exportKeys(self: *Self, allocator: Allocator) ![]PinnedKeyExport { self.mutex.lock(); defer self.mutex.unlock(); const key_count = self.keys.count(); if (key_count == 0) return &[_]PinnedKeyExport{}; const exports = try allocator.alloc(PinnedKeyExport, key_count); errdefer allocator.free(exports); var i: usize = 0; var iter = self.keys.iterator(); while (iter.next()) |entry| { exports[i] = PinnedKeyExport{ .peer_id = entry.key_ptr.*, .public_key = entry.value_ptr.public_key, .first_seen = entry.value_ptr.first_seen, .label = entry.value_ptr.label, .preconfigured = entry.value_ptr.preconfigured, }; i += 1; } return exports; } /// Import pinned keys from persistence pub fn importKeys(self: *Self, exports: []const PinnedKeyExport) Error!usize { self.mutex.lock(); defer self.mutex.unlock(); var imported: usize = 0; const now = std.time.timestamp(); for (exports) |export_item| { if (self.max_keys > 0 and self.keys.count() >= self.max_keys) { break; } var owned_label: ?[]u8 = null; if (export_item.label) |l| { owned_label = self.allocator.dupe(u8, l) catch continue; } self.keys.put(export_item.peer_id, PinnedKey{ .public_key = export_item.public_key, .first_seen = export_item.first_seen, .last_seen = now, .verification_count = 0, .label = owned_label, .preconfigured = export_item.preconfigured, }) catch { if (owned_label) |l| self.allocator.free(l); continue; }; imported += 1; } return imported; } }; /// Export format for persistence pub const PinnedKeyExport = struct { peer_id: [32]u8, public_key: [32]u8, first_seen: i64, label: ?[]const u8, preconfigured: bool, }; // ============================================================================ // File Persistence // ============================================================================ /// Save pinned keys to a file. /// Uses atomic write (temp file + rename) to prevent corruption on crash. pub fn saveToFile(store: *KeyPinStore, path: []const u8) !void { const exports = try store.exportKeys(store.allocator); defer if (exports.len > 0) store.allocator.free(exports); // Build temp path: original path + ".tmp" const tmp_path = try store.allocator.alloc(u8, path.len + 4); defer store.allocator.free(tmp_path); @memcpy(tmp_path[0..path.len], path); @memcpy(tmp_path[path.len..], ".tmp"); // Write to temp file var file = try std.fs.cwd().createFile(tmp_path, .{}); errdefer { file.close(); std.fs.cwd().deleteFile(tmp_path) catch {}; } // Write header: magic + version _ = try file.write("KEYPIN01"); // Write count var count_buf: [4]u8 = undefined; mem.writeInt(u32, &count_buf, @intCast(exports.len), .little); _ = try file.write(&count_buf); // Write each entry for (exports) |entry| { _ = try file.write(&entry.peer_id); _ = try file.write(&entry.public_key); var ts_buf: [8]u8 = undefined; mem.writeInt(i64, &ts_buf, entry.first_seen, .little); _ = try file.write(&ts_buf); const preconf_byte: [1]u8 = .{if (entry.preconfigured) 1 else 0}; _ = try file.write(&preconf_byte); // Write label if (entry.label) |label| { var len_buf: [2]u8 = undefined; mem.writeInt(u16, &len_buf, @intCast(label.len), .little); _ = try file.write(&len_buf); _ = try file.write(label); } else { _ = try file.write(&[_]u8{ 0, 0 }); } } file.close(); // Atomic rename: replaces target in one syscall std.fs.cwd().rename(tmp_path, path) catch |err| { std.fs.cwd().deleteFile(tmp_path) catch {}; return err; }; } /// Load pinned keys from a file pub fn loadFromFile(store: *KeyPinStore, path: []const u8) !usize { var file = std.fs.cwd().openFile(path, .{}) catch |err| { if (err == error.FileNotFound) { return 0; // No saved keys, that's fine } return err; }; defer file.close(); // Read and verify header var magic: [8]u8 = undefined; const magic_read = try file.read(&magic); if (magic_read != 8 or !mem.eql(u8, &magic, "KEYPIN01")) { return error.InvalidFormat; } // Read count var count_buf: [4]u8 = undefined; const count_read = try file.read(&count_buf); if (count_read != 4) return error.InvalidFormat; const count = mem.readInt(u32, &count_buf, .little); // Read entries and import them directly var imported: usize = 0; const now = std.time.timestamp(); for (0..count) |_| { var peer_id: [32]u8 = undefined; var public_key: [32]u8 = undefined; if (try file.read(&peer_id) != 32) return error.InvalidFormat; if (try file.read(&public_key) != 32) return error.InvalidFormat; var ts_buf: [8]u8 = undefined; if (try file.read(&ts_buf) != 8) return error.InvalidFormat; const first_seen = mem.readInt(i64, &ts_buf, .little); var preconf_buf: [1]u8 = undefined; if (try file.read(&preconf_buf) != 1) return error.InvalidFormat; const preconfigured = preconf_buf[0] != 0; var len_buf: [2]u8 = undefined; if (try file.read(&len_buf) != 2) return error.InvalidFormat; const label_len = mem.readInt(u16, &len_buf, .little); var label: ?[]u8 = null; if (label_len > 0) { label = try store.allocator.alloc(u8, label_len); errdefer store.allocator.free(label.?); if (try file.read(label.?) != label_len) { store.allocator.free(label.?); return error.InvalidFormat; } } // Import directly if (store.max_keys > 0 and store.keys.count() >= store.max_keys) { if (label) |l| store.allocator.free(l); break; } store.keys.put(peer_id, PinnedKey{ .public_key = public_key, .first_seen = first_seen, .last_seen = now, .verification_count = 0, .label = label, .preconfigured = preconfigured, }) catch { if (label) |l| store.allocator.free(l); continue; }; imported += 1; } return imported; } // ============================================================================ // Tests // ============================================================================ test "KeyPinStore TOFU mode" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; const public_key = [_]u8{0xAB} ** 32; // First use should pin the key const result1 = try store.verifyPeerKey(peer_id, public_key); try std.testing.expectEqual(VerifyResult.first_use, result1); // Same key should verify const result2 = try store.verifyPeerKey(peer_id, public_key); try std.testing.expectEqual(VerifyResult.verified, result2); // Different key should fail const new_key = [_]u8{0xCD} ** 32; const result3 = try store.verifyPeerKey(peer_id, new_key); try std.testing.expectEqual(VerifyResult.key_changed, result3); } test "KeyPinStore strict mode" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .strict); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; const public_key = [_]u8{0xAB} ** 32; // Unknown peer should be rejected in strict mode const result1 = try store.verifyPeerKey(peer_id, public_key); try std.testing.expectEqual(VerifyResult.unknown_peer, result1); // Pre-pin the key try store.pinKey(peer_id, public_key, "test peer"); // Now it should verify const result2 = try store.verifyPeerKey(peer_id, public_key); try std.testing.expectEqual(VerifyResult.verified, result2); } test "KeyPinStore disabled mode" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .disabled); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; const public_key = [_]u8{0xAB} ** 32; // Should always verify in disabled mode const result = try store.verifyPeerKey(peer_id, public_key); try std.testing.expectEqual(VerifyResult.verified, result); } test "KeyPinStore key update" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; const old_key = [_]u8{0xAB} ** 32; const new_key = [_]u8{0xCD} ** 32; // Pin initial key _ = try store.verifyPeerKey(peer_id, old_key); // Key change should be detected const result1 = try store.verifyPeerKey(peer_id, new_key); try std.testing.expectEqual(VerifyResult.key_changed, result1); // Update the key (user confirmed change is legitimate) try store.updateKey(peer_id, new_key); // New key should now verify const result2 = try store.verifyPeerKey(peer_id, new_key); try std.testing.expectEqual(VerifyResult.verified, result2); } test "KeyPinStore export/import" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); // Add some keys const peer1 = [_]u8{0x01} ** 32; const peer2 = [_]u8{0x02} ** 32; const key1 = [_]u8{0xA1} ** 32; const key2 = [_]u8{0xA2} ** 32; _ = try store.verifyPeerKey(peer1, key1); try store.pinKey(peer2, key2, "labeled peer"); // Export const exports = try store.exportKeys(allocator); defer allocator.free(exports); try std.testing.expectEqual(@as(usize, 2), exports.len); // Create new store and import var store2 = KeyPinStore.init(allocator, .tofu); defer store2.deinit(); const imported = try store2.importKeys(exports); try std.testing.expectEqual(@as(usize, 2), imported); // Verify keys work const result1 = try store2.verifyPeerKey(peer1, key1); try std.testing.expectEqual(VerifyResult.verified, result1); const result2 = try store2.verifyPeerKey(peer2, key2); try std.testing.expectEqual(VerifyResult.verified, result2); } test "KeyPinStore max keys limit" { const allocator = std.testing.allocator; var store = KeyPinStore.initWithConfig(allocator, .tofu, 2); defer store.deinit(); const key = [_]u8{0xAB} ** 32; // Add two keys const peer1 = [_]u8{0x01} ** 32; const peer2 = [_]u8{0x02} ** 32; _ = try store.verifyPeerKey(peer1, key); _ = try store.verifyPeerKey(peer2, key); // Third should fail const peer3 = [_]u8{0x03} ** 32; const result = store.verifyPeerKey(peer3, key); try std.testing.expectError(Error.StorageFull, result); } test "fingerprintFromPublicKey" { const key1 = [_]u8{0xAB} ** 32; const key2 = [_]u8{0xCD} ** 32; const fp1 = fingerprintFromPublicKey(key1); const fp2 = fingerprintFromPublicKey(key2); // Different keys should have different fingerprints try std.testing.expect(!mem.eql(u8, &fp1, &fp2)); // Same key should have same fingerprint const fp1_again = fingerprintFromPublicKey(key1); try std.testing.expect(mem.eql(u8, &fp1, &fp1_again)); } test "verifyKey TOFU mode first use" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const public_key = [_]u8{0xAB} ** 32; // First use should pin the key const result1 = try store.verifyKey(public_key); try std.testing.expectEqual(VerifyResult.first_use, result1); // Same key should verify const result2 = try store.verifyKey(public_key); try std.testing.expectEqual(VerifyResult.verified, result2); } test "verifyKey disabled mode" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .disabled); defer store.deinit(); const public_key = [_]u8{0xAB} ** 32; // Should always verify in disabled mode const result = try store.verifyKey(public_key); try std.testing.expectEqual(VerifyResult.verified, result); } test "verifyKey strict mode unknown peer" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .strict); defer store.deinit(); const public_key = [_]u8{0xAB} ** 32; // Unknown peer should be rejected in strict mode const result = try store.verifyKey(public_key); try std.testing.expectEqual(VerifyResult.unknown_peer, result); } test "verifyKey storage full" { const allocator = std.testing.allocator; var store = KeyPinStore.initWithConfig(allocator, .tofu, 1); defer store.deinit(); const key1 = [_]u8{0xAB} ** 32; const key2 = [_]u8{0xCD} ** 32; // First key should work const result1 = try store.verifyKey(key1); try std.testing.expectEqual(VerifyResult.first_use, result1); // Second key should fail (storage full) const result2 = store.verifyKey(key2); try std.testing.expectError(Error.StorageFull, result2); } test "unpinKey existing" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; const public_key = [_]u8{0xAB} ** 32; // Add a key _ = try store.verifyPeerKey(peer_id, public_key); try std.testing.expectEqual(@as(usize, 1), store.count()); // Remove it const removed = store.unpinKey(peer_id); try std.testing.expect(removed); try std.testing.expectEqual(@as(usize, 0), store.count()); } test "unpinKey non-existent" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; // Try to remove non-existent key const removed = store.unpinKey(peer_id); try std.testing.expect(!removed); } test "unpinKey with label" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; const public_key = [_]u8{0xAB} ** 32; // Add a key with label try store.pinKey(peer_id, public_key, "test label"); try std.testing.expectEqual(@as(usize, 1), store.count()); // Remove it (tests PinnedKey.deinit with label) const removed = store.unpinKey(peer_id); try std.testing.expect(removed); try std.testing.expectEqual(@as(usize, 0), store.count()); } test "getPinnedKey existing" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; const public_key = [_]u8{0xAB} ** 32; // Add a key _ = try store.verifyPeerKey(peer_id, public_key); // Get it const pinned = store.getPinnedKey(peer_id); try std.testing.expect(pinned != null); try std.testing.expect(mem.eql(u8, &pinned.?.public_key, &public_key)); try std.testing.expect(!pinned.?.preconfigured); } test "getPinnedKey non-existent" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; // Get non-existent key const pinned = store.getPinnedKey(peer_id); try std.testing.expect(pinned == null); } test "getPinnedKey preconfigured" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; const public_key = [_]u8{0xAB} ** 32; // Add a preconfigured key try store.pinKey(peer_id, public_key, "test peer"); // Get it const pinned = store.getPinnedKey(peer_id); try std.testing.expect(pinned != null); try std.testing.expect(pinned.?.preconfigured); try std.testing.expect(pinned.?.label != null); } test "isPeerKnown" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; const public_key = [_]u8{0xAB} ** 32; // Unknown peer try std.testing.expect(!store.isPeerKnown(peer_id)); // Add a key _ = try store.verifyPeerKey(peer_id, public_key); // Now known try std.testing.expect(store.isPeerKnown(peer_id)); } test "count" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); // Empty store try std.testing.expectEqual(@as(usize, 0), store.count()); // Add keys const peer1 = [_]u8{0x01} ** 32; const peer2 = [_]u8{0x02} ** 32; const key = [_]u8{0xAB} ** 32; _ = try store.verifyPeerKey(peer1, key); try std.testing.expectEqual(@as(usize, 1), store.count()); _ = try store.verifyPeerKey(peer2, key); try std.testing.expectEqual(@as(usize, 2), store.count()); } var test_callback_invoked: bool = false; var test_callback_old_key: [32]u8 = undefined; var test_callback_new_key: [32]u8 = undefined; fn testKeyChangeCallback(_: PeerFingerprint, old: [32]u8, new: [32]u8) void { test_callback_invoked = true; test_callback_old_key = old; test_callback_new_key = new; } test "setKeyChangeCallback" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); // Set callback store.setKeyChangeCallback(testKeyChangeCallback); const peer_id = [_]u8{0x42} ** 32; const old_key = [_]u8{0xAB} ** 32; const new_key = [_]u8{0xCD} ** 32; // Reset callback state test_callback_invoked = false; // Pin initial key _ = try store.verifyPeerKey(peer_id, old_key); try std.testing.expect(!test_callback_invoked); // Trigger key change const result = try store.verifyPeerKey(peer_id, new_key); try std.testing.expectEqual(VerifyResult.key_changed, result); // Callback should have been invoked try std.testing.expect(test_callback_invoked); try std.testing.expect(mem.eql(u8, &test_callback_old_key, &old_key)); try std.testing.expect(mem.eql(u8, &test_callback_new_key, &new_key)); } test "updateKey unknown peer" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; const new_key = [_]u8{0xCD} ** 32; // Update non-existent peer should fail const result = store.updateKey(peer_id, new_key); try std.testing.expectError(Error.UnknownPeer, result); } test "pinKey storage full" { const allocator = std.testing.allocator; var store = KeyPinStore.initWithConfig(allocator, .tofu, 1); defer store.deinit(); const peer1 = [_]u8{0x01} ** 32; const peer2 = [_]u8{0x02} ** 32; const key = [_]u8{0xAB} ** 32; // First key should work try store.pinKey(peer1, key, null); // Second key should fail (storage full) const result = store.pinKey(peer2, key, null); try std.testing.expectError(Error.StorageFull, result); } test "exportKeys empty" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); // Export empty store const exports = try store.exportKeys(allocator); try std.testing.expectEqual(@as(usize, 0), exports.len); } test "importKeys with label" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer_id = [_]u8{0x42} ** 32; const public_key = [_]u8{0xAB} ** 32; const exports = [_]PinnedKeyExport{ .{ .peer_id = peer_id, .public_key = public_key, .first_seen = 1234567890, .label = "test label", .preconfigured = true, }, }; const imported = try store.importKeys(&exports); try std.testing.expectEqual(@as(usize, 1), imported); // Verify the label was copied const pinned = store.getPinnedKey(peer_id); try std.testing.expect(pinned != null); try std.testing.expect(pinned.?.label != null); try std.testing.expect(mem.eql(u8, pinned.?.label.?, "test label")); } test "importKeys max limit" { const allocator = std.testing.allocator; var store = KeyPinStore.initWithConfig(allocator, .tofu, 1); defer store.deinit(); const peer1 = [_]u8{0x01} ** 32; const peer2 = [_]u8{0x02} ** 32; const key = [_]u8{0xAB} ** 32; const exports = [_]PinnedKeyExport{ .{ .peer_id = peer1, .public_key = key, .first_seen = 0, .label = null, .preconfigured = false }, .{ .peer_id = peer2, .public_key = key, .first_seen = 0, .label = null, .preconfigured = false }, }; // Should only import 1 due to limit const imported = try store.importKeys(&exports); try std.testing.expectEqual(@as(usize, 1), imported); } test "saveToFile and loadFromFile" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); const peer1 = [_]u8{0x01} ** 32; const peer2 = [_]u8{0x02} ** 32; const key1 = [_]u8{0xA1} ** 32; const key2 = [_]u8{0xA2} ** 32; // Add keys _ = try store.verifyPeerKey(peer1, key1); try store.pinKey(peer2, key2, "labeled peer"); // Save to temp file const tmp_path = "/tmp/key_pinning_test.bin"; try saveToFile(&store, tmp_path); defer std.fs.cwd().deleteFile(tmp_path) catch {}; // Create new store and load var store2 = KeyPinStore.init(allocator, .tofu); defer store2.deinit(); const loaded = try loadFromFile(&store2, tmp_path); try std.testing.expectEqual(@as(usize, 2), loaded); // Verify keys work const result1 = try store2.verifyPeerKey(peer1, key1); try std.testing.expectEqual(VerifyResult.verified, result1); const result2 = try store2.verifyPeerKey(peer2, key2); try std.testing.expectEqual(VerifyResult.verified, result2); // Verify label was preserved const pinned = store2.getPinnedKey(peer2); try std.testing.expect(pinned != null); try std.testing.expect(pinned.?.label != null); try std.testing.expect(mem.eql(u8, pinned.?.label.?, "labeled peer")); } test "loadFromFile non-existent" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); // Load non-existent file should return 0 const loaded = try loadFromFile(&store, "/tmp/non_existent_file_12345.bin"); try std.testing.expectEqual(@as(usize, 0), loaded); } test "loadFromFile invalid format" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); // Write invalid data const tmp_path = "/tmp/key_pinning_invalid_test.bin"; { var file = try std.fs.cwd().createFile(tmp_path, .{}); defer file.close(); _ = try file.write("INVALID!"); } defer std.fs.cwd().deleteFile(tmp_path) catch {}; // Load should fail with invalid format const result = loadFromFile(&store, tmp_path); try std.testing.expectError(error.InvalidFormat, result); } test "saveToFile empty store" { const allocator = std.testing.allocator; var store = KeyPinStore.init(allocator, .tofu); defer store.deinit(); // Save empty store const tmp_path = "/tmp/key_pinning_empty_test.bin"; try saveToFile(&store, tmp_path); defer std.fs.cwd().deleteFile(tmp_path) catch {}; // Load it back var store2 = KeyPinStore.init(allocator, .tofu); defer store2.deinit(); const loaded = try loadFromFile(&store2, tmp_path); try std.testing.expectEqual(@as(usize, 0), loaded); } test "loadFromFile with max limit" { const allocator = std.testing.allocator; // Create store with multiple keys var store1 = KeyPinStore.init(allocator, .tofu); defer store1.deinit(); const peer1 = [_]u8{0x01} ** 32; const peer2 = [_]u8{0x02} ** 32; const key = [_]u8{0xAB} ** 32; _ = try store1.verifyPeerKey(peer1, key); _ = try store1.verifyPeerKey(peer2, key); // Save const tmp_path = "/tmp/key_pinning_limit_test.bin"; try saveToFile(&store1, tmp_path); defer std.fs.cwd().deleteFile(tmp_path) catch {}; // Load into store with limit var store2 = KeyPinStore.initWithConfig(allocator, .tofu, 1); defer store2.deinit(); const loaded = try loadFromFile(&store2, tmp_path); try std.testing.expectEqual(@as(usize, 1), loaded); }