This repository was archived by the owner on Aug 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.ts
228 lines (186 loc) · 6.76 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
import * as http from "http";
import * as util from "util";
import Validator from "ajv";
import axios, { AxiosError, AxiosInstance } from "axios";
import * as fastify from "fastify";
import plugin from "fastify-plugin";
import httpErrors from "http-errors";
import * as jwt from "jsonwebtoken";
import memoize from "mem";
import * as jose from "node-jose";
const optionsSchema = {
type: "object",
required: ["region", "userPoolId"],
properties: {
region: {
type: "string"
},
userPoolId: {
type: "string"
},
allowedAudiences: {
type: "array",
items: {
type: "string",
format: "uri"
}
}
}
};
const fastifyAwsCognitoPluginImplementation: fastify.Plugin<
http.Server,
http.IncomingMessage,
http.ServerResponse,
fastifyAwsCognitoPlugin.FastifyAwsCognitoPluginOptions
> = async (instance: fastify.FastifyInstance, options: fastifyAwsCognitoPlugin.FastifyAwsCognitoPluginOptions) => {
await validateOptions(options);
const issuer = `https://cognito-idp.${options.region}.amazonaws.com/${options.userPoolId}`;
const axiosInstance =
options.overrides && options.overrides.axiosInstance ? options.overrides.axiosInstance : axios.create();
const checkJti = options.verifyJtiWith || (async () => true);
const requestVerifier = cognitoVerifier({
issuer,
withAllowedAudiences: options.allowedAudiences,
withAxiosInstance: axiosInstance,
withJtiCheck: checkJti
});
const decoration: fastifyAwsCognitoPlugin.FastifyAwsCognitoDecoration = {
verify: requestVerifier
};
instance.decorate("cognito", decoration);
instance.decorateRequest("verifyCognito", function() {
// @ts-ignore
cognitoVerifier(this as fastify.FastifyRequest);
});
};
interface AwsCognitoVerifierOptions {
issuer: string;
withAllowedAudiences?: string[];
withAxiosInstance: AxiosInstance;
withJtiCheck: (jti: string) => Promise<boolean>;
}
function cognitoVerifier(options: AwsCognitoVerifierOptions) {
const verifyToken = util.promisify<string, string, jwt.VerifyOptions, string | object>(jwt.verify);
const createKeyStoreFromWellKnownKeysOfOptimally = memoize(createKeyStoreFromWellKnownKeysOf, { maxAge: 60000 });
return async function verifyWithCognito(request: fastify.FastifyRequest) {
const header = getHeaderFromRequest(request);
const token = getTokenFromHeader(header);
const keyId = getKeyIdFromToken(token);
const keyStore = await createKeyStoreFromWellKnownKeysOfOptimally(options.issuer, options.withAxiosInstance);
const key = getKeyFromKeyStoreByKeyId(keyStore, keyId);
const pem = await generatePemCertificateFrom(key);
const extraVerificationOptions: jwt.VerifyOptions = options.withAllowedAudiences
? { audience: options.withAllowedAudiences }
: {};
try {
const parsedToken = (await verifyToken(token, pem, {
...extraVerificationOptions,
issuer: options.issuer
})) as { [k: string]: any };
const isJtiInvalid = !(await options.withJtiCheck(parsedToken.jti));
if (isJtiInvalid) {
return Promise.reject(new httpErrors.Unauthorized("Token verification failed: jti is blacklisted"));
}
request.token = parsedToken;
} catch (cause) {
request.log.error(cause);
if (/audience invalid/gi.test(cause.message)) {
throw new httpErrors.Unauthorized("Token verification failed: audience is not allowed");
} else if (/jwt expired/gi.test(cause.message)) {
throw new httpErrors.Unauthorized("Token verification failed: token expired");
}
throw new httpErrors.Unauthorized("Token verification failed");
}
};
}
async function createKeyStoreFromWellKnownKeysOf(
issuer: string,
axiosInstance: AxiosInstance
): Promise<jose.JWK.KeyStore> {
const wellKnownKeysUri = `${issuer}/.well-known/jwks.json`;
const keys = await axiosInstance
.get(wellKnownKeysUri)
.then((r) => r.data)
.catch((error: AxiosError) => {
if (!(error.response && error.response.status < 500)) {
return Promise.reject(
new httpErrors.InternalServerError("An unknown error occurred while retrieving known keys")
);
}
return Promise.resolve(null);
});
if (!keys) {
throw new httpErrors.InternalServerError("Unable to retrieve known keys for user pool id");
}
return jose.JWK.asKeyStore(keys);
}
function getHeaderFromRequest(request: fastify.FastifyRequest): string {
const header = request.headers.authorization;
if (!header) {
throw new httpErrors.Unauthorized("Authorization header is missing");
}
return header;
}
function getTokenFromHeader(header: string): string {
const parts = header.split(" ");
if (parts.length !== 2) {
throw new httpErrors.Unauthorized("Authorization header is malformed");
}
const [, token] = parts;
return token;
}
function getKeyIdFromToken(token: string): string {
let keyInformation;
try {
const [encodedRawKeyInformation] = token.split(".");
const rawKeyInformation = decodeBase64(encodedRawKeyInformation);
keyInformation = JSON.parse(rawKeyInformation);
} catch (error) {
throw new httpErrors.Unauthorized("Unable to verify key of token");
}
if (!(keyInformation && keyInformation.kid)) {
throw new httpErrors.Unauthorized("Unable to retrieve key id of token");
}
return keyInformation.kid;
}
function getKeyFromKeyStoreByKeyId(keyStore: jose.JWK.KeyStore, keyId: string): jose.JWK.RawKey {
const key: jose.JWK.RawKey | null = keyStore.get(keyId);
if (!key) {
throw new httpErrors.Unauthorized("Token was signed with unknown key id");
}
return key;
}
async function generatePemCertificateFrom(rawKey: jose.JWK.RawKey): Promise<string> {
const key = await jose.JWK.asKey(rawKey);
return key.toPEM();
}
function decodeBase64(input: string): string {
return Buffer.from(input, "base64").toString("ascii");
}
const validator = new Validator();
async function validateOptions(options: fastifyAwsCognitoPlugin.FastifyAwsCognitoPluginOptions): Promise<void> {
const isInvalid = !(await validator.validate(optionsSchema, options));
if (isInvalid) {
const [error] = validator.errors!;
const message = error.dataPath ? `options${error.dataPath} ${error.message}` : `options ${error.message}`;
throw new Error(message);
}
}
namespace fastifyAwsCognitoPlugin {
export interface FastifyAwsCognitoPluginOptions {
region: string;
userPoolId: string;
allowedAudiences?: string[];
verifyJtiWith?: (jti: string) => Promise<boolean>;
overrides?: {
axiosInstance?: AxiosInstance;
};
}
export interface FastifyAwsCognitoDecoration {
verify: fastify.RequestHandler;
}
}
const fastifyAwsCognitoPlugin = plugin(fastifyAwsCognitoPluginImplementation, {
name: "fastify-aws-cognito"
});
export = fastifyAwsCognitoPlugin;