forked from aws-samples/cloudfront-authorization-at-edge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared.ts
621 lines (559 loc) · 18.1 KB
/
shared.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
import { CloudFrontHeaders } from "aws-lambda";
import { readFileSync } from "fs";
import { formatWithOptions } from "util";
import { createHmac, randomInt } from "crypto";
import { parse } from "cookie";
import { fetch } from "./https";
import { Agent, RequestOptions } from "https";
import html from "./error-page/template.html";
import { CognitoJwtVerifier } from "aws-jwt-verify";
import { Jwks } from "aws-jwt-verify/jwk";
export {
CognitoJwtInvalidGroupError,
JwtExpiredError,
} from "aws-jwt-verify/error";
export interface CookieSettings {
idToken: string;
accessToken: string;
refreshToken: string;
nonce: string;
[key: string]: string;
}
function getDefaultCookieSettings(props: {
mode: "spaMode" | "staticSiteMode";
compatibility: "amplify" | "elasticsearch";
redirectPathAuthRefresh: string;
}): CookieSettings {
// Defaults can be overridden by the user (CloudFormation Stack parameter) but should be solid enough for most purposes
if (props.compatibility === "amplify") {
if (props.mode === "spaMode") {
return {
idToken: "Path=/; Secure; SameSite=Lax",
accessToken: "Path=/; Secure; SameSite=Lax",
refreshToken: "Path=/; Secure; SameSite=Lax",
nonce: "Path=/; Secure; HttpOnly; SameSite=Lax",
};
} else if (props.mode === "staticSiteMode") {
return {
idToken: "Path=/; Secure; HttpOnly; SameSite=Lax",
accessToken: "Path=/; Secure; HttpOnly; SameSite=Lax",
refreshToken: `Path=${props.redirectPathAuthRefresh}; Secure; HttpOnly; SameSite=Lax`,
nonce: "Path=/; Secure; HttpOnly; SameSite=Lax",
};
}
} else if (props.compatibility === "elasticsearch") {
return {
idToken: "Path=/; Secure; HttpOnly; SameSite=Lax",
accessToken: "Path=/; Secure; HttpOnly; SameSite=Lax",
refreshToken: "Path=/; Secure; HttpOnly; SameSite=Lax",
nonce: "Path=/; Secure; HttpOnly; SameSite=Lax",
cognitoEnabled: "Path=/; Secure; SameSite=Lax",
};
}
throw new Error(
`Cannot determine default cookiesettings for ${props.mode} with compatibility ${props.compatibility}`
);
}
export interface HttpHeaders {
[key: string]: string;
}
type Mode = "spaMode" | "staticSiteMode";
interface ConfigFromDisk {
logLevel: keyof typeof LogLevel;
}
interface ConfigFromDiskWithHeaders extends ConfigFromDisk {
httpHeaders: HttpHeaders;
}
interface ConfigFromDiskComplete extends ConfigFromDiskWithHeaders {
userPoolArn: string;
jwks: Jwks;
clientId: string;
oauthScopes: string[];
cognitoAuthDomain: string;
redirectPathSignIn: string;
redirectPathSignOut: string;
signOutUrl: string;
redirectPathAuthRefresh: string;
cookieSettings: CookieSettings;
mode: Mode;
clientSecret: string;
nonceSigningSecret: string;
cookieCompatibility: "amplify" | "elasticsearch";
additionalCookies: { [name: string]: string };
requiredGroup: string;
secretAllowedCharacters?: string;
pkceLength?: number;
nonceLength?: number;
nonceMaxAge?: number;
}
function isConfigWithHeaders(config: any): config is ConfigFromDiskComplete {
return config["httpHeaders"] !== undefined;
}
function isCompleteConfig(config: any): config is ConfigFromDiskComplete {
return config["userPoolArn"] !== undefined;
}
enum LogLevel {
"none" = 0,
"error" = 10,
"warn" = 20,
"info" = 30,
"debug" = 40,
}
class Logger {
constructor(private logLevel: LogLevel) {}
private format(args: unknown[], depth = 10) {
return args.map((arg) => formatWithOptions({ depth }, arg)).join(" ");
}
public info(...args: unknown[]) {
if (this.logLevel >= LogLevel.info) {
console.log(this.format(args));
}
}
public warn(...args: unknown[]) {
if (this.logLevel >= LogLevel.warn) {
console.warn(this.format(args));
}
}
public error(...args: unknown[]) {
if (this.logLevel >= LogLevel.error) {
console.error(this.format(args));
}
}
public debug(...args: unknown[]) {
if (this.logLevel >= LogLevel.debug) {
console.trace(this.format(args));
}
}
}
export interface Config extends ConfigFromDisk {
logger: Logger;
}
export interface ConfigWithHeaders extends Config, ConfigFromDiskWithHeaders {
cloudFrontHeaders: CloudFrontHeaders;
}
export interface CompleteConfig
extends ConfigWithHeaders,
ConfigFromDiskComplete {
cloudFrontHeaders: CloudFrontHeaders;
secretAllowedCharacters: string;
pkceLength: number;
nonceLength: number;
nonceMaxAge: number;
}
export function getConfig(): Config {
const config = JSON.parse(
readFileSync(`${__dirname}/configuration.json`).toString("utf8")
) as ConfigFromDisk;
return {
logger: new Logger(LogLevel[config.logLevel]),
...config,
};
}
export function getConfigWithHeaders(): ConfigWithHeaders {
const config = getConfig();
if (!isConfigWithHeaders(config)) {
throw new Error("Incomplete config in configuration.json");
}
return {
cloudFrontHeaders: asCloudFrontHeaders(config.httpHeaders),
...config,
};
}
export function getCompleteConfig(): CompleteConfig {
const config = getConfigWithHeaders();
if (!isCompleteConfig(config)) {
throw new Error("Incomplete config in configuration.json");
}
// Derive cookie settings by merging the defaults with the explicitly provided values
const defaultCookieSettings = getDefaultCookieSettings({
compatibility: config.cookieCompatibility,
mode: config.mode,
redirectPathAuthRefresh: config.redirectPathAuthRefresh,
});
const cookieSettings = config.cookieSettings
? (Object.fromEntries(
Object.entries({
...defaultCookieSettings,
...config.cookieSettings,
}).map(([k, v]) => [
k,
v || defaultCookieSettings[k as keyof CookieSettings],
])
) as CookieSettings)
: defaultCookieSettings;
// Defaults for nonce and PKCE
const defaults = {
secretAllowedCharacters:
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",
pkceLength: 43, // Should be between 43 and 128 - per spec
nonceLength: 16,
nonceMaxAge:
(cookieSettings?.nonce &&
parseInt(parse(cookieSettings.nonce.toLowerCase())["max-age"])) ||
60 * 60 * 24,
};
return {
...defaults,
...config,
cookieSettings,
};
}
export function getConfigWithJwtVerifier() {
const config = getCompleteConfig();
const userPoolId = config.userPoolArn.split("/")[1];
const jwtVerifier = CognitoJwtVerifier.create({
userPoolId,
clientId: config.clientId,
tokenUse: "id",
groups: config.requiredGroup || undefined,
});
// Optimization: load the JWKS (as it was at deploy-time) into the cache.
// Then, the JWKS does not need to be fetched at runtime,
// as long as only JWTs come by with a kid that is in this cached JWKS:
jwtVerifier.cacheJwks(config.jwks);
return {
...config,
jwtVerifier,
};
}
type Cookies = { [key: string]: string };
function extractCookiesFromHeaders(headers: CloudFrontHeaders) {
// Cookies are present in the HTTP header "Cookie" that may be present multiple times.
// This utility function parses occurrences of that header and splits out all the cookies and their values
// A simple object is returned that allows easy access by cookie name: e.g. cookies["nonce"]
if (!headers["cookie"]) {
return {};
}
const cookies = headers["cookie"].reduce(
(reduced, header) => Object.assign(reduced, parse(header.value)),
{} as Cookies
);
return cookies;
}
export function asCloudFrontHeaders(headers: HttpHeaders): CloudFrontHeaders {
if (!headers) return {};
// Turn a regular key-value object into the explicit format expected by CloudFront
return Object.entries(headers).reduce(
(reduced, [key, value]) =>
Object.assign(reduced, {
[key.toLowerCase()]: [
{
key,
value,
},
],
}),
{} as CloudFrontHeaders
);
}
export function getAmplifyCookieNames(
clientId: string,
cookiesOrUserName: Cookies | string
) {
const keyPrefix = `CognitoIdentityServiceProvider.${clientId}`;
const lastUserKey = `${keyPrefix}.LastAuthUser`;
let tokenUserName: string;
if (typeof cookiesOrUserName === "string") {
tokenUserName = cookiesOrUserName;
} else {
tokenUserName = cookiesOrUserName[lastUserKey];
}
return {
lastUserKey,
userDataKey: `${keyPrefix}.${tokenUserName}.userData`,
scopeKey: `${keyPrefix}.${tokenUserName}.tokenScopesString`,
idTokenKey: `${keyPrefix}.${tokenUserName}.idToken`,
accessTokenKey: `${keyPrefix}.${tokenUserName}.accessToken`,
refreshTokenKey: `${keyPrefix}.${tokenUserName}.refreshToken`,
};
}
export function getElasticsearchCookieNames() {
return {
idTokenKey: "ID-TOKEN",
accessTokenKey: "ACCESS-TOKEN",
refreshTokenKey: "REFRESH-TOKEN",
cognitoEnabledKey: "COGNITO-ENABLED",
};
}
export function extractAndParseCookies(
headers: CloudFrontHeaders,
clientId: string,
cookieCompatibility: "amplify" | "elasticsearch"
) {
const cookies = extractCookiesFromHeaders(headers);
if (!cookies) {
return {};
}
let cookieNames: { [name: string]: string };
if (cookieCompatibility === "amplify") {
cookieNames = getAmplifyCookieNames(clientId, cookies);
} else {
cookieNames = getElasticsearchCookieNames();
}
return {
tokenUserName: cookies[cookieNames.lastUserKey],
idToken: cookies[cookieNames.idTokenKey],
accessToken: cookies[cookieNames.accessTokenKey],
refreshToken: cookies[cookieNames.refreshTokenKey],
scopes: cookies[cookieNames.scopeKey],
nonce: cookies["spa-auth-edge-nonce"],
nonceHmac: cookies["spa-auth-edge-nonce-hmac"],
pkce: cookies["spa-auth-edge-pkce"],
};
}
interface GenerateCookieHeadersParam {
clientId: string;
oauthScopes: string[];
cookieSettings: CookieSettings;
cookieCompatibility: "amplify" | "elasticsearch";
additionalCookies: { [name: string]: string };
tokens: {
id: string;
access?: string;
refresh?: string;
};
}
export const generateCookieHeaders = {
signIn: (
param: GenerateCookieHeadersParam & {
tokens: { id: string; access: string; refresh: string };
}
) => _generateCookieHeaders({ ...param, event: "signIn" }),
refresh: (
param: GenerateCookieHeadersParam & {
tokens: { id: string; access: string };
}
) => _generateCookieHeaders({ ...param, event: "refresh" }),
signOut: (param: GenerateCookieHeadersParam) =>
_generateCookieHeaders({ ...param, event: "signOut" }),
};
function _generateCookieHeaders(
param: GenerateCookieHeadersParam & {
event: "signIn" | "signOut" | "refresh";
}
) {
/**
* Generate cookie headers for the following scenario's:
* - signIn: called from Parse Auth lambda, when receiving fresh JWTs from Cognito
* - sign out: called from Sign Out Lambda, when the user visits the sign out URL
* - refresh: called from Refresh Auth lambda, when receiving fresh ID and Access JWTs from Cognito
*
* Note that there are other places besides this helper function where cookies can be set (search codebase for "set-cookie")
*/
const decodedIdToken = decodeToken(param.tokens.id);
const tokenUserName = decodedIdToken["cognito:username"];
const cookies: Cookies = {};
let cookieNames:
| ReturnType<typeof getAmplifyCookieNames>
| ReturnType<typeof getElasticsearchCookieNames>;
if (param.cookieCompatibility === "amplify") {
cookieNames = getAmplifyCookieNames(param.clientId, tokenUserName);
const userData = JSON.stringify({
UserAttributes: [
{
Name: "sub",
Value: decodedIdToken["sub"],
},
{
Name: "email",
Value: decodedIdToken["email"],
},
],
Username: tokenUserName,
});
// Construct object with the cookies
Object.assign(cookies, {
[cookieNames.lastUserKey]: `${tokenUserName}; ${param.cookieSettings.idToken}`,
[cookieNames.scopeKey]: `${param.oauthScopes.join(" ")}; ${
param.cookieSettings.accessToken
}`,
[cookieNames.userDataKey]: `${encodeURIComponent(userData)}; ${
param.cookieSettings.idToken
}`,
"amplify-signin-with-hostedUI": `true; ${param.cookieSettings.accessToken}`,
});
} else {
cookieNames = getElasticsearchCookieNames();
cookies[
cookieNames.cognitoEnabledKey
] = `True; ${param.cookieSettings.cognitoEnabled}`;
}
// Set JWTs in the cookies
cookies[
cookieNames.idTokenKey
] = `${param.tokens.id}; ${param.cookieSettings.idToken}`;
if (param.tokens.access) {
cookies[
cookieNames.accessTokenKey
] = `${param.tokens.access}; ${param.cookieSettings.accessToken}`;
}
if (param.tokens.refresh) {
cookies[
cookieNames.refreshTokenKey
] = `${param.tokens.refresh}; ${param.cookieSettings.refreshToken}`;
}
if (param.event === "signOut") {
// Expire all cookies
Object.keys(cookies).forEach(
(key) => (cookies[key] = expireCookie(cookies[key]))
);
}
// Always expire nonce, nonceHmac and pkce - this is valid in all scenario's:
// * event === 'newTokens' --> you just signed in and used your nonce and pkce successfully, don't need them no more
// * event === 'refreshFailed' --> you are signed in already, why do you still have a nonce?
// * event === 'signOut' --> clear ALL cookies anyway
[
"spa-auth-edge-nonce",
"spa-auth-edge-nonce-hmac",
"spa-auth-edge-pkce",
].forEach((key) => {
cookies[key] = expireCookie(`;${param.cookieSettings.nonce}`);
});
// Return cookie object in format of CloudFront headers
return Object.entries({
...param.additionalCookies,
...cookies,
}).map(([k, v]) => ({ key: "set-cookie", value: `${k}=${v}` }));
}
function expireCookie(cookie: string = "") {
const cookieParts = cookie
.split(";")
.map((part) => part.trim())
.filter((part) => !part.toLowerCase().startsWith("max-age"))
.filter((part) => !part.toLowerCase().startsWith("expires"));
const expires = `Expires=${new Date(0).toUTCString()}`;
const [, ...settings] = cookieParts; // first part is the cookie value, which we'll clear
return ["", ...settings, expires].join("; ");
}
function decodeToken(jwt: string) {
const tokenBody = jwt.split(".")[1];
const decodableTokenBody = tokenBody.replace(/-/g, "+").replace(/_/g, "/");
return JSON.parse(Buffer.from(decodableTokenBody, "base64").toString());
}
const AGENT = new Agent({ keepAlive: true });
export async function httpPostToCognitoWithRetry(
url: string,
data: Buffer,
options: RequestOptions,
logger: Logger
) {
let attempts = 0;
while (true) {
++attempts;
try {
return await fetch(url, data, {
agent: AGENT,
...options,
method: "POST",
}).then((res) => {
if (res.status !== 200) {
throw new Error(`Status is ${res.status}, expected 200`);
}
if (!res.headers["content-type"]?.startsWith("application/json")) {
throw new Error(
`Content-Type is ${res.headers["content-type"]}, expected application/json`
);
}
return {
...res,
data: JSON.parse(res.data.toString()),
};
});
} catch (err) {
logger.debug(`HTTP POST to ${url} failed (attempt ${attempts}):`);
logger.debug(err);
if (attempts >= 5) {
// Try 5 times at most
logger.error(
`No success after ${attempts} attempts, seizing further attempts`
);
throw err;
}
if (attempts >= 2) {
// After attempting twice immediately, do some exponential backoff with jitter
logger.debug(
"Doing exponential backoff with jitter, before attempting HTTP POST again ..."
);
await new Promise((resolve) =>
setTimeout(
resolve,
25 * (Math.pow(2, attempts) + Math.random() * attempts)
)
);
logger.debug("Done waiting, will try HTTP POST again now");
}
}
}
}
export function createErrorHtml(props: {
title: string;
message: string;
expandText?: string;
details?: string;
linkUri: string;
linkText: string;
}) {
const params = { ...props, region: process.env.AWS_REGION };
return html.replace(
/\${([^}]*)}/g,
(_: any, v: keyof typeof params) => escapeHtml(params[v]) ?? ""
);
}
function escapeHtml(unsafe: unknown) {
if (typeof unsafe !== "string") {
return undefined;
}
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
export const urlSafe = {
/*
Functions to translate base64-encoded strings, so they can be used:
- in URL's without needing additional encoding
- in OAuth2 PKCE verifier
- in cookies (to be on the safe side, as = + / are in fact valid characters in cookies)
stringify:
use this on a base64-encoded string to translate = + / into replacement characters
parse:
use this on a string that was previously urlSafe.stringify'ed to return it to
its prior pure-base64 form. Note that trailing = are not added, but NodeJS does not care
*/
stringify: (b64encodedString: string) =>
b64encodedString.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"),
parse: (b64encodedString: string) =>
b64encodedString.replace(/-/g, "+").replace(/_/g, "/"),
};
export function sign(
stringToSign: string,
secret: string,
signatureLength: number
) {
const digest = createHmac("sha256", secret)
.update(stringToSign)
.digest("base64")
.slice(0, signatureLength);
const signature = urlSafe.stringify(digest);
return signature;
}
export function timestampInSeconds() {
return (Date.now() / 1000) | 0;
}
export class RequiresConfirmationError extends Error {}
export function generateSecret(
allowedCharacters: string,
secretLength: number
) {
return [...new Array(secretLength)]
.map(() => allowedCharacters[randomInt(0, allowedCharacters.length)])
.join("");
}
export function ensureValidRedirectPath(path: unknown) {
if (typeof path !== "string") return "/";
return path.startsWith("/") ? path : `/${path}`;
}