-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathLoginIntegrationTest.php
More file actions
580 lines (505 loc) · 17.9 KB
/
LoginIntegrationTest.php
File metadata and controls
580 lines (505 loc) · 17.9 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
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
<?php
declare(strict_types=1);
namespace Simplesamlphp\Casserver;
use DOMDocument;
use PHPUnit\Framework\TestCase;
use SAML2\DOMDocumentFactory;
use SimpleSAML\Logger;
use SimpleSAML\TestUtils\BuiltInServer;
/**
*
* These integration tests use an embedded php server to avoid issues that unit tests encounter with SSP use of `exit`.
*
* The embedded server is authenticating users user exampleauth::static to automatically log users in.
*
* @package Simplesamlphp\Casserver
*/
class LoginIntegrationTest extends TestCase
{
/** @var string $LINK_URL */
private static string $LINK_URL = '/module.php/casserver/login.php';
/** @var string $VALIDATE_URL */
private static string $VALIDATE_URL = '/module.php/casserver/serviceValidate.php';
/**
* @var string $SAMLVALIDATE_URL
*/
private static string $SAMLVALIDATE_URL = '/module.php/casserver/samlValidate.php';
/**
* @var \SimpleSAML\TestUtils\BuiltInServer
*/
protected BuiltInServer $server;
/**
* @var string
*/
protected string $server_addr;
/**
* @var int
*/
protected int $server_pid;
/**
* @var string
*/
protected string $shared_file;
/**
* @var string
*/
protected string $cookies_file;
/**
* The setup method that is run before any tests in this class.
*/
protected function setup(): void
{
$this->server = new BuiltInServer('configLoader', dirname(dirname(dirname(__FILE__))) . '/vendor/simplesamlphp/simplesamlphp/www');
$this->server_addr = $this->server->start();
$this->server_pid = $this->server->getPid();
$this->shared_file = sys_get_temp_dir() . '/' . $this->server_pid . '.lock';
$this->cookies_file = sys_get_temp_dir() . '/' . $this->server_pid . '.cookies';
$this->updateConfig([
'baseurlpath' => '/',
'secretsalt' => 'abc123',
'tempdir' => sys_get_temp_dir(),
'loggingdir' => sys_get_temp_dir(),
'module.enable' => [
'casserver' => true,
]
]);
}
/**
* The tear down method that is executed after all tests in this class.
* Removes the lock file and cookies file
*/
protected function tearDown(): void
{
@unlink($this->shared_file);
@unlink($this->cookies_file); // remove it if it exists
$this->server->stop();
}
/**
* @param array $config
*/
protected function updateConfig(array $config): void
{
@unlink($this->shared_file);
$config = "<?php\n\$config = " . var_export($config, true) . ";\n";
file_put_contents($this->shared_file, $config);
}
/**
* Test authenticating to the login endpoint with no parameters.'
*/
public function testNoQueryParameters()
{
/** @var array $resp */
$resp = $this->server->get(
self::$LINK_URL,
[],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file,
CURLOPT_FOLLOWLOCATION => true
]
);
$this->assertEquals(200, $resp['code']);
$this->assertStringContainsString(
'You are logged in.',
$resp['body'],
'Login with no query parameters should make you authenticate and then take you to the login page.'
);
}
/**
* Test incorrect service url
*/
public function testWrongServiceUrl()
{
/** @var array $resp */
$resp = $this->server->get(
self::$LINK_URL,
['service' => 'http://not-legal'],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file,
CURLOPT_FOLLOWLOCATION => true
]
);
$this->assertEquals(500, $resp['code']);
$this->assertStringContainsString(
'CAS server is not listed as a legal service',
$resp['body'],
'Illegal cas service urls should be rejected'
);
}
/**
* Test a valid service URL
* @dataProvider validServiceUrlProvider
* @param string $serviceParam The name of the query parameter to use for the service url
* @param string $ticketParam The name of the query parameter that will contain the ticket
*/
public function testValidServiceUrl(string $serviceParam, string $ticketParam)
{
$service_url = 'http://host1.domain:1234/path1';
$this->authenticate();
/** @var array $resp */
$resp = $this->server->get(
self::$LINK_URL,
[$serviceParam => $service_url],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file
]
);
$this->assertEquals(302, $resp['code']);
$this->assertStringStartsWith(
$service_url . '?' . $ticketParam . '=ST-',
$resp['headers']['Location'],
'Ticket should be part of the redirect.'
);
// Config ticket can be validated
$matches = [];
$this->assertEquals(1, preg_match("@$ticketParam=(.*)@", $resp['headers']['Location'], $matches));
$ticket = $matches[1];
$resp = $this->server->get(
self::$VALIDATE_URL,
[
$serviceParam => $service_url,
'ticket' => $ticket,
],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file
]
);
$expectedResponse = DOMDocumentFactory::fromFile(
dirname(dirname(__FILE__)) . '/resources/xml/testValidServiceUrl.xml'
)->saveXML();
$this->assertEquals(200, $resp['code']);
$this->assertEquals($expectedResponse, $resp['body']);
}
public function validServiceUrlProvider(): array
{
return [
['service', 'ticket'],
['TARGET', 'SAMLart']
];
}
/**
* Test changing the ticket name
*/
public function testValidTicketNameOverride()
{
$service_url = 'http://changeTicketParam/abc';
$this->authenticate();
/** @var array $resp */
$resp = $this->server->get(
self::$LINK_URL,
['TARGET' => $service_url],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file
]
);
$this->assertEquals(302, $resp['code'], $resp['body']);
$this->assertStringStartsWith(
$service_url . '?myTicket=ST-',
$resp['headers']['Location'],
'Ticket should be part of the redirect.'
);
}
/**
* Some clients urls:
* 1. Incorrectly encode query parameters or fragments
* 2. Encode spaces as %20 which php rencodes to +
* 3. Special characters url encoded to lower case hexadecimal (some .net versions) are changed to upper case.
*
* Test to confirm these type of urls work
* @dataProvider encodingIssueProvider
* @param string $service_url The service url submitted by the client
* @param string $expectedStartsWith The redirect location is expected to start with this.
* @param string $expectedEndsWith The redirect location is expected to end with this. Used for testing #fragments.
* @return void
*/
public function testEncodingIssued($service_url, $expectedStartsWith, $expectedEndsWith)
{
$this->authenticate();
/** @var array $resp */
$resp = $this->server->get(
self::$LINK_URL,
['service' => $service_url],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file
]
);
$this->assertEquals(302, $resp['code'], $resp['body']);
$this->assertStringStartsWith(
$expectedStartsWith,
$resp['headers']['Location'],
'Ticket should be part of the redirect.'
);
if (!empty($expectedEndsWith)) {
$this->assertStringEndsWith(
$expectedEndsWith,
$resp['headers']['Location'],
'url fragments happen after the query params'
);
}
}
public function encodingIssueProvider(): array
{
$urlWithQuery = 'https://encoding.edu/bug/portal.do?solo&ct=Search%20Prot&curl=https://kc.edu/IRB.do?se=1875*&rs=1';
$urlNoQuery = 'https://encoding.edu/bug';
$urlMultiKeys = 'https://encoding.edu/bug?a=val1&a=val2';
$urlWithCaseDifference = 'https://encoding.edu?url=https%3a%2f%2Fencoding.edu%3Fa%3Db';
$urlWithSpace = 'https://encoding.edu?a=a%20space';
$urlWithRepeatParams = 'https://encoding.edu?a=b&a=c';
return [
[$urlWithQuery, $urlWithQuery . '&ticket=ST-', ''],
[$urlWithQuery . '#fragment', $urlWithQuery . '&ticket=ST-', '#fragment'],
[$urlMultiKeys, $urlMultiKeys . '&ticket=ST-', ''],
[$urlMultiKeys . '#fragment', $urlMultiKeys . '&ticket=ST-', '#fragment'],
[$urlNoQuery, $urlNoQuery. '?ticket=ST-', ''],
[$urlNoQuery . '#fragment', $urlNoQuery . '?ticket=ST-', '#fragment'],
[$urlWithCaseDifference, $urlWithCaseDifference. '&ticket=ST-', ''],
[$urlWithSpace, $urlWithSpace. '&ticket=ST-', ''],
[$urlWithRepeatParams, $urlWithRepeatParams. '&ticket=ST-', ''],
];
}
/**
* Test outputting user info instead of redirecting
*/
public function testDebugOutput()
{
$service_url = 'http://host1.domain:1234/path1';
$this->authenticate();
/** @var array $resp */
$resp = $this->server->get(
self::$LINK_URL,
['service' => $service_url, 'debugMode' => 'true'],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file
]
);
$this->assertEquals(200, $resp['code']);
$this->assertStringContainsString(
'<cas:eduPersonPrincipalName>testuser@example.com</cas:eduPersonPrincipalName>',
$resp['body'],
'Attributes should have been printed.'
);
}
/**
* Test outputting user info instead of redirecting
*/
public function testDebugOutputSamlValidate()
{
$service_url = 'http://host1.domain:1234/path1';
$this->authenticate();
/** @var array $resp */
$resp = $this->server->get(
self::$LINK_URL,
['service' => $service_url, 'debugMode' => 'samlValidate'],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file
]
);
$this->assertEquals(200, $resp['code']);
$this->assertStringContainsString(
'testuser@example.com</NameIdentifier',
$resp['body'],
'Attributes should have been printed.'
);
}
/**
* Test outputting user info instead of redirecting
*/
public function testAlternateServiceConfigUsed()
{
$service_url = 'https://override.example.com/somepath';
$this->authenticate();
/** @var array $resp */
$resp = $this->server->get(
self::$LINK_URL,
['service' => $service_url, 'debugMode' => 'true'],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file
]
);
$this->assertEquals(200, $resp['code']);
$this->assertStringContainsString(
'<cas:user>testuser</cas:user>',
$resp['body'],
'cas:user attribute should have been overridden'
);
$this->assertStringContainsString(
'<cas:cn>Test User</cas:cn>',
$resp['body'],
'Attributes should have been printed with alternate attribute release'
);
}
/**
* test a valid service URL with Post
*/
public function testValidServiceUrlWithPost()
{
$service_url = 'http://host1.domain:1234/path1';
$this->authenticate();
/** @var array $resp */
$resp = $this->server->get(
self::$LINK_URL,
[
'service' => $service_url,
'method' => 'POST',
],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file
]
);
// POST responds with a form that is uses JavaScript to submit
$this->assertEquals(200, $resp['code']);
// Validate the form contains the required elements
$body = $resp['body'];
$dom = new DOMDocument();
$dom->loadHTML($body);
$form = $dom->getElementsByTagName('form');
$item = $form->item(0);
if (is_null($item)) {
$this->fail('Unable to parse response.');
return;
}
$this->assertEquals($service_url, $item->getAttribute('action'));
$formInputs = $dom->getElementsByTagName('input');
//note: $formInputs[0] is '<input type="submit" style="display:none;" />'. See the post.php template from SSP
$item = $formInputs->item(1);
if (is_null($item)) {
$this->fail('Unable to parse response.');
return;
}
$this->assertEquals(
'ticket',
$item->getAttribute('name')
);
$this->assertStringStartsWith(
'ST-',
$item->getAttribute('value'),
''
);
}
/**
*/
public function testSamlValidate()
{
$service_url = 'http://host1.domain:1234/path1';
$this->authenticate();
/** @var array $resp */
$resp = $this->server->get(
self::$LINK_URL,
['service' => $service_url],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file
]
);
$this->assertEquals(302, $resp['code']);
$this->assertStringStartsWith(
$service_url . '?ticket=ST-',
$resp['headers']['Location'],
'Ticket should be part of the redirect.'
);
$location = $resp['headers']['Location'];
$matches = [];
$this->assertEquals(1, preg_match('@ticket=(.*)@', $location, $matches));
$ticket = $matches[1];
$soapRequest = <<<SOAP
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<samlp:Request xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" MajorVersion="1" MinorVersion="1" RequestID="_192.168.16.51.1024506224022" IssueInstant="2002-06-19T17:03:44.022Z">
<samlp:AssertionArtifact>$ticket</samlp:AssertionArtifact>
</samlp:Request>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
SOAP;
$resp = $this->post(
self::$SAMLVALIDATE_URL,
$soapRequest,
[
'TARGET' => $service_url,
]
);
$this->assertEquals(200, $resp['code']);
$this->assertStringContainsString('testuser@example.com</NameIdentifier>', $resp['body']);
}
/**
* Sets up an authenticated session for the cookie $jar
*/
private function authenticate()
{
// Use cookies Jar to store auth session cookies
/** @var array $resp */
$resp = $this->server->get(
self::$LINK_URL,
[],
[
CURLOPT_COOKIEJAR => $this->cookies_file,
CURLOPT_COOKIEFILE => $this->cookies_file,
CURLOPT_FOLLOWLOCATION => true
]
);
$this->assertEquals(200, $resp['code'], $resp['body']);
}
/**
* TODO: migrate into BuiltInServer
* @param resource $ch
* @return array
*/
private function execAndHandleCurlResponse($ch)
{
$resp = curl_exec($ch);
if ($resp === false) {
throw new \Exception('curl error: ' . curl_error($ch));
}
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
/** @psalm-var string $resp */
list($header, $body) = explode("\r\n\r\n", $resp, 2);
$raw_headers = explode("\r\n", $header);
array_shift($raw_headers);
$headers = [];
foreach ($raw_headers as $header) {
list($name, $value) = explode(':', $header, 2);
$headers[trim($name)] = trim($value);
}
curl_close($ch);
return [
'code' => $code,
'headers' => $headers,
'body' => $body,
];
}
/**
* TODO: migrate into BuiltInServer
* @param string $query The path at the embedded server to query
* @param string|array $body The content to post
* @param array $parameters Any query parameters to add.
* @param array $curlopts Additional curl options
* @return array The response code, headers and body
*/
public function post($query, $body, $parameters = [], $curlopts = [])
{
$ch = curl_init();
$url = 'http://' . $this->server_addr . $query;
$url .= (!empty($parameters)) ? '?' . http_build_query($parameters) : '';
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 1,
CURLOPT_POST => 1,
]);
// body may be multi dimensional, so we convert it ourselves
// https://stackoverflow.com/a/21111209/54396
$postParam = is_string($body) ? $body : http_build_query($body);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postParam);
curl_setopt_array($ch, $curlopts);
return $this->execAndHandleCurlResponse($ch);
}
}