forked from aws-samples/cloudfront-authorization-at-edge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
241 lines (224 loc) · 6.96 KB
/
index.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
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
import { stringify as stringifyQueryString } from "querystring";
import { createHash } from "crypto";
import { CloudFrontRequestHandler } from "aws-lambda";
import * as common from "../shared/shared";
const CONFIG = common.getConfigWithJwtVerifier();
CONFIG.logger.debug("Configuration loaded:", CONFIG);
export const handler: CloudFrontRequestHandler = async (event) => {
CONFIG.logger.debug("Event:", event);
const request = event.Records[0].cf.request;
const domainName = request.headers["host"][0].value;
const requestedUri = `${request.uri}${
request.querystring ? "?" + request.querystring : ""
}`;
try {
const cookies = common.extractAndParseCookies(
request.headers,
CONFIG.clientId,
CONFIG.cookieCompatibility
);
CONFIG.logger.debug("Extracted cookies:", cookies);
// If there's no ID token in your cookies, then you are not signed in yet
if (!cookies.idToken) {
throw new Error("No ID token present in cookies");
}
// Verify the ID-token (JWT), this throws an error if the JWT is not valid
const payload = await CONFIG.jwtVerifier.verify(cookies.idToken);
CONFIG.logger.debug("JWT payload:", payload);
// Return the request unaltered to allow access to the resource:
CONFIG.logger.debug("Access allowed:", request);
return request;
} catch (err) {
CONFIG.logger.info("Access denied:", err);
// If the JWT is expired we can try to refresh it
// This is done by redirecting the user to the refresh path.
// If the refresh works, the user will be redirected back here (this time with valid JWTs)
if (err instanceof common.JwtExpiredError) {
CONFIG.logger.debug("Redirecting user to refresh path");
return redirectToRefreshPath({ domainName, requestedUri });
}
// If the user is not in the right Cognito group, (s)he needs to contact an admin
// If legitimate, the admin should add the user to the Cognito group,
// after that the user will need to re-attempt sign-in
if (err instanceof common.CognitoJwtInvalidGroupError) {
CONFIG.logger.debug("User isn't in the right Cognito group");
return showContactAdminErrorPage({ err, domainName });
}
// Send the user to the Cognito Hosted UI to sign-in
CONFIG.logger.debug("Redirecting user to Cognito Hosted UI to sign-in");
return redirectToCognitoHostedUI({ domainName, requestedUri });
}
};
function redirectToCognitoHostedUI({
domainName,
requestedUri,
}: {
domainName: string;
requestedUri: string;
}) {
// Generate new state which involves a signed nonce
// This way we can check later whether the sign-in redirect was done by us (it should, to prevent CSRF attacks)
const nonce = generateNonce();
const state = {
nonce,
nonceHmac: common.sign(
nonce,
CONFIG.nonceSigningSecret,
CONFIG.nonceLength
),
...generatePkceVerifier(),
};
CONFIG.logger.debug("Using new state\n", state);
const loginQueryString = stringifyQueryString({
redirect_uri: `https://${domainName}${CONFIG.redirectPathSignIn}`,
response_type: "code",
client_id: CONFIG.clientId,
state:
// Encode the state variable as base64 to avoid a bug in Cognito hosted UI when using multiple identity providers
// Cognito decodes the URL, causing a malformed link due to the JSON string, and results in an empty 400 response from Cognito.
common.urlSafe.stringify(
Buffer.from(
JSON.stringify({ nonce: state.nonce, requestedUri })
).toString("base64")
),
scope: CONFIG.oauthScopes.join(" "),
code_challenge_method: "S256",
code_challenge: state.pkceHash,
});
// Return redirect to Cognito Hosted UI for sign-in
const response = {
status: "307",
statusDescription: "Temporary Redirect",
headers: {
location: [
{
key: "location",
value: `https://${CONFIG.cognitoAuthDomain}/oauth2/authorize?${loginQueryString}`,
},
],
"set-cookie": [
...getNonceCookies({ nonce, ...CONFIG }),
{
key: "set-cookie",
value: `spa-auth-edge-pkce=${encodeURIComponent(state.pkce)}; ${
CONFIG.cookieSettings.nonce
}`,
},
],
...CONFIG.cloudFrontHeaders,
},
};
CONFIG.logger.debug("Returning response:\n", response);
return response;
}
function redirectToRefreshPath({
domainName,
requestedUri,
}: {
domainName: string;
requestedUri: string;
}) {
const nonce = generateNonce();
const response = {
status: "307",
statusDescription: "Temporary Redirect",
headers: {
location: [
{
key: "location",
value: `https://${domainName}${
CONFIG.redirectPathAuthRefresh
}?${stringifyQueryString({ requestedUri, nonce })}`,
},
],
"set-cookie": getNonceCookies({ nonce, ...CONFIG }),
...CONFIG.cloudFrontHeaders,
},
};
CONFIG.logger.debug("Returning response:\n", response);
return response;
}
function showContactAdminErrorPage({
err,
domainName,
}: {
err: unknown;
domainName: string;
}) {
const response = {
body: common.createErrorHtml({
title: "Not Authorized",
message:
"You are not authorized for this site. Please contact the admin.",
expandText: "Click for details",
details: `${err}`,
linkUri: `https://${domainName}${CONFIG.signOutUrl}`,
linkText: "Try again",
}),
status: "200",
headers: {
...CONFIG.cloudFrontHeaders,
"content-type": [
{
key: "Content-Type",
value: "text/html; charset=UTF-8",
},
],
},
};
CONFIG.logger.debug("Returning response:\n", response);
return response;
}
function getNonceCookies({
nonce,
nonceLength,
nonceSigningSecret,
cookieSettings,
}: {
nonce: string;
nonceLength: number;
nonceSigningSecret: string;
cookieSettings: {
nonce: string;
};
}) {
return [
{
key: "set-cookie",
value: `spa-auth-edge-nonce=${encodeURIComponent(nonce)}; ${
cookieSettings.nonce
}`,
},
{
key: "set-cookie",
value: `spa-auth-edge-nonce-hmac=${encodeURIComponent(
common.sign(nonce, nonceSigningSecret, nonceLength)
)}; ${cookieSettings.nonce}`,
},
];
}
function generatePkceVerifier() {
const pkce = common.generateSecret(
CONFIG.secretAllowedCharacters,
CONFIG.pkceLength
);
const verifier = {
pkce,
pkceHash: common.urlSafe.stringify(
createHash("sha256").update(pkce, "utf8").digest("base64")
),
};
CONFIG.logger.debug("Generated PKCE verifier:\n", verifier);
return verifier;
}
function generateNonce() {
const randomString = common.generateSecret(
CONFIG.secretAllowedCharacters,
CONFIG.nonceLength
);
const nonce = `${common.timestampInSeconds()}T${randomString}`;
CONFIG.logger.debug("Generated new nonce:", nonce);
return nonce;
}