-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp-routes.js
More file actions
339 lines (321 loc) · 12.2 KB
/
Copy pathapp-routes.js
File metadata and controls
339 lines (321 loc) · 12.2 KB
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
/**
* Configure all routes for express app
*/
const _ = require("lodash");
const config = require("config");
const HttpStatus = require("http-status-codes");
const { v4: uuid } = require('uuid');
const util = require("util");
const helper = require("./src/common/helper");
const errors = require("./src/common/errors");
const logger = require("./src/common/logger");
const routes = require("./src/routes");
const authenticator = require("tc-core-library-js").middleware.jwtAuthenticator;
/**
* Returns whether a normalized auth user has interactive roles.
*
* @param {Object} authUser the decoded auth user from the authenticator
* @returns {Boolean} true when the caller has one or more user roles
*/
function hasInteractiveRoles(authUser) {
const roles = _.get(authUser, "roles");
return _.isArray(roles) ? roles.length > 0 : !!roles;
}
/**
* Read the scope claim from an auth user.
*
* The shared authenticator normally copies Auth0's `scope` string into
* `scopes`, but this also handles callers already carrying either shape or
* Auth0 RBAC `permissions`.
*
* @param {Object} authUser the decoded auth user from the authenticator
* @returns {Array|String|undefined} scopes from the token
*/
function getAuthUserScopes(authUser) {
if (!authUser) {
return undefined;
}
return (
authUser.scopes ||
authUser.permissions ||
_.find(authUser, (value, key) => {
return key.indexOf("scope") !== -1;
})
);
}
/**
* Determine whether an auth user represents an M2M caller.
*
* Some valid client-credentials tokens are decoded with scopes but without the
* `isMachine` flag. Treat no-role scoped callers as M2M so route-level scope
* checks, not user group membership, decide access.
*
* @param {Object} authUser the decoded auth user from the authenticator
* @returns {Boolean} true when the caller should be handled as M2M
*/
function isM2MAuthUser(authUser) {
return !!(
authUser &&
(_.get(authUser, "isMachine", false) ||
(getAuthUserScopes(authUser) && !hasInteractiveRoles(authUser)))
);
}
/**
* Check whether an M2M caller has any scope required by the route definition.
*
* @param {Object} def route definition from src/routes.js
* @param {Object} authUser the decoded auth user from the authenticator
* @returns {Boolean} true when one required route scope is present
*/
function hasRequiredM2MScopes(def, authUser) {
const scopes = getAuthUserScopes(authUser);
return !!(def.scopes && scopes && helper.checkIfExists(def.scopes, scopes));
}
/**
* Normalize a valid M2M caller to the shape expected by service authorization.
*
* @param {Object} def route definition from src/routes.js
* @param {Object} authUser the decoded auth user from the authenticator
* @returns {Boolean} true when the caller has required M2M scopes
*/
function normalizeM2MAuthUser(def, authUser) {
if (!isM2MAuthUser(authUser) || !hasRequiredM2MScopes(def, authUser)) {
return false;
}
const scopes = getAuthUserScopes(authUser);
authUser.isMachine = true;
authUser.scopes = _.isString(scopes) ? scopes.split(" ") : scopes;
return true;
}
const sanitizeForLog = (value) => {
const seen = new WeakSet();
try {
return JSON.parse(
JSON.stringify(value, (key, val) => {
if (typeof val === "object" && val !== null) {
if (seen.has(val)) return "<circular>";
seen.add(val);
}
if (Buffer.isBuffer(val)) return `<Buffer length=${val.length}>`;
if (val && typeof val === "object" && val.type === "Buffer" && Array.isArray(val.data)) {
return `<Buffer length=${val.data.length}>`;
}
if (Array.isArray(val) && val.length > 30) return `Array(${val.length})`;
if (typeof val === "string" && val.length > 500) return `${val.slice(0, 500)}...<truncated>`;
return val;
})
);
} catch (err) {
return `<unserializable: ${err.message}>`;
}
};
const safeInspect = (payload) => util.inspect(sanitizeForLog(payload), { breakLength: Infinity });
const getSignature = (req) => req.signature || req._reqLogId || "no-signature";
/**
* Configure all routes for express app
* @param app the express app
*/
function configureRoutes(app) {
// Load all routes
_.each(routes, (verbs, path) => {
_.each(verbs, (def, verb) => {
const controllerPath = `./src/controllers/${def.controller}`;
const method = require(controllerPath)[def.method]; // eslint-disable-line
if (!method) {
throw new Error(`${def.method} is undefined`);
}
const actions = [];
actions.push((req, res, next) => {
if (def.method !== "checkHealth") {
req._id = uuid();
req.signature = `${req._id}-${def.controller}#${def.method}`;
logger.info(
`Started request handling, ${req.signature} ${req.method} ${req.originalUrl} controller=${def.controller}.${def.method} query=${safeInspect(
req.query
)} params=${safeInspect(req.params)} body=${safeInspect(req.body)}`
);
}
next();
});
actions.push((req, res, next) => {
if (_.get(req, "query.token")) {
_.set(req, "headers.authorization", `Bearer ${_.trim(req.query.token)}`);
logger.info(`[${getSignature(req)}] Promoted query.token to Authorization header`);
}
next();
});
if (def.auth) {
// add Authenticator/Authorization check if route has auth
actions.push((req, res, next) => {
authenticator(_.pick(config, ["AUTH_SECRET", "VALID_ISSUERS"]))(req, res, next);
});
actions.push((req, res, next) => {
if (isM2MAuthUser(req.authUser)) {
// M2M
if (!normalizeM2MAuthUser(def, req.authUser)) {
logger.warn(
`[${getSignature(req)}] Machine token scope mismatch. required=${safeInspect(
def.scopes
)} provided=${safeInspect(getAuthUserScopes(req.authUser))}`
);
next(
new errors.ForbiddenError(`You are not allowed to perform this action, because the scopes are incorrect. \
Required scopes: ${JSON.stringify(def.scopes)} \
Provided scopes: ${JSON.stringify(getAuthUserScopes(req.authUser))}`)
);
} else {
req.authUser.handle = config.M2M_AUDIT_HANDLE;
req.authUser.userId = config.M2M_AUDIT_USERID;
req.userToken = req.headers.authorization.split(" ")[1];
logger.info(
`[${getSignature(req)}] Authenticated M2M token scopes=${safeInspect(
req.authUser.scopes
)}`
);
next();
}
} else {
req.authUser.userId = String(req.authUser.userId);
// User roles authorization
if (req.authUser.roles) {
if (
def.access &&
!helper.checkIfExists(
_.map(def.access, (a) => a.toLowerCase()),
_.map(req.authUser.roles, (r) => r.toLowerCase())
)
) {
logger.warn(
`[${getSignature(req)}] User role mismatch required=${safeInspect(
def.access
)} provided=${safeInspect(req.authUser.roles)}`
);
next(
new errors.ForbiddenError(`You are not allowed to perform this action, because the roles are incorrect. \
Required roles: ${JSON.stringify(def.access)} \
Provided roles: ${JSON.stringify(req.authUser.roles)}`)
);
} else {
// user token is used in create/update challenge to ensure user can create/update challenge under specific project
req.userToken = req.headers.authorization.split(" ")[1];
logger.info(
`[${getSignature(req)}] Authenticated user=${req.authUser.userId} roles=${safeInspect(
req.authUser.roles
)}`
);
next();
}
} else {
logger.warn(`[${getSignature(req)}] Authenticated user missing roles`);
next(
new errors.ForbiddenError(
"You are not authorized to perform this action, \
because no roles were provided"
)
);
}
}
});
} else {
// public API, but still try to authenticate token if provided, but allow missing/invalid token
actions.push((req, res, next) => {
const hasToken =
!!req.headers.authorization || !!_.get(req, "query.token") || !!req.authUser;
if (!hasToken) {
return next();
}
const interceptRes = {};
interceptRes.status = () => interceptRes;
interceptRes.json = () => interceptRes;
interceptRes.send = (payload) => {
logger.info(
`[${getSignature(req)}] Public route: authenticator send called payload=${safeInspect(
payload
)}`
);
return next();
};
const authMw = authenticator(_.pick(config, ["AUTH_SECRET", "VALID_ISSUERS"]));
let finished = false;
const bailoutTimer = setTimeout(() => {
if (finished) return;
finished = true;
next();
}, 8000);
authMw(req, interceptRes, (...args) => {
if (finished) return;
finished = true;
clearTimeout(bailoutTimer);
next(...args);
});
});
actions.push((req, res, next) => {
if (!req.authUser) {
logger.info(`[${getSignature(req)}] Public route: no authUser context`);
next();
} else if (isM2MAuthUser(req.authUser)) {
if (!normalizeM2MAuthUser(def, req.authUser)) {
logger.info(
`[${getSignature(req)}] Public route: preserving machine token whitelist bypass despite scope mismatch`
);
req.authUser = {
bypassChallengeWhitelist: true,
};
} else {
logger.info(`[${getSignature(req)}] Public route: valid machine token attached`);
}
next();
} else {
req.authUser.userId = String(req.authUser.userId);
logger.info(
`[${getSignature(req)}] Public route: user present userId=${req.authUser.userId}`
);
next();
}
});
}
actions.push(async (req, res, next) => {
logger.info(`[${getSignature(req)}] Invoking ${def.controller}.${def.method}`);
try {
const resultPromise = method(req, res, next);
if (resultPromise && typeof resultPromise.then === "function") {
await resultPromise;
}
logger.info(
`[${getSignature(req)}] Completed ${def.controller}.${def.method} headersSent=${res.headersSent} status=${res.statusCode}`
);
} catch (err) {
logger.error(
`[${getSignature(req)}] ${def.controller}.${def.method} threw error: ${
err.message || "unknown error"
}`
);
throw err;
}
});
app[verb](`/${config.API_VERSION}${path}`, helper.autoWrapExpress(actions));
});
});
// Check if the route is not found or HTTP method is not supported
app.use((req, res) => {
if (routes[req.baseUrl]) {
logger.warn(`Unsupported method ${req.method} for ${req.originalUrl}`);
res.status(HttpStatus.METHOD_NOT_ALLOWED).json({
message: "The requested HTTP method is not supported.",
});
} else {
logger.warn(`Route not found for ${req.method} ${req.originalUrl}`);
res.status(HttpStatus.NOT_FOUND).json({
message: "The requested resource cannot be found.",
});
}
});
}
module.exports = configureRoutes;
module.exports.__testables = {
getAuthUserScopes,
hasInteractiveRoles,
hasRequiredM2MScopes,
isM2MAuthUser,
normalizeM2MAuthUser,
};