-
Notifications
You must be signed in to change notification settings - Fork 0
/
github-cookie-auth.ts
345 lines (333 loc) · 11.1 KB
/
github-cookie-auth.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
import * as cdk from "aws-cdk-lib"
import * as constructs from "constructs"
import * as lambda from "aws-cdk-lib/aws-lambda"
import * as kms from "aws-cdk-lib/aws-kms"
import * as dynamodb from "aws-cdk-lib/aws-dynamodb"
import * as apigateway from "aws-cdk-lib/aws-apigateway"
import * as route53 from "aws-cdk-lib/aws-route53"
import * as route53targets from "aws-cdk-lib/aws-route53-targets"
import * as sm from "aws-cdk-lib/aws-secretsmanager"
import * as cm from "aws-cdk-lib/aws-certificatemanager"
import * as logs from "aws-cdk-lib/aws-logs"
import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs"
import * as path from "path"
type Props = {
/**
* The amount of time to cache responses from
* the Lambda authorizer
*/
authorizerResponseTtl: cdk.Duration
/**
* The ID of the GitHub application.
*/
gitHubAppId: string
/**
* A Secrets Manager secret containing the client credentials
* for the GitHub App in JSON format:
* {
* "clientId": "<client-id>",
* "clientSecret": "<client-secret>"
* }
*/
clientCredentials: sm.ISecret
authCookieConfiguration: {
/**
* A KMS key that will be used to encrypt the access token
* stored in the cookie.
*/
encryptionKey: kms.IKey
/**
* The name of the cookie to store the encrypted GitHub access token in.
* @default token
*/
name?: string
attributes?: {
/**
* @default true
*/
secure?: boolean
/**
* @default true
*/
httpOnly?: boolean
/**
* @default null
*/
domain?: string
/**
* @default Strict
*/
sameSite?: "Strict" | "Lax" | "None"
}
}
nonceCookieConfiguration: {
/**
* The name of the cookie to store the nonce in.
* @default nonce
*/
name?: string
attributes?: {
/**
* @default true
*/
secure?: boolean
/**
* @default true
*/
httpOnly?: boolean
/**
* @default null
*/
domain?: string
/**
* NOTE: This needs to be Lax in order for the nonce
* cookie to be sent when GitHub redirects the client to
* our callback
*
* @default Lax
*/
sameSite?: "Strict" | "Lax" | "None"
}
}
/**
* The access control to use in the Lambda authorizer.
*/
accessControl: {
/**
* The type of access control to perform, either
* based on username or the user's organization membership.
*
* NOTE: `ORG_MEMBERSHIP` requires that the associated GitHub
* application has been installed in the respective organization(s)
*/
type: "USERNAME" | "ORG_MEMBERSHIP"
/**
* A list of GitHub usernames or GitHub organization names that will
* be granted access.
*/
whitelist: string[]
}
/**
* Configuration for a Lambda-backed API Gateway that
* is used to exchange temporary codes for GitHub
* access tokens using GitHub's web application flow
* and ultimately stores these in encrypted cookies.
*/
apiConfiguration: {
/**
* The hosted zone to create the A record
* for the domain name
*/
hostedZone: route53.IHostedZone
/**
* The domain name to use for the API.
*/
domainName: string
/**
* Certificate set up in us-east-1 to use with the proxy API
*/
certificate: cm.ICertificate
/**
* The origin that is allowed to communicate with the API.
* This is sent as part of the CORS preflight response, and
* also verified in the Lambda authorizer to prevent CSRF
* (especially important if the authorizer is used for a
* WebSocket API).
*
* NOTE: This can't be a wildcard as it is not compatible with
* the Access-Control-Allow-Credentials header.
*/
allowedOrigin: string
/**
* The URL to redirect the client to after an access token
* has been obtained from GitHub.
*/
redirectUrl: string
}
}
/**
* An API Gateway REST API that implements GitHub's
* web application flow for generating a user access token,
* stores the access token in an encrypted cookie, and a
* Lambda authorizer that can use the cookie (and thus access
* token) for authentication and authorization purposes.
*/
export class GitHubCookieAuth extends constructs.Construct {
public readonly authorizer
public readonly authorizerFn
constructor(scope: constructs.Construct, id: string, props: Props) {
super(scope, id)
const responseHeaders = {
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": apigateway.Cors.ALL_METHODS.join(","),
"Access-Control-Allow-Origin": props.apiConfiguration.allowedOrigin,
}
/*
* Table for caching Lambda authorizer responses
* There is built-in support for this in REST APIs, but not for WebSocket APIs
*/
const cacheTable = new dynamodb.Table(this, "CacheTable", {
partitionKey: {
name: "PK",
type: dynamodb.AttributeType.STRING,
},
sortKey: {
name: "SK",
type: dynamodb.AttributeType.STRING,
},
timeToLiveAttribute: "ttl",
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
removalPolicy: cdk.RemovalPolicy.DESTROY,
})
// Set default values
const authCookieName = props.authCookieConfiguration.name || "token"
const authCookieAttributes: Props["authCookieConfiguration"]["attributes"] =
{
secure: true,
httpOnly: true,
sameSite: "Strict",
...props.authCookieConfiguration.attributes,
}
const nonceCookieName = props.nonceCookieConfiguration.name || "nonce"
const nonceCookieAttributes: Props["nonceCookieConfiguration"]["attributes"] =
{
secure: true,
httpOnly: true,
sameSite: "Lax",
...props.nonceCookieConfiguration.attributes,
}
this.authorizerFn = new NodejsFunction(this, "AuthorizerLambda", {
entry: path.join(__dirname, "../assets/github-cookie-auth/authorizer.ts"),
handler: "handler",
runtime: lambda.Runtime.NODEJS_20_X,
timeout: cdk.Duration.seconds(10),
logRetention: logs.RetentionDays.ONE_MONTH,
environment: {
ALLOWED_ORIGIN: props.apiConfiguration.allowedOrigin,
SECRET_NAME: props.clientCredentials.secretName,
AUTH_COOKIE_NAME: authCookieName,
AUTH_COOKIE_ENCRYPTION_KEY_ARN:
props.authCookieConfiguration.encryptionKey.keyArn,
ACCESS_CONTROL: JSON.stringify({
...props.accessControl,
whitelist: props.accessControl.whitelist.map((item) =>
item.toLowerCase(),
),
}),
GITHUB_APP_ID: props.gitHubAppId,
AUTHORIZER_CACHE_TABLE_NAME: cacheTable.tableName,
AUTHORIZER_CACHE_TTL: `${props.authorizerResponseTtl.toSeconds()}`,
},
tracing: lambda.Tracing.ACTIVE,
})
cacheTable.grantReadWriteData(this.authorizerFn)
props.clientCredentials.grantRead(this.authorizerFn)
props.authCookieConfiguration.encryptionKey.grantDecrypt(this.authorizerFn)
this.authorizer = new apigateway.RequestAuthorizer(this, "Authorizer", {
handler: this.authorizerFn,
resultsCacheTtl: props.authorizerResponseTtl,
identitySources: [apigateway.IdentitySource.header("Cookie")],
})
const requestFn = new NodejsFunction(this, "RequestLambda", {
entry: path.join(
__dirname,
"../assets/github-cookie-auth/oauth-flow-request.ts",
),
handler: "handler",
runtime: lambda.Runtime.NODEJS_20_X,
timeout: cdk.Duration.seconds(10),
logRetention: logs.RetentionDays.ONE_MONTH,
tracing: lambda.Tracing.ACTIVE,
environment: {
RESPONSE_HEADERS: JSON.stringify(responseHeaders),
NONCE_COOKIE_NAME: nonceCookieName,
SECRET_NAME: props.clientCredentials.secretName,
CALLBACK_URL: `https://${props.apiConfiguration.domainName}/callback`,
NONCE_COOKIE_ATTRIBUTES: Object.entries(nonceCookieAttributes)
.map(([attribute, value]) => {
const capitalized =
attribute.charAt(0).toUpperCase() + attribute.slice(1)
return typeof value === "boolean"
? value
? capitalized
: undefined
: `${capitalized}=${value}`
})
.filter((v) => v)
.join("; "),
},
})
props.clientCredentials.grantRead(requestFn)
const callbackFn = new NodejsFunction(this, "CallbackFn", {
entry: path.join(
__dirname,
"../assets/github-cookie-auth/oauth-flow-callback.ts",
),
handler: "handler",
runtime: lambda.Runtime.NODEJS_20_X,
timeout: cdk.Duration.seconds(10),
logRetention: logs.RetentionDays.ONE_MONTH,
tracing: lambda.Tracing.ACTIVE,
environment: {
REDIRECT_URL: props.apiConfiguration.redirectUrl,
NONCE_COOKIE_NAME: nonceCookieName,
SECRET_NAME: props.clientCredentials.secretName,
RESPONSE_HEADERS: JSON.stringify(responseHeaders),
AUTH_COOKIE_NAME: authCookieName,
AUTH_COOKIE_ENCRYPTION_KEY_ARN:
props.authCookieConfiguration.encryptionKey.keyArn,
AUTH_COOKIE_ATTRIBUTES: Object.entries(authCookieAttributes)
.map(([attribute, value]) => {
const capitalized =
attribute.charAt(0).toUpperCase() + attribute.slice(1)
return typeof value === "boolean"
? value
? capitalized
: undefined
: `${capitalized}=${value}`
})
.filter((v) => v)
.join("; "),
},
})
props.clientCredentials.grantRead(callbackFn)
props.authCookieConfiguration.encryptionKey.grantEncrypt(callbackFn)
const authProxyApi = new apigateway.RestApi(this, "ProxyApi", {
defaultMethodOptions: {
authorizationType: apigateway.AuthorizationType.NONE,
},
endpointTypes: [apigateway.EndpointType.EDGE],
domainName: {
domainName: props.apiConfiguration.domainName,
endpointType: apigateway.EndpointType.EDGE,
certificate: props.apiConfiguration.certificate,
},
defaultCorsPreflightOptions: {
allowMethods: apigateway.Cors.ALL_METHODS,
allowCredentials: true,
allowHeaders: apigateway.Cors.DEFAULT_HEADERS,
allowOrigins: props.apiConfiguration.allowedOrigin
? [props.apiConfiguration.allowedOrigin]
: [],
},
disableExecuteApiEndpoint: true,
})
authProxyApi.root
.addResource("request")
.addMethod("GET", new apigateway.LambdaIntegration(requestFn))
authProxyApi.root
.addResource("callback")
.addMethod("GET", new apigateway.LambdaIntegration(callbackFn))
// Enable tracing
;(
authProxyApi.deploymentStage.node.defaultChild as apigateway.CfnStage
).addPropertyOverride("TracingEnabled", true)
new route53.ARecord(this, "Record", {
zone: props.apiConfiguration.hostedZone,
recordName: props.apiConfiguration.domainName,
target: route53.RecordTarget.fromAlias(
new route53targets.ApiGateway(authProxyApi),
),
})
}
}