DomainDig/S3UploadClient.swift
159 lines · 6633 bytes
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}