DomainDigTests/LocalAPIRoutingTests.swift
149 lines · 6495 bytes
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 moved to `LocalAPISuccessTests` once the handler took an
9/// injected store; `/inspect` is still uncovered, because it runs a live
10/// lookup.
11final class LocalAPIRoutingTests: XCTestCase {
12
13 // MARK: Every documented route
14
15 func testGetRoutes() {
16 XCTAssertEqual(LocalAPIRoute.match(method: "GET", pathComponents: ["portfolio"]), .portfolio)
17 XCTAssertEqual(LocalAPIRoute.match(method: "GET", pathComponents: ["domains"]), .domains)
18 XCTAssertEqual(LocalAPIRoute.match(method: "GET", pathComponents: ["events"]), .events)
19 XCTAssertEqual(LocalAPIRoute.match(method: "GET", pathComponents: ["monitoring"]), .monitoring)
20 }
21
22 func testDomainScopedGetRoutesCarryTheDomain() {
23 XCTAssertEqual(
24 LocalAPIRoute.match(method: "GET", pathComponents: ["domains", "example.com"]),
25 .domainDetails("example.com")
26 )
27 XCTAssertEqual(
28 LocalAPIRoute.match(method: "GET", pathComponents: ["domains", "example.com", "history"]),
29 .domainHistory("example.com")
30 )
31 }
32
33 func testPostRoutes() {
34 XCTAssertEqual(LocalAPIRoute.match(method: "POST", pathComponents: ["inspect"]), .inspectFromBody)
35 XCTAssertEqual(
36 LocalAPIRoute.match(method: "POST", pathComponents: ["inspect", "example.com"]),
37 .inspect("example.com")
38 )
39 }
40
41 func testMonitoringTogglesCarryBothDomainAndState() {
42 XCTAssertEqual(
43 LocalAPIRoute.match(method: "POST", pathComponents: ["monitoring", "example.com", "enable"]),
44 .setMonitoring(domain: "example.com", enabled: true)
45 )
46 XCTAssertEqual(
47 LocalAPIRoute.match(method: "POST", pathComponents: ["monitoring", "example.com", "disable"]),
48 .setMonitoring(domain: "example.com", enabled: false)
49 )
50 }
51
52 // MARK: What must not match
53
54 /// The method is part of the route, not decoration: a read route must not
55 /// answer a write and the reverse.
56 func testTheMethodIsPartOfTheRoute() {
57 XCTAssertNil(LocalAPIRoute.match(method: "POST", pathComponents: ["portfolio"]))
58 XCTAssertNil(LocalAPIRoute.match(method: "GET", pathComponents: ["inspect"]))
59 XCTAssertNil(LocalAPIRoute.match(method: "DELETE", pathComponents: ["domains", "example.com"]))
60 }
61
62 func testUnknownTrailingSegmentsDoNotMatch() {
63 XCTAssertNil(LocalAPIRoute.match(method: "GET", pathComponents: ["domains", "example.com", "notes"]))
64 XCTAssertNil(LocalAPIRoute.match(method: "POST", pathComponents: ["monitoring", "example.com", "pause"]))
65 }
66
67 func testUnknownAndEmptyPathsDoNotMatch() {
68 XCTAssertNil(LocalAPIRoute.match(method: "GET", pathComponents: ["nope"]))
69 XCTAssertNil(LocalAPIRoute.match(method: "GET", pathComponents: []))
70 XCTAssertNil(LocalAPIRoute.match(method: "GET", pathComponents: ["portfolio", "extra"]))
71 }
72
73 // MARK: Authorisation
74
75 func testEitherDocumentedHeaderAuthorises() {
76 XCTAssertTrue(LocalAPIRequestHandler.isAuthorized(
77 request: request(headers: ["x-api-token": "secret"]), expectedToken: "secret"
78 ))
79 XCTAssertTrue(LocalAPIRequestHandler.isAuthorized(
80 request: request(headers: ["authorization": "Bearer secret"]), expectedToken: "secret"
81 ))
82 }
83
84 func testAWrongOrMissingTokenIsRefused() {
85 XCTAssertFalse(LocalAPIRequestHandler.isAuthorized(
86 request: request(headers: ["x-api-token": "wrong"]), expectedToken: "secret"
87 ))
88 XCTAssertFalse(LocalAPIRequestHandler.isAuthorized(request: request(headers: [:]), expectedToken: "secret"))
89 XCTAssertFalse(LocalAPIRequestHandler.isAuthorized(
90 request: request(headers: ["authorization": "secret"]), expectedToken: "secret"
91 ))
92 }
93
94 /// With no token configured the server must refuse everything rather than
95 /// treat an absent credential as a match.
96 func testAnUnconfiguredTokenRefusesEverything() {
97 XCTAssertFalse(LocalAPIRequestHandler.isAuthorized(request: request(headers: [:]), expectedToken: ""))
98 XCTAssertFalse(LocalAPIRequestHandler.isAuthorized(
99 request: request(headers: ["x-api-token": ""]), expectedToken: ""
100 ))
101 }
102
103 // MARK: The error envelopes the contract documents
104
105 func testAnUnauthorisedRequestAnswers401InTheEnvelope() async throws {
106 let response = await LocalAPIRequestHandler().handle(
107 request: request(path: "/portfolio", headers: [:]), expectedToken: "secret"
108 )
109
110 XCTAssertEqual(response.statusCode, 401)
111 let envelope = try JSONDecoder().decode(ErrorEnvelope.self, from: response.body)
112 XCTAssertFalse(envelope.success)
113 XCTAssertEqual(envelope.version, "v1")
114 XCTAssertEqual(envelope.error.code, "unauthorized")
115 }
116
117 func testAnUnknownRouteAnswers404InTheEnvelope() async throws {
118 let response = await LocalAPIRequestHandler().handle(
119 request: request(path: "/nope", headers: ["x-api-token": "secret"]), expectedToken: "secret"
120 )
121
122 XCTAssertEqual(response.statusCode, 404)
123 let envelope = try JSONDecoder().decode(ErrorEnvelope.self, from: response.body)
124 XCTAssertFalse(envelope.success)
125 XCTAssertEqual(envelope.version, "v1")
126 XCTAssertEqual(envelope.error.code, "not_found")
127 }
128
129 // MARK: Helpers
130
131 /// Header keys are lowercased by the request parser, which is why the
132 /// handler looks them up in lower case.
133 private func request(path: String = "/portfolio", headers: [String: String]) -> LocalAPIHTTPRequest {
134 LocalAPIHTTPRequest(method: "GET", path: path, queryItems: [], headers: headers, body: Data())
135 }
136}
137
138/// Decoded independently of the app's own envelope type, so the test asserts
139/// the wire shape the contract promises rather than agreeing with itself.
140private struct ErrorEnvelope: Decodable {
141 struct Failure: Decodable {
142 let code: String
143 let message: String
144 }
145
146 let success: Bool
147 let version: String
148 let error: Failure
149}