DomainDig/AWSSigV4.swift

233 lines · 9348 bytes

  1import CryptoKit
  2import Foundation
  3
  4/// AWS Signature Version 4 request signing, for S3-compatible object storage.
  5///
  6/// Hand-rolled on CryptoKit, which the project already links, rather than
  7/// taking the AWS SDK for Swift and its dependency tree.
  8///
  9/// The stages below are the algorithm's own, exposed individually because each
 10/// one is pinned to AWS's published worked examples in `AWSSigV4Tests`. That is
 11/// worth doing here: the algorithm is fully specified and the vectors are
 12/// exact, so this is testable to certainty rather than to plausibility.
 13///
 14/// S3-specific, and the reason this is not a general signer: the URI path is
 15/// **not** normalised. A bucket may hold an object named `a//b`, and collapsing
 16/// the slashes would sign a request for a different object.
 17nonisolated struct AWSSigV4 {
 18    static let algorithm = "AWS4-HMAC-SHA256"
 19
 20    /// `Hex(SHA256(""))`, the payload hash for a request with no body.
 21    static let emptyPayloadSHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
 22
 23    /// Sent in place of a payload hash when the body is not to be hashed.
 24    static let unsignedPayload = "UNSIGNED-PAYLOAD"
 25
 26    struct Credentials: Sendable, Equatable {
 27        let accessKeyID: String
 28        let secretAccessKey: String
 29
 30        init(accessKeyID: String, secretAccessKey: String) {
 31            self.accessKeyID = accessKeyID
 32            self.secretAccessKey = secretAccessKey
 33        }
 34    }
 35
 36    /// One request to sign.
 37    struct Request: Sendable {
 38        /// `GET`, `PUT`, and so on.
 39        var method: String
 40        /// The path, unencoded and starting with `/`. Slashes within it are
 41        /// part of the object key and stay unencoded.
 42        var path: String
 43        var queryItems: [URLQueryItem]
 44        /// Header names in any case; signing lowercases them. `host` is
 45        /// required, and whichever `x-amz-*` headers the request will carry.
 46        var headers: [String: String]
 47        /// `Hex(SHA256(body))`, or `unsignedPayload`.
 48        var payloadSHA256: String
 49
 50        init(
 51            method: String,
 52            path: String,
 53            queryItems: [URLQueryItem] = [],
 54            headers: [String: String],
 55            payloadSHA256: String
 56        ) {
 57            self.method = method
 58            self.path = path
 59            self.queryItems = queryItems
 60            self.headers = headers
 61            self.payloadSHA256 = payloadSHA256
 62        }
 63    }
 64
 65    /// Where and when a signature is valid.
 66    struct Scope: Sendable, Equatable {
 67        var region: String
 68        var service: String
 69        var date: Date
 70
 71        init(region: String, service: String = "s3", date: Date) {
 72            self.region = region
 73            self.service = service
 74            self.date = date
 75        }
 76
 77        /// `20130524T000000Z`
 78        var amzDate: String { AWSSigV4.amzDateFormatter.string(from: date) }
 79        /// `20130524`
 80        var dateStamp: String { AWSSigV4.dateStampFormatter.string(from: date) }
 81        /// `20130524/us-east-1/s3/aws4_request`
 82        var credentialScope: String { "\(dateStamp)/\(region)/\(service)/aws4_request" }
 83    }
 84
 85    // MARK: Signing
 86
 87    /// The `Authorization` header value for `request`.
 88    static func authorizationHeader(
 89        for request: Request,
 90        scope: Scope,
 91        credentials: Credentials
 92    ) -> String {
 93        let canonical = canonicalRequest(for: request)
 94        let toSign = stringToSign(canonicalRequest: canonical, scope: scope)
 95        let signature = signature(stringToSign: toSign, scope: scope, secretAccessKey: credentials.secretAccessKey)
 96        // AWS's own S3 examples put no space after the commas; servers accept
 97        // either, and matching the documented form lets the tests pin the
 98        // whole header rather than only the signature.
 99        return "\(algorithm) "
100            + "Credential=\(credentials.accessKeyID)/\(scope.credentialScope),"
101            + "SignedHeaders=\(signedHeaders(for: request.headers)),"
102            + "Signature=\(signature)"
103    }
104
105    static func signature(stringToSign: String, scope: Scope, secretAccessKey: String) -> String {
106        let key = signingKey(secretAccessKey: secretAccessKey, scope: scope)
107        return hex(hmac(Data(stringToSign.utf8), key: key))
108    }
109
110    /// `HMAC(HMAC(HMAC(HMAC("AWS4"+secret, date), region), service), "aws4_request")`
111    static func signingKey(secretAccessKey: String, scope: Scope) -> SymmetricKey {
112        let initial = SymmetricKey(data: Data("AWS4\(secretAccessKey)".utf8))
113        let dateKey = hmac(Data(scope.dateStamp.utf8), key: initial)
114        let regionKey = hmac(Data(scope.region.utf8), key: SymmetricKey(data: dateKey))
115        let serviceKey = hmac(Data(scope.service.utf8), key: SymmetricKey(data: regionKey))
116        let signingKey = hmac(Data("aws4_request".utf8), key: SymmetricKey(data: serviceKey))
117        return SymmetricKey(data: signingKey)
118    }
119
120    static func stringToSign(canonicalRequest: String, scope: Scope) -> String {
121        [
122            algorithm,
123            scope.amzDate,
124            scope.credentialScope,
125            sha256Hex(Data(canonicalRequest.utf8))
126        ].joined(separator: "\n")
127    }
128
129    // MARK: Canonicalisation
130
131    static func canonicalRequest(for request: Request) -> String {
132        [
133            request.method.uppercased(),
134            canonicalURI(for: request.path),
135            canonicalQueryString(request.queryItems),
136            canonicalHeaders(for: request.headers),
137            signedHeaders(for: request.headers),
138            request.payloadSHA256
139        ].joined(separator: "\n")
140    }
141
142    /// The path, URI-encoded except for the slashes that separate key
143    /// components. Not normalised: see the type's note.
144    static func canonicalURI(for path: String) -> String {
145        guard !path.isEmpty else { return "/" }
146        let prefixed = path.hasPrefix("/") ? path : "/" + path
147        return uriEncode(prefixed, encodeSlash: false)
148    }
149
150    /// Parameters encoded individually, then sorted by name and value.
151    static func canonicalQueryString(_ queryItems: [URLQueryItem]) -> String {
152        var encoded: [(name: String, value: String)] = []
153        for item in queryItems {
154            encoded.append((
155                name: uriEncode(item.name, encodeSlash: true),
156                value: uriEncode(item.value ?? "", encodeSlash: true)
157            ))
158        }
159        encoded.sort { left, right in
160            left.name == right.name ? left.value < right.value : left.name < right.name
161        }
162        return encoded.map { "\($0.name)=\($0.value)" }.joined(separator: "&")
163    }
164
165    /// Each header as `name:value`, lowercased, sorted, and newline-terminated
166    /// — including the last, which is what produces the blank line before the
167    /// signed-header list.
168    ///
169    /// Values are trimmed at the ends only, which is what the S3
170    /// specification calls for and what every published vector needs.
171    static func canonicalHeaders(for headers: [String: String]) -> String {
172        headers
173            .map { ($0.key.lowercased(), $0.value.trimmingCharacters(in: .whitespaces)) }
174            .sorted { $0.0 < $1.0 }
175            .map { "\($0.0):\($0.1)\n" }
176            .joined()
177    }
178
179    static func signedHeaders(for headers: [String: String]) -> String {
180        headers.keys.map { $0.lowercased() }.sorted().joined(separator: ";")
181    }
182
183    /// Percent-encoding as SigV4 defines it, which is not what
184    /// `addingPercentEncoding` produces: every byte outside the unreserved set
185    /// is encoded, uppercase, and a space becomes `%20` rather than `+`.
186    static func uriEncode(_ value: String, encodeSlash: Bool) -> String {
187        var encoded = ""
188        for byte in Array(value.utf8) {
189            switch byte {
190            case UInt8(ascii: "A")...UInt8(ascii: "Z"),
191                 UInt8(ascii: "a")...UInt8(ascii: "z"),
192                 UInt8(ascii: "0")...UInt8(ascii: "9"),
193                 UInt8(ascii: "-"), UInt8(ascii: "."), UInt8(ascii: "_"), UInt8(ascii: "~"):
194                encoded.append(Character(UnicodeScalar(byte)))
195            case UInt8(ascii: "/"):
196                encoded += encodeSlash ? "%2F" : "/"
197            default:
198                encoded += String(format: "%%%02X", byte)
199            }
200        }
201        return encoded
202    }
203
204    // MARK: Primitives
205
206    static func sha256Hex(_ data: Data) -> String {
207        hex(Data(SHA256.hash(data: data)))
208    }
209
210    private static func hmac(_ data: Data, key: SymmetricKey) -> Data {
211        Data(HMAC<SHA256>.authenticationCode(for: data, using: key))
212    }
213
214    private static func hex(_ data: Data) -> String {
215        data.map { String(format: "%02x", $0) }.joined()
216    }
217
218    private static let amzDateFormatter: DateFormatter = {
219        let formatter = DateFormatter()
220        formatter.locale = Locale(identifier: "en_US_POSIX")
221        formatter.timeZone = TimeZone(identifier: "UTC")
222        formatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'"
223        return formatter
224    }()
225
226    private static let dateStampFormatter: DateFormatter = {
227        let formatter = DateFormatter()
228        formatter.locale = Locale(identifier: "en_US_POSIX")
229        formatter.timeZone = TimeZone(identifier: "UTC")
230        formatter.dateFormat = "yyyyMMdd"
231        return formatter
232    }()
233}