-
Notifications
You must be signed in to change notification settings - Fork 0
/
ResponseHandlerTest.php
543 lines (497 loc) · 19.5 KB
/
ResponseHandlerTest.php
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
<?php
namespace CashID\Tests\CashID;
use CashID\Cache\RequestCacheInterface;
use CashID\RequestGenerator;
use CashID\ResponseHandler;
use CashID\Tests\ResponseGenerator;
/**
* Test the ResponseHandler class
*
* Unit tests for each function
*/
class ResponseHandlerTest extends \PHPUnit\Framework\TestCase
{
use \phpmock\phpunit\PHPMock;
private $generator;
private $responder;
private $handler;
private $cashaddr = 'qpjvm3u8cvjddupctguwatrlaxtutprg8s04ekldyr';
private $metadata = [
'name' => 'Alice',
'family' => 'Smith',
'nickname' => 'ajsmith',
'age' => 20,
'gender' => 'female',
'birthdate' => '1999-01-01',
'national' => 'USA',
'country' => 'USA',
'state' => 'CA',
'city' => 'Los Angeles',
'streetname' => 'Main',
'streetnumber' => '123',
'email' => 'ajsmith@example.com',
'social' => '123-45-6789',
'phone' => '123-123-1234',
'postal' => '12345',
];
/**
* Set up the default objects for the test
*/
public function setUp()
{
$this->generator = new RequestGenerator("demo.cashid.info", "/api/parse.php");
$this->responder = new ResponseGenerator($this->metadata);
$this->handler = new ResponseHandler("demo.cashid.info", "/api/parse.php");
}
/**
* Test the parseRequest() function
*
* Ensure the function produces the correct array from the given JSON string.
*
* @dataProvider dataProviderForTestParseRequest
*/
public function testParseRequest(string $request, array $expected_array)
{
$result = $this->handler->parseRequest($request);
$this->assertEquals($expected_array, $result);
}
/**
* Data for the testParseRequest test case
*/
public function dataProviderForTestParseRequest()
{
return [
// Test 1
[
'cashid:demo.cashid.info/api/parse.php?a=login&d=15366-4133-6141-9638&r=c3&o=p4&x=95261230581',
[
"parameters" => [
"action" => "login",
"data" => "15366-4133-6141-9638",
"optional" => [
'streetname' => '4',
],
"required" => [
'social' => '3'
],
'nonce' => '95261230581',
],
'scheme' => 'cashid:',
'domain' => 'demo.cashid.info',
'path' => '/api/parse.php',
],
],
];
}
/**
* Test failures in the validateRequest() function
*
* Ensure the function throws the correct exception for malformed requests.
* All of these failures occur before the function checks if the nonce was
* actually created by the requestGenerator, so we can pass them to
* validateRequest() in isolation. This should probably be changed in case
* the function is refactored.
*
* @runInSeparateProcess
* @dataProvider dataProviderForInvalidResponse
* @dataProvider dataProviderForUserInitiatedResponse
*/
public function testInvalidResponse(string $JSON_string, array $response_array)
{
// Verify that the function return false
$this->assertFalse($this->handler->validateRequest($JSON_string));
// Verify the correct status code is produce
$this->expectOutputString(json_encode($response_array));
$this->handler->confirmRequest();
}
/**
* Provide an assortment of malformed response strings
*/
public function dataProviderForInvalidResponse()
{
return [
[ // Not a JSON String
'Not JSON',
[
"status" => 200,
"message" => "Response data is not a valid JSON object.",
],
],
[ // Missing request
'{"address": "qqagsast3fq0g43wnrnweefjsk28pmyvwg7t0jqgg4"}',
[
"status" => 211,
"message" => "Response data is missing required 'request' property.",
],
],
[ // Missing address
'{
"request": "cashid:bitcoin.com/api/cashid?a=register&d=newsletter&r=i12l1c1&o=i458l3&x=95261230581"
}',
[
"status" => 212,
"message" => "Response data is missing required 'address' property.",
],
],
[ // Missing Signature
'{
"request": "cashid:bitcoin.com/api/cashid?a=register&d=newsletter&r=i12l1c1&o=i458l3&x=95261230581",
"address": "qqagsast3fq0g43wnrnweefjsk28pmyvwg7t0jqgg4"
}',
[
"status" => 213,
"message" => "Response data is missing required 'signature' property.",
],
],
[ // Mismatched domain
'{
"request": "cashid:bitcoin.com/api/cashid?a=register&d=newsletter&r=i12l1c1&o=i458l3&x=95261230581",
"address": "qqagsast3fq0g43wnrnweefjsk28pmyvwg7t0jqgg4",
"signature": "IKjtNWdIp+tofJQrhxBrq91jLwdmOVNlMhfnKRiaC2t2C7vqsHRoUA+BkdgjnOqX6hv4ZdeG9ZpB6dMh/sXJg/0="
}',
[
"status" => 131,
"message" => "Request domain 'bitcoin.com' is invalid, this service uses 'demo.cashid.info'.",
],
],
[ // Incorrect scheme
'{
"request": "cashid1:bitcoin.com/api/cashid?a=register&d=newsletter&r=i12l1c1&o=i458l3&x=95261230581",
"address": "qqagsast3fq0g43wnrnweefjsk28pmyvwg7t0jqgg4",
"signature": "IKjtNWdIp+tofJQrhxBrq91jLwdmOVNlMhfnKRiaC2t2C7vqsHRoUA+BkdgjnOqX6hv4ZdeG9ZpB6dMh/sXJg/0="
}',
[
"status" => 121,
"message" => "Request scheme 'cashid1:' is invalid, should be 'cashid:'.",
],
],
[ // Missing nonce
'{
"request": "cashid:demo.cashid.info/api/cashid?a=register&d=newsletter&r=i12l1c1&o=i458l3",
"address": "qqagsast3fq0g43wnrnweefjsk28pmyvwg7t0jqgg4",
"signature": "IKjtNWdIp+tofJQrhxBrq91jLwdmOVNlMhfnKRiaC2t2C7vqsHRoUA+BkdgjnOqX6hv4ZdeG9ZpB6dMh/sXJg/0="
}',
[
"status" => 113,
"message" => "Request parameter 'nonce' is missing.",
],
],
[ // Request was not issued.
'{
"request": "cashid:demo.cashid.info/api/cashid?a=register&d=newsletter&r=i12l1c1&o=i458l3&x=95261230581",
"address": "qqagsast3fq0g43wnrnweefjsk28pmyvwg7t0jqgg4",
"signature": "IKjtNWdIp+tofJQrhxBrq91jLwdmOVNlMhfnKRiaC2t2C7vqsHRoUA+BkdgjnOqX6hv4ZdeG9ZpB6dMh/sXJg/0="
}',
[
"status" => 132,
"message" => "The request nonce was not issued by this service.",
],
],
];
}
/**
* Provide an assortment of malformed user-initiated response strings
*/
public function dataProviderForUserInitiatedResponse()
{
return [
[ // Old request
'{
"request": "cashid:demo.cashid.info/api/parse.php?a=delete&x=20180929T063418Z",
"address": "qzvelmkfzvq8gw0d4fvmf904ghefq66keq68qwupsv",
"signature": "IDwIyQCsmFKwWWibwtxVqppt+KCDBgTKy4IN8+rL+8a9XtGN/AAl/koKPKnIQOr2/nlzOW9XaxtWP96298XkiJE="
}',
[
'status' => 132,
'message' => 'Request nonce for user initated action is not a valid and recent timestamp.',
],
],
];
}
/**
* Test failures in the validateRequest() function.
*
* Ensure the function throws the correct exception for malformed requests.
* All these failures are checked after the signature is checked.
*
* @runInSeparateProcess
* @dataProvider dataProviderForInvalidSignedResponse
*/
public function testInvalidSignedResponse(array $request, array $response, array $confirmation)
{
// Create the request from the provided $request array
$json_request = $this->generator->createRequest($request['action'], $request['data'], $request['metadata']);
// Create a valid response given the request and the default metadata
$response_array = $this->responder->createResponse($json_request);
// Replace the correct values with values from the dataProvider
foreach ($response as $key => $value) {
$response_array[$key] = $value;
}
// Verify that the validation fails
$this->assertFalse($this->handler->validateRequest(json_encode($response_array)));
// Verify that the correct exception and message is produced
$this->expectOutputString(json_encode($confirmation));
$this->handler->confirmRequest();
}
public function dataProviderForInvalidSignedResponse()
{
return [
[ // Missing required field
[
'action' => 'login',
'data' => '987',
'metadata' => [
'optional' => [
'position' => ['streetname'],
],
'required' => [
'identification' => ['nickname'],
],
],
],
[
'metadata' => [
'streetname' => 'Main',
],
],
[
'status' => 214,
'message' => "The required metadata field(s) 'nickname' was not provided.",
],
],
[ // Extra optional field
[
'action' => 'login',
'data' => '987',
'metadata' => [
'optional' => [
'position' => ['streetnumber'],
],
'required' => [
'identification' => ['nickname'],
],
],
],
[
'metadata' => [
'streetname' => 'Main',
'nickname' => 'ajsmith',
],
],
[
'status' => 234,
'message' => "The metadata field 'streetname' was not part of the request.",
],
],
[ // Empty metadata field
[
'action' => 'login',
'data' => '987',
'metadata' => [
'optional' => [
'position' => ['streetnumber'],
],
'required' => [
'identification' => ['nickname'],
],
],
],
[
'metadata' => [
'streetnumber' => '',
'nickname' => 'ajsmith',
],
],
[
'status' => 223,
'message' => "The metadata field 'streetnumber' did not contain any value.",
],
],
[ // Incorrect Signature
[
'action' => 'login',
'data' => '987',
'metadata' => [
'optional' => [
'position' => ['streetnumber'],
],
'required' => [
'identification' => ['nickname'],
],
],
],
[
'signature' => 'IKjtNWdIp+tofJQrhxBrq91jLwdmOVNlMhfnKRiaC2t2C7vqsHRoUA+BkdgjnOqX6hv4ZdeG9ZpB6dMh/sXJg/0=',
],
[
'status' => 233,
'message' => "Signature verification failed.",
],
],
];
}
/**
* Test failures in the validateRequest() function.
*
* Ensure that the function correctly identifies tampered requests
*
* @runInSeparateProcess
* @dataProvider dataProviderForTamperedRequest
*/
public function testTamperedRequest(array $original_request, string $new_request, array $confirmation)
{
// Create the request from the provided $request array
$json_request = $this->generator->createRequest($original_request['action'], $original_request['data'], $original_request['metadata']);
// Alter the request
// Append the nonce from the original request to the new request
$new_json_request = $new_request . substr($json_request, -9);
// Create a valid response given the altered request and the default metadata
$response_array = $this->responder->createResponse($new_json_request);
// Verify that the validation fails
$this->assertFalse($this->handler->validateRequest(json_encode($response_array)));
// Verify that the correct exception and message is produced
$this->expectOutputString(json_encode($confirmation));
$this->handler->confirmRequest();
}
public function dataProviderForTamperedRequest()
{
return [
[
[
'action' => 'login',
'data' => '987',
'metadata' => [
'optional' => [
'position' => ['streetnumber'],
],
'required' => [
'identification' => ['nickname'],
],
],
],
"cashid:demo.cashid.info/api/parse.php?a=login&d=986&r=c3&o=p4&x=",
[
'status' => 141,
'message' => "The response does not match the request parameters.",
],
],
];
}
/**
* Test APCu response storage failure
*
* @runInSeparateProcess
*/
public function testAPCuResponseFailure()
{
// Create a mock request cache whos storage fails, but successfully fetches
$cache = $this->createMock(RequestCacheInterface::class);
$cache->method('store')->willReturn(false);
$cache->method('fetch')->will($this->returnCallback(
function ($key) {
return apcu_fetch($key);
}
));
// Use the default notary
$notary = new \CashID\Notary\DefaultNotary();
// Create or hobbled response handler
$handler = new ResponseHandler("demo.cashid.info", "/api/parse.php", $notary, $cache);
// Generate a request using the fully functional generator
$json_request = $this->generator->createRequest();
// Create the response
$response_array = $this->responder->createResponse($json_request);
// Validate storage failure
$this->assertFalse($handler->validateRequest(json_encode($response_array)));
// Verify that the correct exception and message is produced
$this->expectOutputString('{"status":331,"message":"Internal server error, could not store response object."}');
$this->handler->confirmRequest();
}
/**
* Test APCu response storage failure
*
* @runInSeparateProcess
*/
public function testAPCuConfirmationFailure()
{
// Create a mock request cache whos storage fails the second time,
// but successfully fetches
$cache = $this->createMock(RequestCacheInterface::class);
$cache->method('store')->will($this->onConsecutiveCalls(true, false));
$cache->method('fetch')->will($this->returnCallback(
function ($key) {
return apcu_fetch($key);
}
));
// Use the default notary
$notary = new \CashID\Notary\DefaultNotary();
// Create a hobbled handler
$handler = new ResponseHandler("demo.cashid.info", "/api/parse.php", $notary, $cache);
// Generate a request using the fully functional generator
$json_request = $this->generator->createRequest();
// Create the response
$response_array = $this->responder->createResponse($json_request);
// Validate storage failure
$this->assertFalse($handler->validateRequest(json_encode($response_array)));
// Verify that the correct exception and message is produced
$this->expectOutputString('{"status":331,"message":"Internal server error, could not store confirmation object."}');
$this->handler->confirmRequest();
}
/**
* Expect an exception if headers have been sent prior to confirmation
*
* @testCase ConfirmRequestHeadersSentException
*/
public function testConfirmRequestHeadersSentException()
{
// PHPUnit has already sent headers at this point
$this->expectException(\Exception::class);
$this->handler->confirmRequest();
}
/**
* Expect an exception if no request was every sent
*
* This runs in a separate process to ensure the exception is independant
* from the exception thrown in ConfirmRequestHeadersSentException
*
* @runInSeparateProcess
*/
public function testConfirmRequestNotVerifiedException()
{
$this->expectException(\Exception::class);
$this->handler->confirmRequest();
}
/**
* Test that the invalidateRequest function returns the expected output
*
* @testCase ConfirmRequestNotVerifiedException
* @runInSeparateProcess
*/
public function testInvalidateRequest()
{
$this->handler->invalidateRequest(142, 'test');
$this->expectOutputString(json_encode(["status" => "142", "message" => "test"]));
$this->handler->confirmRequest();
}
/**
* Test that a response to an old request causes a failure
*
* This test runs in a seperate process because earlier calls to time()
* will prevent it from being overridden
*
* @runInSeparateProcess
*/
public function testOldRequest()
{
$time = $this->getFunctionMock('CashID', "time");
$time->expects($this->exactly(4))->willReturn(strtotime('-1 month'), strtotime('now'), strtotime('now'), strtotime('now'));
// Create a request
$json_request = $this->generator->createRequest();
// Create the response
$response_array = $this->responder->createResponse($json_request);
// Validate against today's date and verify failure
$this->assertFalse($this->handler->validateRequest(json_encode($response_array)));
// Verify that the correct exception and message is produced
$this->expectOutputString('{"status":142,"message":"The request has expired and is no longer available."}');
$this->handler->confirmRequest();
}
}