Separate Local API routing from execution, and cover it !18
3 files changed, +212 −54
Layout: unified · split
DomainDig.xcodeproj/project.pbxproj +4
| @@ -29,6 +29,7 @@ | ||
| 29 | 29 | A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000201 /* InspectionInputTests.swift */; }; |
| 30 | 30 | A1B2C3D40000000000000602 /* FeatureAccessTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000601 /* FeatureAccessTests.swift */; }; |
| 31 | 31 | A1B2C3D40000000000000702 /* SMTPMessageTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000701 /* SMTPMessageTests.swift */; }; |
| 32 | A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */; }; | |
| 32 | 33 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; }; |
| 33 | 34 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; }; |
| 34 | 35 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; }; |
| @@ -105,6 +106,7 @@ | ||
| 105 | 106 | A1B2C3D40000000000000201 /* InspectionInputTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InspectionInputTests.swift; sourceTree = "<group>"; }; |
| 106 | 107 | A1B2C3D40000000000000601 /* FeatureAccessTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = FeatureAccessTests.swift; sourceTree = "<group>"; }; |
| 107 | 108 | 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>"; }; | |
| 108 | 110 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; }; |
| 109 | 111 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; }; |
| 110 | 112 | A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; }; |
| @@ -246,6 +248,7 @@ | ||
| 246 | 248 | A1B2C3D40000000000000201 /* InspectionInputTests.swift */, |
| 247 | 249 | A1B2C3D40000000000000601 /* FeatureAccessTests.swift */, |
| 248 | 250 | A1B2C3D40000000000000701 /* SMTPMessageTests.swift */, |
| 251 | A1B2C3D40000000000000801 /* LocalAPIRoutingTests.swift */, | |
| 249 | 252 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */, |
| 250 | 253 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */, |
| 251 | 254 | A1B2C3D40000000000000501 /* DomainNameTests.swift */, |
| @@ -512,6 +515,7 @@ | ||
| 512 | 515 | A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */, |
| 513 | 516 | A1B2C3D40000000000000602 /* FeatureAccessTests.swift in Sources */, |
| 514 | 517 | A1B2C3D40000000000000702 /* SMTPMessageTests.swift in Sources */, |
| 518 | A1B2C3D40000000000000802 /* LocalAPIRoutingTests.swift in Sources */, | |
| 515 | 519 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */, |
| 516 | 520 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */, |
| 517 | 521 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */, |
DomainDigTests/LocalAPIRoutingTests.swift added +147
| @@ -0,0 +1,147 @@ | ||
| 1 | import 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. | |
| 9 | final 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. | |
| 138 | private 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 { | ||
| 478 | 478 | } |
| 479 | 479 | } |
| 480 | 480 | |
| 481 | private 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. | |
| 484 | enum 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 | ||
| 523 | struct LocalAPIRequestHandler { | |
| 482 | 524 | private let encoder = LocalAPIContract.makeEncoder() |
| 483 | 525 | |
| 484 | 526 | private let decoder: JSONDecoder = { |
| @@ -491,72 +533,37 @@ private struct LocalAPIRequestHandler { | ||
| 491 | 533 | private let reportBuilder = DomainReportBuilder() |
| 492 | 534 | |
| 493 | 535 | 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 { | |
| 495 | 537 | return .error(statusCode: 401, code: "unauthorized", message: "A valid local API token is required.") |
| 496 | 538 | } |
| 497 | 539 | |
| 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.") | |
| 500 | 542 | } |
| 501 | 543 | |
| 502 | if request.method == "GET", request.pathComponents == ["domains"] { | |
| 544 | switch route { | |
| 545 | case .portfolio: | |
| 546 | return successResponse(PortfolioPayload(summary: buildPortfolioSummary())) | |
| 547 | case .domains: | |
| 503 | 548 | 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): | |
| 510 | 550 | 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): | |
| 518 | 552 | return successResponse(DomainHistoryPayload(domain: normalizedDomain(domain), history: historyEntries(for: domain))) |
| 519 | } | |
| 520 | ||
| 521 | if request.method == "GET", request.pathComponents == ["events"] { | |
| 553 | case .events: | |
| 522 | 554 | return successResponse(RecentEventsPayload(events: recentEvents())) |
| 523 | } | |
| 524 | ||
| 525 | if request.method == "GET", request.pathComponents == ["monitoring"] { | |
| 555 | case .monitoring: | |
| 526 | 556 | return successResponse(monitoringPayload()) |
| 527 | } | |
| 528 | ||
| 529 | if request.method == "POST", request.pathComponents == ["inspect"] { | |
| 557 | case .inspectFromBody: | |
| 530 | 558 | 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): | |
| 537 | 560 | return await inspectResponse(for: domain) |
| 561 | case let .setMonitoring(domain, enabled): | |
| 562 | return await setMonitoring(enabled: enabled, for: domain) | |
| 538 | 563 | } |
| 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.") | |
| 557 | 564 | } |
| 558 | 565 | |
| 559 | private func isAuthorized(request: LocalAPIHTTPRequest, expectedToken: String) -> Bool { | |
| 566 | static func isAuthorized(request: LocalAPIHTTPRequest, expectedToken: String) -> Bool { | |
| 560 | 567 | guard !expectedToken.isEmpty else { return false } |
| 561 | 568 | |
| 562 | 569 | if request.headers["x-api-token"] == expectedToken { |
| @@ -766,7 +773,7 @@ private struct LocalAPIRequestHandler { | ||
| 766 | 773 | } |
| 767 | 774 | } |
| 768 | 775 | |
| 769 | private struct LocalAPIHTTPRequest { | |
| 776 | struct LocalAPIHTTPRequest { | |
| 770 | 777 | let method: String |
| 771 | 778 | let path: String |
| 772 | 779 | let queryItems: [URLQueryItem] |
| @@ -788,7 +795,7 @@ private struct LocalAPIHTTPRequest { | ||
| 788 | 795 | } |
| 789 | 796 | } |
| 790 | 797 | |
| 791 | private struct LocalAPIHTTPResponse { | |
| 798 | struct LocalAPIHTTPResponse { | |
| 792 | 799 | let statusCode: Int |
| 793 | 800 | let body: Data |
| 794 | 801 | |