|
| 1 | +import { BSON } from '../../bson'; |
| 2 | +import { type AWSCredentials } from '../../deps'; |
| 3 | + |
| 4 | +export type AwsSigv4Options = { |
| 5 | + path: '/'; |
| 6 | + body: string; |
| 7 | + host: string; |
| 8 | + method: 'POST'; |
| 9 | + headers: { |
| 10 | + 'Content-Type': 'application/x-www-form-urlencoded'; |
| 11 | + 'Content-Length': number; |
| 12 | + 'X-MongoDB-Server-Nonce': string; |
| 13 | + 'X-MongoDB-GS2-CB-Flag': 'n'; |
| 14 | + }; |
| 15 | + service: string; |
| 16 | + region: string; |
| 17 | + date: Date; |
| 18 | +}; |
| 19 | + |
| 20 | +export type SignedHeaders = { |
| 21 | + Authorization: string; |
| 22 | + 'X-Amz-Date': string; |
| 23 | +}; |
| 24 | + |
| 25 | +/** |
| 26 | + * Calculates the SHA-256 hash of a string. |
| 27 | + * |
| 28 | + * @param str - String to hash. |
| 29 | + * @returns Hexadecimal representation of the hash. |
| 30 | + */ |
| 31 | +const getHexSha256 = async (str: string): Promise<string> => { |
| 32 | + const data = stringToBuffer(str); |
| 33 | + const hashBuffer = await crypto.subtle.digest('SHA-256', data); |
| 34 | + const hashHex = BSON.onDemand.ByteUtils.toHex(new Uint8Array(hashBuffer)); |
| 35 | + return hashHex; |
| 36 | +}; |
| 37 | + |
| 38 | +/** |
| 39 | + * Calculates the HMAC-SHA256 of a string using the provided key. |
| 40 | + * @param key - Key to use for HMAC calculation. Can be a string or Uint8Array. |
| 41 | + * @param str - String to calculate HMAC for. |
| 42 | + * @returns Uint8Array containing the HMAC-SHA256 digest. |
| 43 | + */ |
| 44 | +const getHmacSha256 = async (key: string | Uint8Array, str: string): Promise<Uint8Array> => { |
| 45 | + let keyData: Uint8Array; |
| 46 | + if (typeof key === 'string') { |
| 47 | + keyData = stringToBuffer(key); |
| 48 | + } else { |
| 49 | + keyData = key; |
| 50 | + } |
| 51 | + |
| 52 | + const importedKey = await crypto.subtle.importKey( |
| 53 | + 'raw', |
| 54 | + keyData, |
| 55 | + { name: 'HMAC', hash: { name: 'SHA-256' } }, |
| 56 | + false, |
| 57 | + ['sign'] |
| 58 | + ); |
| 59 | + const strData = stringToBuffer(str); |
| 60 | + const signature = await crypto.subtle.sign('HMAC', importedKey, strData); |
| 61 | + const digest = new Uint8Array(signature); |
| 62 | + return digest; |
| 63 | +}; |
| 64 | + |
| 65 | +/** |
| 66 | + * Converts header values according to AWS requirements, |
| 67 | + * From https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html#create-canonical-request |
| 68 | + * For values, you must: |
| 69 | + - trim any leading or trailing spaces. |
| 70 | + - convert sequential spaces to a single space. |
| 71 | + * @param value - Header value to convert. |
| 72 | + * @returns - Converted header value. |
| 73 | + */ |
| 74 | +const convertHeaderValue = (value: string | number) => { |
| 75 | + return value.toString().trim().replace(/\s+/g, ' '); |
| 76 | +}; |
| 77 | + |
| 78 | +/** |
| 79 | + * Returns a Uint8Array representation of a string, encoded in UTF-8. |
| 80 | + * @param str - String to convert. |
| 81 | + * @returns Uint8Array containing the UTF-8 encoded string. |
| 82 | + */ |
| 83 | +function stringToBuffer(str: string): Uint8Array { |
| 84 | + const data = new Uint8Array(BSON.onDemand.ByteUtils.utf8ByteLength(str)); |
| 85 | + BSON.onDemand.ByteUtils.encodeUTF8Into(data, str, 0); |
| 86 | + return data; |
| 87 | +} |
| 88 | + |
| 89 | +/** |
| 90 | + * This method implements AWS Signature 4 logic for a very specific request format. |
| 91 | + * The signing logic is described here: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html |
| 92 | + */ |
| 93 | +export async function aws4Sign( |
| 94 | + options: AwsSigv4Options, |
| 95 | + credentials: AWSCredentials |
| 96 | +): Promise<SignedHeaders> { |
| 97 | + /** |
| 98 | + * From the spec: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html |
| 99 | + * |
| 100 | + * Summary of signing steps |
| 101 | + * 1. Create a canonical request |
| 102 | + * Arrange the contents of your request (host, action, headers, etc.) into a standard canonical format. The canonical request is one of the inputs used to create the string to sign. |
| 103 | + * 2. Create a hash of the canonical request |
| 104 | + * Hash the canonical request using the same algorithm that you used to create the hash of the payload. The hash of the canonical request is a string of lowercase hexadecimal characters. |
| 105 | + * 3. Create a string to sign |
| 106 | + * Create a string to sign with the canonical request and extra information such as the algorithm, request date, credential scope, and the hash of the canonical request. |
| 107 | + * 4. Derive a signing key |
| 108 | + * Use the secret access key to derive the key used to sign the request. |
| 109 | + * 5. Calculate the signature |
| 110 | + * Perform a keyed hash operation on the string to sign using the derived signing key as the hash key. |
| 111 | + * 6. Add the signature to the request |
| 112 | + * Add the calculated signature to an HTTP header or to the query string of the request. |
| 113 | + */ |
| 114 | + |
| 115 | + // 1: Create a canonical request |
| 116 | + |
| 117 | + // Date – The date and time used to sign the request. |
| 118 | + const date = options.date; |
| 119 | + // RequestDateTime – The date and time used in the credential scope. This value is the current UTC time in ISO 8601 format (for example, 20130524T000000Z). |
| 120 | + const requestDateTime = date.toISOString().replace(/[:-]|\.\d{3}/g, ''); |
| 121 | + // RequestDate – The date used in the credential scope. This value is the current UTC date in YYYYMMDD format (for example, 20130524). |
| 122 | + const requestDate = requestDateTime.substring(0, 8); |
| 123 | + // Method – The HTTP request method. For us, this is always 'POST'. |
| 124 | + const method = options.method; |
| 125 | + // CanonicalUri – The URI-encoded version of the absolute path component URI, starting with the / that follows the domain name and up to the end of the string |
| 126 | + // For our requests, this is always '/' |
| 127 | + const canonicalUri = options.path; |
| 128 | + // CanonicalQueryString – The URI-encoded query string parameters. For our requests, there are no query string parameters, so this is always an empty string. |
| 129 | + const canonicalQuerystring = ''; |
| 130 | + |
| 131 | + // CanonicalHeaders – A list of request headers with their values. Individual header name and value pairs are separated by the newline character ("\n"). |
| 132 | + // All of our known/expected headers are included here, there are no extra headers. |
| 133 | + const headers = new Headers({ |
| 134 | + 'content-length': convertHeaderValue(options.headers['Content-Length']), |
| 135 | + 'content-type': convertHeaderValue(options.headers['Content-Type']), |
| 136 | + host: convertHeaderValue(options.host), |
| 137 | + 'x-amz-date': convertHeaderValue(requestDateTime), |
| 138 | + 'x-mongodb-gs2-cb-flag': convertHeaderValue(options.headers['X-MongoDB-GS2-CB-Flag']), |
| 139 | + 'x-mongodb-server-nonce': convertHeaderValue(options.headers['X-MongoDB-Server-Nonce']) |
| 140 | + }); |
| 141 | + // If session token is provided, include it in the headers |
| 142 | + if ('sessionToken' in credentials && credentials.sessionToken) { |
| 143 | + headers.append('x-amz-security-token', convertHeaderValue(credentials.sessionToken)); |
| 144 | + } |
| 145 | + |
| 146 | + // Canonical headers are lowercased and sorted. |
| 147 | + const canonicalHeaders = Array.from(headers.entries()) |
| 148 | + .map(([key, value]) => `${key.toLowerCase()}:${value}`) |
| 149 | + .sort() |
| 150 | + .join('\n'); |
| 151 | + const canonicalHeaderNames = Array.from(headers.keys()).map(header => header.toLowerCase()); |
| 152 | + // SignedHeaders – An alphabetically sorted, semicolon-separated list of lowercase request header names. |
| 153 | + const signedHeaders = canonicalHeaderNames.sort().join(';'); |
| 154 | + |
| 155 | + // HashedPayload – A string created using the payload in the body of the HTTP request as input to a hash function. This string uses lowercase hexadecimal characters. |
| 156 | + const hashedPayload = await getHexSha256(options.body); |
| 157 | + |
| 158 | + // CanonicalRequest – A string that includes the above elements, separated by newline characters. |
| 159 | + const canonicalRequest = [ |
| 160 | + method, |
| 161 | + canonicalUri, |
| 162 | + canonicalQuerystring, |
| 163 | + canonicalHeaders + '\n', |
| 164 | + signedHeaders, |
| 165 | + hashedPayload |
| 166 | + ].join('\n'); |
| 167 | + |
| 168 | + // 2. Create a hash of the canonical request |
| 169 | + // HashedCanonicalRequest – A string created by using the canonical request as input to a hash function. |
| 170 | + const hashedCanonicalRequest = await getHexSha256(canonicalRequest); |
| 171 | + |
| 172 | + // 3. Create a string to sign |
| 173 | + // Algorithm – The algorithm used to create the hash of the canonical request. For SigV4, use AWS4-HMAC-SHA256. |
| 174 | + const algorithm = 'AWS4-HMAC-SHA256'; |
| 175 | + // CredentialScope – The credential scope, which restricts the resulting signature to the specified Region and service. |
| 176 | + // Has the following format: YYYYMMDD/region/service/aws4_request. |
| 177 | + const credentialScope = `${requestDate}/${options.region}/${options.service}/aws4_request`; |
| 178 | + // StringToSign – A string that includes the above elements, separated by newline characters. |
| 179 | + const stringToSign = [algorithm, requestDateTime, credentialScope, hashedCanonicalRequest].join( |
| 180 | + '\n' |
| 181 | + ); |
| 182 | + |
| 183 | + // 4. Derive a signing key |
| 184 | + // To derive a signing key for SigV4, perform a succession of keyed hash operations (HMAC) on the request date, Region, and service, with your AWS secret access key as the key for the initial hashing operation. |
| 185 | + const dateKey = await getHmacSha256('AWS4' + credentials.secretAccessKey, requestDate); |
| 186 | + const dateRegionKey = await getHmacSha256(dateKey, options.region); |
| 187 | + const dateRegionServiceKey = await getHmacSha256(dateRegionKey, options.service); |
| 188 | + const signingKey = await getHmacSha256(dateRegionServiceKey, 'aws4_request'); |
| 189 | + |
| 190 | + // 5. Calculate the signature |
| 191 | + const signatureBuffer = await getHmacSha256(signingKey, stringToSign); |
| 192 | + const signature = BSON.onDemand.ByteUtils.toHex(signatureBuffer); |
| 193 | + |
| 194 | + // 6. Add the signature to the request |
| 195 | + // Calculate the Authorization header |
| 196 | + const authorizationHeader = [ |
| 197 | + 'AWS4-HMAC-SHA256 Credential=' + credentials.accessKeyId + '/' + credentialScope, |
| 198 | + 'SignedHeaders=' + signedHeaders, |
| 199 | + 'Signature=' + signature |
| 200 | + ].join(', '); |
| 201 | + |
| 202 | + // Return the calculated headers |
| 203 | + return { |
| 204 | + Authorization: authorizationHeader, |
| 205 | + 'X-Amz-Date': requestDateTime |
| 206 | + }; |
| 207 | +} |
0 commit comments