generated from shorn/tf-download
-
Notifications
You must be signed in to change notification settings - Fork 3
/
AuthorizeUser.ts
284 lines (261 loc) · 8.33 KB
/
AuthorizeUser.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
import { AuthorizeUserResponse } from "Shared/ApiTypes";
import { AuthError, forceError } from "Util/Error";
import { signAuthzToken } from "ZincApi/Authz/AuthzToken";
import { Algorithm, decode, JwtPayload, verify } from "jsonwebtoken";
import { GENERIC_DENIAL, guardGenericAuthz } from "ZincApi/Authz/GuardAuthz";
import { ZincApiRuntime } from "ZincApi/ZincApiHandler";
const oneDaySeconds = 1 * 24 * 60 * 60;
const tenMinutesSeconds = 10 * 60;
const accessTokenLifeSeconds = oneDaySeconds;
type CognitoPocIdToken = JwtPayload & {sub: string, email: string};
/** Exchange an OAuth/OIDC standard IdToken for an app-specific AccessToken */
export async function authorizeUser(
idToken: string,
config: ZincApiRuntime,
): Promise<AuthorizeUserResponse>{
// verify signature of token and shape of payload
const payload: CognitoPocIdToken =
await verifyCognitoIdToken(idToken, config);
const userId: string = payload.sub;
const userEmail: string = payload.email;
/* We use the cognito `subject` (AKA "user name") as our userId - it is not
PII. I believe these are UUID values (not sure of the flavour) and are
intended to be globally unique. If Cognito assigns the same `subject` to two
different principles across our user pools - that that would result in
undesirable behaviour (user-A sees user-B's data).
For a direct login, the `subject` is the user identifier that the idprovider
uses - i.e. authn direct with Github instead of through Cognito,
the "subject" will be a numeric id that Github assigned to the user. */
let user = await config.database.getServerUser(userId);
if( !user ){
/* there's no signup flow or authorization process, if a user wants to use
the PoC and we've been able to identify them - automatically add them. */
user = await config.database.addUser({
userId, email: userEmail, enabled: true
});
}
/* all access-restricted endpoints will check at least this, no point issuing
an accessToken that won't validate :) */
guardGenericAuthz(user);
console.log("idToken and User is valid, generating accessToken");
const accessToken = signAuthzToken({
payload: {
userId,
email: user.email,
userCreated: user.created,
role: "user" // not used yet
},
secret: config.authzSigningSecret,
expiresInSeconds: accessTokenLifeSeconds
});
return {
succeeded: true,
accessToken,
}
}
function isCognitoPocIdToken(payload: JwtPayload): payload is CognitoPocIdToken{
if( !payload.sub || typeof (payload.sub) !== "string" ){
return false;
}
if( !payload.email || typeof (payload.email) !== "string" ){
return false;
}
return true;
}
/** verfies the idToken against the relvant Cognito user pool, depending on
* the intended `audience` of the token.
*/
async function verifyCognitoIdToken(
idToken: string,
config: ZincApiRuntime,
): Promise<CognitoPocIdToken>{
/* used to dig out the `aud` claim to decide which pool to verify against,
but the token itself is NOT verified */
const decoded = decode(idToken) as JwtPayload;
console.log("authorize decode", decoded);
let payload: JwtPayload;
/* IMPROVE: it's about time to make this a map of verifier keyed by audience,
verifier objects need to know how to do both RSA and HMAC.
Or better; leave the Cognito verfiers the way they are, but unify all the
direct authentication under a "zincApi" audience secured with a single HS256
secret. Make each direct lambda handler responsible for mapping a successful
user authentication through to the single standard zincApi id_token.
Less config flying around and also more secure (zincApi lambda then wouldn't
need to be allowed to all the direct lambda's config params. */
if( decoded.aud === config.cognito.google.userPoolClientId ){
try {
payload = await config.rsaVerifier.googleCognito.verify(idToken);
payload = await config.rsaVerifier.googleCognito.verify(idToken);
}
catch( err ){
throw new AuthError({
publicMsg: "while verifying google cognito",
privateMsg: forceError(err).message
});
}
}
else if( decoded.aud === config.cognito.email.userPoolClientId ){
try {
payload = await config.rsaVerifier.emailCognito.verify(idToken);
}
catch( err ){
throw new AuthError({
publicMsg: "while verifying email cognito",
privateMsg: forceError(err).message
});
}
}
else if( decoded.aud === config.cognito.github.userPoolClientId ){
try {
payload = await config.rsaVerifier.githubCognito.verify(idToken);
}
catch( err ){
throw new AuthError({
publicMsg: "while verifying github cognito",
privateMsg: forceError(err).message
});
}
}
else if( decoded.aud === config.directAuthn.github.clientId ){
try {
payload = await verifyGithubDirectAuthn(
idToken, {...config.directAuthn.github} );
}
catch( err ){
throw new AuthError({
publicMsg: "while verifying github direct",
privateMsg: forceError(err).message
});
}
}
else if( decoded.aud === config.directAuthn.google.clientId ){
try {
payload = await config.rsaVerifier.googleDirect.verify(idToken);
}
catch( err ){
throw new AuthError({
publicMsg: "while verifying google direct",
privateMsg: forceError(err).message
});
}
}
else if( decoded.aud === config.directAuthn.facebook.clientId ){
try {
payload = await config.rsaVerifier.facebookDirect.verify(idToken);
}
catch( err ){
throw new AuthError({
publicMsg: "while verifying facebook direct",
privateMsg: forceError(err).message
});
}
}
else if( decoded.aud === config.directAuthn.twitter.twitterConsumerKey ){
try {
payload = await verifyTwitterDirectAuthn(
idToken, {...config.directAuthn.twitter} );
}
catch( err ){
throw new AuthError({
publicMsg: "while verifying twitter direct",
privateMsg: forceError(err).message
});
}
}
else if( decoded.aud === config.directAuthn.aaf.clientId ){
try {
payload = await config.rsaVerifier.aafDirect.verify(idToken);
}
catch( err ){
throw new AuthError({
publicMsg: "while verifying aaf direct",
privateMsg: forceError(err).message
});
}
}
else {
console.error("unknown JWT [aud]: ", decoded);
throw new AuthError({
publicMsg: "while authorizing",
privateMsg: "unknown JWT [aud]: " + decoded.aud
});
}
if( !isCognitoPocIdToken(payload) ){
console.error("idToken payload is wrong shape", decoded);
throw new AuthError({
publicMsg: "while authorizing",
privateMsg: "unknown JWT [aud]" + decoded.aud
});
}
return payload;
}
function verifyTwitterDirectAuthn(
idToken: string,
config: {
functionUrl: string,
twitterConsumerKey: string,
idTokenSecret: string,
}
): JwtPayload{
let result: string | JwtPayload;
try {
result = verify(
idToken,
config.idTokenSecret,
{
algorithms: ["HS256"] as Algorithm[],
issuer: config.functionUrl,
audience: config.twitterConsumerKey,
}
);
}
catch( err ){
console.log("problem verifying twitter idToken", err);
throw new AuthError({
publicMsg: GENERIC_DENIAL,
privateMsg: "failed direct twitter verify: " + forceError(err).message
});
}
if( typeof(result) === 'string' ){
throw new AuthError({
publicMsg: GENERIC_DENIAL,
privateMsg: "direct twitter payload was string: " + result
});
}
return result;
}
function verifyGithubDirectAuthn(
idToken: string,
config: {
functionUrl: string,
clientId: string,
clientSecret: string,
}
): JwtPayload{
let result: string | JwtPayload;
try {
result = verify(
idToken,
config.clientSecret,
{
algorithms: ["HS256"] as Algorithm[],
issuer: config.functionUrl,
audience: config.clientId,
}
);
}
catch( err ){
console.log("problem verifying", err);
throw new AuthError({
publicMsg: GENERIC_DENIAL,
privateMsg: "failed direct github verify: " + forceError(err).message
});
}
if( typeof(result) === 'string' ){
throw new AuthError({
publicMsg: GENERIC_DENIAL,
privateMsg: "direct github payload was string: " + result
});
}
return result;
}