Commit f6aa4eff5f

f6aa4eff5fb9d408b4a70b6d2e6700b08e84f944

parent: a600c93377

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-24 06:50 UTC

Separate Local API routing from execution, and cover it

handle was ten chained ifs that mixed matching with execution, so a new route
could silently shadow an existing one. Matching is now a pure
LocalAPIRoute.match returning an enum, and handle switches over it, which the
compiler checks for exhaustiveness. Authorisation became a static function, and
the handler, request and response types are internal, so the whole decision
surface is reachable from a test.

Twelve tests: every documented route, the near-misses that must not match
(wrong method, unknown trailing segment, extra segment), both documented auth
headers, a wrong and a missing token, and the case that matters for a server on
a shared device — an unconfigured token refuses everything rather than treating
an absent credential as a match. The 401 and 404 envelopes are decoded into a
locally declared type so the assertion is about the published wire shape rather
than agreeing with the app's own encoder.

The success paths stay uncovered: /portfolio and /domains read the real store
through DomainDataPortabilityService with no injected defaults, and /inspect
runs a live lookup. Those need W5's injectable store.

Layout: unified · split

DomainDig.xcodeproj/project.pbxproj +4
@@ -29,6 +29,7 @@
2929 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000201 /* InspectionInputTests.swift */; };
3030 A1B2C3D40000000000000602 /* FeatureAccessTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000601 /* FeatureAccessTests.swift */; };
3131 A1B2C3D40000000000000702 /* SMTPMessageTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000701 /* SMTPMessageTests.swift */; };
32 A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */; };
3233 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; };
3334 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; };
3435 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; };
@@ -105,6 +106,7 @@
105106 A1B2C3D40000000000000201 /* InspectionInputTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InspectionInputTests.swift; sourceTree = "<group>"; };
106107 A1B2C3D40000000000000601 /* FeatureAccessTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FeatureAccessTests.swift; sourceTree = "<group>"; };
107108 A1B2C3D40000000000000701 /* SMTPMessageTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SMTPMessageTests.swift; sourceTree = "<group>"; };
109 A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LocalAPIRoutingTests.swift; sourceTree = "<group>"; };
108110 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; };
109111 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; };
110112 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; };
@@ -246,6 +248,7 @@
246248 A1B2C3D40000000000000201 /* InspectionInputTests.swift */,
247249 A1B2C3D40000000000000601 /* FeatureAccessTests.swift */,
248250 A1B2C3D40000000000000701 /* SMTPMessageTests.swift */,
251 A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */,
249252 A1B2C3D40000000000000301 /* AvailabilityTests.swift */,
250253 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */,
251254 A1B2C3D40000000000000501 /* DomainNameTests.swift */,
@@ -512,6 +515,7 @@
512515 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */,
513516 A1B2C3D40000000000000602 /* FeatureAccessTests.swift in Sources */,
514517 A1B2C3D40000000000000702 /* SMTPMessageTests.swift in Sources */,
518 A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */,
515519 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */,
516520 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */,
517521 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */,
DomainDigTests/LocalAPIRoutingTests.swift added +147
@@ -0,0 +1,147 @@
1import XCTest
2@testable import DomainDig
3
4/// The Local API's routing and auth had no coverage: `LocalAPIContractTests`
5/// pins the JSON shape of a response, not which request produces it. Matching
6/// and authorisation are both pure, and `handle` answers 401 and 404 before it
7/// reaches the store or the network, so all of that is reachable here. The
8/// success paths are not — they read the real store and run live lookups.
9final class LocalAPIRoutingTests: XCTestCase {
10
11 // MARK: Every documented route
12
13 func testGetRoutes() {
14 XCTAssertEqual(LocalAPIRoute.match(method: "GET", pathComponents: ["portfolio"]), .portfolio)
15 XCTAssertEqual(LocalAPIRoute.match(method: "GET", pathComponents: ["domains"]), .domains)
16 XCTAssertEqual(LocalAPIRoute.match(method: "GET", pathComponents: ["events"]), .events)
17 XCTAssertEqual(LocalAPIRoute.match(method: "GET", pathComponents: ["monitoring"]), .monitoring)
18 }
19
20 func testDomainScopedGetRoutesCarryTheDomain() {
21 XCTAssertEqual(
22 LocalAPIRoute.match(method: "GET", pathComponents: ["domains", "example.com"]),
23 .domainDetails("example.com")
24 )
25 XCTAssertEqual(
26 LocalAPIRoute.match(method: "GET", pathComponents: ["domains", "example.com", "history"]),
27 .domainHistory("example.com")
28 )
29 }
30
31 func testPostRoutes() {
32 XCTAssertEqual(LocalAPIRoute.match(method: "POST", pathComponents: ["inspect"]), .inspectFromBody)
33 XCTAssertEqual(
34 LocalAPIRoute.match(method: "POST", pathComponents: ["inspect", "example.com"]),
35 .inspect("example.com")
36 )
37 }
38
39 func testMonitoringTogglesCarryBothDomainAndState() {
40 XCTAssertEqual(
41 LocalAPIRoute.match(method: "POST", pathComponents: ["monitoring", "example.com", "enable"]),
42 .setMonitoring(domain: "example.com", enabled: true)
43 )
44 XCTAssertEqual(
45 LocalAPIRoute.match(method: "POST", pathComponents: ["monitoring", "example.com", "disable"]),
46 .setMonitoring(domain: "example.com", enabled: false)
47 )
48 }
49
50 // MARK: What must not match
51
52 /// The method is part of the route, not decoration: a read route must not
53 /// answer a write and the reverse.
54 func testTheMethodIsPartOfTheRoute() {
55 XCTAssertNil(LocalAPIRoute.match(method: "POST", pathComponents: ["portfolio"]))
56 XCTAssertNil(LocalAPIRoute.match(method: "GET", pathComponents: ["inspect"]))
57 XCTAssertNil(LocalAPIRoute.match(method: "DELETE", pathComponents: ["domains", "example.com"]))
58 }
59
60 func testUnknownTrailingSegmentsDoNotMatch() {
61 XCTAssertNil(LocalAPIRoute.match(method: "GET", pathComponents: ["domains", "example.com", "notes"]))
62 XCTAssertNil(LocalAPIRoute.match(method: "POST", pathComponents: ["monitoring", "example.com", "pause"]))
63 }
64
65 func testUnknownAndEmptyPathsDoNotMatch() {
66 XCTAssertNil(LocalAPIRoute.match(method: "GET", pathComponents: ["nope"]))
67 XCTAssertNil(LocalAPIRoute.match(method: "GET", pathComponents: []))
68 XCTAssertNil(LocalAPIRoute.match(method: "GET", pathComponents: ["portfolio", "extra"]))
69 }
70
71 // MARK: Authorisation
72
73 func testEitherDocumentedHeaderAuthorises() {
74 XCTAssertTrue(LocalAPIRequestHandler.isAuthorized(
75 request: request(headers: ["x-api-token": "secret"]), expectedToken: "secret"
76 ))
77 XCTAssertTrue(LocalAPIRequestHandler.isAuthorized(
78 request: request(headers: ["authorization": "Bearer secret"]), expectedToken: "secret"
79 ))
80 }
81
82 func testAWrongOrMissingTokenIsRefused() {
83 XCTAssertFalse(LocalAPIRequestHandler.isAuthorized(
84 request: request(headers: ["x-api-token": "wrong"]), expectedToken: "secret"
85 ))
86 XCTAssertFalse(LocalAPIRequestHandler.isAuthorized(request: request(headers: [:]), expectedToken: "secret"))
87 XCTAssertFalse(LocalAPIRequestHandler.isAuthorized(
88 request: request(headers: ["authorization": "secret"]), expectedToken: "secret"
89 ))
90 }
91
92 /// With no token configured the server must refuse everything rather than
93 /// treat an absent credential as a match.
94 func testAnUnconfiguredTokenRefusesEverything() {
95 XCTAssertFalse(LocalAPIRequestHandler.isAuthorized(request: request(headers: [:]), expectedToken: ""))
96 XCTAssertFalse(LocalAPIRequestHandler.isAuthorized(
97 request: request(headers: ["x-api-token": ""]), expectedToken: ""
98 ))
99 }
100
101 // MARK: The error envelopes the contract documents
102
103 func testAnUnauthorisedRequestAnswers401InTheEnvelope() async throws {
104 let response = await LocalAPIRequestHandler().handle(
105 request: request(path: "/portfolio", headers: [:]), expectedToken: "secret"
106 )
107
108 XCTAssertEqual(response.statusCode, 401)
109 let envelope = try JSONDecoder().decode(ErrorEnvelope.self, from: response.body)
110 XCTAssertFalse(envelope.success)
111 XCTAssertEqual(envelope.version, "v1")
112 XCTAssertEqual(envelope.error.code, "unauthorized")
113 }
114
115 func testAnUnknownRouteAnswers404InTheEnvelope() async throws {
116 let response = await LocalAPIRequestHandler().handle(
117 request: request(path: "/nope", headers: ["x-api-token": "secret"]), expectedToken: "secret"
118 )
119
120 XCTAssertEqual(response.statusCode, 404)
121 let envelope = try JSONDecoder().decode(ErrorEnvelope.self, from: response.body)
122 XCTAssertFalse(envelope.success)
123 XCTAssertEqual(envelope.version, "v1")
124 XCTAssertEqual(envelope.error.code, "not_found")
125 }
126
127 // MARK: Helpers
128
129 /// Header keys are lowercased by the request parser, which is why the
130 /// handler looks them up in lower case.
131 private func request(path: String = "/portfolio", headers: [String: String]) -> LocalAPIHTTPRequest {
132 LocalAPIHTTPRequest(method: "GET", path: path, queryItems: [], headers: headers, body: Data())
133 }
134}
135
136/// Decoded independently of the app's own envelope type, so the test asserts
137/// the wire shape the contract promises rather than agreeing with itself.
138private struct ErrorEnvelope: Decodable {
139 struct Failure: Decodable {
140 let code: String
141 let message: String
142 }
143
144 let success: Bool
145 let version: String
146 let error: Failure
147}
LocalAPIService.swift +61 −54
@@ -478,7 +478,49 @@ private final class LocalAPIServer: @unchecked Sendable {
478478 }
479479}
480480
481private struct LocalAPIRequestHandler {
481/// The `v1` routes. Matching is separated from execution so the table can be
482/// exercised without reading the store or reaching the network, and so adding a
483/// route cannot silently shadow an existing one.
484enum LocalAPIRoute: Equatable {
485 case portfolio
486 case domains
487 case domainDetails(String)
488 case domainHistory(String)
489 case events
490 case monitoring
491 case inspectFromBody
492 case inspect(String)
493 case setMonitoring(domain: String, enabled: Bool)
494
495 static func match(method: String, pathComponents: [String]) -> LocalAPIRoute? {
496 switch (method, pathComponents.first, pathComponents.count) {
497 case ("GET", "portfolio", 1):
498 return .portfolio
499 case ("GET", "domains", 1):
500 return .domains
501 case ("GET", "domains", 2):
502 return .domainDetails(pathComponents[1])
503 case ("GET", "domains", 3) where pathComponents[2] == "history":
504 return .domainHistory(pathComponents[1])
505 case ("GET", "events", 1):
506 return .events
507 case ("GET", "monitoring", 1):
508 return .monitoring
509 case ("POST", "inspect", 1):
510 return .inspectFromBody
511 case ("POST", "inspect", 2):
512 return .inspect(pathComponents[1])
513 case ("POST", "monitoring", 3) where pathComponents[2] == "enable":
514 return .setMonitoring(domain: pathComponents[1], enabled: true)
515 case ("POST", "monitoring", 3) where pathComponents[2] == "disable":
516 return .setMonitoring(domain: pathComponents[1], enabled: false)
517 default:
518 return nil
519 }
520 }
521}
522
523struct LocalAPIRequestHandler {
482524 private let encoder = LocalAPIContract.makeEncoder()
483525
484526 private let decoder: JSONDecoder = {
@@ -491,72 +533,37 @@ private struct LocalAPIRequestHandler {
491533 private let reportBuilder = DomainReportBuilder()
492534
493535 func handle(request: LocalAPIHTTPRequest, expectedToken: String) async -> LocalAPIHTTPResponse {
494 guard isAuthorized(request: request, expectedToken: expectedToken) else {
536 guard Self.isAuthorized(request: request, expectedToken: expectedToken) else {
495537 return .error(statusCode: 401, code: "unauthorized", message: "A valid local API token is required.")
496538 }
497539
498 if request.method == "GET", request.pathComponents == ["portfolio"] {
499 return successResponse(PortfolioPayload(summary: buildPortfolioSummary()))
540 guard let route = LocalAPIRoute.match(method: request.method, pathComponents: request.pathComponents) else {
541 return .error(statusCode: 404, code: "not_found", message: "The requested Local API route does not exist.")
500542 }
501543
502 if request.method == "GET", request.pathComponents == ["domains"] {
544 switch route {
545 case .portfolio:
546 return successResponse(PortfolioPayload(summary: buildPortfolioSummary()))
547 case .domains:
503548 return successResponse(DomainListPayload(domains: DomainDataPortabilityService.loadTrackedDomains()))
504 }
505
506 if request.method == "GET",
507 request.pathComponents.count == 2,
508 request.pathComponents.first == "domains" {
509 let domain = request.pathComponents[1]
549 case let .domainDetails(domain):
510550 return domainDetailsResponse(for: domain)
511 }
512
513 if request.method == "GET",
514 request.pathComponents.count == 3,
515 request.pathComponents.first == "domains",
516 request.pathComponents.last == "history" {
517 let domain = request.pathComponents[1]
551 case let .domainHistory(domain):
518552 return successResponse(DomainHistoryPayload(domain: normalizedDomain(domain), history: historyEntries(for: domain)))
519 }
520
521 if request.method == "GET", request.pathComponents == ["events"] {
553 case .events:
522554 return successResponse(RecentEventsPayload(events: recentEvents()))
523 }
524
525 if request.method == "GET", request.pathComponents == ["monitoring"] {
555 case .monitoring:
526556 return successResponse(monitoringPayload())
527 }
528
529 if request.method == "POST", request.pathComponents == ["inspect"] {
557 case .inspectFromBody:
530558 return await inspectBodyResponse(request.body)
531 }
532
533 if request.method == "POST",
534 request.pathComponents.count == 2,
535 request.pathComponents.first == "inspect" {
536 let domain = request.pathComponents[1]
559 case let .inspect(domain):
537560 return await inspectResponse(for: domain)
561 case let .setMonitoring(domain, enabled):
562 return await setMonitoring(enabled: enabled, for: domain)
538563 }
539
540 if request.method == "POST",
541 request.pathComponents.count == 3,
542 request.pathComponents.first == "monitoring",
543 request.pathComponents.last == "enable" {
544 let domain = request.pathComponents[1]
545 return await setMonitoring(enabled: true, for: domain)
546 }
547
548 if request.method == "POST",
549 request.pathComponents.count == 3,
550 request.pathComponents.first == "monitoring",
551 request.pathComponents.last == "disable" {
552 let domain = request.pathComponents[1]
553 return await setMonitoring(enabled: false, for: domain)
554 }
555
556 return .error(statusCode: 404, code: "not_found", message: "The requested Local API route does not exist.")
557564 }
558565
559 private func isAuthorized(request: LocalAPIHTTPRequest, expectedToken: String) -> Bool {
566 static func isAuthorized(request: LocalAPIHTTPRequest, expectedToken: String) -> Bool {
560567 guard !expectedToken.isEmpty else { return false }
561568
562569 if request.headers["x-api-token"] == expectedToken {
@@ -766,7 +773,7 @@ private struct LocalAPIRequestHandler {
766773 }
767774}
768775
769private struct LocalAPIHTTPRequest {
776struct LocalAPIHTTPRequest {
770777 let method: String
771778 let path: String
772779 let queryItems: [URLQueryItem]
@@ -788,7 +795,7 @@ private struct LocalAPIHTTPRequest {
788795 }
789796}
790797
791private struct LocalAPIHTTPResponse {
798struct LocalAPIHTTPResponse {
792799 let statusCode: Int
793800 let body: Data
794801