DomainDigTests/LocalAPIRoutingTests.swift

147 lines · 6411 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 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}