DomainDigTests/S3UploadClientTests.swift

433 lines · 16988 bytes

31 symbols in this file
  1import XCTest
  2@testable import DomainDig
  3
  4/// `AWSSigV4Tests` pins the signature itself to AWS's published vectors, so
  5/// what is left to check here is that the client hands the signer the right
  6/// inputs — and, above all, that the URL it sends carries the same encoded
  7/// path the signature was computed over. If those two disagree the upload
  8/// fails as `SignatureDoesNotMatch`, which says nothing about why.
  9final class S3UploadClientTests: XCTestCase {
 10
 11    private let credentials = AWSSigV4.Credentials(
 12        accessKeyID: "AKIAIOSFODNN7EXAMPLE",
 13        secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
 14    )
 15
 16    private let now = Date(timeIntervalSince1970: 1_369_353_600)
 17
 18    private func configuration(
 19        endpoint: String = "https://s3.eu-central-1.amazonaws.com",
 20        region: String = "eu-central-1",
 21        bucket: String = "my-bucket",
 22        keyPrefix: String = "domaindig",
 23        usesPathStyle: Bool = false
 24    ) -> S3IntegrationConfiguration {
 25        S3IntegrationConfiguration(
 26            endpoint: endpoint,
 27            region: region,
 28            bucket: bucket,
 29            keyPrefix: keyPrefix,
 30            usesPathStyle: usesPathStyle,
 31            accessKeyID: credentials.accessKeyID,
 32            credentialReference: "ref"
 33        )
 34    }
 35
 36    private func object(key: String = "example.com/2013-05-24T00:00:00Z.json") -> S3UploadClient.Object {
 37        S3UploadClient.Object(key: key, body: Data("{}".utf8), contentType: "application/json")
 38    }
 39
 40    // MARK: Addressing
 41
 42    func testVirtualHostedAddressingPutsTheBucketInTheHost() throws {
 43        let request = try S3UploadClient.request(
 44            for: object(),
 45            configuration: configuration(),
 46            credentials: credentials,
 47            now: now
 48        )
 49
 50        XCTAssertEqual(request.httpMethod, "PUT")
 51        XCTAssertEqual(
 52            request.url?.absoluteString,
 53            "https://my-bucket.s3.eu-central-1.amazonaws.com/domaindig/example.com/2013-05-24T00%3A00%3A00Z.json"
 54        )
 55    }
 56
 57    /// MinIO and R2 custom domains need the bucket in the path instead.
 58    func testPathStyleAddressingPutsTheBucketInThePath() throws {
 59        let request = try S3UploadClient.request(
 60            for: object(),
 61            configuration: configuration(endpoint: "https://minio.example.com", usesPathStyle: true),
 62            credentials: credentials,
 63            now: now
 64        )
 65
 66        XCTAssertEqual(
 67            request.url?.absoluteString,
 68            "https://minio.example.com/my-bucket/domaindig/example.com/2013-05-24T00%3A00%3A00Z.json"
 69        )
 70    }
 71
 72    /// A non-default port is part of the signed host header, because the
 73    /// server compares the header it received.
 74    func testANonDefaultPortReachesTheSignedHostHeader() throws {
 75        let request = try S3UploadClient.request(
 76            for: object(),
 77            configuration: configuration(endpoint: "https://minio.example.com:9000", usesPathStyle: true),
 78            credentials: credentials,
 79            now: now
 80        )
 81
 82        XCTAssertEqual(request.url?.port, 9000)
 83        // Signed under the host:port form, which is what the signature below
 84        // has to have been computed over.
 85        let expected = AWSSigV4.authorizationHeader(
 86            for: AWSSigV4.Request(
 87                method: "PUT",
 88                path: "/my-bucket/domaindig/example.com/2013-05-24T00:00:00Z.json",
 89                headers: [
 90                    "Host": "minio.example.com:9000",
 91                    "Content-Type": "application/json",
 92                    "x-amz-content-sha256": AWSSigV4.sha256Hex(Data("{}".utf8)),
 93                    "x-amz-date": "20130524T000000Z"
 94                ],
 95                payloadSHA256: AWSSigV4.sha256Hex(Data("{}".utf8))
 96            ),
 97            scope: AWSSigV4.Scope(region: "eu-central-1", service: "s3", date: now),
 98            credentials: credentials
 99        )
100        XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), expected)
101    }
102
103    // MARK: The URL and the signature have to agree
104
105    /// The invariant the whole client turns on: whatever encoding the URL
106    /// carries is the encoding the signature covers. A space is the case
107    /// `URLComponents` and SigV4 disagree about.
108    func testTheSentPathIsExactlyThePathThatWasSigned() throws {
109        let configuration = configuration(keyPrefix: "")
110        let object = object(key: "a domain/with space.json")
111
112        let request = try S3UploadClient.request(
113            for: object,
114            configuration: configuration,
115            credentials: credentials,
116            now: now
117        )
118
119        let signedPath = AWSSigV4.canonicalURI(for: "/a domain/with space.json")
120        XCTAssertEqual(signedPath, "/a%20domain/with%20space.json")
121        XCTAssertEqual(
122            request.url?.absoluteString,
123            "https://my-bucket.s3.eu-central-1.amazonaws.com\(signedPath)"
124        )
125    }
126
127    func testTheContentHashHeaderIsTheHashOfTheBody() throws {
128        let body = Data("some report".utf8)
129        let request = try S3UploadClient.request(
130            for: S3UploadClient.Object(key: "k.json", body: body, contentType: "application/json"),
131            configuration: configuration(),
132            credentials: credentials,
133            now: now
134        )
135
136        XCTAssertEqual(
137            request.value(forHTTPHeaderField: "x-amz-content-sha256"),
138            AWSSigV4.sha256Hex(body)
139        )
140        XCTAssertEqual(request.httpBody, body)
141    }
142
143    /// `URLSession` sets Host from the URL, so the client must not also set it
144    /// — a duplicate would be sent twice and break the signature.
145    func testTheHostHeaderIsLeftToURLSession() throws {
146        let request = try S3UploadClient.request(
147            for: object(),
148            configuration: configuration(),
149            credentials: credentials,
150            now: now
151        )
152
153        XCTAssertNil(request.value(forHTTPHeaderField: "Host"))
154        XCTAssertNotNil(request.value(forHTTPHeaderField: "Authorization"))
155        XCTAssertEqual(request.value(forHTTPHeaderField: "x-amz-date"), "20130524T000000Z")
156    }
157
158    // MARK: Rejected configurations
159
160    /// The one that matters: http would put the access key ID and the
161    /// signature on the wire in the clear, and F3's NSAllowsArbitraryLoads
162    /// means nothing else would stop it.
163    func testAnHTTPEndpointIsRejected() {
164        XCTAssertThrowsError(
165            try S3UploadClient.request(
166                for: object(),
167                configuration: configuration(endpoint: "http://s3.example.com"),
168                credentials: credentials,
169                now: now
170            )
171        ) { error in
172            XCTAssertEqual(error as? S3UploadClient.UploadError, .insecureEndpoint)
173        }
174    }
175
176    func testAnEndpointWithNoHostIsRejected() {
177        XCTAssertThrowsError(
178            try S3UploadClient.request(
179                for: object(),
180                configuration: configuration(endpoint: "not a url"),
181                credentials: credentials,
182                now: now
183            )
184        ) { error in
185            XCTAssertEqual(error as? S3UploadClient.UploadError, .invalidEndpoint)
186        }
187    }
188
189    func testAMissingBucketIsRejected() {
190        XCTAssertThrowsError(
191            try S3UploadClient.request(
192                for: object(),
193                configuration: configuration(bucket: "   "),
194                credentials: credentials,
195                now: now
196            )
197        ) { error in
198            XCTAssertEqual(error as? S3UploadClient.UploadError, .missingBucket)
199        }
200    }
201
202    // MARK: Keys
203
204    func testThePrefixIsJoinedWithoutDoubledSlashes() {
205        let object = object(key: "/example.com/x.json")
206
207        XCTAssertEqual(
208            S3UploadClient.objectKey(for: object, configuration: configuration(keyPrefix: "domaindig/")),
209            "domaindig/example.com/x.json"
210        )
211        XCTAssertEqual(
212            S3UploadClient.objectKey(for: object, configuration: configuration(keyPrefix: "/reports/")),
213            "reports/example.com/x.json"
214        )
215    }
216
217    func testAnEmptyPrefixLeavesTheKeyAlone() {
218        XCTAssertEqual(
219            S3UploadClient.objectKey(for: object(key: "example.com/x.json"), configuration: configuration(keyPrefix: "  ")),
220            "example.com/x.json"
221        )
222    }
223
224    // MARK: Responses
225
226    func testASuccessfulStatusPasses() {
227        XCTAssertNoThrow(try S3UploadClient.validate(statusCode: 200, body: Data()))
228        XCTAssertNoThrow(try S3UploadClient.validate(statusCode: 204, body: Data()))
229    }
230
231    func testAnErrorStatusCarriesTheServicesOwnErrorCode() {
232        let body = Data("""
233            <?xml version="1.0" encoding="UTF-8"?>
234            <Error><Code>AccessDenied</Code><Message>Access Denied</Message></Error>
235            """.utf8)
236
237        XCTAssertThrowsError(try S3UploadClient.validate(statusCode: 403, body: body)) { error in
238            XCTAssertEqual(error as? S3UploadClient.UploadError, .rejected(statusCode: 403, message: "AccessDenied"))
239        }
240    }
241
242    /// SigV4 refuses a request signed more than 15 minutes from server time,
243    /// and the service's own message does not say the device's clock is the
244    /// problem. This is the same device-clock failure D9 addresses in sync.
245    func testASkewedClockIsReportedAsSuch() {
246        let body = Data("<Error><Code>RequestTimeTooSkewed</Code></Error>".utf8)
247
248        XCTAssertThrowsError(try S3UploadClient.validate(statusCode: 403, body: body)) { error in
249            XCTAssertEqual(error as? S3UploadClient.UploadError, .clockSkew)
250            XCTAssertTrue(
251                error.localizedDescription.contains("clock"),
252                "the message has to point at the clock, since the service's does not"
253            )
254        }
255    }
256
257    func testAnErrorWithNoParsableCodeStillReportsTheStatus() {
258        XCTAssertThrowsError(try S3UploadClient.validate(statusCode: 500, body: Data("nope".utf8))) { error in
259            XCTAssertEqual(error as? S3UploadClient.UploadError, .rejected(statusCode: 500, message: nil))
260        }
261    }
262
263    func testErrorCodeParsing() {
264        XCTAssertEqual(S3UploadClient.errorCode(in: Data("<Code>NoSuchBucket</Code>".utf8)), "NoSuchBucket")
265        XCTAssertNil(S3UploadClient.errorCode(in: Data("<Code></Code>".utf8)))
266        XCTAssertNil(S3UploadClient.errorCode(in: Data("<Other>x</Other>".utf8)))
267        XCTAssertNil(S3UploadClient.errorCode(in: Data()))
268    }
269
270    // MARK: The configuration round-trips
271
272    /// The target is persisted as JSON, so a new case in
273    /// `IntegrationConfiguration` has to survive the trip.
274    func testTheS3TargetRoundTripsThroughCoding() throws {
275        let target = IntegrationTarget(
276            type: .s3,
277            name: "Backups",
278            configuration: .s3(configuration(usesPathStyle: true))
279        )
280
281        let decoded = try JSONDecoder().decode(
282            IntegrationTarget.self,
283            from: try JSONEncoder().encode(target)
284        )
285
286        XCTAssertEqual(decoded, target)
287        XCTAssertEqual(decoded.configuration.type, .s3)
288        guard case .s3(let configuration) = decoded.configuration else {
289            return XCTFail("expected an s3 configuration")
290        }
291        XCTAssertTrue(configuration.usesPathStyle)
292        XCTAssertEqual(configuration.bucket, "my-bucket")
293    }
294
295    // MARK: Triggers
296
297    /// Scheduled, monitoring and batch upload by default; an interactive Run
298    /// does not, because every tap would otherwise ship an object (D1).
299    func testInteractiveRunIsTheOnlyTriggerOffByDefault() {
300        let configuration = S3IntegrationConfiguration()
301
302        XCTAssertTrue(configuration.uploads(on: .scheduled))
303        XCTAssertTrue(configuration.uploads(on: .monitoring))
304        XCTAssertTrue(configuration.uploads(on: .batch))
305        XCTAssertFalse(configuration.uploads(on: .interactiveRun))
306    }
307
308    func testTriggersAreIndependentlySettable() {
309        var configuration = S3IntegrationConfiguration(triggers: [.interactiveRun])
310
311        XCTAssertTrue(configuration.uploads(on: .interactiveRun))
312        XCTAssertFalse(configuration.uploads(on: .monitoring))
313
314        configuration.triggers = []
315        for trigger in S3ExportTrigger.allCases {
316            XCTAssertFalse(configuration.uploads(on: trigger))
317        }
318    }
319
320    // MARK: Formats
321
322    /// JSON always uploads: it is the only format that round-trips, and the
323    /// others are renderings of it.
324    func testJSONUploadsEvenWithNoExtraFormats() {
325        XCTAssertEqual(S3IntegrationConfiguration().formats, [.json])
326    }
327
328    func testExtraFormatsAreAddedAfterJSON() {
329        let configuration = S3IntegrationConfiguration(extraFormats: [.pdf, .csv])
330
331        XCTAssertEqual(configuration.formats.first, .json)
332        XCTAssertEqual(Set(configuration.formats), [.json, .csv, .pdf])
333    }
334
335    /// JSON is implicit, so selecting it as an extra must not upload it twice.
336    func testJSONAsAnExtraFormatIsNotDuplicated() {
337        XCTAssertEqual(S3IntegrationConfiguration(extraFormats: [.json]).formats, [.json])
338    }
339
340    /// The key template is `{prefix}/{domain}/{iso8601}.{ext}`, so each format
341    /// lands at its own key rather than overwriting the last one.
342    func testEachFormatHasItsOwnExtension() {
343        XCTAssertEqual(DomainExportFormat.json.fileExtension, "json")
344        XCTAssertEqual(DomainExportFormat.pdf.fileExtension, "pdf")
345        XCTAssertEqual(DomainExportFormat.csv.fileExtension, "csv")
346        XCTAssertEqual(DomainExportFormat.pdf.mimeType, "application/pdf")
347        XCTAssertEqual(DomainExportFormat.json.mimeType, "application/json")
348    }
349
350    /// The export carrier is not an alert, so it must not appear in the list a
351    /// user filters an integration on.
352    func testTheExportEventTypeIsNotFilterable() {
353        XCTAssertFalse(MonitoringEventType.filterable.contains(.reportExported))
354        XCTAssertFalse(MonitoringEventType.filterable.contains(.test))
355        XCTAssertTrue(MonitoringEventType.filterable.contains(.dnsChanged))
356    }
357
358    /// Queue entries written before exports existed have no `export` field and
359    /// still have to decode.
360    func testAQueueEntryWithoutAnExportDescriptorStillDecodes() throws {
361        let json = Data("""
362            {
363              "id": "5E7E4B0E-0000-4000-8000-000000000001",
364              "integrationID": "5E7E4B0E-0000-4000-8000-000000000002",
365              "event": {
366                "id": "5E7E4B0E-0000-4000-8000-000000000003",
367                "type": "dnsChanged",
368                "severity": "warning",
369                "domain": "example.com",
370                "timestamp": 0,
371                "summary": "changed",
372                "details": {}
373              },
374              "createdAt": 0,
375              "attemptCount": 0,
376              "nextAttemptAt": 0,
377              "expiresAt": 1
378            }
379            """.utf8)
380
381        let decoded = try JSONDecoder().decode(QueuedDelivery.self, from: json)
382
383        XCTAssertNil(decoded.export)
384        XCTAssertEqual(decoded.event.domain, "example.com")
385    }
386
387    func testAnExportQueueEntryRoundTrips() throws {
388        let entry = QueuedDelivery(
389            integrationID: UUID(),
390            event: MonitoringEvent(
391                type: .reportExported,
392                severity: .info,
393                domain: "example.com",
394                summary: "Batch lookups: example.com as PDF"
395            ),
396            export: ExportDelivery(format: .pdf, trigger: .batch)
397        )
398
399        let decoded = try JSONDecoder().decode(
400            QueuedDelivery.self,
401            from: try JSONEncoder().encode(entry)
402        )
403
404        XCTAssertEqual(decoded.export, ExportDelivery(format: .pdf, trigger: .batch))
405        XCTAssertEqual(decoded.event.type, .reportExported)
406    }
407
408    /// Triggers and formats are persisted with the target.
409    func testTriggersAndFormatsRoundTripThroughCoding() throws {
410        var configuration = configuration()
411        configuration.triggers = [.interactiveRun, .batch]
412        configuration.extraFormats = [.pdf]
413
414        let decoded = try JSONDecoder().decode(
415            S3IntegrationConfiguration.self,
416            from: try JSONEncoder().encode(configuration)
417        )
418
419        XCTAssertEqual(decoded.triggers, [.interactiveRun, .batch])
420        XCTAssertEqual(decoded.extraFormats, [.pdf])
421        XCTAssertEqual(decoded.formats, [.json, .pdf])
422    }
423
424    /// The secret is never part of the configuration — it lives in the
425    /// Keychain and only the reference is stored.
426    func testTheConfigurationCarriesNoSecret() throws {
427        let encoded = try JSONEncoder().encode(configuration())
428        let json = try XCTUnwrap(String(data: encoded, encoding: .utf8))
429
430        XCTAssertFalse(json.contains(credentials.secretAccessKey))
431        XCTAssertTrue(json.contains(credentials.accessKeyID), "the key ID is not a secret and is shown in the editor")
432    }
433}