/
SignatureV4.ts
340 lines (301 loc) · 11.3 KB
/
SignatureV4.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import {
Credentials,
DateInput,
EventSigner,
EventSigningArguments,
FormattedEvent,
HashConstructor,
HeaderBag,
HttpRequest,
Provider,
RequestPresigner,
RequestPresigningArguments,
RequestSigner,
RequestSigningArguments,
SigningArguments,
StringSigner,
} from "@aws-sdk/types";
import { toHex } from "@aws-sdk/util-hex-encoding";
import { normalizeProvider } from "@aws-sdk/util-middleware";
import {
ALGORITHM_IDENTIFIER,
ALGORITHM_QUERY_PARAM,
AMZ_DATE_HEADER,
AMZ_DATE_QUERY_PARAM,
AUTH_HEADER,
CREDENTIAL_QUERY_PARAM,
EVENT_ALGORITHM_IDENTIFIER,
EXPIRES_QUERY_PARAM,
MAX_PRESIGNED_TTL,
SHA256_HEADER,
SIGNATURE_QUERY_PARAM,
SIGNED_HEADERS_QUERY_PARAM,
TOKEN_HEADER,
TOKEN_QUERY_PARAM,
} from "./constants";
import { createScope, getSigningKey } from "./credentialDerivation";
import { getCanonicalHeaders } from "./getCanonicalHeaders";
import { getCanonicalQuery } from "./getCanonicalQuery";
import { getPayloadHash } from "./getPayloadHash";
import { hasHeader } from "./headerUtil";
import { moveHeadersToQuery } from "./moveHeadersToQuery";
import { prepareRequest } from "./prepareRequest";
import { iso8601 } from "./utilDate";
export interface SignatureV4Init {
/**
* The service signing name.
*/
service: string;
/**
* The region name or a function that returns a promise that will be
* resolved with the region name.
*/
region: string | Provider<string>;
/**
* The credentials with which the request should be signed or a function
* that returns a promise that will be resolved with credentials.
*/
credentials: Credentials | Provider<Credentials>;
/**
* A constructor function for a hash object that will calculate SHA-256 HMAC
* checksums.
*/
sha256?: HashConstructor;
/**
* Whether to uri-escape the request URI path as part of computing the
* canonical request string. This is required for every AWS service, except
* Amazon S3, as of late 2017.
*
* @default [true]
*/
uriEscapePath?: boolean;
/**
* Whether to calculate a checksum of the request body and include it as
* either a request header (when signing) or as a query string parameter
* (when presigning). This is required for AWS Glacier and Amazon S3 and optional for
* every other AWS service as of late 2017.
*
* @default [true]
*/
applyChecksum?: boolean;
}
export interface SignatureV4CryptoInit {
sha256: HashConstructor;
}
export class SignatureV4 implements RequestPresigner, RequestSigner, StringSigner, EventSigner {
private readonly service: string;
private readonly regionProvider: Provider<string>;
private readonly credentialProvider: Provider<Credentials>;
private readonly sha256: HashConstructor;
private readonly uriEscapePath: boolean;
private readonly applyChecksum: boolean;
constructor({
applyChecksum,
credentials,
region,
service,
sha256,
uriEscapePath = true,
}: SignatureV4Init & SignatureV4CryptoInit) {
this.service = service;
this.sha256 = sha256;
this.uriEscapePath = uriEscapePath;
// default to true if applyChecksum isn't set
this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
this.regionProvider = normalizeProvider(region);
this.credentialProvider = normalizeProvider(credentials);
}
public async presign(originalRequest: HttpRequest, options: RequestPresigningArguments = {}): Promise<HttpRequest> {
const {
signingDate = new Date(),
expiresIn = 3600,
unsignableHeaders,
unhoistableHeaders,
signableHeaders,
signingRegion,
signingService,
} = options;
const credentials = await this.credentialProvider();
const region = signingRegion ?? (await this.regionProvider());
const { longDate, shortDate } = formatDate(signingDate);
if (expiresIn > MAX_PRESIGNED_TTL) {
return Promise.reject(
"Signature version 4 presigned URLs" + " must have an expiration date less than one week in" + " the future"
);
}
const scope = createScope(shortDate, region, signingService ?? this.service);
const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders });
if (credentials.sessionToken) {
request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken;
}
request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`;
request.query[AMZ_DATE_QUERY_PARAM] = longDate;
request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);
request.query[SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList(canonicalHeaders);
request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(
longDate,
scope,
this.getSigningKey(credentials, region, shortDate, signingService),
this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))
);
return request;
}
public async sign(stringToSign: string, options?: SigningArguments): Promise<string>;
public async sign(event: FormattedEvent, options: EventSigningArguments): Promise<string>;
public async sign(requestToSign: HttpRequest, options?: RequestSigningArguments): Promise<HttpRequest>;
public async sign(toSign: any, options: any): Promise<any> {
if (typeof toSign === "string") {
return this.signString(toSign, options);
} else if (toSign.headers && toSign.payload) {
return this.signEvent(toSign, options);
} else {
return this.signRequest(toSign, options);
}
}
private async signEvent(
{ headers, payload }: FormattedEvent,
{ signingDate = new Date(), priorSignature, signingRegion, signingService }: EventSigningArguments
): Promise<string> {
const region = signingRegion ?? (await this.regionProvider());
const { shortDate, longDate } = formatDate(signingDate);
const scope = createScope(shortDate, region, signingService ?? this.service);
const hashedPayload = await getPayloadHash({ headers: {}, body: payload } as any, this.sha256);
const hash = new this.sha256();
hash.update(headers);
const hashedHeaders = toHex(await hash.digest());
const stringToSign = [
EVENT_ALGORITHM_IDENTIFIER,
longDate,
scope,
priorSignature,
hashedHeaders,
hashedPayload,
].join("\n");
return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
}
private async signString(
stringToSign: string,
{ signingDate = new Date(), signingRegion, signingService }: SigningArguments = {}
): Promise<string> {
const credentials = await this.credentialProvider();
const region = signingRegion ?? (await this.regionProvider());
const { shortDate } = formatDate(signingDate);
const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService));
hash.update(stringToSign);
return toHex(await hash.digest());
}
private async signRequest(
requestToSign: HttpRequest,
{
signingDate = new Date(),
signableHeaders,
unsignableHeaders,
signingRegion,
signingService,
}: RequestSigningArguments = {}
): Promise<HttpRequest> {
const credentials = await this.credentialProvider();
const region = signingRegion ?? (await this.regionProvider());
const request = prepareRequest(requestToSign);
const { longDate, shortDate } = formatDate(signingDate);
const scope = createScope(shortDate, region, signingService ?? this.service);
request.headers[AMZ_DATE_HEADER] = longDate;
if (credentials.sessionToken) {
request.headers[TOKEN_HEADER] = credentials.sessionToken;
}
const payloadHash = await getPayloadHash(request, this.sha256);
if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) {
request.headers[SHA256_HEADER] = payloadHash;
}
const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);
const signature = await this.getSignature(
longDate,
scope,
this.getSigningKey(credentials, region, shortDate, signingService),
this.createCanonicalRequest(request, canonicalHeaders, payloadHash)
);
request.headers[AUTH_HEADER] =
`${ALGORITHM_IDENTIFIER} ` +
`Credential=${credentials.accessKeyId}/${scope}, ` +
`SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, ` +
`Signature=${signature}`;
return request;
}
private createCanonicalRequest(request: HttpRequest, canonicalHeaders: HeaderBag, payloadHash: string): string {
const sortedHeaders = Object.keys(canonicalHeaders).sort();
return `${request.method}
${this.getCanonicalPath(request)}
${getCanonicalQuery(request)}
${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")}
${sortedHeaders.join(";")}
${payloadHash}`;
}
private async createStringToSign(
longDate: string,
credentialScope: string,
canonicalRequest: string
): Promise<string> {
const hash = new this.sha256();
hash.update(canonicalRequest);
const hashedRequest = await hash.digest();
return `${ALGORITHM_IDENTIFIER}
${longDate}
${credentialScope}
${toHex(hashedRequest)}`;
}
private getCanonicalPath({ path }: HttpRequest): string {
if (this.uriEscapePath) {
// Non-S3 services, we normalize the path and then double URI encode it.
// Ref: "Remove Dot Segments" https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
const normalizedPathSegments = [];
for (const pathSegment of path.split("/")) {
if (pathSegment?.length === 0) continue;
if (pathSegment === ".") continue;
if (pathSegment === "..") {
normalizedPathSegments.pop();
} else {
normalizedPathSegments.push(pathSegment);
}
}
// Joining by single slashes to remove consecutive slashes.
const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${
normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""
}`;
const doubleEncoded = encodeURIComponent(normalizedPath);
return doubleEncoded.replace(/%2F/g, "/");
}
// For S3, we shouldn't normalize the path. For example, object name
// my-object//example//photo.user should not be normalized to
// my-object/example/photo.user
return path;
}
private async getSignature(
longDate: string,
credentialScope: string,
keyPromise: Promise<Uint8Array>,
canonicalRequest: string
): Promise<string> {
const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest);
const hash = new this.sha256(await keyPromise);
hash.update(stringToSign);
return toHex(await hash.digest());
}
private getSigningKey(
credentials: Credentials,
region: string,
shortDate: string,
service?: string
): Promise<Uint8Array> {
return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service);
}
}
const formatDate = (now: DateInput): { longDate: string; shortDate: string } => {
const longDate = iso8601(now).replace(/[\-:]/g, "");
return {
longDate,
shortDate: longDate.slice(0, 8),
};
};
const getCanonicalHeaderList = (headers: object): string => Object.keys(headers).sort().join(";");