aboutsummaryrefslogtreecommitdiffstats
path: root/test/middleware-mockserver.cjs
blob: a7a7a47b93b964f3a3afa86bf763c47a94b188ed (plain)
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
"use strict";

const url = require( "url" );
const fs = require( "fs" );
const getRawBody = require( "raw-body" );
const multiparty = require( "multiparty" );

let cspLog = "";

/**
 * Keep in sync with /test/mock.php
 */
function cleanCallback( callback ) {
	return callback.replace( /[^a-z0-9_]/gi, "" );
}

const mocks = {
	contentType: function( req, resp ) {
		resp.writeHead( 200, {
			"content-type": req.query.contentType
		} );
		resp.end( req.query.response );
	},
	wait: function( req, resp ) {
		const wait = Number( req.query.wait ) * 1000;
		setTimeout( function() {
			if ( req.query.script ) {
				resp.writeHead( 200, { "content-type": "text/javascript" } );
			} else {
				resp.writeHead( 200, { "content-type": "text/html" } );
				resp.end( "ERROR <script>QUnit.assert.ok( true, \"mock executed\" );</script>" );
			}
		}, wait );
	},
	name: function( req, resp, next ) {
		resp.writeHead( 200 );
		if ( req.query.name === "foo" ) {
			resp.end( "bar" );
			return;
		}
		getBody( req ).then( function( body ) {
			if ( body === "name=peter" ) {
				resp.end( "pan" );
			} else {
				resp.end( "ERROR" );
			}
		}, next );
	},
	xml: function( req, resp, next ) {
		const content = "<math><calculation>5-2</calculation><result>3</result></math>";
		resp.writeHead( 200, { "content-type": "text/xml" } );

		if ( req.query.cal === "5-2" ) {
			resp.end( content );
			return;
		}
		getBody( req ).then( function( body ) {
			if ( body === "cal=5-2" ) {
				resp.end( content );
			} else {
				resp.end( "<error>ERROR</error>" );
			}
		}, next );
	},
	atom: function( _req, resp ) {
		resp.writeHead( 200, { "content-type": "atom+xml" } );
		resp.end( "<root><element /></root>" );
	},
	script: function( req, resp ) {
		const headers = {};
		if ( req.query.header === "ecma" ) {
			headers[ "content-type" ] = "application/ecmascript";
		} else if ( "header" in req.query ) {
			headers[ "content-type" ] = "text/javascript";
		} else {
			headers[ "content-type" ] = "text/html";
		}

		if ( req.query.cors ) {
			headers[ "access-control-allow-origin" ] = "*";
		}

		if ( resp.set ) {
			resp.set( headers );
		} else {
			for ( const key in headers ) {
				resp.writeHead( 200, { [ key ]: headers[ key ] } );
			}
		}

		if ( req.query.callback ) {
			resp.end( `${ cleanCallback( req.query.callback ) }(${ JSON.stringify( {
				headers: req.headers
			} ) })` );
		} else {
			resp.end( "QUnit.assert.ok( true, \"mock executed\" );" );
		}
	},
	testbar: function( _req, resp ) {
		resp.writeHead( 200 );
		resp.end(
			"this.testBar = 'bar'; " +
			"jQuery('#ap').html('bar'); " +
			"QUnit.assert.ok( true, 'mock executed');"
		);
	},
	json: function( req, resp ) {
		if ( req.query.header ) {
			resp.writeHead( 200, { "content-type": "application/json" } );
		}
		if ( req.query.cors ) {
			resp.writeHead( 200, { "access-control-allow-origin": "*" } );
		}
		if ( req.query.array ) {
			resp.end( JSON.stringify(
				[ { name: "John", age: 21 }, { name: "Peter", age: 25 } ]
			) );
		} else {
			resp.end( JSON.stringify(
				{ data: { lang: "en", length: 25 } }
			) );
		}
	},
	jsonp: function( req, resp, next ) {
		let callback;
		if ( Array.isArray( req.query.callback ) ) {
			callback = Promise.resolve( req.query.callback[ req.query.callback.length - 1 ] );
		} else if ( req.query.callback ) {
			callback = Promise.resolve( req.query.callback );
		} else if ( req.method === "GET" ) {
			callback = Promise.resolve( req.url.match( /^.+\/([^\/?]+)\?.+$/ )[ 1 ] );
		} else {
			callback = getBody( req ).then( function( body ) {
				return body.trim().replace( "callback=", "" );
			} );
		}
		const json = req.query.array ?
			JSON.stringify(
				[ { name: "John", age: 21 }, { name: "Peter", age: 25 } ]
			) :
			JSON.stringify(
				{ data: { lang: "en", length: 25 } }
			);
		callback.then( function( cb ) {
			resp.end( `${ cleanCallback( cb ) }(${ json })` );
		}, next );
	},
	xmlOverJsonp: function( req, resp ) {
		const callback = req.query.callback;
		const body = fs.readFileSync( `${ __dirname }/data/with_fries.xml` ).toString();
		resp.writeHead( 200 );
		resp.end( `${ cleanCallback( callback ) }(${ JSON.stringify( body ) })\n` );
	},
	formData: function( req, resp, next ) {
		const prefix = "multipart/form-data; boundary=--";
		const contentTypeValue = req.headers[ "content-type" ];
		resp.writeHead( 200 );
		if ( ( prefix || "" ).startsWith( prefix ) ) {
			getMultiPartContent( req ).then( function( { fields = {} } ) {
				resp.end( `key1 -> ${ fields.key1 }, key2 -> ${ fields.key2 }` );
			}, next );
		} else {
			resp.end( `Incorrect Content-Type: ${ contentTypeValue
				}\nExpected prefix: ${ prefix }` );
		}
	},
	error: function( req, resp ) {
		if ( req.query.json ) {
			resp.writeHead( 400, { "content-type": "application/json" } );
			resp.end( "{ \"code\": 40, \"message\": \"Bad Request\" }" );
		} else {
			resp.writeHead( 400 );
			resp.end( "plain text message" );
		}
	},
	headers: function( req, resp ) {
		const headers = {
			"Sample-Header": "Hello World",
			"Empty-Header": "",
			"Sample-Header2": "Hello World 2",
			"List-Header": "Item 1",
			"list-header": "Item 2",
			"constructor": "prototype collision (constructor)"
		};

		// Use resp.append in express to
		// avoid overwriting List-Header
		if ( resp.append ) {

			for ( const key in headers ) {
				resp.append( key, headers[ key ] );
			}
		} else {
			resp.writeHead( 200, headers );
		}
		req.query.keys.split( "|" ).forEach( function( key ) {
			if ( key.toLowerCase() in req.headers ) {
				resp.write( `${ key }: ${ req.headers[ key.toLowerCase() ] }\n` );
			}
		} );
		resp.end();
	},
	echoData: function( req, resp, next ) {
		getBody( req ).then( function( body ) {
			resp.end( body );
		}, next );
	},
	echoQuery: function( req, resp ) {
		resp.end( req.parsed.search.slice( 1 ) );
	},
	echoMethod: function( req, resp ) {
		resp.end( req.method );
	},
	echoHtml: function( req, resp, next ) {
		resp.writeHead( 200, { "Content-Type": "text/html" } );
		resp.write( `<div id='method'>${ req.method }</div>` );
		resp.write( `<div id='query'>${ req.parsed.search.slice( 1 ) }</div>` );
		getBody( req ).then( function( body ) {
			resp.write( `<div id='data'>${ body }</div>` );
			resp.end( body );
		}, next );
	},
	etag: function( req, resp ) {
		const hash = Number( req.query.ts ).toString( 36 );
		const etag = `W/"${ hash }"`;
		if ( req.headers[ "if-none-match" ] === etag ) {
			resp.writeHead( 304 );
			resp.end();
			return;
		}
		resp.writeHead( 200, {
			"Etag": etag
		} );
		resp.end();
	},
	ims: function( req, resp ) {
		const ts = req.query.ts;
		if ( req.headers[ "if-modified-since" ] === ts ) {
			resp.writeHead( 304 );
			resp.end();
			return;
		}
		resp.writeHead( 200, {
			"Last-Modified": ts
		} );
		resp.end();
	},
	status: function( req, resp ) {
		resp.writeHead( Number( req.query.code ) );
		resp.end();
	},
	testHTML: function( req, resp ) {
		resp.writeHead( 200, { "Content-Type": "text/html" } );
		const body = fs
			.readFileSync( `${ __dirname }/data/test.include.html` )
			.toString()
			.replace( /{{baseURL}}/g, req.query.baseURL );
		resp.end( body );
	},
	cspFrame: function( _req, resp ) {
		resp.writeHead( 200, {
			"Content-Type": "text/html",
			"Content-Security-Policy": "default-src 'self'; require-trusted-types-for 'script'; " +
				"report-uri /base/test/data/mock.php?action=cspLog"
		} );
		const body = fs.readFileSync( `${ __dirname }/data/csp.include.html` ).toString();
		resp.end( body );
	},
	cspNonce: function( req, resp ) {
		const testParam = req.query.test ? `-${ req.query.test }` : "";
		resp.writeHead( 200, {
			"Content-Type": "text/html",
			"Content-Security-Policy": "script-src 'nonce-jquery+hardcoded+nonce'; " +
				"report-uri /base/test/data/mock.php?action=cspLog"
		} );
		const body = fs.readFileSync(
			`${ __dirname }/data/csp-nonce${ testParam }.html` ).toString();
		resp.end( body );
	},
	cspAjaxScript: function( _req, resp ) {
		resp.writeHead( 200, {
			"Content-Type": "text/html",
			"Content-Security-Policy": "script-src 'self'; " +
				"report-uri /base/test/data/mock.php?action=cspLog"
		} );
		const body = fs.readFileSync(
			`${ __dirname }/data/csp-ajax-script.html` ).toString();
		resp.end( body );
	},
	cspLog: function( _req, resp ) {
		cspLog = "error";
		resp.writeHead( 200 );
		resp.end();
	},
	cspClean: function( _req, resp ) {
		cspLog = "";
		resp.writeHead( 200 );
		resp.end();
	},
	trustedHtml: function( _req, resp ) {
		resp.writeHead( 200, {
			"Content-Type": "text/html",
			"Content-Security-Policy": "require-trusted-types-for 'script'; " +
				"report-uri /base/test/data/mock.php?action=cspLog"
		} );
		const body = fs.readFileSync( `${ __dirname }/data/trusted-html.html` ).toString();
		resp.end( body );
	},
	trustedTypesAttributes: function( _req, resp ) {
		resp.writeHead( 200, {
			"Content-Type": "text/html",
			"Content-Security-Policy": "require-trusted-types-for 'script'; " +
				"report-uri /base/test/data/mock.php?action=cspLog"
		} );
		const body = fs.readFileSync(
			`${ __dirname }/data/trusted-types-attributes.html` ).toString();
		resp.end( body );
	},
	errorWithScript: function( req, resp ) {
		if ( req.query.withScriptContentType ) {
			resp.writeHead( 404, { "Content-Type": "application/javascript" } );
		} else {
			resp.writeHead( 404, { "Content-Type": "text/html; charset=UTF-8" } );
		}
		if ( req.query.callback ) {
			resp.end( `${ cleanCallback( req.query.callback )
				}( {"status": 404, "msg": "Not Found"} )` );
		} else {
			resp.end( "QUnit.assert.ok( false, \"Mock return erroneously executed\" );" );
		}
	}
};
const handlers = {
	"test/data/mock.php": function( req, resp, next ) {
		if ( !mocks[ req.query.action ] ) {
			resp.writeHead( 400 );
			resp.end( "Invalid action query.\n" );
			console.log( "Invalid action query:", req.method, req.url );
			return;
		}
		mocks[ req.query.action ]( req, resp, next );
	},
	"test/data/support/csp.log": function( _req, resp ) {
		resp.writeHead( 200 );
		resp.end( cspLog );
	},
	"test/data/404.txt": function( _req, resp ) {
		resp.writeHead( 404 );
		resp.end( "" );
	}
};

/**
 * Connect-compatible middleware factory for mocking server responses.
 * Used by Ajax unit tests when run via Karma.
 *
 * Despite Karma using Express, it uses Connect to deal with custom middleware,
 * which passes the raw Node Request and Response objects instead of the
 * Express versions of these (e.g. no req.path, req.query, resp.set).
 */
function MockserverMiddlewareFactory() {

	/**
	 * @param {http.IncomingMessage} req
	 * @param {http.ServerResponse} resp
	 * @param {Function} next Continue request handling
	 */
	return function( req, resp, next ) {
		const parsed = url.parse( req.url, /* parseQuery */ true );
		let path = parsed.pathname.replace( /^\/base\//, "" );
		const query = parsed.query;
		const subReq = Object.assign( Object.create( req ), {
			query: query,
			parsed: parsed
		} );

		if ( /^\/?test\/data\/mock.php\/?/.test( path ) ) {

			// Support REST-like Apache PathInfo
			path = "test\/data\/mock.php";
		}

		if ( !handlers[ path ] ) {
			next();
			return;
		}

		// console.log( "Mock handling", req.method, parsed.href );
		handlers[ path ]( subReq, resp, next );
	};
}

function getBody( req ) {
	return req.method !== "POST" ?
		Promise.resolve( "" ) :
		getRawBody( req, {
			encoding: true
		} );
}

function getMultiPartContent( req ) {
	return new Promise( function( resolve ) {
		if ( req.method !== "POST" ) {
			resolve( "" );
			return;
		}

		const form = new multiparty.Form();
		form.parse( req, function( _err, fields, files ) {
			resolve( { fields, files } );
		} );
	} );
}

module.exports = MockserverMiddlewareFactory;