Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ AGENTS.md

# Xcode / iOS local state
/mobile/ios/Kinic.xcodeproj/
/mobile/ios/Kinic-manual-*.xcodeproj/
**/DerivedData/
**/build/
**/xcuserdata/
Expand Down
1 change: 1 addition & 0 deletions mobile/ios/KinicUITests/VaultUITests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ final class VaultUITests: XCTestCase {
continueAfterFailure = false
}

@MainActor
private func launchVault(screen: String = "list", darkMode: Bool = true) -> XCUIApplication {
let app = XCUIApplication()
app.launchEnvironment["KINIC_SCREENSHOT_MODE"] = "vault"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,25 +112,89 @@ public enum VaultCredentialCodec {
"javascript", "data", "vbscript", "blob", "file", "about", "mailto", "tel",
]

/// Zero-allocation UTF-8 fast-path for already-normalized lowercase ASCII multi-label hostnames
/// (non-IPv4, non-punycode). Matches WHATWG URL `https://\(raw)` identically.
@inline(__always)
private static func isFastNormalizedHost(_ raw: String) -> Bool {
var mutable = raw
return mutable.withUTF8 { buf -> Bool in
let count = buf.count
guard count >= 3, count <= 255 else { return false }
var hasDot = false
var labelLen = 0
var lastLabelStart = 0
for i in 0..<count {
let b = buf[i]
if b == 0x2E { // '.'
if labelLen == 0 { return false }
hasDot = true
labelLen = 0
lastLabelStart = i &+ 1
continue
}
let isLowerAlpha = b >= 0x61 && b <= 0x7A
let isDigit = b >= 0x30 && b <= 0x39
if !isLowerAlpha && !isDigit && b != 0x2D {
return false
}
if labelLen == 3 && b == 0x2D && buf[i &- 3] == 0x78 && buf[i &- 2] == 0x6E && buf[i &- 1] == 0x2D {
return false
}
labelLen &+= 1
}
guard hasDot, labelLen > 0 else { return false }
var allDigits = true
for i in lastLabelStart..<count {
let b = buf[i]
if b < 0x30 || b > 0x39 { allDigits = false; break }
}
if allDigits { return false }
if labelLen >= 2 && buf[lastLabelStart] == 0x30 && buf[lastLabelStart &+ 1] == 0x78 {
var restHex = true
for i in (lastLabelStart &+ 2)..<count {
let b = buf[i]
if !((b >= 0x30 && b <= 0x39) || (b >= 0x61 && b <= 0x66)) { restHex = false; break }
}
if restHex { return false }
}
return true
}
}

public static func normalizeDomain(_ raw: String) -> String? {
if isFastNormalizedHost(raw) {
return raw
}
return normalizeDomainSlow(raw)
}

internal static func normalizeDomainSlow(_ raw: String) -> String? {
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed.count <= 2048 else { return nil }

var scheme: String?
var hasSchemeSeparator = false
if let colon = trimmed.firstIndex(of: ":") {
let prefix = String(trimmed[..<colon]).lowercased()
let validScheme = prefix.first?.isLetter == true && prefix.allSatisfy {
$0.isLetter || $0.isNumber || $0 == "+" || $0 == "." || $0 == "-"
}
if validScheme {
if blockedSchemes.contains(prefix) { return nil }
if prefix != "http" && prefix != "https" && prefix != "android" && !trimmed.contains("://") {
let prefix = trimmed[..<colon]
if let first = prefix.utf8.first,
(first >= 0x41 && first <= 0x5A) || (first >= 0x61 && first <= 0x7A),
prefix.utf8.allSatisfy({
($0 >= 0x41 && $0 <= 0x5A) || ($0 >= 0x61 && $0 <= 0x7A)
|| ($0 >= 0x30 && $0 <= 0x39) || $0 == 0x2B || $0 == 0x2E || $0 == 0x2D
})
{
let lower = prefix.lowercased()
if blockedSchemes.contains(lower) { return nil }
hasSchemeSeparator = trimmed[trimmed.index(after: colon)...].hasPrefix("//")
if lower != "http" && lower != "https" && lower != "android" && !hasSchemeSeparator {
return nil
}
scheme = lower
}
}

var candidate = trimmed
if !candidate.contains("://") {
if !hasSchemeSeparator {
if candidate.rangeOfCharacter(from: .whitespacesAndNewlines) != nil { return nil }
candidate = "https://\(candidate)"
}
Expand All @@ -156,8 +220,11 @@ public enum VaultCredentialCodec {
else {
return nil
}
let isSpecialScheme = scheme == nil || scheme == "http" || scheme == "https" || scheme == "ws" || scheme == "wss" || scheme == "ftp"
if endsInNumber(host) {
return normalizeIPv4Host(host)
guard let normalized = normalizeIPv4Host(host) else { return nil }
if !isSpecialScheme && normalized != host { return nil }
return normalized
}
if host != "localhost" && !host.contains(".") {
return nil
Expand Down Expand Up @@ -269,13 +336,28 @@ public enum VaultCredentialCodec {

private static func isIpOrLocalhost(_ host: String) -> Bool {
if host == "localhost" { return true }
if host.hasPrefix("[") && host.hasSuffix("]") { return true }
let parts = host.split(separator: ".", omittingEmptySubsequences: false)
return parts.count == 4 && parts.allSatisfy { !$0.isEmpty && $0.count <= 3 && $0.allSatisfy(\.isNumber) }
let utf8 = host.utf8
if utf8.first == 0x5B && utf8.last == 0x5D { return true } // '[' ... ']'
var groups = 1
var digits = 0
for b in utf8 {
if b == 0x2E { // '.'
if digits == 0 || digits > 3 { return false }
groups += 1
if groups > 4 { return false }
digits = 0
} else if b >= 0x30 && b <= 0x39 {
digits += 1
if digits > 3 { return false }
} else {
return false
}
}
return groups == 4 && digits >= 1 && digits <= 3
}

fileprivate static func canMatchAsParentDomain(_ domain: String) -> Bool {
guard domain.contains("."), !isIpOrLocalhost(domain) else { return false }
guard domain.utf8.contains(0x2E), !isIpOrLocalhost(domain) else { return false }
return !nonMatchableParentDomains.contains(domain)
}

Expand Down Expand Up @@ -381,16 +463,13 @@ public struct VaultDomainIndex<Item> {
for (index, item) in items.enumerated() {
let domains = getDomains(item)
guard !domains.isEmpty else { continue }
var seenExact = Set<String>()
var seenParent = Set<String>()
var seen = Set<String>()
for raw in domains {
guard let domain = VaultCredentialCodec.normalizeDomain(raw) else { continue }
if seenExact.insert(domain).inserted {
exact[domain, default: []].append(index)
}
if VaultCredentialCodec.canMatchAsParentDomain(domain),
seenParent.insert(domain).inserted
{
guard let domain = VaultCredentialCodec.normalizeDomain(raw),
seen.insert(domain).inserted
else { continue }
exact[domain, default: []].append(index)
if VaultCredentialCodec.canMatchAsParentDomain(domain) {
parent[domain, default: []].append(index)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -534,20 +534,113 @@ struct KinicVaultCoreTests {
)
}

@Test("normalizeDomain matches WHATWG URL behavior for IPv4, IPv6, and non-HTTP schemes")
func normalizeDomainMatchesWHATWG() {
#expect(VaultCredentialCodec.normalizeDomain("https://[::1]") == "[::1]")
#expect(VaultCredentialCodec.normalizeDomain("https://[2001:db8:0:0::1]:8080/a") == "[2001:db8::1]")
#expect(VaultCredentialCodec.normalizeDomain("https://127.1") == "127.0.0.1")
#expect(VaultCredentialCodec.normalizeDomain("https://0x7f.1") == "127.0.0.1")
#expect(VaultCredentialCodec.normalizeDomain("https://2130706433") == "127.0.0.1")
#expect(VaultCredentialCodec.normalizeDomain("https://0177.0.0.1") == "127.0.0.1")
#expect(VaultCredentialCodec.normalizeDomain("https://example.com.") == "example.com")
#expect(VaultCredentialCodec.normalizeDomain("android://jp.1") == nil)
#expect(VaultCredentialCodec.normalizeDomain("https://jp.1") == nil)
#expect(VaultCredentialCodec.normalizeDomain("https://1.2.3.4.5") == nil)
#expect(VaultCredentialCodec.normalizeDomain("https://256.0.0.1") == nil)
#expect(VaultCredentialCodec.normalizeDomain("https://..example.com") == nil)
@Test("Property-based invariants: normalizeDomain fast-path parity, idempotency, matchesDomain isolation, and VaultDomainIndex differential equivalence")
func domainPropertyBasedInvariants() {
var state: UInt64 = 0x2026_1203_CAFE_BABE
func nextUInt64() -> UInt64 {
state &+= 0x9E37_79B9_7F4A_7C15
var z = state
z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
return z ^ (z >> 31)
}
func pick<T>(_ arr: [T]) -> T { arr[Int(nextUInt64() % UInt64(arr.count))] }

let labels = ["a", "sub", "example", "com", "co", "jp", "127", "0", "1", "0x7f", "0x1", "0x", "0177", "xn--b", "", "."]
let schemes = ["", "https://", "http://", "android://", "javascript:"]

// 1. Fast-path == slow-path parity & idempotency across 600 generated inputs.
for _ in 0..<600 {
let scheme = pick(schemes)
let count = 1 + Int(nextUInt64() % 5)
let host = (0..<count).map { _ in pick(labels) }.joined(separator: ".")
let raw = scheme + host
let fast = VaultCredentialCodec.normalizeDomain(raw)
let slow = VaultCredentialCodec.normalizeDomainSlow(raw)
#expect(fast == slow, "fast/slow mismatch for \(raw)")
if let once = fast {
#expect(VaultCredentialCodec.normalizeDomain(once) == once)
#expect(VaultCredentialCodec.normalizeDomain("https://\(once)") == once)
#expect(once == once.lowercased())
#expect(!once.hasSuffix("."))
}
}

// 2. Differential PBT: VaultDomainIndex.match == linear matchesDomain scan (exact order, no duplicates).
let pool = [
"github.com", "gist.github.com", "api.github.com", "example.com",
"a.b.example.com", "co.jp", "bank.co.jp", "icp0.io", "canister.icp0.io",
"localhost", "127.0.0.1", "0x7f.0x1", "https://Sub.Example.org/login", "invalid host",
]
struct Item: Equatable { let id: Int; let domains: [String] }
let items = (0..<80).map { id in
let n = Int(nextUInt64() % 4)
return Item(id: id, domains: (0..<n).map { _ in pick(pool) })
}
let index = VaultDomainIndex(items: items, domains: \.domains)
let queries = pool + [
"https://deep.a.b.example.com/path",
"https://sub.bank.co.jp/",
"https://sub.canister.icp0.io/",
"https://evilgithub.com/",
"example.com/a://b",
"android://12345",
"javascript:alert(1)",
"",
]
for q in queries {
let expected = items.filter { VaultCredentialCodec.matchesDomain(domains: $0.domains, queryHost: q) }
#expect(index.match(queryHost: q) == expected, "index parity mismatch for \(q)")
}

// 3. Canonical Unicode equivalence parity between matchesDomain and VaultDomainIndex.
let unicodeItems = [Item(id: 0, domains: ["https://é.example"])]
let unicodeIndex = VaultDomainIndex(items: unicodeItems, domains: \.domains)
let unicodeQuery = "https://a.e%CC%81.example"
#expect(VaultCredentialCodec.matchesDomain(domains: ["https://é.example"], queryHost: unicodeQuery) == !unicodeIndex.match(queryHost: unicodeQuery).isEmpty)
}

@Test("Matches shared Swift/TypeScript domain normalization and matching vectors")
func matchesSharedDomainVectors() throws {
struct SharedDomainVectors: Decodable {
struct NormalizeCase: Decodable {
let input: String
let expected: String?
}
struct MatchCase: Decodable {
let domains: [String]
let queryHost: String
let expected: Bool
}
let normalizeDomain: [NormalizeCase]
let matchesDomain: [MatchCase]
}

// File sits at mobile/ios/Packages/KinicVaultCore/Tests/KinicVaultCoreTests/KinicVaultCoreTests.swift
var repoRoot = URL(fileURLWithPath: #filePath)
for _ in 0..<7 {
repoRoot.deleteLastPathComponent()
}
let vectorsURL = repoRoot.appendingPathComponent("shared/vault-domain-vectors.json")
let data = try Data(contentsOf: vectorsURL)
let vectors = try JSONDecoder().decode(SharedDomainVectors.self, from: data)
#expect(!vectors.normalizeDomain.isEmpty)
#expect(!vectors.matchesDomain.isEmpty)

for tc in vectors.normalizeDomain {
#expect(
VaultCredentialCodec.normalizeDomain(tc.input) == tc.expected,
"normalizeDomain(\(tc.input))"
)
}
for tc in vectors.matchesDomain {
#expect(
VaultCredentialCodec.matchesDomain(domains: tc.domains, queryHost: tc.queryHost) == tc.expected,
"matchesDomain(\(tc.domains), \(tc.queryHost))"
)
let index = VaultDomainIndex(items: [tc.domains], domains: { $0 })
#expect(!index.match(queryHost: tc.queryHost).isEmpty == tc.expected)
}
}

@Test("listCandidates prefilters with verified encrypted index and never drops incomplete manifests")
Expand Down
Loading
Loading