/
openapi.security.ts
268 lines (238 loc) 路 7.74 KB
/
openapi.security.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
import {
OpenAPIV3,
OpenApiRequest,
SecurityHandlers,
OpenApiRequestMetadata,
OpenApiRequestHandler,
} from '../framework/types';
import { validationError } from './util';
import { OpenApiContext } from '../framework/openapi.context';
const defaultSecurityHandler = (
req: Express.Request,
scopes: string[],
schema: OpenAPIV3.SecuritySchemeObject,
) => true;
type SecuritySchemesMap = {
[key: string]: OpenAPIV3.ReferenceObject | OpenAPIV3.SecuritySchemeObject;
};
interface SecurityHandlerResult {
success: boolean;
status?: number;
error?: string;
}
export function security(
context: OpenApiContext,
securityHandlers: SecurityHandlers,
): OpenApiRequestHandler {
return async (req, res, next) => {
// TODO move the folllowing 3 check conditions to a dedicated upstream middleware
if (!req.openapi) {
// this path was not found in open api and
// this path is not defined under an openapi base path
// skip it
return next();
}
const openapi = <OpenApiRequestMetadata>req.openapi;
const expressRoute = openapi.expressRoute;
if (!expressRoute) {
return next(validationError(404, req.path, 'not found'));
}
const pathSchema = openapi.schema;
if (!pathSchema) {
// add openapi metadata to make this case more clear
// its not obvious that missig schema means methodNotAllowed
return next(
validationError(405, req.path, `${req.method} method not allowed`),
);
}
// use the local security object or fallbac to api doc's security or undefined
const securities: OpenAPIV3.SecurityRequirementObject[] =
openapi.schema.security ?? context.apiDoc.security;
const path: string = openapi.openApiRoute;
if (!path || !Array.isArray(securities) || securities.length === 0) {
return next();
}
const securitySchemes = context.apiDoc.components?.securitySchemes;
if (!securitySchemes) {
const message = `security referenced at path ${path}, but not defined in 'components.securitySchemes'`;
return next(validationError(500, path, message));
}
try {
const results = await new SecuritySchemes(
securitySchemes,
securityHandlers,
securities,
).executeHandlers(req);
// TODO handle AND'd and OR'd security
// This assumes OR only! i.e. at least one security passed authentication
let firstError: SecurityHandlerResult = null;
let success = false;
for (var r of results) {
if (r.success) {
success = true;
break;
} else if (!firstError) {
firstError = r;
}
}
if (success) next();
else throw firstError;
} catch (e) {
const message = e?.error?.message || 'unauthorized';
const err = validationError(e.status, path, message);
next(err);
}
};
}
class SecuritySchemes {
private securitySchemes: SecuritySchemesMap;
private securityHandlers: SecurityHandlers;
private securities: OpenAPIV3.SecurityRequirementObject[];
constructor(
securitySchemes: SecuritySchemesMap,
securityHandlers: SecurityHandlers,
securities: OpenAPIV3.SecurityRequirementObject[],
) {
this.securitySchemes = securitySchemes;
this.securityHandlers = securityHandlers;
this.securities = securities;
}
async executeHandlers(req: OpenApiRequest): Promise<SecurityHandlerResult[]> {
// use a fallback handler if security handlers is not specified
// This means if security handlers is specified, the user must define
// all security handlers
const fallbackHandler = !this.securityHandlers
? defaultSecurityHandler
: null;
const promises = this.securities.map(async s => {
try {
if (Util.isEmptyObject(s)) {
// anonumous security
return { success: true };
}
const securityKey = Object.keys(s)[0];
const scheme: any = this.securitySchemes[securityKey];
const handler = this.securityHandlers?.[securityKey] ?? fallbackHandler;
const scopesTmp = s[securityKey];
const scopes = Array.isArray(scopesTmp) ? scopesTmp : [];
if (!scheme) {
const message = `components.securitySchemes.${securityKey} does not exist`;
throw { status: 500, message };
}
if (!scheme.type) {
const message = `components.securitySchemes.${securityKey} must have property 'type'`;
throw { status: 500, message };
}
if (!handler) {
const message = `a security handler for '${securityKey}' does not exist`;
throw { status: 500, message };
}
new AuthValidator(req, scheme, scopes).validate();
// expected handler results are:
// - throw exception,
// - return true,
// - return Promise<true>,
// - return false,
// - return Promise<false>
// everything else should be treated as false
const success = await handler(req, scopes, scheme);
if (success === true) {
return { success };
} else {
throw Error();
}
} catch (e) {
return {
success: false,
status: e.status ?? 401,
error: e,
};
}
});
return Promise.all(promises);
}
}
class AuthValidator {
private req: OpenApiRequest;
private scheme;
private path: string;
private scopes: string[];
constructor(req: OpenApiRequest, scheme, scopes: string[] = []) {
const openapi = <OpenApiRequestMetadata>req.openapi;
this.req = req;
this.scheme = scheme;
this.path = openapi.openApiRoute;
this.scopes = scopes;
}
public validate(): void {
this.validateApiKey();
this.validateHttp();
this.validateOauth2();
this.validateOpenID();
}
private validateOauth2() {
const { req, scheme, path } = this;
if (['oauth2'].includes(scheme.type.toLowerCase())) {
// TODO oauth2 validation
}
}
private validateOpenID() {
const { req, scheme, path } = this;
if (['openIdConnect'].includes(scheme.type.toLowerCase())) {
// TODO openidconnect validation
}
}
private validateHttp() {
const { req, scheme, path } = this;
if (['http'].includes(scheme.type.toLowerCase())) {
const authHeader =
req.headers['authorization'] &&
req.headers['authorization'].toLowerCase();
if (!authHeader) {
throw Error(`Authorization header required`);
}
const type = scheme.scheme && scheme.scheme.toLowerCase();
if (type === 'bearer' && !authHeader.includes('bearer')) {
throw Error(`Authorization header with scheme 'Bearer' required`);
}
if (type === 'basic' && !authHeader.includes('basic')) {
throw Error(`Authorization header with scheme 'Basic' required`);
}
this.dissallowScopes();
}
}
private validateApiKey() {
const { req, scheme, path } = this;
if (scheme.type === 'apiKey') {
if (scheme.in === 'header') {
if (!req.headers[scheme.name.toLowerCase()]) {
throw Error(`'${scheme.name}' header required`);
}
} else if (scheme.in === 'query') {
if (!req.query[scheme.name]) {
throw Error(`query parameter '${scheme.name}' required`);
}
}
// TODO scheme in cookie
this.dissallowScopes();
}
}
private dissallowScopes() {
if (this.scopes.length > 0) {
// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#security-requirement-object
throw {
status: 500,
message: "scopes array must be empty for security type 'http'",
};
}
}
}
class Util {
static isEmptyObject(o: {}): boolean {
return (
typeof o === 'object' &&
Object.entries(o).length === 0 &&
o.constructor === Object
);
}
}