DomainDigTests/AWSSigV4Tests.swift
350 lines · 13641 bytes
1import XCTest
2@testable import DomainDig
3
4/// AWS publishes four fully worked SigV4 examples for S3 — canonical request,
5/// string to sign, signature and `Authorization` header, all exact — and says
6/// they are there to check an implementation against. This pins every stage of
7/// `AWSSigV4` to them.
8///
9/// It is worth pinning the intermediate stages and not only the signature: a
10/// wrong canonical request and a wrong signing key both end as
11/// `SignatureDoesNotMatch` from the server, and these tests say which.
12///
13/// Source: "Signature Calculations for the Authorization Header: Transferring
14/// Payload in a Single Chunk (AWS Signature Version 4)", Amazon S3 developer
15/// guide. Note the secret below ends `/bPxRfiCY…` — the S3 examples use a
16/// slash where the generic SigV4 test suite uses a plus, and the signatures
17/// differ accordingly.
18final class AWSSigV4Tests: XCTestCase {
19
20 private let credentials = AWSSigV4.Credentials(
21 accessKeyID: "AKIAIOSFODNN7EXAMPLE",
22 secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
23 )
24
25 /// 20130524T000000Z — "Fri, 24 May 2013 00:00:00 GMT".
26 private let scope = AWSSigV4.Scope(
27 region: "us-east-1",
28 service: "s3",
29 date: Date(timeIntervalSince1970: 1_369_353_600)
30 )
31
32 private let host = "examplebucket.s3.amazonaws.com"
33
34 // MARK: The timestamp the vectors are built on
35
36 func testTheScopeFormatsTheExampleTimestamp() {
37 XCTAssertEqual(scope.amzDate, "20130524T000000Z")
38 XCTAssertEqual(scope.dateStamp, "20130524")
39 XCTAssertEqual(scope.credentialScope, "20130524/us-east-1/s3/aws4_request")
40 }
41
42 // MARK: Example — GET Object
43
44 private var getObjectRequest: AWSSigV4.Request {
45 AWSSigV4.Request(
46 method: "GET",
47 path: "/test.txt",
48 headers: [
49 "Host": host,
50 "Range": "bytes=0-9",
51 "x-amz-content-sha256": AWSSigV4.emptyPayloadSHA256,
52 "x-amz-date": "20130524T000000Z"
53 ],
54 payloadSHA256: AWSSigV4.emptyPayloadSHA256
55 )
56 }
57
58 func testGetObjectCanonicalRequest() {
59 XCTAssertEqual(
60 AWSSigV4.canonicalRequest(for: getObjectRequest),
61 """
62 GET
63 /test.txt
64
65 host:examplebucket.s3.amazonaws.com
66 range:bytes=0-9
67 x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
68 x-amz-date:20130524T000000Z
69
70 host;range;x-amz-content-sha256;x-amz-date
71 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
72 """
73 )
74 }
75
76 func testGetObjectStringToSign() {
77 XCTAssertEqual(
78 AWSSigV4.stringToSign(
79 canonicalRequest: AWSSigV4.canonicalRequest(for: getObjectRequest),
80 scope: scope
81 ),
82 """
83 AWS4-HMAC-SHA256
84 20130524T000000Z
85 20130524/us-east-1/s3/aws4_request
86 7344ae5b7ee6c3e7e6b0fe0640412a37625d1fbfff95c48bbb2dc43964946972
87 """
88 )
89 }
90
91 func testGetObjectAuthorizationHeader() {
92 XCTAssertEqual(
93 AWSSigV4.authorizationHeader(for: getObjectRequest, scope: scope, credentials: credentials),
94 "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,"
95 + "SignedHeaders=host;range;x-amz-content-sha256;x-amz-date,"
96 + "Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
97 )
98 }
99
100 // MARK: Example — PUT Object
101
102 /// The example that matters most here: an upload, with a signed payload and
103 /// a `$` in the key that has to encode to `%24`.
104 private var putObjectRequest: AWSSigV4.Request {
105 AWSSigV4.Request(
106 method: "PUT",
107 path: "/test$file.text",
108 headers: [
109 "Date": "Fri, 24 May 2013 00:00:00 GMT",
110 "Host": host,
111 "x-amz-content-sha256": "44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072",
112 "x-amz-date": "20130524T000000Z",
113 "x-amz-storage-class": "REDUCED_REDUNDANCY"
114 ],
115 payloadSHA256: "44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072"
116 )
117 }
118
119 /// The payload hash in the vector is the hash of this exact body, so it
120 /// also pins `sha256Hex`.
121 func testPutObjectPayloadHashMatchesTheExampleBody() {
122 XCTAssertEqual(
123 AWSSigV4.sha256Hex(Data("Welcome to Amazon S3.".utf8)),
124 "44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072"
125 )
126 }
127
128 func testPutObjectCanonicalRequest() {
129 XCTAssertEqual(
130 AWSSigV4.canonicalRequest(for: putObjectRequest),
131 """
132 PUT
133 /test%24file.text
134
135 date:Fri, 24 May 2013 00:00:00 GMT
136 host:examplebucket.s3.amazonaws.com
137 x-amz-content-sha256:44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072
138 x-amz-date:20130524T000000Z
139 x-amz-storage-class:REDUCED_REDUNDANCY
140
141 date;host;x-amz-content-sha256;x-amz-date;x-amz-storage-class
142 44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072
143 """
144 )
145 }
146
147 func testPutObjectStringToSign() {
148 XCTAssertEqual(
149 AWSSigV4.stringToSign(
150 canonicalRequest: AWSSigV4.canonicalRequest(for: putObjectRequest),
151 scope: scope
152 ),
153 """
154 AWS4-HMAC-SHA256
155 20130524T000000Z
156 20130524/us-east-1/s3/aws4_request
157 9e0e90d9c76de8fa5b200d8c849cd5b8dc7a3be3951ddb7f6a76b4158342019d
158 """
159 )
160 }
161
162 func testPutObjectAuthorizationHeader() {
163 XCTAssertEqual(
164 AWSSigV4.authorizationHeader(for: putObjectRequest, scope: scope, credentials: credentials),
165 "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,"
166 + "SignedHeaders=date;host;x-amz-content-sha256;x-amz-date;x-amz-storage-class,"
167 + "Signature=98ad721746da40c64f1a55b78f14c238d841ea1380cd77a1b5971af0ece108bd"
168 )
169 }
170
171 // MARK: Example — GET Bucket Lifecycle (a valueless query parameter)
172
173 private var lifecycleRequest: AWSSigV4.Request {
174 AWSSigV4.Request(
175 method: "GET",
176 path: "/",
177 queryItems: [URLQueryItem(name: "lifecycle", value: nil)],
178 headers: [
179 "Host": host,
180 "x-amz-content-sha256": AWSSigV4.emptyPayloadSHA256,
181 "x-amz-date": "20130524T000000Z"
182 ],
183 payloadSHA256: AWSSigV4.emptyPayloadSHA256
184 )
185 }
186
187 /// A subresource has no value, and canonicalises to `lifecycle=` rather
188 /// than to a bare `lifecycle`.
189 func testLifecycleCanonicalRequest() {
190 XCTAssertEqual(
191 AWSSigV4.canonicalRequest(for: lifecycleRequest),
192 """
193 GET
194 /
195 lifecycle=
196 host:examplebucket.s3.amazonaws.com
197 x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
198 x-amz-date:20130524T000000Z
199
200 host;x-amz-content-sha256;x-amz-date
201 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
202 """
203 )
204 }
205
206 func testLifecycleAuthorizationHeader() {
207 XCTAssertEqual(
208 AWSSigV4.authorizationHeader(for: lifecycleRequest, scope: scope, credentials: credentials),
209 "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,"
210 + "SignedHeaders=host;x-amz-content-sha256;x-amz-date,"
211 + "Signature=fea454ca298b7da1c68078a5d1bdbfbbe0d65c699e0f91ac7a200a0136783543"
212 )
213 }
214
215 // MARK: Example — List Objects (two query parameters)
216
217 /// Declared out of order on purpose: the canonical form has to sort them.
218 private var listObjectsRequest: AWSSigV4.Request {
219 AWSSigV4.Request(
220 method: "GET",
221 path: "/",
222 queryItems: [
223 URLQueryItem(name: "prefix", value: "J"),
224 URLQueryItem(name: "max-keys", value: "2")
225 ],
226 headers: [
227 "Host": host,
228 "x-amz-content-sha256": AWSSigV4.emptyPayloadSHA256,
229 "x-amz-date": "20130524T000000Z"
230 ],
231 payloadSHA256: AWSSigV4.emptyPayloadSHA256
232 )
233 }
234
235 func testListObjectsCanonicalRequest() {
236 XCTAssertEqual(
237 AWSSigV4.canonicalRequest(for: listObjectsRequest),
238 """
239 GET
240 /
241 max-keys=2&prefix=J
242 host:examplebucket.s3.amazonaws.com
243 x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
244 x-amz-date:20130524T000000Z
245
246 host;x-amz-content-sha256;x-amz-date
247 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
248 """
249 )
250 }
251
252 func testListObjectsAuthorizationHeader() {
253 XCTAssertEqual(
254 AWSSigV4.authorizationHeader(for: listObjectsRequest, scope: scope, credentials: credentials),
255 "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,"
256 + "SignedHeaders=host;x-amz-content-sha256;x-amz-date,"
257 + "Signature=34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7"
258 )
259 }
260
261 // MARK: The pieces the vectors do not reach
262
263 func testTheEmptyPayloadConstantIsTheHashOfTheEmptyString() {
264 XCTAssertEqual(AWSSigV4.sha256Hex(Data()), AWSSigV4.emptyPayloadSHA256)
265 }
266
267 /// SigV4's encoding is not `addingPercentEncoding`: everything outside the
268 /// unreserved set goes, uppercase, and a space is `%20` not `+`.
269 func testUriEncodeFollowsTheSigV4Rules() {
270 XCTAssertEqual(AWSSigV4.uriEncode("AZaz09-._~", encodeSlash: true), "AZaz09-._~")
271 XCTAssertEqual(AWSSigV4.uriEncode("a b", encodeSlash: true), "a%20b")
272 XCTAssertEqual(AWSSigV4.uriEncode("a+b", encodeSlash: true), "a%2Bb")
273 XCTAssertEqual(AWSSigV4.uriEncode("a=b&c", encodeSlash: true), "a%3Db%26c")
274 XCTAssertEqual(AWSSigV4.uriEncode("$", encodeSlash: true), "%24")
275 }
276
277 func testUriEncodeKeepsKeySlashesButEncodesThemInQueryValues() {
278 XCTAssertEqual(AWSSigV4.uriEncode("photos/Jan/sample.jpg", encodeSlash: false), "photos/Jan/sample.jpg")
279 XCTAssertEqual(AWSSigV4.uriEncode("photos/Jan/sample.jpg", encodeSlash: true), "photos%2FJan%2Fsample.jpg")
280 }
281
282 /// Multi-byte characters encode per UTF-8 byte, not per character.
283 func testUriEncodeEncodesEachUTF8Byte() {
284 XCTAssertEqual(AWSSigV4.uriEncode("é", encodeSlash: true), "%C3%A9")
285 }
286
287 /// The path is deliberately not normalised: an object really can be called
288 /// `a//b`, and collapsing the slashes would sign for a different key.
289 func testCanonicalURIDoesNotNormalisePaths() {
290 XCTAssertEqual(AWSSigV4.canonicalURI(for: "/my-object//example//photo.user"), "/my-object//example//photo.user")
291 XCTAssertEqual(AWSSigV4.canonicalURI(for: "/a/../b"), "/a/../b")
292 }
293
294 func testCanonicalURIDefaultsToRootAndAddsTheLeadingSlash() {
295 XCTAssertEqual(AWSSigV4.canonicalURI(for: ""), "/")
296 XCTAssertEqual(AWSSigV4.canonicalURI(for: "key.json"), "/key.json")
297 }
298
299 func testAnEmptyQueryStringCanonicalisesToEmpty() {
300 XCTAssertEqual(AWSSigV4.canonicalQueryString([]), "")
301 }
302
303 /// Repeated names sort by value once the names tie.
304 func testRepeatedQueryNamesSortByValue() {
305 XCTAssertEqual(
306 AWSSigV4.canonicalQueryString([
307 URLQueryItem(name: "a", value: "2"),
308 URLQueryItem(name: "a", value: "1")
309 ]),
310 "a=1&a=2"
311 )
312 }
313
314 /// Header names are matched case-insensitively by lowercasing, so a
315 /// caller's capitalisation cannot change the signature.
316 func testHeaderCaseDoesNotChangeTheSignature() {
317 var shouting = getObjectRequest
318 shouting.headers = [
319 "HOST": host,
320 "RANGE": "bytes=0-9",
321 "X-Amz-Content-Sha256": AWSSigV4.emptyPayloadSHA256,
322 "X-AMZ-DATE": "20130524T000000Z"
323 ]
324
325 XCTAssertEqual(
326 AWSSigV4.authorizationHeader(for: shouting, scope: scope, credentials: credentials),
327 AWSSigV4.authorizationHeader(for: getObjectRequest, scope: scope, credentials: credentials)
328 )
329 }
330
331 /// Surrounding whitespace in a header value is trimmed before signing.
332 func testHeaderValuesAreTrimmed() {
333 XCTAssertEqual(
334 AWSSigV4.canonicalHeaders(for: ["host": " example.com "]),
335 "host:example.com\n"
336 )
337 }
338
339 /// The signing key is derived per date, region and service, so the same
340 /// secret signs differently in another region — the check that the chain is
341 /// not collapsing to one HMAC.
342 func testTheSigningKeyIsScopedToRegionAndService() {
343 let other = AWSSigV4.Scope(region: "eu-west-1", service: "s3", date: scope.date)
344
345 XCTAssertNotEqual(
346 AWSSigV4.signature(stringToSign: "x", scope: scope, secretAccessKey: credentials.secretAccessKey),
347 AWSSigV4.signature(stringToSign: "x", scope: other, secretAccessKey: credentials.secretAccessKey)
348 )
349 }
350}