]> BookStack Code Mirror - bookstack/blob - tests/Auth/OidcTest.php
CommentDisplayTest correct namespace
[bookstack] / tests / Auth / OidcTest.php
1 <?php
2
3 namespace Tests\Auth;
4
5 use BookStack\Activity\ActivityType;
6 use BookStack\Facades\Theme;
7 use BookStack\Theming\ThemeEvents;
8 use BookStack\Uploads\UserAvatars;
9 use BookStack\Users\Models\Role;
10 use BookStack\Users\Models\User;
11 use GuzzleHttp\Psr7\Response;
12 use Illuminate\Testing\TestResponse;
13 use Tests\Helpers\OidcJwtHelper;
14 use Tests\TestCase;
15
16 class OidcTest extends TestCase
17 {
18     protected string $keyFilePath;
19     protected $keyFile;
20
21     protected function setUp(): void
22     {
23         parent::setUp();
24         // Set default config for OpenID Connect
25
26         $this->keyFile = tmpfile();
27         $this->keyFilePath = 'file://' . stream_get_meta_data($this->keyFile)['uri'];
28         file_put_contents($this->keyFilePath, OidcJwtHelper::publicPemKey());
29
30         config()->set([
31             'auth.method'                 => 'oidc',
32             'auth.defaults.guard'         => 'oidc',
33             'oidc.name'                   => 'SingleSignOn-Testing',
34             'oidc.display_name_claims'    => 'name',
35             'oidc.client_id'              => OidcJwtHelper::defaultClientId(),
36             'oidc.client_secret'          => 'testpass',
37             'oidc.jwt_public_key'         => $this->keyFilePath,
38             'oidc.issuer'                 => OidcJwtHelper::defaultIssuer(),
39             'oidc.authorization_endpoint' => 'https://oidc.local/auth',
40             'oidc.token_endpoint'         => 'https://oidc.local/token',
41             'oidc.userinfo_endpoint'      => 'https://oidc.local/userinfo',
42             'oidc.discover'               => false,
43             'oidc.dump_user_details'      => false,
44             'oidc.additional_scopes'      => '',
45             'odic.fetch_avatar'           => false,
46             'oidc.user_to_groups'         => false,
47             'oidc.groups_claim'           => 'group',
48             'oidc.remove_from_groups'     => false,
49             'oidc.external_id_claim'      => 'sub',
50             'oidc.end_session_endpoint'   => false,
51         ]);
52     }
53
54     protected function tearDown(): void
55     {
56         parent::tearDown();
57         if (file_exists($this->keyFilePath)) {
58             unlink($this->keyFilePath);
59         }
60     }
61
62     public function test_login_option_shows_on_login_page()
63     {
64         $req = $this->get('/login');
65         $req->assertSeeText('SingleSignOn-Testing');
66         $this->withHtml($req)->assertElementExists('form[action$="/oidc/login"][method=POST] button');
67     }
68
69     public function test_oidc_routes_are_only_active_if_oidc_enabled()
70     {
71         config()->set(['auth.method' => 'standard']);
72         $routes = ['/login' => 'post', '/callback' => 'get'];
73         foreach ($routes as $uri => $method) {
74             $req = $this->call($method, '/oidc' . $uri);
75             $this->assertPermissionError($req);
76         }
77     }
78
79     public function test_forgot_password_routes_inaccessible()
80     {
81         $resp = $this->get('/password/email');
82         $this->assertPermissionError($resp);
83
84         $resp = $this->post('/password/email');
85         $this->assertPermissionError($resp);
86
87         $resp = $this->get('/password/reset/abc123');
88         $this->assertPermissionError($resp);
89
90         $resp = $this->post('/password/reset');
91         $this->assertPermissionError($resp);
92     }
93
94     public function test_standard_login_routes_inaccessible()
95     {
96         $resp = $this->post('/login');
97         $this->assertPermissionError($resp);
98     }
99
100     public function test_logout_route_functions()
101     {
102         $this->actingAs($this->users->editor());
103         $this->post('/logout');
104         $this->assertFalse(auth()->check());
105     }
106
107     public function test_user_invite_routes_inaccessible()
108     {
109         $resp = $this->get('/register/invite/abc123');
110         $this->assertPermissionError($resp);
111
112         $resp = $this->post('/register/invite/abc123');
113         $this->assertPermissionError($resp);
114     }
115
116     public function test_user_register_routes_inaccessible()
117     {
118         $resp = $this->get('/register');
119         $this->assertPermissionError($resp);
120
121         $resp = $this->post('/register');
122         $this->assertPermissionError($resp);
123     }
124
125     public function test_login()
126     {
127         $req = $this->post('/oidc/login');
128         $redirect = $req->headers->get('location');
129
130         $this->assertStringStartsWith('https://oidc.local/auth', $redirect, 'Login redirects to SSO location');
131         $this->assertFalse($this->isAuthenticated());
132         $this->assertStringContainsString('scope=openid%20profile%20email', $redirect);
133         $this->assertStringContainsString('client_id=' . OidcJwtHelper::defaultClientId(), $redirect);
134         $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $redirect);
135     }
136
137     public function test_login_success_flow()
138     {
139         // Start auth
140         $this->post('/oidc/login');
141         $state = session()->get('oidc_state');
142
143         $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
144             'email' => '[email protected]',
145             'sub'   => 'benny1010101',
146         ])]);
147
148         // Callback from auth provider
149         // App calls token endpoint to get id token
150         $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
151         $resp->assertRedirect('/');
152         $this->assertEquals(1, $transactions->requestCount());
153         $tokenRequest = $transactions->latestRequest();
154         $this->assertEquals('https://oidc.local/token', (string) $tokenRequest->getUri());
155         $this->assertEquals('POST', $tokenRequest->getMethod());
156         $this->assertEquals('Basic ' . base64_encode(OidcJwtHelper::defaultClientId() . ':testpass'), $tokenRequest->getHeader('Authorization')[0]);
157         $this->assertStringContainsString('grant_type=authorization_code', $tokenRequest->getBody());
158         $this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody());
159         $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody());
160
161         $this->assertTrue(auth()->check());
162         $this->assertDatabaseHas('users', [
163             'email'            => '[email protected]',
164             'external_auth_id' => 'benny1010101',
165             'email_confirmed'  => false,
166         ]);
167
168         $user = User::query()->where('email', '=', '[email protected]')->first();
169         $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, "oidc; ({$user->id}) Barry Scott");
170     }
171
172     public function test_login_uses_custom_additional_scopes_if_defined()
173     {
174         config()->set([
175             'oidc.additional_scopes' => 'groups, badgers',
176         ]);
177
178         $redirect = $this->post('/oidc/login')->headers->get('location');
179
180         $this->assertStringContainsString('scope=openid%20profile%20email%20groups%20badgers', $redirect);
181     }
182
183     public function test_callback_fails_if_no_state_present_or_matching()
184     {
185         $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
186         $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
187
188         $this->post('/oidc/login');
189         $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
190         $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
191     }
192
193     public function test_dump_user_details_option_outputs_as_expected()
194     {
195         config()->set('oidc.dump_user_details', true);
196
197         $resp = $this->runLogin([
198             'email' => '[email protected]',
199             'sub'   => 'benny505',
200         ]);
201
202         $resp->assertStatus(200);
203         $resp->assertJson([
204             'email' => '[email protected]',
205             'sub'   => 'benny505',
206             'iss'   => OidcJwtHelper::defaultIssuer(),
207             'aud'   => OidcJwtHelper::defaultClientId(),
208         ]);
209         $this->assertFalse(auth()->check());
210     }
211
212     public function test_auth_fails_if_no_email_exists_in_user_data()
213     {
214         config()->set('oidc.userinfo_endpoint', null);
215
216         $this->runLogin([
217             'email' => '',
218             'sub'   => 'benny505',
219         ]);
220
221         $this->assertSessionError('Could not find an email address, for this user, in the data provided by the external authentication system');
222     }
223
224     public function test_auth_fails_if_already_logged_in()
225     {
226         $this->asEditor();
227
228         $this->runLogin([
229             'email' => '[email protected]',
230             'sub'   => 'benny505',
231         ]);
232
233         $this->assertSessionError('Already logged in');
234     }
235
236     public function test_auth_login_as_existing_user()
237     {
238         $editor = $this->users->editor();
239         $editor->external_auth_id = 'benny505';
240         $editor->save();
241
242         $this->assertFalse(auth()->check());
243
244         $this->runLogin([
245             'email' => '[email protected]',
246             'sub'   => 'benny505',
247         ]);
248
249         $this->assertTrue(auth()->check());
250         $this->assertEquals($editor->id, auth()->user()->id);
251     }
252
253     public function test_auth_login_as_existing_user_email_with_different_auth_id_fails()
254     {
255         $editor = $this->users->editor();
256         $editor->external_auth_id = 'editor101';
257         $editor->save();
258
259         $this->assertFalse(auth()->check());
260
261         $resp = $this->runLogin([
262             'email' => $editor->email,
263             'sub'   => 'benny505',
264         ]);
265         $resp = $this->followRedirects($resp);
266
267         $resp->assertSeeText('A user with the email ' . $editor->email . ' already exists but with different credentials.');
268         $this->assertFalse(auth()->check());
269     }
270
271     public function test_auth_login_with_invalid_token_fails()
272     {
273         $resp = $this->runLogin([
274             'sub' => null,
275         ]);
276         $resp = $this->followRedirects($resp);
277
278         $resp->assertSeeText('ID token validation failed with error: Missing token subject value');
279         $this->assertFalse(auth()->check());
280     }
281
282     public function test_auth_fails_if_endpoints_start_with_https()
283     {
284         $endpointConfigKeys = [
285             'oidc.token_endpoint' => 'tokenEndpoint',
286             'oidc.authorization_endpoint' => 'authorizationEndpoint',
287             'oidc.userinfo_endpoint' => 'userinfoEndpoint',
288         ];
289
290         foreach ($endpointConfigKeys as $endpointConfigKey => $endpointName) {
291             $logger = $this->withTestLogger();
292             $original = config()->get($endpointConfigKey);
293             $new = str_replace('https://', 'http://', $original);
294             config()->set($endpointConfigKey, $new);
295
296             $this->withoutExceptionHandling();
297             $err = null;
298             try {
299                 $resp = $this->runLogin();
300                 $resp->assertRedirect('/login');
301             } catch (\Exception $exception) {
302                 $err = $exception;
303             }
304             $this->assertEquals("Endpoint value for \"{$endpointName}\" must start with https://", $err->getMessage());
305
306             config()->set($endpointConfigKey, $original);
307         }
308     }
309
310     public function test_auth_login_with_autodiscovery()
311     {
312         $this->withAutodiscovery();
313
314         $transactions = $this->mockHttpClient([
315             $this->getAutoDiscoveryResponse(),
316             $this->getJwksResponse(),
317         ]);
318
319         $this->assertFalse(auth()->check());
320
321         $this->runLogin();
322
323         $this->assertTrue(auth()->check());
324
325         $discoverRequest = $transactions->requestAt(0);
326         $keysRequest = $transactions->requestAt(1);
327         $this->assertEquals('GET', $keysRequest->getMethod());
328         $this->assertEquals('GET', $discoverRequest->getMethod());
329         $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/.well-known/openid-configuration', $discoverRequest->getUri());
330         $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/oidc/keys', $keysRequest->getUri());
331     }
332
333     public function test_auth_fails_if_autodiscovery_fails()
334     {
335         $this->withAutodiscovery();
336         $this->mockHttpClient([
337             new Response(404, [], 'Not found'),
338         ]);
339
340         $resp = $this->followRedirects($this->runLogin());
341         $this->assertFalse(auth()->check());
342         $resp->assertSeeText('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
343     }
344
345     public function test_autodiscovery_calls_are_cached()
346     {
347         $this->withAutodiscovery();
348
349         $transactions = $this->mockHttpClient([
350             $this->getAutoDiscoveryResponse(),
351             $this->getJwksResponse(),
352             $this->getAutoDiscoveryResponse([
353                 'issuer' => 'https://auto.example.com',
354             ]),
355             $this->getJwksResponse(),
356         ]);
357
358         // Initial run
359         $this->post('/oidc/login');
360         $this->assertEquals(2, $transactions->requestCount());
361         // Second run, hits cache
362         $this->post('/oidc/login');
363         $this->assertEquals(2, $transactions->requestCount());
364
365         // Third run, different issuer, new cache key
366         config()->set(['oidc.issuer' => 'https://auto.example.com']);
367         $this->post('/oidc/login');
368         $this->assertEquals(4, $transactions->requestCount());
369     }
370
371     public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_alg_property()
372     {
373         $this->withAutodiscovery();
374
375         $keyArray = OidcJwtHelper::publicJwkKeyArray();
376         unset($keyArray['alg']);
377
378         $this->mockHttpClient([
379             $this->getAutoDiscoveryResponse(),
380             new Response(200, [
381                 'Content-Type'  => 'application/json',
382                 'Cache-Control' => 'no-cache, no-store',
383                 'Pragma'        => 'no-cache',
384             ], json_encode([
385                 'keys' => [
386                     $keyArray,
387                 ],
388             ])),
389         ]);
390
391         $this->assertFalse(auth()->check());
392         $this->runLogin();
393         $this->assertTrue(auth()->check());
394     }
395
396     public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_use_property()
397     {
398         // Based on reading the OIDC discovery spec:
399         // > This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also
400         // > contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When
401         // > both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all
402         // > keys in the referenced JWK Set to indicate each key's intended usage.
403         // We can assume that keys without use are intended for signing.
404         $this->withAutodiscovery();
405
406         $keyArray = OidcJwtHelper::publicJwkKeyArray();
407         unset($keyArray['use']);
408
409         $this->mockHttpClient([
410             $this->getAutoDiscoveryResponse(),
411             new Response(200, [
412                 'Content-Type'  => 'application/json',
413                 'Cache-Control' => 'no-cache, no-store',
414                 'Pragma'        => 'no-cache',
415             ], json_encode([
416                 'keys' => [
417                     $keyArray,
418                 ],
419             ])),
420         ]);
421
422         $this->assertFalse(auth()->check());
423         $this->runLogin();
424         $this->assertTrue(auth()->check());
425     }
426
427     public function test_auth_uses_configured_external_id_claim_option()
428     {
429         config()->set([
430             'oidc.external_id_claim' => 'super_awesome_id',
431         ]);
432
433         $resp = $this->runLogin([
434             'email'            => '[email protected]',
435             'sub'              => 'benny1010101',
436             'super_awesome_id' => 'xXBennyTheGeezXx',
437         ]);
438         $resp->assertRedirect('/');
439
440         /** @var User $user */
441         $user = User::query()->where('email', '=', '[email protected]')->first();
442         $this->assertEquals('xXBennyTheGeezXx', $user->external_auth_id);
443     }
444
445     public function test_auth_uses_mulitple_display_name_claims_if_configured()
446     {
447         config()->set(['oidc.display_name_claims' => 'first_name|last_name']);
448
449         $this->runLogin([
450             'email'      => '[email protected]',
451             'sub'        => 'benny1010101',
452             'first_name' => 'Benny',
453             'last_name'  => 'Jenkins'
454         ]);
455
456         $this->assertDatabaseHas('users', [
457             'name' => 'Benny Jenkins',
458             'email' => '[email protected]',
459         ]);
460     }
461
462     public function test_user_avatar_fetched_from_picture_on_first_login_if_enabled()
463     {
464         config()->set(['oidc.fetch_avatar' => true]);
465
466         $this->runLogin([
467             'email' => '[email protected]',
468             'picture' => 'https://example.com/my-avatar.jpg',
469         ], [
470             new Response(200, ['Content-Type' => 'image/jpeg'], $this->files->jpegImageData())
471         ]);
472
473         $user = User::query()->where('email', '=', '[email protected]')->first();
474         $this->assertNotNull($user);
475
476         $this->assertTrue($user->avatar()->exists());
477     }
478
479     public function test_user_avatar_fetched_for_existing_user_when_no_avatar_already_assigned()
480     {
481         config()->set(['oidc.fetch_avatar' => true]);
482         $editor = $this->users->editor();
483         $editor->external_auth_id = 'benny509';
484         $editor->save();
485
486         $this->assertFalse($editor->avatar()->exists());
487
488         $this->runLogin([
489             'picture' => 'https://example.com/my-avatar.jpg',
490             'sub' => 'benny509',
491         ], [
492             new Response(200, ['Content-Type' => 'image/jpeg'], $this->files->jpegImageData())
493         ]);
494
495         $editor->refresh();
496         $this->assertTrue($editor->avatar()->exists());
497     }
498
499     public function test_user_avatar_not_fetched_if_image_data_format_unknown()
500     {
501         config()->set(['oidc.fetch_avatar' => true]);
502
503         $this->runLogin([
504             'email' => '[email protected]',
505             'picture' => 'https://example.com/my-avatar.jpg',
506         ], [
507             new Response(200, ['Content-Type' => 'image/jpeg'], str_repeat('abc123', 5))
508         ]);
509
510         $user = User::query()->where('email', '=', '[email protected]')->first();
511         $this->assertNotNull($user);
512
513         $this->assertFalse($user->avatar()->exists());
514     }
515
516     public function test_user_avatar_not_fetched_when_avatar_already_assigned()
517     {
518         config()->set(['oidc.fetch_avatar' => true]);
519         $editor = $this->users->editor();
520         $editor->external_auth_id = 'benny509';
521         $editor->save();
522
523         $avatars = $this->app->make(UserAvatars::class);
524         $originalImageData = $this->files->pngImageData();
525         $avatars->assignToUserFromExistingData($editor, $originalImageData, 'png');
526
527         $this->runLogin([
528             'picture' => 'https://example.com/my-avatar.jpg',
529             'sub' => 'benny509',
530         ], [
531             new Response(200, ['Content-Type' => 'image/jpeg'], $this->files->jpegImageData())
532         ]);
533
534         $editor->refresh();
535         $newAvatarData = file_get_contents($this->files->relativeToFullPath($editor->avatar->path));
536         $this->assertEquals($originalImageData, $newAvatarData);
537     }
538
539     public function test_user_avatar_fetch_follows_up_to_three_redirects()
540     {
541         config()->set(['oidc.fetch_avatar' => true]);
542
543         $logger = $this->withTestLogger();
544
545         $this->runLogin([
546             'email' => '[email protected]',
547             'picture' => 'https://example.com/my-avatar.jpg',
548         ], [
549             new Response(302, ['Location' => 'https://example.com/a']),
550             new Response(302, ['Location' => 'https://example.com/b']),
551             new Response(302, ['Location' => 'https://example.com/c']),
552             new Response(302, ['Location' => 'https://example.com/d']),
553         ]);
554
555         $user = User::query()->where('email', '=', '[email protected]')->first();
556         $this->assertFalse($user->avatar()->exists());
557
558         $this->assertStringContainsString('"Failed to fetch image, max redirect limit of 3 tries reached. Last fetched URL: https://example.com/c"', $logger->getRecords()[0]->formatted);
559     }
560
561     public function test_login_group_sync()
562     {
563         config()->set([
564             'oidc.user_to_groups'     => true,
565             'oidc.groups_claim'       => 'groups',
566             'oidc.remove_from_groups' => false,
567         ]);
568         $roleA = Role::factory()->create(['display_name' => 'Wizards']);
569         $roleB = Role::factory()->create(['display_name' => 'ZooFolks', 'external_auth_id' => 'zookeepers']);
570         $roleC = Role::factory()->create(['display_name' => 'Another Role']);
571
572         $resp = $this->runLogin([
573             'email'  => '[email protected]',
574             'sub'    => 'benny1010101',
575             'groups' => ['Wizards', 'Zookeepers'],
576         ]);
577         $resp->assertRedirect('/');
578
579         /** @var User $user */
580         $user = User::query()->where('email', '=', '[email protected]')->first();
581
582         $this->assertTrue($user->hasRole($roleA->id));
583         $this->assertTrue($user->hasRole($roleB->id));
584         $this->assertFalse($user->hasRole($roleC->id));
585     }
586
587     public function test_login_group_sync_with_nested_groups_in_token()
588     {
589         config()->set([
590             'oidc.user_to_groups'     => true,
591             'oidc.groups_claim'       => 'my.custom.groups.attr',
592             'oidc.remove_from_groups' => false,
593         ]);
594         $roleA = Role::factory()->create(['display_name' => 'Wizards']);
595
596         $resp = $this->runLogin([
597             'email'  => '[email protected]',
598             'sub'    => 'benny1010101',
599             'my'     => [
600                 'custom' => [
601                     'groups' => [
602                         'attr' => ['Wizards'],
603                     ],
604                 ],
605             ],
606         ]);
607         $resp->assertRedirect('/');
608
609         /** @var User $user */
610         $user = User::query()->where('email', '=', '[email protected]')->first();
611         $this->assertTrue($user->hasRole($roleA->id));
612     }
613
614     public function test_oidc_logout_form_active_when_oidc_active()
615     {
616         $this->runLogin();
617
618         $resp = $this->get('/');
619         $this->withHtml($resp)->assertElementExists('header form[action$="/oidc/logout"] button');
620     }
621     public function test_logout_with_autodiscovery_with_oidc_logout_enabled()
622     {
623         config()->set(['oidc.end_session_endpoint' => true]);
624         $this->withAutodiscovery();
625
626         $transactions = $this->mockHttpClient([
627             $this->getAutoDiscoveryResponse(),
628             $this->getJwksResponse(),
629         ]);
630
631         $resp = $this->asEditor()->post('/oidc/logout');
632         $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode(url('/')));
633
634         $this->assertEquals(2, $transactions->requestCount());
635         $this->assertFalse(auth()->check());
636     }
637
638     public function test_logout_with_autodiscovery_with_oidc_logout_disabled()
639     {
640         $this->withAutodiscovery();
641         config()->set(['oidc.end_session_endpoint' => false]);
642
643         $this->mockHttpClient([
644             $this->getAutoDiscoveryResponse(),
645             $this->getJwksResponse(),
646         ]);
647
648         $resp = $this->asEditor()->post('/oidc/logout');
649         $resp->assertRedirect('/');
650         $this->assertFalse(auth()->check());
651     }
652
653     public function test_logout_without_autodiscovery_but_with_endpoint_configured()
654     {
655         config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
656
657         $resp = $this->asEditor()->post('/oidc/logout');
658         $resp->assertRedirect('https://example.com/logout?post_logout_redirect_uri=' . urlencode(url('/')));
659         $this->assertFalse(auth()->check());
660     }
661
662     public function test_logout_without_autodiscovery_with_configured_endpoint_adds_to_query_if_existing()
663     {
664         config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout?a=b']);
665
666         $resp = $this->asEditor()->post('/oidc/logout');
667         $resp->assertRedirect('https://example.com/logout?a=b&post_logout_redirect_uri=' . urlencode(url('/')));
668         $this->assertFalse(auth()->check());
669     }
670
671     public function test_logout_with_autodiscovery_and_auto_initiate_returns_to_auto_prevented_login()
672     {
673         $this->withAutodiscovery();
674         config()->set([
675             'auth.auto_initiate' => true,
676             'services.google.client_id' => false,
677             'services.github.client_id' => false,
678             'oidc.end_session_endpoint' => true,
679         ]);
680
681         $this->mockHttpClient([
682             $this->getAutoDiscoveryResponse(),
683             $this->getJwksResponse(),
684         ]);
685
686         $resp = $this->asEditor()->post('/oidc/logout');
687
688         $redirectUrl = url('/login?prevent_auto_init=true');
689         $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode($redirectUrl));
690         $this->assertFalse(auth()->check());
691     }
692
693     public function test_logout_endpoint_url_overrides_autodiscovery_endpoint()
694     {
695         config()->set(['oidc.end_session_endpoint' => 'https://a.example.com']);
696         $this->withAutodiscovery();
697
698         $transactions = $this->mockHttpClient([
699             $this->getAutoDiscoveryResponse(),
700             $this->getJwksResponse(),
701         ]);
702
703         $resp = $this->asEditor()->post('/oidc/logout');
704         $resp->assertRedirect('https://a.example.com?post_logout_redirect_uri=' . urlencode(url('/')));
705
706         $this->assertEquals(2, $transactions->requestCount());
707         $this->assertFalse(auth()->check());
708     }
709
710     public function test_logout_with_autodiscovery_does_not_use_rp_logout_if_no_url_via_autodiscovery()
711     {
712         config()->set(['oidc.end_session_endpoint' => true]);
713         $this->withAutodiscovery();
714
715         $this->mockHttpClient([
716             $this->getAutoDiscoveryResponse(['end_session_endpoint' => null]),
717             $this->getJwksResponse(),
718         ]);
719
720         $resp = $this->asEditor()->post('/oidc/logout');
721         $resp->assertRedirect('/');
722         $this->assertFalse(auth()->check());
723     }
724
725     public function test_logout_redirect_contains_id_token_hint_if_existing()
726     {
727         config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
728
729         // Fix times so our token is predictable
730         $claimOverrides = [
731             'iat' => time(),
732             'exp' => time() + 720,
733             'auth_time' => time()
734         ];
735         $this->runLogin($claimOverrides);
736
737         $resp = $this->asEditor()->post('/oidc/logout');
738         $query = 'id_token_hint=' . urlencode(OidcJwtHelper::idToken($claimOverrides)) .  '&post_logout_redirect_uri=' . urlencode(url('/'));
739         $resp->assertRedirect('https://example.com/logout?' . $query);
740     }
741
742     public function test_oidc_id_token_pre_validate_theme_event_without_return()
743     {
744         $args = [];
745         $callback = function (...$eventArgs) use (&$args) {
746             $args = $eventArgs;
747         };
748         Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
749
750         $resp = $this->runLogin([
751             'email' => '[email protected]',
752             'sub'   => 'benny1010101',
753             'name'  => 'Benny',
754         ]);
755         $resp->assertRedirect('/');
756
757         $this->assertDatabaseHas('users', [
758             'external_auth_id' => 'benny1010101',
759         ]);
760
761         $this->assertArrayHasKey('iss', $args[0]);
762         $this->assertArrayHasKey('sub', $args[0]);
763         $this->assertEquals('Benny', $args[0]['name']);
764         $this->assertEquals('benny1010101', $args[0]['sub']);
765
766         $this->assertArrayHasKey('access_token', $args[1]);
767         $this->assertArrayHasKey('expires_in', $args[1]);
768         $this->assertArrayHasKey('refresh_token', $args[1]);
769     }
770
771     public function test_oidc_id_token_pre_validate_theme_event_with_return()
772     {
773         $callback = function (...$eventArgs) {
774             return array_merge($eventArgs[0], [
775                 'email' => '[email protected]',
776                 'sub' => 'lenny1010101',
777                 'name' => 'Lenny',
778             ]);
779         };
780         Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
781
782         $resp = $this->runLogin([
783             'email' => '[email protected]',
784             'sub'   => 'benny1010101',
785             'name'  => 'Benny',
786         ]);
787         $resp->assertRedirect('/');
788
789         $this->assertDatabaseHas('users', [
790             'email' => '[email protected]',
791             'external_auth_id' => 'lenny1010101',
792             'name' => 'Lenny',
793         ]);
794     }
795
796     public function test_pkce_used_on_authorize_and_access()
797     {
798         // Start auth
799         $resp = $this->post('/oidc/login');
800         $state = session()->get('oidc_state');
801
802         $pkceCode = session()->get('oidc_pkce_code');
803         $this->assertGreaterThan(30, strlen($pkceCode));
804
805         $expectedCodeChallenge = trim(strtr(base64_encode(hash('sha256', $pkceCode, true)), '+/', '-_'), '=');
806         $redirect = $resp->headers->get('Location');
807         $redirectParams = [];
808         parse_str(parse_url($redirect, PHP_URL_QUERY), $redirectParams);
809         $this->assertEquals($expectedCodeChallenge, $redirectParams['code_challenge']);
810         $this->assertEquals('S256', $redirectParams['code_challenge_method']);
811
812         $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
813             'email' => '[email protected]',
814             'sub'   => 'benny1010101',
815         ])]);
816
817         $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
818         $tokenRequest = $transactions->latestRequest();
819         $bodyParams = [];
820         parse_str($tokenRequest->getBody(), $bodyParams);
821         $this->assertEquals($pkceCode, $bodyParams['code_verifier']);
822     }
823
824     public function test_userinfo_endpoint_used_if_missing_claims_in_id_token()
825     {
826         config()->set('oidc.display_name_claims', 'first_name|last_name');
827         $this->post('/oidc/login');
828         $state = session()->get('oidc_state');
829
830         $client = $this->mockHttpClient([
831             $this->getMockAuthorizationResponse(['name' => null]),
832             new Response(200, [
833                 'Content-Type'  => 'application/json',
834             ], json_encode([
835                 'sub' => OidcJwtHelper::defaultPayload()['sub'],
836                 'first_name' => 'Barry',
837                 'last_name' => 'Userinfo',
838             ]))
839         ]);
840
841         $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
842         $resp->assertRedirect('/');
843         $this->assertEquals(2, $client->requestCount());
844
845         $userinfoRequest = $client->requestAt(1);
846         $this->assertEquals('GET', $userinfoRequest->getMethod());
847         $this->assertEquals('https://oidc.local/userinfo', (string) $userinfoRequest->getUri());
848
849         $this->assertEquals('Barry Userinfo', user()->name);
850     }
851
852     public function test_userinfo_endpoint_fetch_with_different_sub_throws_error()
853     {
854         $userinfoResponseData = ['sub' => 'dcba4321'];
855         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/json'], json_encode($userinfoResponseData));
856         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
857         $resp->assertRedirect('/login');
858         $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
859     }
860
861     public function test_userinfo_endpoint_fetch_returning_no_sub_throws_error()
862     {
863         $userinfoResponseData = ['name' => 'testing'];
864         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/json'], json_encode($userinfoResponseData));
865         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
866         $resp->assertRedirect('/login');
867         $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
868     }
869
870     public function test_userinfo_endpoint_fetch_can_parsed_nested_groups()
871     {
872         config()->set([
873             'oidc.user_to_groups'     => true,
874             'oidc.groups_claim'       => 'my.nested.groups.attr',
875             'oidc.remove_from_groups' => false,
876         ]);
877
878         $roleA = Role::factory()->create(['display_name' => 'Ducks']);
879         $userinfoResponseData = [
880             'sub' => OidcJwtHelper::defaultPayload()['sub'],
881             'my' => ['nested' => ['groups' => ['attr' => ['Ducks', 'Donkeys']]]]
882         ];
883         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/json'], json_encode($userinfoResponseData));
884         $resp = $this->runLogin(['groups' => null], [$userinfoResponse]);
885         $resp->assertRedirect('/');
886
887         $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
888         $this->assertTrue($user->hasRole($roleA->id));
889     }
890
891     public function test_userinfo_endpoint_response_with_complex_json_content_type_handled()
892     {
893         $userinfoResponseData = [
894             'sub' => OidcJwtHelper::defaultPayload()['sub'],
895             'name' => 'Barry',
896         ];
897         $userinfoResponse = new Response(200, ['Content-Type'  => 'Application/Json ; charset=utf-8'], json_encode($userinfoResponseData));
898         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
899         $resp->assertRedirect('/');
900
901         $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
902         $this->assertEquals('Barry', $user->name);
903     }
904
905     public function test_userinfo_endpoint_jwks_response_handled()
906     {
907         $userinfoResponseData = OidcJwtHelper::idToken(['name' => 'Barry Jwks']);
908         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], $userinfoResponseData);
909
910         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
911         $resp->assertRedirect('/');
912
913         $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
914         $this->assertEquals('Barry Jwks', $user->name);
915     }
916
917     public function test_userinfo_endpoint_jwks_response_returning_no_sub_throws()
918     {
919         $userinfoResponseData = OidcJwtHelper::idToken(['sub' => null]);
920         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], $userinfoResponseData);
921
922         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
923         $resp->assertRedirect('/login');
924         $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
925     }
926
927     public function test_userinfo_endpoint_jwks_response_returning_non_matching_sub_throws()
928     {
929         $userinfoResponseData = OidcJwtHelper::idToken(['sub' => 'zzz123']);
930         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], $userinfoResponseData);
931
932         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
933         $resp->assertRedirect('/login');
934         $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
935     }
936
937     public function test_userinfo_endpoint_jwks_response_with_invalid_signature_throws()
938     {
939         $userinfoResponseData = OidcJwtHelper::idToken();
940         $exploded = explode('.', $userinfoResponseData);
941         $exploded[2] = base64_encode(base64_decode($exploded[2]) . 'ABC');
942         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], implode('.', $exploded));
943
944         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
945         $resp->assertRedirect('/login');
946         $this->assertSessionError('Userinfo endpoint response validation failed with error: Token signature could not be validated using the provided keys');
947     }
948
949     public function test_userinfo_endpoint_jwks_response_with_invalid_signature_alg_throws()
950     {
951         $userinfoResponseData = OidcJwtHelper::idToken([], ['alg' => 'ZZ512']);
952         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], $userinfoResponseData);
953
954         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
955         $resp->assertRedirect('/login');
956         $this->assertSessionError('Userinfo endpoint response validation failed with error: Only RS256 signature validation is supported. Token reports using ZZ512');
957     }
958
959     public function test_userinfo_endpoint_response_with_invalid_content_type_throws()
960     {
961         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/beans'], json_encode(OidcJwtHelper::defaultPayload()));
962         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
963         $resp->assertRedirect('/login');
964         $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
965     }
966
967     public function test_userinfo_endpoint_not_called_if_empty_groups_array_provided_in_id_token()
968     {
969         config()->set([
970             'oidc.user_to_groups'     => true,
971             'oidc.groups_claim'       => 'groups',
972             'oidc.remove_from_groups' => false,
973         ]);
974
975         $this->post('/oidc/login');
976         $state = session()->get('oidc_state');
977         $client = $this->mockHttpClient([$this->getMockAuthorizationResponse([
978             'groups' => [],
979         ])]);
980
981         $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
982         $resp->assertRedirect('/');
983         $this->assertEquals(1, $client->requestCount());
984         $this->assertTrue(auth()->check());
985     }
986
987     protected function withAutodiscovery(): void
988     {
989         config()->set([
990             'oidc.issuer'                 => OidcJwtHelper::defaultIssuer(),
991             'oidc.discover'               => true,
992             'oidc.authorization_endpoint' => null,
993             'oidc.token_endpoint'         => null,
994             'oidc.userinfo_endpoint'      => null,
995             'oidc.jwt_public_key'         => null,
996         ]);
997     }
998
999     protected function runLogin($claimOverrides = [], $additionalHttpResponses = []): TestResponse
1000     {
1001         $this->post('/oidc/login');
1002         $state = session()->get('oidc_state');
1003         $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides), ...$additionalHttpResponses]);
1004
1005         return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
1006     }
1007
1008     protected function getAutoDiscoveryResponse($responseOverrides = []): Response
1009     {
1010         return new Response(200, [
1011             'Content-Type'  => 'application/json',
1012             'Cache-Control' => 'no-cache, no-store',
1013             'Pragma'        => 'no-cache',
1014         ], json_encode(array_merge([
1015             'token_endpoint'         => OidcJwtHelper::defaultIssuer() . '/oidc/token',
1016             'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
1017             'userinfo_endpoint'      => OidcJwtHelper::defaultIssuer() . '/oidc/userinfo',
1018             'jwks_uri'               => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
1019             'issuer'                 => OidcJwtHelper::defaultIssuer(),
1020             'end_session_endpoint'   => OidcJwtHelper::defaultIssuer() . '/oidc/logout',
1021         ], $responseOverrides)));
1022     }
1023
1024     protected function getJwksResponse(): Response
1025     {
1026         return new Response(200, [
1027             'Content-Type'  => 'application/json',
1028             'Cache-Control' => 'no-cache, no-store',
1029             'Pragma'        => 'no-cache',
1030         ], json_encode([
1031             'keys' => [
1032                 OidcJwtHelper::publicJwkKeyArray(),
1033             ],
1034         ]));
1035     }
1036
1037     protected function getMockAuthorizationResponse($claimOverrides = []): Response
1038     {
1039         return new Response(200, [
1040             'Content-Type'  => 'application/json',
1041             'Cache-Control' => 'no-cache, no-store',
1042             'Pragma'        => 'no-cache',
1043         ], json_encode([
1044             'access_token' => 'abc123',
1045             'token_type'   => 'Bearer',
1046             'expires_in'   => 3600,
1047             'id_token'     => OidcJwtHelper::idToken($claimOverrides),
1048         ]));
1049     }
1050 }