-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
246 lines (239 loc) · 7.29 KB
/
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
import { FastifyPluginAsync, FastifyReply, FastifyRequest } from "fastify";
import fp from "fastify-plugin";
import jwksClient from "jwks-rsa";
import jwt, { Algorithm } from "jsonwebtoken";
import {
SecretsManagerClient,
GetSecretValueCommand,
} from "@aws-sdk/client-secrets-manager";
import { AppRoles } from "../../common/roles.js";
import {
BaseError,
InternalServerError,
UnauthenticatedError,
UnauthorizedError,
} from "../../common/errors/index.js";
import { genericConfig, SecretConfig } from "../../common/config.js";
import { getGroupRoles, getUserRoles } from "../functions/authorization.js";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
export function intersection<T>(setA: Set<T>, setB: Set<T>): Set<T> {
const _intersection = new Set<T>();
for (const elem of setB) {
if (setA.has(elem)) {
_intersection.add(elem);
}
}
return _intersection;
}
export type AadToken = {
aud: string;
iss: string;
iat: number;
nbf: number;
exp: number;
acr: string;
aio: string;
amr: string[];
appid: string;
appidacr: string;
email?: string;
groups?: string[];
idp: string;
ipaddr: string;
name: string;
oid: string;
rh: string;
scp: string;
sub: string;
tid: string;
unique_name: string;
uti: string;
ver: string;
roles?: string[];
};
export const getSecretValue = async (
smClient: SecretsManagerClient,
secretId: string,
): Promise<Record<string, string | number | boolean> | null | SecretConfig> => {
const data = await smClient.send(
new GetSecretValueCommand({ SecretId: secretId }),
);
if (!data.SecretString) {
return null;
}
try {
return JSON.parse(data.SecretString) as Record<
string,
string | number | boolean
>;
} catch {
return null;
}
};
const authPlugin: FastifyPluginAsync = async (fastify, _options) => {
fastify.decorate(
"authorize",
async function (
request: FastifyRequest,
_reply: FastifyReply,
validRoles: AppRoles[],
): Promise<Set<AppRoles>> {
const userRoles = new Set([] as AppRoles[]);
try {
const authHeader = request.headers.authorization;
if (!authHeader) {
throw new UnauthenticatedError({
message: "Did not find bearer token in expected header.",
});
}
const [method, token] = authHeader.split(" ");
if (method !== "Bearer") {
throw new UnauthenticatedError({
message: `Did not find bearer token, found ${method} token.`,
});
}
/* eslint-disable @typescript-eslint/no-explicit-any */
const decoded = jwt.decode(token, { complete: true }) as Record<
string,
any
>;
let signingKey = "";
let verifyOptions = {};
if (decoded?.payload.iss === "custom_jwt") {
if (fastify.runEnvironment === "prod") {
throw new UnauthenticatedError({
message: "Custom JWTs cannot be used in Prod environment.",
});
}
signingKey =
process.env.JwtSigningKey ||
((
(await getSecretValue(
fastify.secretsManagerClient,
genericConfig.ConfigSecretName,
)) || {
jwt_key: "",
}
).jwt_key as string) ||
"";
if (signingKey === "") {
throw new UnauthenticatedError({
message: "Invalid token.",
});
}
verifyOptions = { algorithms: ["HS256" as Algorithm] };
} else {
const AadClientId = fastify.environmentConfig.AadValidClientId;
if (!AadClientId) {
request.log.error(
"Server is misconfigured, could not find `AadValidClientId`!",
);
throw new InternalServerError({
message:
"Server authentication is misconfigured, please contact your administrator.",
});
}
const header = decoded?.header;
if (!header) {
throw new UnauthenticatedError({
message: "Could not decode token header.",
});
}
verifyOptions = {
algorithms: ["RS256" as Algorithm],
header: decoded?.header,
audience: `api://${AadClientId}`,
};
const client = jwksClient({
jwksUri: "https://login.microsoftonline.com/common/discovery/keys",
});
signingKey = (await client.getSigningKey(header.kid)).getPublicKey();
}
const verifiedTokenData = jwt.verify(
token,
signingKey,
verifyOptions,
) as AadToken;
request.tokenPayload = verifiedTokenData;
request.username = verifiedTokenData.email || verifiedTokenData.sub;
const expectedRoles = new Set(validRoles);
if (verifiedTokenData.groups) {
const groupRoles = await Promise.allSettled(
verifiedTokenData.groups.map((x) =>
getGroupRoles(fastify.dynamoClient, fastify, x),
),
);
for (const result of groupRoles) {
if (result.status === "fulfilled") {
for (const role of result.value) {
userRoles.add(role);
}
} else {
request.log.warn(`Failed to get group roles: ${result.reason}`);
}
}
} else {
if (
verifiedTokenData.roles &&
fastify.environmentConfig.AzureRoleMapping
) {
for (const group of verifiedTokenData.roles) {
if (fastify.environmentConfig["AzureRoleMapping"][group]) {
for (const role of fastify.environmentConfig[
"AzureRoleMapping"
][group]) {
userRoles.add(role);
}
}
}
}
}
// add user-specific role overrides
if (request.username) {
try {
const userAuth = await getUserRoles(
fastify.dynamoClient,
fastify,
request.username,
);
for (const role of userAuth) {
userRoles.add(role);
}
} catch (e) {
request.log.warn(
`Failed to get user role mapping for ${request.username}: ${e}`,
);
}
}
if (
expectedRoles.size > 0 &&
intersection(userRoles, expectedRoles).size === 0
) {
throw new UnauthorizedError({
message: "User does not have the privileges for this task.",
});
}
} catch (err: unknown) {
if (err instanceof BaseError) {
throw err;
}
if (err instanceof jwt.TokenExpiredError) {
throw new UnauthenticatedError({
message: "Token has expired.",
});
}
if (err instanceof Error) {
request.log.error(`Failed to verify JWT: ${err.toString()} `);
throw err;
}
throw new UnauthenticatedError({
message: "Invalid token.",
});
}
request.log.info(`authenticated request from ${request.username} `);
return userRoles;
},
);
};
const fastifyAuthPlugin = fp(authPlugin);
export default fastifyAuthPlugin;