Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/LocalChatCoreTests/SecurityTests.swift3// Description: Tests of LocalChatSecurity: AEAD envelope, key derivation vectors, pairing codes, API keys, path sandbox, app lock, Keychain.4import CryptoKit5import Foundation6import Testing7@testable import LocalChatSecurity89private func hex(_ s: String) -> Data {10 var d = Data(); var i = s.startIndex11 while i < s.endIndex { let j = s.index(i, offsetBy: 2); d.append(UInt8(s[i..<j], radix: 16)!); i = j }12 return d13}14private func hex(_ d: Data) -> String { d.map { String(format: "%02x", $0) }.joined() }1516@Suite struct SecuritySecretBoxTests {17 @Test func roundTripWithAssociatedData() throws {18 let key = SymmetricKey(size: .bits256)19 let sealed = try SecretBox.seal(Data("hello".utf8), key: key, associatedData: Data("hdr".utf8))20 #expect(sealed.first == SecretBox.version)21 #expect(try SecretBox.open(sealed, key: key, associatedData: Data("hdr".utf8)) == Data("hello".utf8))22 #expect(try SecretBox.seal(Data("hello".utf8), key: key) != SecretBox.seal(Data("hello".utf8), key: key)) // random nonce23 }24 @Test func rejectsWrongKeyWrongAADAndTampering() throws {25 let key = SymmetricKey(size: .bits256)26 var sealed = try SecretBox.seal(Data("secret".utf8), key: key, associatedData: Data("a".utf8))27 #expect(throws: CryptoError.authenticationFailed) { try SecretBox.open(sealed, key: SymmetricKey(size: .bits256), associatedData: Data("a".utf8)) }28 #expect(throws: CryptoError.authenticationFailed) { try SecretBox.open(sealed, key: key, associatedData: Data("b".utf8)) }29 sealed[sealed.count - 20] ^= 0x0130 #expect(throws: CryptoError.authenticationFailed) { try SecretBox.open(sealed, key: key, associatedData: Data("a".utf8)) }31 #expect(throws: CryptoError.malformedEnvelope) { try SecretBox.open(Data([1, 2, 3]), key: key) }32 var other = try SecretBox.seal(Data(), key: key); other[0] = 933 #expect(throws: CryptoError.unsupportedVersion(9)) { try SecretBox.open(other, key: key) }34 }35}3637@Suite struct SecurityKeyDerivationTests {38 // PBKDF2-HMAC-SHA256 known answers (RFC 7914 §11 and the widely published "password"/"salt" vectors)39 @Test func pbkdf2KnownAnswers() throws {40 #expect(hex(try KeyDerivation.pbkdf2(password: Data("password".utf8), salt: Data("salt".utf8), iterations: 1, length: 32))41 == "120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b")42 #expect(hex(try KeyDerivation.pbkdf2(password: Data("password".utf8), salt: Data("salt".utf8), iterations: 4096, length: 32))43 == "c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a")44 #expect(hex(try KeyDerivation.pbkdf2(password: Data("passwd".utf8), salt: Data("salt".utf8), iterations: 1, length: 64))45 == "55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783")46 }47 // RFC 5869 test case 148 @Test func hkdfKnownAnswer() {49 let ikm = SymmetricKey(data: hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"))50 let okm = HKDF<SHA256>.deriveKey(inputKeyMaterial: ikm, salt: hex("000102030405060708090a0b0c"), info: hex("f0f1f2f3f4f5f6f7f8f9"), outputByteCount: 42)51 #expect(hex(okm.withUnsafeBytes { Data($0) }) == "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865")52 }53 @Test func subkeysDependOnPurpose() {54 let master = SymmetricKey(size: .bits256)55 let a = KeyDerivation.subkey(from: master, purpose: "sync-records"), b = KeyDerivation.subkey(from: master, purpose: "sync-verify")56 #expect(a != b)57 #expect(a == KeyDerivation.subkey(from: master, purpose: "sync-records"))58 #expect(a.bitCount == 256)59 }60 @Test func passphraseKeyIsStableAndSaltSensitive() throws {61 let salt = KeyDerivation.randomSalt()62 #expect(salt.count == 16)63 #expect(KeyDerivation.defaultIterations >= 600_000)64 let k1 = try KeyDerivation.key(fromPassphrase: "correct horse", salt: salt, iterations: 1000)65 #expect(k1 == (try KeyDerivation.key(fromPassphrase: "correct horse", salt: salt, iterations: 1000)))66 #expect(k1 != (try KeyDerivation.key(fromPassphrase: "correct horse", salt: KeyDerivation.randomSalt(), iterations: 1000)))67 #expect(k1 != (try KeyDerivation.key(fromPassphrase: "Correct horse", salt: salt, iterations: 1000)))68 }69 @Test func pairingCodes() throws {70 let code = PairingCode.generate()71 #expect(code.split(separator: "-").count == 6)72 #expect(code.split(separator: "-").allSatisfy { $0.count == 4 })73 #expect(PairingCode.isValid(code))74 #expect(!code.contains(where: { "0O1IL".contains($0) }))75 #expect(PairingCode.generate() != code)76 // typed without dashes, in lower case, with spaces: same code, same key77 let sloppy = code.lowercased().replacingOccurrences(of: "-", with: " ")78 #expect(try PairingCode.validated(sloppy) == code)79 let salt = Data(repeating: 7, count: 16)80 #expect(try KeyDerivation.key(fromPassphrase: sloppy, salt: salt, iterations: 500) == KeyDerivation.key(fromPassphrase: code, salt: salt, iterations: 500))81 // a single wrong character is caught by the checksum group82 var chars = Array(code); chars[0] = chars[0] == "A" ? "B" : "A"83 #expect(!PairingCode.isValid(String(chars)))84 #expect(throws: CryptoError.invalidCode) { try PairingCode.validated("ABCD-EFGH") }85 }86}8788@Suite struct SecurityAPIKeyTests {89 @Test func generateHashVerify() {90 let key = APIKeyHasher.generate()91 #expect(key.hasPrefix("lc-") && key.count == 35)92 #expect(key.dropFirst(3).allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber) })93 #expect(APIKeyHasher.generate() != key)94 let hash = APIKeyHasher.hash(key)95 #expect(hash.count == 64)96 #expect(APIKeyHasher.verify(key, againstHash: hash))97 #expect(!APIKeyHasher.verify(key + "x", againstHash: hash))98 #expect(APIKeyHasher.hash("abc") == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")99 #expect(APIKeyHasher.constantTimeEquals("abc", "abc"))100 #expect(!APIKeyHasher.constantTimeEquals("abc", "abd"))101 #expect(!APIKeyHasher.constantTimeEquals("abc", "abcd"))102 #expect(!APIKeyHasher.constantTimeEquals("", "a"))103 #expect(APIKeyHasher.masked(key).contains("…") && !APIKeyHasher.masked(key).contains(key.dropFirst(8).prefix(10)))104 }105}106107@Suite struct SecurityPathSandboxTests {108 let root: URL, outside: URL109 init() throws {110 let base = FileManager.default.temporaryDirectory.appendingPathComponent("lc-sandbox-\(UUID().uuidString)")111 root = base.appendingPathComponent("granted"); outside = base.appendingPathComponent("outside")112 try FileManager.default.createDirectory(at: root.appendingPathComponent("sub"), withIntermediateDirectories: true)113 try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)114 try Data("in".utf8).write(to: root.appendingPathComponent("sub/a.txt"))115 try Data("secret".utf8).write(to: outside.appendingPathComponent("secret.txt"))116 }117118 @Test func allowsPathsInside() throws {119 let box = PathSandbox(roots: [root])120 #expect(try box.resolve("sub/a.txt").lastPathComponent == "a.txt")121 #expect(try box.resolve(root.appendingPathComponent("sub/a.txt").path).path.hasSuffix("granted/sub/a.txt"))122 #expect(try box.resolve("new/deep/file.txt").path.hasSuffix("granted/new/deep/file.txt")) // not created yet123 #expect(try box.resolve("sub/../sub/a.txt").path.hasSuffix("granted/sub/a.txt"))124 #expect(box.displayPath(try box.resolve("sub/a.txt")) == "sub/a.txt")125 #expect(box.contains(root))126 }127128 @Test func rejectsEscapes() throws {129 let box = PathSandbox(roots: [root])130 #expect(throws: PathSandboxError.self) { try box.resolve("../outside/secret.txt") }131 #expect(throws: PathSandboxError.self) { try box.resolve("sub/../../outside/secret.txt") }132 #expect(throws: PathSandboxError.self) { try box.resolve(outside.appendingPathComponent("secret.txt").path) }133 #expect(throws: PathSandboxError.self) { try box.resolve("/etc/passwd") }134 #expect(throws: PathSandboxError.self) { try box.resolve("~/.ssh/id_ed25519") }135 #expect(throws: PathSandboxError.self) { try box.resolve("") }136 #expect(throws: PathSandboxError.self) { try box.resolve("a\0b") }137 // a sibling whose name starts like the root is not inside it138 let sibling = root.deletingLastPathComponent().appendingPathComponent("granted-evil")139 try FileManager.default.createDirectory(at: sibling, withIntermediateDirectories: true)140 #expect(throws: PathSandboxError.self) { try box.resolve(sibling.appendingPathComponent("x").path) }141 #expect(!box.contains(outside))142 }143144 @Test func rejectsSymlinkEscapes() throws {145 let box = PathSandbox(roots: [root])146 try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("link"), withDestinationURL: outside)147 try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("filelink"), withDestinationURL: outside.appendingPathComponent("secret.txt"))148 try FileManager.default.createSymbolicLink(atPath: root.appendingPathComponent("dangling").path, withDestinationPath: "/etc/nonexistent-target")149 #expect(throws: PathSandboxError.self) { try box.resolve("link/secret.txt") }150 #expect(throws: PathSandboxError.self) { try box.resolve("link/new-file.txt") }151 #expect(throws: PathSandboxError.self) { try box.resolve("filelink") }152 #expect(throws: PathSandboxError.self) { try box.resolve("dangling") }153 // a symlink that stays inside is fine154 try FileManager.default.createSymbolicLink(at: root.appendingPathComponent("inner"), withDestinationURL: root.appendingPathComponent("sub"))155 #expect(try box.resolve("inner/a.txt").path.hasSuffix("granted/sub/a.txt"))156 }157158 @Test func symlinkedRootIsCanonicalized() throws {159 let alias = root.deletingLastPathComponent().appendingPathComponent("alias")160 try FileManager.default.createSymbolicLink(at: alias, withDestinationURL: root)161 let box = PathSandbox(roots: [alias])162 #expect(try box.resolve("sub/a.txt").path.hasSuffix("granted/sub/a.txt"))163 #expect(throws: PathSandboxError.self) { try box.resolve("../outside/secret.txt") }164 }165166 @Test func noRoots() {167 #expect(throws: PathSandboxError.noGrantedFolders) { try PathSandbox(roots: []).resolve("a") }168 }169}170171private final class FakeAuthenticator: LockAuthenticating, @unchecked Sendable {172 var available = true; var succeed = true; var calls = 0173 func canAuthenticate() -> (available: Bool, biometry: AppLock.Biometry, reason: String?) { (available, .faceID, available ? nil : "No passcode") }174 func authenticate(reason: String) async throws -> Bool { calls += 1; return succeed }175}176private final class Clock: @unchecked Sendable { var now = Date(timeIntervalSince1970: 1_000_000) }177178@Suite @MainActor struct SecurityAppLockTests {179 @Test func stateMachine() async {180 let auth = FakeAuthenticator(); let clock = Clock()181 let lock = AppLock(isEnabled: true, gracePeriod: 60, authenticator: auth, now: { clock.now })182 #expect(lock.state == .locked && lock.isLocked)183 auth.succeed = false184 #expect(await lock.unlock() == false)185 #expect(lock.state == .locked)186 auth.succeed = true187 #expect(await lock.unlock())188 #expect(lock.state == .unlocked)189 // background shorter than the grace period keeps the app unlocked190 lock.didEnterBackground(); clock.now += 30; lock.willEnterForeground()191 #expect(lock.state == .unlocked)192 lock.didEnterBackground(); clock.now += 61; lock.willEnterForeground()193 #expect(lock.state == .locked)194 lock.isEnabled = false195 #expect(lock.state == .unlocked)196 lock.lock()197 #expect(lock.state == .unlocked) // lock() does nothing when the feature is off198 }199 @Test func enablingRequiresAuthentication() async {200 let auth = FakeAuthenticator()201 let lock = AppLock(isEnabled: false, authenticator: auth)202 #expect(lock.state == .unlocked)203 auth.succeed = false204 #expect(await lock.enable() == false)205 #expect(!lock.isEnabled)206 auth.available = false; auth.succeed = true207 #expect(await lock.enable() == false)208 #expect(lock.lastError != nil)209 auth.available = true210 #expect(await lock.enable())211 #expect(lock.isEnabled && lock.state == .unlocked)212 #expect(lock.availability.biometry == .faceID)213 }214}215216@Suite(.serialized) struct SecurityKeychainTests {217 /// The Keychain needs entitlements the SwiftPM test runner may not have: probe first and skip with the reason.218 static func probe(_ store: KeychainStore) -> String? {219 do { try store.set("probe", for: "probe"); try store.delete("probe"); return nil }220 catch { return (error as? LocalizedError)?.errorDescription ?? String(describing: error) }221 }222223 @Test func crud() throws {224 let store = KeychainStore(service: "ai.spboucher.localchat.tests.\(UUID().uuidString)")225 if let reason = Self.probe(store) {226 print("KEYCHAIN-TESTS-SKIPPED: \(reason)")227 withKnownIssue("Keychain unavailable in this test runner: \(reason)") { Issue.record("skipped") }228 return229 }230 print("KEYCHAIN-TESTS-RAN")231 defer { try? store.deleteAll() }232 #expect(try store.string(for: "a") == nil)233 try store.set("one", for: "a"); try store.set(Data([1, 2, 3]), for: "b")234 #expect(try store.string(for: "a") == "one")235 #expect(try store.data(for: "b") == Data([1, 2, 3]))236 try store.set("two", for: "a") // update in place237 #expect(try store.string(for: "a") == "two")238 #expect(try store.accounts() == ["a", "b"])239 #expect(try store.delete("a"))240 #expect(try store.delete("a") == false)241 #expect(try store.accounts() == ["b"])242 // another service does not see these items243 #expect(try KeychainStore(service: "ai.spboucher.localchat.tests.other.\(UUID().uuidString)").accounts().isEmpty)244 try store.deleteAll()245 #expect(try store.accounts().isEmpty)246 }247}248