/
openapi_app.js
323 lines (298 loc) · 10.9 KB
/
openapi_app.js
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
const _ = require( "lodash" );
const { initialize } = require( "express-openapi" );
const swaggerUi = require( "swagger-ui-express" );
const bodyParser = require( "body-parser" );
const fs = require( "fs" );
const path = require( "path" );
const multer = require( "multer" );
const crypto = require( "crypto" );
const jwt = require( "jsonwebtoken" );
const openapiCoercer = require( "openapi-request-coercer" );
const config = require( "./config" );
const v1ApiDoc = require( "./openapi/doc" );
const util = require( "./lib/util" );
const Logstasher = require( "./lib/logstasher" );
const logstashPath = path.join(
path.dirname( fs.realpathSync( __filename ) ), "./log", "inaturalist_api.4000.log"
);
Logstasher.setLogStreamFilePath( logstashPath );
const InaturalistAPI = require( "./lib/inaturalist_api" ); // eslint-disable-line global-require
const app = InaturalistAPI.server( );
let initializedApi = null;
const sendWrapper = ( req, res, err, results ) => {
if ( err ) { return void initializedApi.args.errorMiddleware( err, null, res, null ); }
res.status( 200 ).header( "Content-Type", "application/json" ).send( results );
};
app.use( bodyParser.json( {
type: req => {
// Parser the request body for everything other than multipart requests,
// which should specify body data as plain old form data which express can
// parse on its own.
if ( !req.headers["content-type"] ) {
return true;
}
return req.headers["content-type"].match( /multipart/ ) === null;
}
} ) );
app.use( ( req, res, next ) => {
util.timingMiddleware( req, res, next );
} );
app.use( ( req, res, next ) => {
const methodOverride = req.header( "X-HTTP-Method-Override" );
if ( req.method === "POST" && methodOverride === "GET" && initializedApi ) {
const basePath = initializedApi.basePaths[0].path;
const basePathRegex = new RegExp( `^${_.escapeRegExp( basePath )}` );
const apiPath = req.path.replace( basePathRegex, "" );
const apiMethod = initializedApi.apiDoc.paths[apiPath];
if ( apiMethod && apiMethod.post ) {
const allowsOverride = _.find( apiMethod.post.parameters, p => (
p.name === "X-HTTP-Method-Override" && p.in === "header"
) );
if ( allowsOverride ) {
req.originalMethod = req.originalMethod || req.method;
req.method = "GET";
}
}
}
next( );
} );
const storage = multer.diskStorage( {
destination: ( req, file, callback ) => {
crypto.pseudoRandomBytes( 16, ( err, raw ) => {
const time = Date.now( );
const hash = raw.toString( "hex" );
// create a directory in which to store the upload
const uploadDir = `openapi/uploads/tmp_${time}_${hash}`;
if ( !fs.existsSync( uploadDir ) ) {
fs.mkdirSync( uploadDir );
}
callback( null, uploadDir );
} );
},
filename: ( req, file, callback ) => callback( null, file.originalname )
} );
const upload = multer( { storage } );
const resolveSchema = ( req, schema ) => {
const schemaRef = schema.$ref;
if ( schemaRef && schemaRef.match( /#\/components\/schemas\// ) ) {
const schemaName = schemaRef.replace( "#/components/schemas/", "" );
return req.apiDoc.components.schemas[schemaName];
}
return schema;
};
const requestFields = req => {
const fields = req.body.fields || req.query.fields;
if ( _.isObject( fields ) ) {
return fields;
}
if ( !_.isEmpty( fields ) ) {
try {
const fieldsJson = JSON.parse( fields );
return fieldsJson;
} catch {
// ignore parse failures
}
const fieldsStringMatch = fields.match( /^[a-z_]+(,[a-z_]+)?$/ );
if ( fieldsStringMatch ) {
return fields.split( "," );
}
return false;
}
return null;
};
const responseItemSchema = req => {
if ( req.operationDoc
&& req.operationDoc.responses["200"]
&& req.operationDoc.responses["200"].content["application/json"]
&& req.operationDoc.responses["200"].content["application/json"].schema ) {
const responseSchema = resolveSchema( req,
req.operationDoc.responses["200"].content["application/json"].schema );
if ( responseSchema.properties
&& responseSchema.properties.results
&& responseSchema.properties.results.items ) {
return resolveSchema( req, responseSchema.properties.results );
}
}
return null;
};
let applyFieldSelectionToItem = ( ) => { };
const applyFieldSelectionToObject = ( req, item, fieldsRequested, itemSchema ) => {
let fieldsToReturn = { };
_.each( itemSchema.required, k => {
fieldsToReturn[k] = true;
} );
if ( _.isArray( fieldsRequested ) ) {
fieldsToReturn = Object.assign( fieldsToReturn, _.keyBy( fieldsRequested, r => r ) );
} else {
fieldsToReturn = Object.assign( fieldsToReturn, fieldsRequested );
}
const prunedItem = { };
// loop through the requested fields
_.each( fieldsToReturn, ( v, k ) => {
// the root item has the field, and is in the root item definition
const fieldSchema = itemSchema.properties[k];
if ( item[k] && fieldSchema ) {
const propertySchema = resolveSchema( req, fieldSchema );
prunedItem[k] = applyFieldSelectionToItem( req, item[k], v, propertySchema );
}
} );
return prunedItem;
};
applyFieldSelectionToItem = ( req, item, fields, itemSchema ) => {
if ( itemSchema.type === "array" && _.isArray( item ) ) {
item = _.map( item, i => applyFieldSelectionToItem(
req, i, fields, resolveSchema( req, itemSchema.items )
) );
} else if ( itemSchema.type === "object" && _.isObject( item ) ) {
item = applyFieldSelectionToObject( req, item, fields, itemSchema );
}
return item;
};
const validateAllResponses = ( req, res, next ) => {
const strictValidation = !!req.apiDoc["x-express-openapi-validation-strict"];
if ( typeof res.validateResponse === "function" ) {
const { send } = res;
res.send = ( ...args ) => {
const onlyWarn = !strictValidation;
if ( res.get( "x-express-openapi-validated" ) !== undefined ) {
return send.apply( res, args );
}
const body = args[0];
const itemSchema = responseItemSchema( req );
if ( body && !_.isEmpty( body.results ) && itemSchema ) {
const fields = requestFields( req );
if ( fields === false ) {
res.set( "x-express-openapi-validated", true );
return sendWrapper( req, res, new Error( "invalid fields parameter" ) );
}
if ( fields !== "all" ) {
body.results = applyFieldSelectionToItem( req, body.results, fields, itemSchema );
}
}
let validation = res.validateResponse( res.statusCode, body );
let validationMessage;
if ( validation === undefined ) {
validation = { message: undefined, errors: undefined };
}
if ( validation.errors ) {
const errorList = Array.from( validation.errors ).map( e => e.message ).join( "," );
validationMessage = `Invalid response for status code ${res.statusCode}: ${errorList}`;
console.warn( ["validationMessage", validationMessage] );
// Set to avoid a loop, and to provide the original status code
res.set( "x-express-openapi-validation-error-for", res.statusCode.toString( ) );
}
res.set( "x-express-openapi-validated", true );
if ( onlyWarn || !validation.errors ) {
if ( _.has( req.originalQuery || req.query, "pretty" ) ) {
args[0] = JSON.stringify( body, null, 2 );
}
return send.apply( res, args );
}
return sendWrapper( req, res, new Error( validationMessage ) );
};
}
next( );
};
const jwtValidate = req => new Promise( resolve => {
if ( !req.headers.authorization ) {
return void resolve( );
}
const token = _.last( req.headers.authorization.split( /\s+/ ) );
jwt.verify( token, config.jwtSecret || "secret", { algorithms: ["HS512"] }, ( err, payload ) => {
if ( err ) {
return void resolve( );
}
req.userSession = payload;
resolve( true );
} );
} );
initializedApi = initialize( {
app,
docPath: "api-docs",
apiDoc: {
...v1ApiDoc,
"x-express-openapi-additional-middleware": [validateAllResponses],
"x-express-openapi-validation-strict": true
},
enableObjectCoercion: true,
dependencies: {
sendWrapper
},
securityFilter: ( req, res ) => {
// remove x-express-* attributes which don't need to be in the official documentation
res.status( 200 ).json( _.pickBy( req.apiDoc, ( value, key ) => !key.match( /^x-/ ) ) );
},
paths: "./openapi/paths/v2",
promiseMode: true,
securityHandlers: {
jwtOptional: req => jwtValidate( req ).then( ( ) => true ),
jwtRequired: req => jwtValidate( req )
},
consumesMiddleware: {
// TODO: custom coercion for JSON bodies?
"multipart/form-data": ( req, res, next ) => {
const knownUploadFields = [];
const { properties } = req.operationDoc.requestBody.content["multipart/form-data"].schema;
_.each( properties, ( schema, name ) => {
if ( schema.type === "string" && schema.format === "binary" ) {
knownUploadFields.push( name );
}
} );
const props = req.operationDoc.requestBody.content["multipart/form-data"].schema.properties;
const parameters = _.map( _.keys( props ), k => ( {
in: "formData",
name: k,
schema: req.operationDoc.requestBody.content["multipart/form-data"].schema.properties[k]
} ) );
const coercer = new openapiCoercer.default( {
extensionBase: "x-express-openapi-coercion",
loggingKey: "express-openapi-coercion",
parameters,
enableObjectCoercion: true
} );
coercer.coerce( req );
upload.fields( _.map( knownUploadFields, f => ( { name: f } ) ) )( req, res, err => {
const originalBody = _.cloneDeep( req.body );
const newBody = { };
_.each( originalBody, ( v, k ) => {
if ( _.isObject( v ) ) {
newBody[k] = { };
_.each( v, ( vv, kk ) => {
if ( vv !== "" ) {
newBody[k][kk] = vv;
}
} );
} else {
newBody[k] = v;
}
} );
req.body = newBody;
coercer.coerce( req );
next( );
} );
}
},
// this needs all 4 parameters even if next is not used
/* eslint-disable-next-line no-unused-vars */
errorMiddleware: ( err, req, res, next ) => {
if ( err.errorCode === "authentication.openapi.security" ) {
res.status( err.status || 401 ).json( {
status: err.status || 401,
message: "Unauthorized"
} );
return;
}
console.log( "Error trace from errorMiddleware ------->" );
console.trace( err );
res.status( err.status || 500 ).json( err instanceof Error
? {
status: 500,
message: err.message,
stack: err.stack.split( "\n" ),
from: "errorMiddleware"
} : err );
}
} );
app.get( "/v2/", ( req, res ) => res.redirect( "/v2/docs" ) );
app.use( "/v2/docs", swaggerUi.serve, swaggerUi.setup( initializedApi.apiDoc ) );
app.listen( 4000 );