Commit 3f5274031a
Unsigned
Layout: unified · split
DomainDig.xcodeproj/project.pbxproj +4
| @@ -38,6 +38,7 @@ | ||
| 38 | 38 | A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */; }; |
| 39 | 39 | A1B2C3D40000000000001602 /* InspectionScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001601 /* InspectionScopeTests.swift */; }; |
| 40 | 40 | A1B2C3D40000000000001702 /* AWSSigV4Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001701 /* AWSSigV4Tests.swift */; }; |
| 41 | A1B2C3D40000000000001802 /* S3UploadClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001801 /* S3UploadClientTests.swift */; }; | |
| 41 | 42 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; }; |
| 42 | 43 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; }; |
| 43 | 44 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; }; |
| @@ -123,6 +124,7 @@ | ||
| 123 | 124 | A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PortfolioDashboardTests.swift; sourceTree = "<group>"; }; |
| 124 | 125 | A1B2C3D40000000000001601 /* InspectionScopeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InspectionScopeTests.swift; sourceTree = "<group>"; }; |
| 125 | 126 | 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>"; }; | |
| 126 | 128 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; }; |
| 127 | 129 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; }; |
| 128 | 130 | A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; }; |
| @@ -273,6 +275,7 @@ | ||
| 273 | 275 | A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */, |
| 274 | 276 | A1B2C3D40000000000001601 /* InspectionScopeTests.swift */, |
| 275 | 277 | A1B2C3D40000000000001701 /* AWSSigV4Tests.swift */, |
| 278 | A1B2C3D40000000000001801 /* S3UploadClientTests.swift */, | |
| 276 | 279 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */, |
| 277 | 280 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */, |
| 278 | 281 | A1B2C3D40000000000000501 /* DomainNameTests.swift */, |
| @@ -548,6 +551,7 @@ | ||
| 548 | 551 | A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */, |
| 549 | 552 | A1B2C3D40000000000001602 /* InspectionScopeTests.swift in Sources */, |
| 550 | 553 | A1B2C3D40000000000001702 /* AWSSigV4Tests.swift in Sources */, |
| 554 | A1B2C3D40000000000001802 /* S3UploadClientTests.swift in Sources */, | |
| 551 | 555 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */, |
| 552 | 556 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */, |
| 553 | 557 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */, |
DomainDig/FeatureAccessService.swift +5 −2
| @@ -32,6 +32,7 @@ enum FeatureCapability: String, CaseIterable, Identifiable { | ||
| 32 | 32 | case sharedPortfolios |
| 33 | 33 | case auditDepth |
| 34 | 34 | case intelligenceDetail |
| 35 | case bucketExport | |
| 35 | 36 | |
| 36 | 37 | var id: String { rawValue } |
| 37 | 38 | |
| @@ -61,6 +62,8 @@ enum FeatureCapability: String, CaseIterable, Identifiable { | ||
| 61 | 62 | return "Unlimited audits" |
| 62 | 63 | case .intelligenceDetail: |
| 63 | 64 | return "Intelligence detail" |
| 65 | case .bucketExport: | |
| 66 | return "Export to your own bucket" | |
| 64 | 67 | } |
| 65 | 68 | } |
| 66 | 69 | } |
| @@ -191,7 +194,7 @@ enum FeatureAccessService { | ||
| 191 | 194 | case .workflows, .batchOperations, .automatedMonitoring, .localAlerts, .advancedExports, |
| 192 | 195 | .extendedSubdomains: |
| 193 | 196 | return "Available in Pro" |
| 194 | case .sharedPortfolios, .auditDepth, .intelligenceDetail: | |
| 197 | case .sharedPortfolios, .auditDepth, .intelligenceDetail, .bucketExport: | |
| 195 | 198 | return "Available in Pro+" |
| 196 | 199 | case .limitedTracking: |
| 197 | 200 | return "Tracking is limited on Free" |
| @@ -253,7 +256,7 @@ enum FeatureAccessService { | ||
| 253 | 256 | static func upgradePrompt(for capability: FeatureCapability) -> UpgradePromptContext { |
| 254 | 257 | let title: String |
| 255 | 258 | switch capability { |
| 256 | case .sharedPortfolios, .auditDepth, .intelligenceDetail: | |
| 259 | case .sharedPortfolios, .auditDepth, .intelligenceDetail, .bucketExport: | |
| 257 | 260 | title = "Available in Pro+" |
| 258 | 261 | default: |
| 259 | 262 | title = "Available in Pro" |
DomainDig/IntegrationService.swift +78 −1
| @@ -34,7 +34,8 @@ final class IntegrationService { | ||
| 34 | 34 | target: IntegrationTarget, |
| 35 | 35 | webhookURL: String? = nil, |
| 36 | 36 | slackWebhookURL: String? = nil, |
| 37 | emailPassword: String? = nil | |
| 37 | emailPassword: String? = nil, | |
| 38 | s3SecretAccessKey: String? = nil | |
| 38 | 39 | ) throws { |
| 39 | 40 | var updatedTarget = target |
| 40 | 41 | |
| @@ -64,6 +65,18 @@ final class IntegrationService { | ||
| 64 | 65 | configuration.credentialReference = reference |
| 65 | 66 | updatedTarget.configuration = .email(configuration) |
| 66 | 67 | } |
| 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) | |
| 67 | 80 | } |
| 68 | 81 | |
| 69 | 82 | if let index = targets.firstIndex(where: { $0.id == updatedTarget.id }) { |
| @@ -233,6 +246,8 @@ final class IntegrationService { | ||
| 233 | 246 | configuration.credentialReference |
| 234 | 247 | case .email(let configuration): |
| 235 | 248 | configuration.credentialReference |
| 249 | case .s3(let configuration): | |
| 250 | configuration.credentialReference | |
| 236 | 251 | } |
| 237 | 252 | } |
| 238 | 253 | } |
| @@ -391,6 +406,26 @@ final class IntegrationService { | ||
| 391 | 406 | headers: [:], |
| 392 | 407 | timeoutSeconds: 15 |
| 393 | 408 | ) |
| 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 | ) | |
| 394 | 429 | case .email(let configuration): |
| 395 | 430 | guard let reference = configuration.credentialReference else { |
| 396 | 431 | throw IntegrationError.missingSecret |
| @@ -422,6 +457,42 @@ final class IntegrationService { | ||
| 422 | 457 | Self.save(queue, key: StorageKey.queue, defaults: defaults) |
| 423 | 458 | } |
| 424 | 459 | |
| 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 | ||
| 425 | 496 | private func deleteSecrets(for target: IntegrationTarget) { |
| 426 | 497 | switch target.configuration { |
| 427 | 498 | case .webhook(let configuration): |
| @@ -436,6 +507,10 @@ final class IntegrationService { | ||
| 436 | 507 | if let reference = configuration.credentialReference { |
| 437 | 508 | try? IntegrationSecretStore.delete(reference: reference) |
| 438 | 509 | } |
| 510 | case .s3(let configuration): | |
| 511 | if let reference = configuration.credentialReference { | |
| 512 | try? IntegrationSecretStore.delete(reference: reference) | |
| 513 | } | |
| 439 | 514 | } |
| 440 | 515 | } |
| 441 | 516 | |
| @@ -447,6 +522,8 @@ final class IntegrationService { | ||
| 447 | 522 | return configuration.destinationLabel |
| 448 | 523 | case .email(let configuration): |
| 449 | 524 | return configuration.recipientAddresses.joined(separator: ", ") |
| 525 | case .s3(let configuration): | |
| 526 | return configuration.bucket.isEmpty ? target.name : configuration.bucket | |
| 450 | 527 | } |
| 451 | 528 | } |
| 452 | 529 | |
DomainDig/IntegrationsView.swift +130 −1
| @@ -88,6 +88,8 @@ struct IntegrationsSettingsView: View { | ||
| 88 | 88 | return configuration.destinationLabel |
| 89 | 89 | case .email(let configuration): |
| 90 | 90 | return configuration.recipientAddresses.joined(separator: ", ") |
| 91 | case .s3(let configuration): | |
| 92 | return configuration.bucket.isEmpty ? "S3 bucket" : configuration.bucket | |
| 91 | 93 | } |
| 92 | 94 | } |
| 93 | 95 | } |
| @@ -183,6 +185,8 @@ private struct IntegrationDetailView: View { | ||
| 183 | 185 | return configuration.destinationLabel |
| 184 | 186 | case .email(let configuration): |
| 185 | 187 | return configuration.recipientAddresses.joined(separator: ", ") |
| 188 | case .s3(let configuration): | |
| 189 | return configuration.bucket | |
| 186 | 190 | } |
| 187 | 191 | } |
| 188 | 192 | } |
| @@ -198,6 +202,13 @@ private struct IntegrationEditorView: View { | ||
| 198 | 202 | @State private var isEnabled = true |
| 199 | 203 | @State private var minimumSeverity: EventSeverity = .warning |
| 200 | 204 | @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 = "" | |
| 201 | 212 | @State private var domainsText = "" |
| 202 | 213 | |
| 203 | 214 | @State private var webhookURL = "" |
| @@ -216,12 +227,18 @@ private struct IntegrationEditorView: View { | ||
| 216 | 227 | Form { |
| 217 | 228 | Section("Integration") { |
| 218 | 229 | Picker("Type", selection: $type) { |
| 219 | ForEach(IntegrationType.allCases) { integrationType in | |
| 230 | ForEach(selectableTypes) { integrationType in | |
| 220 | 231 | Text(integrationType.title).tag(integrationType) |
| 221 | 232 | } |
| 222 | 233 | } |
| 223 | 234 | .disabled(existingTarget != nil) |
| 224 | 235 | |
| 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 | ||
| 225 | 242 | TextField("Name", text: $name) |
| 226 | 243 | Toggle("Enabled", isOn: $isEnabled) |
| 227 | 244 | } |
| @@ -322,6 +339,52 @@ private struct IntegrationEditorView: View { | ||
| 322 | 339 | .foregroundStyle(Color(.appTextSecondary)) |
| 323 | 340 | } |
| 324 | 341 | } |
| 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 | } | |
| 325 | 388 | } |
| 326 | 389 | |
| 327 | 390 | if let validationMessage { |
| @@ -372,6 +435,13 @@ private struct IntegrationEditorView: View { | ||
| 372 | 435 | senderAddress = configuration.senderAddress |
| 373 | 436 | recipientAddresses = configuration.recipientAddresses.joined(separator: ", ") |
| 374 | 437 | 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 | |
| 375 | 445 | } |
| 376 | 446 | } |
| 377 | 447 | |
| @@ -499,6 +569,54 @@ private struct IntegrationEditorView: View { | ||
| 499 | 569 | target: target, |
| 500 | 570 | emailPassword: emailPassword.nilIfBlank |
| 501 | 571 | ) |
| 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 | ) | |
| 502 | 620 | } |
| 503 | 621 | |
| 504 | 622 | dismiss() |
| @@ -507,6 +625,17 @@ private struct IntegrationEditorView: View { | ||
| 507 | 625 | } |
| 508 | 626 | } |
| 509 | 627 | |
| 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 | ||
| 510 | 639 | private func existingWebhookDisplayHost() -> String { |
| 511 | 640 | guard case .webhook(let configuration) = existingTarget?.configuration else { |
| 512 | 641 | return "" |
DomainDig/Models.swift +50
| @@ -1735,6 +1735,7 @@ enum IntegrationType: String, Codable, CaseIterable, Identifiable, Sendable { | ||
| 1735 | 1735 | case webhook |
| 1736 | 1736 | case slack |
| 1737 | 1737 | case email |
| 1738 | case s3 | |
| 1738 | 1739 | |
| 1739 | 1740 | var id: String { rawValue } |
| 1740 | 1741 | |
| @@ -1819,16 +1820,58 @@ struct EmailIntegrationConfiguration: Codable, Equatable, Sendable { | ||
| 1819 | 1820 | } |
| 1820 | 1821 | } |
| 1821 | 1822 | |
| 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. | |
| 1828 | struct 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 | ||
| 1822 | 1863 | enum IntegrationConfiguration: Codable, Equatable, Sendable { |
| 1823 | 1864 | case webhook(WebhookIntegrationConfiguration) |
| 1824 | 1865 | case slack(SlackIntegrationConfiguration) |
| 1825 | 1866 | case email(EmailIntegrationConfiguration) |
| 1867 | case s3(S3IntegrationConfiguration) | |
| 1826 | 1868 | |
| 1827 | 1869 | private enum CodingKeys: String, CodingKey { |
| 1828 | 1870 | case type |
| 1829 | 1871 | case webhook |
| 1830 | 1872 | case slack |
| 1831 | 1873 | case email |
| 1874 | case s3 | |
| 1832 | 1875 | } |
| 1833 | 1876 | |
| 1834 | 1877 | init(from decoder: Decoder) throws { |
| @@ -1841,6 +1884,8 @@ enum IntegrationConfiguration: Codable, Equatable, Sendable { | ||
| 1841 | 1884 | self = .slack(try container.decode(SlackIntegrationConfiguration.self, forKey: .slack)) |
| 1842 | 1885 | case .email: |
| 1843 | 1886 | self = .email(try container.decode(EmailIntegrationConfiguration.self, forKey: .email)) |
| 1887 | case .s3: | |
| 1888 | self = .s3(try container.decode(S3IntegrationConfiguration.self, forKey: .s3)) | |
| 1844 | 1889 | } |
| 1845 | 1890 | } |
| 1846 | 1891 | |
| @@ -1856,6 +1901,9 @@ enum IntegrationConfiguration: Codable, Equatable, Sendable { | ||
| 1856 | 1901 | case .email(let configuration): |
| 1857 | 1902 | try container.encode(IntegrationType.email, forKey: .type) |
| 1858 | 1903 | 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) | |
| 1859 | 1907 | } |
| 1860 | 1908 | } |
| 1861 | 1909 | |
| @@ -1867,6 +1915,8 @@ enum IntegrationConfiguration: Codable, Equatable, Sendable { | ||
| 1867 | 1915 | return .slack |
| 1868 | 1916 | case .email: |
| 1869 | 1917 | return .email |
| 1918 | case .s3: | |
| 1919 | return .s3 | |
| 1870 | 1920 | } |
| 1871 | 1921 | } |
| 1872 | 1922 | } |
DomainDig/S3UploadClient.swift added +159
| @@ -0,0 +1,159 @@ | ||
| 1 | import 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. | |
| 8 | nonisolated 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 { | ||
| 160 | 160 | XCTAssertFalse(FeatureAccessService.canAddTrackedDomain(currentCount: 500, tier: .free)) |
| 161 | 161 | XCTAssertTrue(FeatureAccessService.canAddTrackedDomain(currentCount: 500, tier: .pro)) |
| 162 | 162 | } |
| 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 | } | |
| 163 | 177 | } |
DomainDigTests/S3UploadClientTests.swift added +304
| @@ -0,0 +1,304 @@ | ||
| 1 | import 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. | |
| 9 | final 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 | } | |