Commit 3f5274031a

3f5274031a4ad11a9c848f4ec698d796eb912d6f

parent: d652697ea7

Unsigned

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

Add an S3-compatible export target, https only (!38)

W14's second and third parts, on top of the signer in !37. Covers D1's export
axis for S3, R2, B2, MinIO, Wasabi and Spaces.

`IntegrationType.s3` with a configuration model (endpoint, region, bucket, key
prefix, path-style flag, access key ID), the secret access key in the Keychain
through the existing `IntegrationSecretStore`, an editor section in
`IntegrationsView`, and delivery through the queue and retry that already
exist.

**https only.** The endpoint is validated on every save, not only when a new
key is supplied, because the endpoint is editable on its own. Signing puts the
access key ID on the wire and the signature with it, and F3 enabled
`NSAllowsArbitraryLoads`, so nothing else would stop an http endpoint. The
upload client checks again at request time, so a target that somehow got
persisted with http still cannot send.

**The URL and the signature have to agree.** The request's path is set from the
signer's own encoding rather than left to `URLComponents`, which encodes to a
different rule — a space is the clear case. When the two disagree the server
computes a different canonical request and the upload fails as
`SignatureDoesNotMatch`, which says nothing about why. There is a test for the
invariant.

**What gets uploaded.** `QueuedDelivery` holds a small `MonitoringEvent` and
persists to UserDefaults, so putting a report in the queue would bloat it.
Delivery re-renders the report from local history at upload time instead; the
data is already on the device and this keeps the queue small enough to survive
being cut off mid-refresh. A test delivery finds no report and uploads the
event, which is the point of the test action — it proves the endpoint, the
signature and the bucket policy without needing a lookup to have happened.

`RequestTimeTooSkewed` is surfaced as a device-clock problem. SigV4 refuses a
request signed more than 15 minutes from server time and the service's message
does not mention the clock. Same failure D9 addresses in sync.

**Tier gate.** New `bucketExport` capability, Pro+ per D1. Pro+ takes
`Set(FeatureCapability.allCases)` so it lands there by construction, while free
and pro enumerate explicitly and therefore exclude it — with a test that it did
not leak into either. The type picker omits it and `save()` refuses it, so the
gate does not rest on the picker alone. An existing target keeps its type
listed, so a downgrade leaves the editor readable instead of blank.

Adding the enum case made the compiler name all five switches in
`IntegrationsView` that needed it, which is the argument for the case over a
stringly-typed flag.

20 new tests, 320 green on iOS 18.6 and 27.0. Ratchet unchanged at 280.

Still to come in W14: part 4, the four completion triggers (scheduled, monitoring
and batch upload by default, interactive Run opt-in) and the PDF/CSV format
selection. Until those land the target uploads on monitoring events and on a
test delivery.

Layout: unified · split

DomainDig.xcodeproj/project.pbxproj +4
@@ -38,6 +38,7 @@
3838 A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */; };
3939 A1B2C3D40000000000001602 /* InspectionScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001601 /* InspectionScopeTests.swift */; };
4040 A1B2C3D40000000000001702 /* AWSSigV4Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001701 /* AWSSigV4Tests.swift */; };
41 A1B2C3D40000000000001802 /* S3UploadClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001801 /* S3UploadClientTests.swift */; };
4142 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; };
4243 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; };
4344 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; };
@@ -123,6 +124,7 @@
123124 A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PortfolioDashboardTests.swift; sourceTree = "<group>"; };
124125 A1B2C3D40000000000001601 /* InspectionScopeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InspectionScopeTests.swift; sourceTree = "<group>"; };
125126 A1B2C3D40000000000001701 /* AWSSigV4Tests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AWSSigV4Tests.swift; sourceTree = "<group>"; };
127 A1B2C3D40000000000001801 /* S3UploadClientTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = S3UploadClientTests.swift; sourceTree = "<group>"; };
126128 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; };
127129 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; };
128130 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; };
@@ -273,6 +275,7 @@
273275 A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */,
274276 A1B2C3D40000000000001601 /* InspectionScopeTests.swift */,
275277 A1B2C3D40000000000001701 /* AWSSigV4Tests.swift */,
278 A1B2C3D40000000000001801 /* S3UploadClientTests.swift */,
276279 A1B2C3D40000000000000301 /* AvailabilityTests.swift */,
277280 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */,
278281 A1B2C3D40000000000000501 /* DomainNameTests.swift */,
@@ -548,6 +551,7 @@
548551 A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */,
549552 A1B2C3D40000000000001602 /* InspectionScopeTests.swift in Sources */,
550553 A1B2C3D40000000000001702 /* AWSSigV4Tests.swift in Sources */,
554 A1B2C3D40000000000001802 /* S3UploadClientTests.swift in Sources */,
551555 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */,
552556 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */,
553557 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */,
DomainDig/FeatureAccessService.swift +5 −2
@@ -32,6 +32,7 @@ enum FeatureCapability: String, CaseIterable, Identifiable {
3232 case sharedPortfolios
3333 case auditDepth
3434 case intelligenceDetail
35 case bucketExport
3536
3637 var id: String { rawValue }
3738
@@ -61,6 +62,8 @@ enum FeatureCapability: String, CaseIterable, Identifiable {
6162 return "Unlimited audits"
6263 case .intelligenceDetail:
6364 return "Intelligence detail"
65 case .bucketExport:
66 return "Export to your own bucket"
6467 }
6568 }
6669}
@@ -191,7 +194,7 @@ enum FeatureAccessService {
191194 case .workflows, .batchOperations, .automatedMonitoring, .localAlerts, .advancedExports,
192195 .extendedSubdomains:
193196 return "Available in Pro"
194 case .sharedPortfolios, .auditDepth, .intelligenceDetail:
197 case .sharedPortfolios, .auditDepth, .intelligenceDetail, .bucketExport:
195198 return "Available in Pro+"
196199 case .limitedTracking:
197200 return "Tracking is limited on Free"
@@ -253,7 +256,7 @@ enum FeatureAccessService {
253256 static func upgradePrompt(for capability: FeatureCapability) -> UpgradePromptContext {
254257 let title: String
255258 switch capability {
256 case .sharedPortfolios, .auditDepth, .intelligenceDetail:
259 case .sharedPortfolios, .auditDepth, .intelligenceDetail, .bucketExport:
257260 title = "Available in Pro+"
258261 default:
259262 title = "Available in Pro"
DomainDig/IntegrationService.swift +78 −1
@@ -34,7 +34,8 @@ final class IntegrationService {
3434 target: IntegrationTarget,
3535 webhookURL: String? = nil,
3636 slackWebhookURL: String? = nil,
37 emailPassword: String? = nil
37 emailPassword: String? = nil,
38 s3SecretAccessKey: String? = nil
3839 ) throws {
3940 var updatedTarget = target
4041
@@ -64,6 +65,18 @@ final class IntegrationService {
6465 configuration.credentialReference = reference
6566 updatedTarget.configuration = .email(configuration)
6667 }
68 case .s3(var configuration):
69 // Validated on every save, not only when a new key is supplied:
70 // the endpoint is editable on its own, and an http endpoint would
71 // put the access key ID and the signature on the wire in the
72 // clear. F3's NSAllowsArbitraryLoads means nothing else stops it.
73 try Self.validateHTTPS(configuration.endpoint)
74 if let s3SecretAccessKey {
75 let reference = configuration.credentialReference ?? Self.secretReference(for: updatedTarget.id, suffix: "s3")
76 try IntegrationSecretStore.save(secret: s3SecretAccessKey, reference: reference)
77 configuration.credentialReference = reference
78 }
79 updatedTarget.configuration = .s3(configuration)
6780 }
6881
6982 if let index = targets.firstIndex(where: { $0.id == updatedTarget.id }) {
@@ -233,6 +246,8 @@ final class IntegrationService {
233246 configuration.credentialReference
234247 case .email(let configuration):
235248 configuration.credentialReference
249 case .s3(let configuration):
250 configuration.credentialReference
236251 }
237252 }
238253 }
@@ -391,6 +406,26 @@ final class IntegrationService {
391406 headers: [:],
392407 timeoutSeconds: 15
393408 )
409 case .s3(let configuration):
410 guard let reference = configuration.credentialReference else {
411 throw IntegrationError.missingSecret
412 }
413 let secretAccessKey = try IntegrationSecretStore.secret(reference: reference)
414 let object = Self.s3Object(for: event)
415 let request = try S3UploadClient.request(
416 for: object,
417 configuration: configuration,
418 credentials: AWSSigV4.Credentials(
419 accessKeyID: configuration.accessKeyID,
420 secretAccessKey: secretAccessKey
421 ),
422 now: Date()
423 )
424 let (data, response) = try await URLSession.shared.data(for: request)
425 try S3UploadClient.validate(
426 statusCode: (response as? HTTPURLResponse)?.statusCode ?? 0,
427 body: data
428 )
394429 case .email(let configuration):
395430 guard let reference = configuration.credentialReference else {
396431 throw IntegrationError.missingSecret
@@ -422,6 +457,42 @@ final class IntegrationService {
422457 Self.save(queue, key: StorageKey.queue, defaults: defaults)
423458 }
424459
460 /// What an event uploads: the domain's latest stored report when there is
461 /// one, and the event itself otherwise.
462 ///
463 /// A test delivery takes the second path, which is the point of it — it
464 /// proves the endpoint, the signature and the bucket policy without
465 /// needing a lookup to have happened first.
466 private static func s3Object(for event: MonitoringEvent) -> S3UploadClient.Object {
467 let encoder = JSONEncoder()
468 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
469 encoder.dateEncodingStrategy = .iso8601
470
471 let domain = event.domain.isEmpty ? "unknown" : event.domain
472 let snapshot = MonitoringStorage.loadHistoryEntries()
473 .first { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }?
474 .snapshot
475
476 let body: Data
477 if let snapshot, let encoded = try? encoder.encode(DomainReportBuilder().build(from: snapshot)) {
478 body = encoded
479 } else {
480 body = (try? encoder.encode(IntegrationEventPayload(event: event))) ?? Data()
481 }
482
483 return S3UploadClient.Object(
484 key: "\(domain)/\(Self.objectTimestampFormatter.string(from: event.timestamp)).json",
485 body: body,
486 contentType: "application/json"
487 )
488 }
489
490 private static let objectTimestampFormatter: ISO8601DateFormatter = {
491 let formatter = ISO8601DateFormatter()
492 formatter.timeZone = TimeZone(identifier: "UTC")
493 return formatter
494 }()
495
425496 private func deleteSecrets(for target: IntegrationTarget) {
426497 switch target.configuration {
427498 case .webhook(let configuration):
@@ -436,6 +507,10 @@ final class IntegrationService {
436507 if let reference = configuration.credentialReference {
437508 try? IntegrationSecretStore.delete(reference: reference)
438509 }
510 case .s3(let configuration):
511 if let reference = configuration.credentialReference {
512 try? IntegrationSecretStore.delete(reference: reference)
513 }
439514 }
440515 }
441516
@@ -447,6 +522,8 @@ final class IntegrationService {
447522 return configuration.destinationLabel
448523 case .email(let configuration):
449524 return configuration.recipientAddresses.joined(separator: ", ")
525 case .s3(let configuration):
526 return configuration.bucket.isEmpty ? target.name : configuration.bucket
450527 }
451528 }
452529
DomainDig/IntegrationsView.swift +130 −1
@@ -88,6 +88,8 @@ struct IntegrationsSettingsView: View {
8888 return configuration.destinationLabel
8989 case .email(let configuration):
9090 return configuration.recipientAddresses.joined(separator: ", ")
91 case .s3(let configuration):
92 return configuration.bucket.isEmpty ? "S3 bucket" : configuration.bucket
9193 }
9294 }
9395}
@@ -183,6 +185,8 @@ private struct IntegrationDetailView: View {
183185 return configuration.destinationLabel
184186 case .email(let configuration):
185187 return configuration.recipientAddresses.joined(separator: ", ")
188 case .s3(let configuration):
189 return configuration.bucket
186190 }
187191 }
188192}
@@ -198,6 +202,13 @@ private struct IntegrationEditorView: View {
198202 @State private var isEnabled = true
199203 @State private var minimumSeverity: EventSeverity = .warning
200204 @State private var selectedEventTypes: Set<MonitoringEventType> = Set(MonitoringEventType.allCases.filter { $0 != .test })
205 @State private var s3Endpoint = ""
206 @State private var s3Region = "us-east-1"
207 @State private var s3Bucket = ""
208 @State private var s3KeyPrefix = "domaindig"
209 @State private var s3UsesPathStyle = false
210 @State private var s3AccessKeyID = ""
211 @State private var s3SecretAccessKey = ""
201212 @State private var domainsText = ""
202213
203214 @State private var webhookURL = ""
@@ -216,12 +227,18 @@ private struct IntegrationEditorView: View {
216227 Form {
217228 Section("Integration") {
218229 Picker("Type", selection: $type) {
219 ForEach(IntegrationType.allCases) { integrationType in
230 ForEach(selectableTypes) { integrationType in
220231 Text(integrationType.title).tag(integrationType)
221232 }
222233 }
223234 .disabled(existingTarget != nil)
224235
236 if !FeatureAccessService.hasAccess(to: .bucketExport) {
237 Text("Export to your own bucket is \(FeatureAccessService.upgradeMessage(for: .bucketExport)).")
238 .font(.caption)
239 .foregroundStyle(Color(.appTextSecondary))
240 }
241
225242 TextField("Name", text: $name)
226243 Toggle("Enabled", isOn: $isEnabled)
227244 }
@@ -322,6 +339,52 @@ private struct IntegrationEditorView: View {
322339 .foregroundStyle(Color(.appTextSecondary))
323340 }
324341 }
342 case .s3:
343 Section("Bucket") {
344 TextField("https://s3.eu-central-1.amazonaws.com", text: $s3Endpoint)
345 .textInputAutocapitalization(.never)
346 .autocorrectionDisabled()
347 .keyboardType(.URL)
348
349 Text("Must be https. Signing puts your access key ID on the wire, and the signature with it.")
350 .font(.caption)
351 .foregroundStyle(Color(.appTextSecondary))
352
353 TextField("Bucket", text: $s3Bucket)
354 .textInputAutocapitalization(.never)
355 .autocorrectionDisabled()
356
357 TextField("Region", text: $s3Region)
358 .textInputAutocapitalization(.never)
359 .autocorrectionDisabled()
360
361 TextField("Key prefix", text: $s3KeyPrefix)
362 .textInputAutocapitalization(.never)
363 .autocorrectionDisabled()
364
365 Toggle("Path-style addressing", isOn: $s3UsesPathStyle)
366
367 Text("Addresses the bucket as endpoint/bucket/key. MinIO needs this, and so do R2 custom domains.")
368 .font(.caption)
369 .foregroundStyle(Color(.appTextSecondary))
370 }
371
372 Section("Credentials") {
373 TextField("Access key ID", text: $s3AccessKeyID)
374 .textInputAutocapitalization(.never)
375 .autocorrectionDisabled()
376
377 SecureField(
378 existingTarget == nil ? "Secret access key" : "Replace secret access key",
379 text: $s3SecretAccessKey
380 )
381
382 if existingTarget != nil {
383 Text("Saved secret access key remains in Keychain unless you replace it.")
384 .font(.caption)
385 .foregroundStyle(Color(.appTextSecondary))
386 }
387 }
325388 }
326389
327390 if let validationMessage {
@@ -372,6 +435,13 @@ private struct IntegrationEditorView: View {
372435 senderAddress = configuration.senderAddress
373436 recipientAddresses = configuration.recipientAddresses.joined(separator: ", ")
374437 smtpSecurity = configuration.securityMode
438 case .s3(let configuration):
439 s3Endpoint = configuration.endpoint
440 s3Region = configuration.region
441 s3Bucket = configuration.bucket
442 s3KeyPrefix = configuration.keyPrefix
443 s3UsesPathStyle = configuration.usesPathStyle
444 s3AccessKeyID = configuration.accessKeyID
375445 }
376446 }
377447
@@ -499,6 +569,54 @@ private struct IntegrationEditorView: View {
499569 target: target,
500570 emailPassword: emailPassword.nilIfBlank
501571 )
572 case .s3:
573 guard FeatureAccessService.hasAccess(to: .bucketExport) else {
574 validationMessage = "Export to your own bucket is \(FeatureAccessService.upgradeMessage(for: .bucketExport))."
575 return
576 }
577
578 let existingReference: String? = {
579 guard case .s3(let configuration) = existingTarget?.configuration else { return nil }
580 return configuration.credentialReference
581 }()
582
583 let trimmedBucket = s3Bucket.trimmingCharacters(in: .whitespacesAndNewlines)
584 guard !trimmedBucket.isEmpty else {
585 validationMessage = "Bucket is required."
586 return
587 }
588 let trimmedAccessKeyID = s3AccessKeyID.trimmingCharacters(in: .whitespacesAndNewlines)
589 guard !trimmedAccessKeyID.isEmpty else {
590 validationMessage = "Access key ID is required."
591 return
592 }
593 if s3SecretAccessKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && existingReference == nil {
594 validationMessage = "Secret access key is required."
595 return
596 }
597
598 let target = IntegrationTarget(
599 id: targetID,
600 type: .s3,
601 name: trimmedName,
602 isEnabled: isEnabled,
603 configuration: .s3(
604 S3IntegrationConfiguration(
605 endpoint: s3Endpoint.trimmingCharacters(in: .whitespacesAndNewlines),
606 region: s3Region.trimmingCharacters(in: .whitespacesAndNewlines),
607 bucket: trimmedBucket,
608 keyPrefix: s3KeyPrefix.trimmingCharacters(in: .whitespacesAndNewlines),
609 usesPathStyle: s3UsesPathStyle,
610 accessKeyID: trimmedAccessKeyID,
611 credentialReference: existingReference
612 )
613 ),
614 filters: filters
615 )
616 try integrationService.upsert(
617 target: target,
618 s3SecretAccessKey: s3SecretAccessKey.nilIfBlank
619 )
502620 }
503621
504622 dismiss()
@@ -507,6 +625,17 @@ private struct IntegrationEditorView: View {
507625 }
508626 }
509627
628 /// Bucket export is Pro+ (D1), so a tier without it does not get the
629 /// option. An existing target keeps its type listed, so a downgrade leaves
630 /// the editor readable rather than blank.
631 private var selectableTypes: [IntegrationType] {
632 IntegrationType.allCases.filter { integrationType in
633 if integrationType == existingTarget?.type { return true }
634 guard integrationType == .s3 else { return true }
635 return FeatureAccessService.hasAccess(to: .bucketExport)
636 }
637 }
638
510639 private func existingWebhookDisplayHost() -> String {
511640 guard case .webhook(let configuration) = existingTarget?.configuration else {
512641 return ""
DomainDig/Models.swift +50
@@ -1735,6 +1735,7 @@ enum IntegrationType: String, Codable, CaseIterable, Identifiable, Sendable {
17351735 case webhook
17361736 case slack
17371737 case email
1738 case s3
17381739
17391740 var id: String { rawValue }
17401741
@@ -1819,16 +1820,58 @@ struct EmailIntegrationConfiguration: Codable, Equatable, Sendable {
18191820 }
18201821}
18211822
1823/// An S3-compatible bucket the user owns: S3 itself, R2, B2, MinIO, Wasabi or
1824/// Spaces.
1825///
1826/// The secret access key is not here. It lives in the Keychain through
1827/// `IntegrationSecretStore`, and `credentialReference` is how this finds it.
1828struct S3IntegrationConfiguration: Codable, Equatable, Sendable {
1829 /// The service endpoint, for example `https://s3.eu-central-1.amazonaws.com`
1830 /// or `https://<account>.r2.cloudflarestorage.com`. Rejected unless https.
1831 var endpoint: String
1832 /// The SigV4 signing region. R2 and most MinIO deployments want `auto` or
1833 /// `us-east-1`; it has to match whatever the endpoint expects.
1834 var region: String
1835 var bucket: String
1836 /// Prepended to every object key.
1837 var keyPrefix: String
1838 /// Address the bucket as `endpoint/bucket/key` rather than
1839 /// `bucket.endpoint/key`. MinIO needs this, and so do R2 custom domains.
1840 var usesPathStyle: Bool
1841 var accessKeyID: String
1842 var credentialReference: String?
1843
1844 init(
1845 endpoint: String = "",
1846 region: String = "us-east-1",
1847 bucket: String = "",
1848 keyPrefix: String = "domaindig",
1849 usesPathStyle: Bool = false,
1850 accessKeyID: String = "",
1851 credentialReference: String? = nil
1852 ) {
1853 self.endpoint = endpoint
1854 self.region = region
1855 self.bucket = bucket
1856 self.keyPrefix = keyPrefix
1857 self.usesPathStyle = usesPathStyle
1858 self.accessKeyID = accessKeyID
1859 self.credentialReference = credentialReference
1860 }
1861}
1862
18221863enum IntegrationConfiguration: Codable, Equatable, Sendable {
18231864 case webhook(WebhookIntegrationConfiguration)
18241865 case slack(SlackIntegrationConfiguration)
18251866 case email(EmailIntegrationConfiguration)
1867 case s3(S3IntegrationConfiguration)
18261868
18271869 private enum CodingKeys: String, CodingKey {
18281870 case type
18291871 case webhook
18301872 case slack
18311873 case email
1874 case s3
18321875 }
18331876
18341877 init(from decoder: Decoder) throws {
@@ -1841,6 +1884,8 @@ enum IntegrationConfiguration: Codable, Equatable, Sendable {
18411884 self = .slack(try container.decode(SlackIntegrationConfiguration.self, forKey: .slack))
18421885 case .email:
18431886 self = .email(try container.decode(EmailIntegrationConfiguration.self, forKey: .email))
1887 case .s3:
1888 self = .s3(try container.decode(S3IntegrationConfiguration.self, forKey: .s3))
18441889 }
18451890 }
18461891
@@ -1856,6 +1901,9 @@ enum IntegrationConfiguration: Codable, Equatable, Sendable {
18561901 case .email(let configuration):
18571902 try container.encode(IntegrationType.email, forKey: .type)
18581903 try container.encode(configuration, forKey: .email)
1904 case .s3(let configuration):
1905 try container.encode(IntegrationType.s3, forKey: .type)
1906 try container.encode(configuration, forKey: .s3)
18591907 }
18601908 }
18611909
@@ -1867,6 +1915,8 @@ enum IntegrationConfiguration: Codable, Equatable, Sendable {
18671915 return .slack
18681916 case .email:
18691917 return .email
1918 case .s3:
1919 return .s3
18701920 }
18711921 }
18721922}
DomainDig/S3UploadClient.swift added +159
@@ -0,0 +1,159 @@
1import Foundation
2
3/// Builds and sends a single signed `PUT` to an S3-compatible endpoint.
4///
5/// Request construction is separated from sending so it can be asserted
6/// without a network: `request(for:…)` is pure, and the signature it carries is
7/// the part that has to be exactly right.
8nonisolated struct S3UploadClient {
9 /// What to upload, and under what key.
10 struct Object: Sendable, Equatable {
11 /// The key within the bucket, without the configuration's prefix.
12 var key: String
13 var body: Data
14 var contentType: String
15
16 init(key: String, body: Data, contentType: String) {
17 self.key = key
18 self.body = body
19 self.contentType = contentType
20 }
21 }
22
23 enum UploadError: LocalizedError, Equatable {
24 case invalidEndpoint
25 case insecureEndpoint
26 case missingBucket
27 case rejected(statusCode: Int, message: String?)
28 case clockSkew
29
30 var errorDescription: String? {
31 switch self {
32 case .invalidEndpoint:
33 return "The bucket endpoint is not a valid URL."
34 case .insecureEndpoint:
35 return "The bucket endpoint must use https. Signing sends your access key ID in the clear over http, and the signature with it."
36 case .missingBucket:
37 return "The integration has no bucket name."
38 case let .rejected(statusCode, message):
39 if let message, !message.isEmpty {
40 return "The bucket rejected the upload (\(statusCode)): \(message)"
41 }
42 return "The bucket rejected the upload (\(statusCode))."
43 case .clockSkew:
44 // SigV4 refuses a request signed more than 15 minutes from the
45 // server's clock, and the message it returns does not say that
46 // the device is what is wrong.
47 return "The bucket rejected the upload because this device's clock is more than 15 minutes from the server's. Check Settings → General → Date & Time."
48 }
49 }
50 }
51
52 /// The full object key, prefix included.
53 static func objectKey(for object: Object, configuration: S3IntegrationConfiguration) -> String {
54 let prefix = configuration.keyPrefix
55 .trimmingCharacters(in: .whitespaces)
56 .trimmingCharacters(in: CharacterSet(charactersIn: "/"))
57 let key = object.key.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
58 return prefix.isEmpty ? key : "\(prefix)/\(key)"
59 }
60
61 /// A signed `PUT` for `object`.
62 ///
63 /// The URL's path is set from the signer's own encoding rather than left to
64 /// `URLComponents`, which percent-encodes to a different rule — if the two
65 /// disagree the server computes a different canonical request and the
66 /// upload fails as `SignatureDoesNotMatch`.
67 static func request(
68 for object: Object,
69 configuration: S3IntegrationConfiguration,
70 credentials: AWSSigV4.Credentials,
71 now: Date
72 ) throws -> URLRequest {
73 let bucket = configuration.bucket.trimmingCharacters(in: .whitespaces)
74 guard !bucket.isEmpty else { throw UploadError.missingBucket }
75
76 let endpoint = configuration.endpoint.trimmingCharacters(in: .whitespaces)
77 guard let endpointURL = URL(string: endpoint), let endpointHost = endpointURL.host else {
78 throw UploadError.invalidEndpoint
79 }
80 guard endpointURL.scheme?.lowercased() == "https" else {
81 throw UploadError.insecureEndpoint
82 }
83
84 let key = objectKey(for: object, configuration: configuration)
85 let host = configuration.usesPathStyle ? endpointHost : "\(bucket).\(endpointHost)"
86 let signedPath = configuration.usesPathStyle ? "/\(bucket)/\(key)" : "/\(key)"
87
88 // The host header carries a non-default port, because the signature
89 // covers the header and the server compares what it received.
90 let hostHeader: String
91 if let port = endpointURL.port, port != 443 {
92 hostHeader = "\(host):\(port)"
93 } else {
94 hostHeader = host
95 }
96
97 let scope = AWSSigV4.Scope(region: configuration.region, service: "s3", date: now)
98 let payloadHash = AWSSigV4.sha256Hex(object.body)
99 var headers = [
100 "Host": hostHeader,
101 "Content-Type": object.contentType,
102 "x-amz-content-sha256": payloadHash,
103 "x-amz-date": scope.amzDate
104 ]
105
106 let signed = AWSSigV4.Request(
107 method: "PUT",
108 path: signedPath,
109 headers: headers,
110 payloadSHA256: payloadHash
111 )
112 headers["Authorization"] = AWSSigV4.authorizationHeader(
113 for: signed,
114 scope: scope,
115 credentials: credentials
116 )
117
118 var components = URLComponents()
119 components.scheme = "https"
120 components.host = host
121 components.port = endpointURL.port
122 components.percentEncodedPath = AWSSigV4.canonicalURI(for: signedPath)
123 guard let url = components.url else { throw UploadError.invalidEndpoint }
124
125 var request = URLRequest(url: url)
126 request.httpMethod = "PUT"
127 request.httpBody = object.body
128 // The host header is signed but set by URLSession from the URL, so it
129 // is left out here; everything else goes on the request.
130 for (name, value) in headers where name.lowercased() != "host" {
131 request.setValue(value, forHTTPHeaderField: name)
132 }
133 return request
134 }
135
136 /// Classifies a response. S3-compatible services answer errors as XML, and
137 /// the `Code` element is the part worth showing.
138 static func validate(statusCode: Int, body: Data) throws {
139 guard !(200...299).contains(statusCode) else { return }
140 let code = errorCode(in: body)
141 if code == "RequestTimeTooSkewed" {
142 throw UploadError.clockSkew
143 }
144 throw UploadError.rejected(statusCode: statusCode, message: code)
145 }
146
147 /// The `<Code>` element of an S3 error document, if there is one.
148 static func errorCode(in body: Data) -> String? {
149 guard let text = String(data: body, encoding: .utf8),
150 let open = text.range(of: "<Code>"),
151 let close = text.range(of: "</Code>"),
152 open.upperBound <= close.lowerBound
153 else {
154 return nil
155 }
156 let code = text[open.upperBound..<close.lowerBound]
157 return code.isEmpty ? nil : String(code)
158 }
159}
DomainDigTests/FeatureAccessTests.swift +14
@@ -160,4 +160,18 @@ final class FeatureAccessTests: XCTestCase {
160160 XCTAssertFalse(FeatureAccessService.canAddTrackedDomain(currentCount: 500, tier: .free))
161161 XCTAssertTrue(FeatureAccessService.canAddTrackedDomain(currentCount: 500, tier: .pro))
162162 }
163
164 /// Export to the user's own bucket is Pro+ (D1). Pro+ takes
165 /// `allCases`, so a new capability lands there by construction — this is
166 /// the check that it did not also land in free or pro.
167 func testBucketExportIsProPlusOnly() {
168 XCTAssertFalse(FeatureAccessService.entitlements(for: .free).capabilities.contains(.bucketExport))
169 XCTAssertFalse(FeatureAccessService.entitlements(for: .pro).capabilities.contains(.bucketExport))
170 XCTAssertTrue(FeatureAccessService.entitlements(for: .proPlus).capabilities.contains(.bucketExport))
171 }
172
173 func testBucketExportPromptsForProPlus() {
174 XCTAssertEqual(FeatureAccessService.upgradeMessage(for: .bucketExport), "Available in Pro+")
175 XCTAssertEqual(FeatureAccessService.upgradePrompt(for: .bucketExport).title, "Available in Pro+")
176 }
163177}
DomainDigTests/S3UploadClientTests.swift added +304
@@ -0,0 +1,304 @@
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 /// The secret is never part of the configuration — it lives in the
296 /// Keychain and only the reference is stored.
297 func testTheConfigurationCarriesNoSecret() throws {
298 let encoded = try JSONEncoder().encode(configuration())
299 let json = try XCTUnwrap(String(data: encoded, encoding: .utf8))
300
301 XCTAssertFalse(json.contains(credentials.secretAccessKey))
302 XCTAssertTrue(json.contains(credentials.accessKeyID), "the key ID is not a secret and is shown in the editor")
303 }
304}