]> BookStack Code Mirror - bookstack/blob - tests/Auth/OidcTest.php
OIDC: Updated avatar fetching to run on each login
[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_login_group_sync()
540     {
541         config()->set([
542             'oidc.user_to_groups'     => true,
543             'oidc.groups_claim'       => 'groups',
544             'oidc.remove_from_groups' => false,
545         ]);
546         $roleA = Role::factory()->create(['display_name' => 'Wizards']);
547         $roleB = Role::factory()->create(['display_name' => 'ZooFolks', 'external_auth_id' => 'zookeepers']);
548         $roleC = Role::factory()->create(['display_name' => 'Another Role']);
549
550         $resp = $this->runLogin([
551             'email'  => '[email protected]',
552             'sub'    => 'benny1010101',
553             'groups' => ['Wizards', 'Zookeepers'],
554         ]);
555         $resp->assertRedirect('/');
556
557         /** @var User $user */
558         $user = User::query()->where('email', '=', '[email protected]')->first();
559
560         $this->assertTrue($user->hasRole($roleA->id));
561         $this->assertTrue($user->hasRole($roleB->id));
562         $this->assertFalse($user->hasRole($roleC->id));
563     }
564
565     public function test_login_group_sync_with_nested_groups_in_token()
566     {
567         config()->set([
568             'oidc.user_to_groups'     => true,
569             'oidc.groups_claim'       => 'my.custom.groups.attr',
570             'oidc.remove_from_groups' => false,
571         ]);
572         $roleA = Role::factory()->create(['display_name' => 'Wizards']);
573
574         $resp = $this->runLogin([
575             'email'  => '[email protected]',
576             'sub'    => 'benny1010101',
577             'my'     => [
578                 'custom' => [
579                     'groups' => [
580                         'attr' => ['Wizards'],
581                     ],
582                 ],
583             ],
584         ]);
585         $resp->assertRedirect('/');
586
587         /** @var User $user */
588         $user = User::query()->where('email', '=', '[email protected]')->first();
589         $this->assertTrue($user->hasRole($roleA->id));
590     }
591
592     public function test_oidc_logout_form_active_when_oidc_active()
593     {
594         $this->runLogin();
595
596         $resp = $this->get('/');
597         $this->withHtml($resp)->assertElementExists('header form[action$="/oidc/logout"] button');
598     }
599     public function test_logout_with_autodiscovery_with_oidc_logout_enabled()
600     {
601         config()->set(['oidc.end_session_endpoint' => true]);
602         $this->withAutodiscovery();
603
604         $transactions = $this->mockHttpClient([
605             $this->getAutoDiscoveryResponse(),
606             $this->getJwksResponse(),
607         ]);
608
609         $resp = $this->asEditor()->post('/oidc/logout');
610         $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode(url('/')));
611
612         $this->assertEquals(2, $transactions->requestCount());
613         $this->assertFalse(auth()->check());
614     }
615
616     public function test_logout_with_autodiscovery_with_oidc_logout_disabled()
617     {
618         $this->withAutodiscovery();
619         config()->set(['oidc.end_session_endpoint' => false]);
620
621         $this->mockHttpClient([
622             $this->getAutoDiscoveryResponse(),
623             $this->getJwksResponse(),
624         ]);
625
626         $resp = $this->asEditor()->post('/oidc/logout');
627         $resp->assertRedirect('/');
628         $this->assertFalse(auth()->check());
629     }
630
631     public function test_logout_without_autodiscovery_but_with_endpoint_configured()
632     {
633         config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
634
635         $resp = $this->asEditor()->post('/oidc/logout');
636         $resp->assertRedirect('https://example.com/logout?post_logout_redirect_uri=' . urlencode(url('/')));
637         $this->assertFalse(auth()->check());
638     }
639
640     public function test_logout_without_autodiscovery_with_configured_endpoint_adds_to_query_if_existing()
641     {
642         config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout?a=b']);
643
644         $resp = $this->asEditor()->post('/oidc/logout');
645         $resp->assertRedirect('https://example.com/logout?a=b&post_logout_redirect_uri=' . urlencode(url('/')));
646         $this->assertFalse(auth()->check());
647     }
648
649     public function test_logout_with_autodiscovery_and_auto_initiate_returns_to_auto_prevented_login()
650     {
651         $this->withAutodiscovery();
652         config()->set([
653             'auth.auto_initiate' => true,
654             'services.google.client_id' => false,
655             'services.github.client_id' => false,
656             'oidc.end_session_endpoint' => true,
657         ]);
658
659         $this->mockHttpClient([
660             $this->getAutoDiscoveryResponse(),
661             $this->getJwksResponse(),
662         ]);
663
664         $resp = $this->asEditor()->post('/oidc/logout');
665
666         $redirectUrl = url('/login?prevent_auto_init=true');
667         $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode($redirectUrl));
668         $this->assertFalse(auth()->check());
669     }
670
671     public function test_logout_endpoint_url_overrides_autodiscovery_endpoint()
672     {
673         config()->set(['oidc.end_session_endpoint' => 'https://a.example.com']);
674         $this->withAutodiscovery();
675
676         $transactions = $this->mockHttpClient([
677             $this->getAutoDiscoveryResponse(),
678             $this->getJwksResponse(),
679         ]);
680
681         $resp = $this->asEditor()->post('/oidc/logout');
682         $resp->assertRedirect('https://a.example.com?post_logout_redirect_uri=' . urlencode(url('/')));
683
684         $this->assertEquals(2, $transactions->requestCount());
685         $this->assertFalse(auth()->check());
686     }
687
688     public function test_logout_with_autodiscovery_does_not_use_rp_logout_if_no_url_via_autodiscovery()
689     {
690         config()->set(['oidc.end_session_endpoint' => true]);
691         $this->withAutodiscovery();
692
693         $this->mockHttpClient([
694             $this->getAutoDiscoveryResponse(['end_session_endpoint' => null]),
695             $this->getJwksResponse(),
696         ]);
697
698         $resp = $this->asEditor()->post('/oidc/logout');
699         $resp->assertRedirect('/');
700         $this->assertFalse(auth()->check());
701     }
702
703     public function test_logout_redirect_contains_id_token_hint_if_existing()
704     {
705         config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
706
707         // Fix times so our token is predictable
708         $claimOverrides = [
709             'iat' => time(),
710             'exp' => time() + 720,
711             'auth_time' => time()
712         ];
713         $this->runLogin($claimOverrides);
714
715         $resp = $this->asEditor()->post('/oidc/logout');
716         $query = 'id_token_hint=' . urlencode(OidcJwtHelper::idToken($claimOverrides)) .  '&post_logout_redirect_uri=' . urlencode(url('/'));
717         $resp->assertRedirect('https://example.com/logout?' . $query);
718     }
719
720     public function test_oidc_id_token_pre_validate_theme_event_without_return()
721     {
722         $args = [];
723         $callback = function (...$eventArgs) use (&$args) {
724             $args = $eventArgs;
725         };
726         Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
727
728         $resp = $this->runLogin([
729             'email' => '[email protected]',
730             'sub'   => 'benny1010101',
731             'name'  => 'Benny',
732         ]);
733         $resp->assertRedirect('/');
734
735         $this->assertDatabaseHas('users', [
736             'external_auth_id' => 'benny1010101',
737         ]);
738
739         $this->assertArrayHasKey('iss', $args[0]);
740         $this->assertArrayHasKey('sub', $args[0]);
741         $this->assertEquals('Benny', $args[0]['name']);
742         $this->assertEquals('benny1010101', $args[0]['sub']);
743
744         $this->assertArrayHasKey('access_token', $args[1]);
745         $this->assertArrayHasKey('expires_in', $args[1]);
746         $this->assertArrayHasKey('refresh_token', $args[1]);
747     }
748
749     public function test_oidc_id_token_pre_validate_theme_event_with_return()
750     {
751         $callback = function (...$eventArgs) {
752             return array_merge($eventArgs[0], [
753                 'email' => '[email protected]',
754                 'sub' => 'lenny1010101',
755                 'name' => 'Lenny',
756             ]);
757         };
758         Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
759
760         $resp = $this->runLogin([
761             'email' => '[email protected]',
762             'sub'   => 'benny1010101',
763             'name'  => 'Benny',
764         ]);
765         $resp->assertRedirect('/');
766
767         $this->assertDatabaseHas('users', [
768             'email' => '[email protected]',
769             'external_auth_id' => 'lenny1010101',
770             'name' => 'Lenny',
771         ]);
772     }
773
774     public function test_pkce_used_on_authorize_and_access()
775     {
776         // Start auth
777         $resp = $this->post('/oidc/login');
778         $state = session()->get('oidc_state');
779
780         $pkceCode = session()->get('oidc_pkce_code');
781         $this->assertGreaterThan(30, strlen($pkceCode));
782
783         $expectedCodeChallenge = trim(strtr(base64_encode(hash('sha256', $pkceCode, true)), '+/', '-_'), '=');
784         $redirect = $resp->headers->get('Location');
785         $redirectParams = [];
786         parse_str(parse_url($redirect, PHP_URL_QUERY), $redirectParams);
787         $this->assertEquals($expectedCodeChallenge, $redirectParams['code_challenge']);
788         $this->assertEquals('S256', $redirectParams['code_challenge_method']);
789
790         $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
791             'email' => '[email protected]',
792             'sub'   => 'benny1010101',
793         ])]);
794
795         $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
796         $tokenRequest = $transactions->latestRequest();
797         $bodyParams = [];
798         parse_str($tokenRequest->getBody(), $bodyParams);
799         $this->assertEquals($pkceCode, $bodyParams['code_verifier']);
800     }
801
802     public function test_userinfo_endpoint_used_if_missing_claims_in_id_token()
803     {
804         config()->set('oidc.display_name_claims', 'first_name|last_name');
805         $this->post('/oidc/login');
806         $state = session()->get('oidc_state');
807
808         $client = $this->mockHttpClient([
809             $this->getMockAuthorizationResponse(['name' => null]),
810             new Response(200, [
811                 'Content-Type'  => 'application/json',
812             ], json_encode([
813                 'sub' => OidcJwtHelper::defaultPayload()['sub'],
814                 'first_name' => 'Barry',
815                 'last_name' => 'Userinfo',
816             ]))
817         ]);
818
819         $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
820         $resp->assertRedirect('/');
821         $this->assertEquals(2, $client->requestCount());
822
823         $userinfoRequest = $client->requestAt(1);
824         $this->assertEquals('GET', $userinfoRequest->getMethod());
825         $this->assertEquals('https://oidc.local/userinfo', (string) $userinfoRequest->getUri());
826
827         $this->assertEquals('Barry Userinfo', user()->name);
828     }
829
830     public function test_userinfo_endpoint_fetch_with_different_sub_throws_error()
831     {
832         $userinfoResponseData = ['sub' => 'dcba4321'];
833         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/json'], json_encode($userinfoResponseData));
834         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
835         $resp->assertRedirect('/login');
836         $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
837     }
838
839     public function test_userinfo_endpoint_fetch_returning_no_sub_throws_error()
840     {
841         $userinfoResponseData = ['name' => 'testing'];
842         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/json'], json_encode($userinfoResponseData));
843         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
844         $resp->assertRedirect('/login');
845         $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
846     }
847
848     public function test_userinfo_endpoint_fetch_can_parsed_nested_groups()
849     {
850         config()->set([
851             'oidc.user_to_groups'     => true,
852             'oidc.groups_claim'       => 'my.nested.groups.attr',
853             'oidc.remove_from_groups' => false,
854         ]);
855
856         $roleA = Role::factory()->create(['display_name' => 'Ducks']);
857         $userinfoResponseData = [
858             'sub' => OidcJwtHelper::defaultPayload()['sub'],
859             'my' => ['nested' => ['groups' => ['attr' => ['Ducks', 'Donkeys']]]]
860         ];
861         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/json'], json_encode($userinfoResponseData));
862         $resp = $this->runLogin(['groups' => null], [$userinfoResponse]);
863         $resp->assertRedirect('/');
864
865         $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
866         $this->assertTrue($user->hasRole($roleA->id));
867     }
868
869     public function test_userinfo_endpoint_response_with_complex_json_content_type_handled()
870     {
871         $userinfoResponseData = [
872             'sub' => OidcJwtHelper::defaultPayload()['sub'],
873             'name' => 'Barry',
874         ];
875         $userinfoResponse = new Response(200, ['Content-Type'  => 'Application/Json ; charset=utf-8'], json_encode($userinfoResponseData));
876         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
877         $resp->assertRedirect('/');
878
879         $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
880         $this->assertEquals('Barry', $user->name);
881     }
882
883     public function test_userinfo_endpoint_jwks_response_handled()
884     {
885         $userinfoResponseData = OidcJwtHelper::idToken(['name' => 'Barry Jwks']);
886         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], $userinfoResponseData);
887
888         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
889         $resp->assertRedirect('/');
890
891         $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
892         $this->assertEquals('Barry Jwks', $user->name);
893     }
894
895     public function test_userinfo_endpoint_jwks_response_returning_no_sub_throws()
896     {
897         $userinfoResponseData = OidcJwtHelper::idToken(['sub' => null]);
898         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], $userinfoResponseData);
899
900         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
901         $resp->assertRedirect('/login');
902         $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
903     }
904
905     public function test_userinfo_endpoint_jwks_response_returning_non_matching_sub_throws()
906     {
907         $userinfoResponseData = OidcJwtHelper::idToken(['sub' => 'zzz123']);
908         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], $userinfoResponseData);
909
910         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
911         $resp->assertRedirect('/login');
912         $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
913     }
914
915     public function test_userinfo_endpoint_jwks_response_with_invalid_signature_throws()
916     {
917         $userinfoResponseData = OidcJwtHelper::idToken();
918         $exploded = explode('.', $userinfoResponseData);
919         $exploded[2] = base64_encode(base64_decode($exploded[2]) . 'ABC');
920         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/jwt'], implode('.', $exploded));
921
922         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
923         $resp->assertRedirect('/login');
924         $this->assertSessionError('Userinfo endpoint response validation failed with error: Token signature could not be validated using the provided keys');
925     }
926
927     public function test_userinfo_endpoint_jwks_response_with_invalid_signature_alg_throws()
928     {
929         $userinfoResponseData = OidcJwtHelper::idToken([], ['alg' => 'ZZ512']);
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: Only RS256 signature validation is supported. Token reports using ZZ512');
935     }
936
937     public function test_userinfo_endpoint_response_with_invalid_content_type_throws()
938     {
939         $userinfoResponse = new Response(200, ['Content-Type'  => 'application/beans'], json_encode(OidcJwtHelper::defaultPayload()));
940         $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
941         $resp->assertRedirect('/login');
942         $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
943     }
944
945     public function test_userinfo_endpoint_not_called_if_empty_groups_array_provided_in_id_token()
946     {
947         config()->set([
948             'oidc.user_to_groups'     => true,
949             'oidc.groups_claim'       => 'groups',
950             'oidc.remove_from_groups' => false,
951         ]);
952
953         $this->post('/oidc/login');
954         $state = session()->get('oidc_state');
955         $client = $this->mockHttpClient([$this->getMockAuthorizationResponse([
956             'groups' => [],
957         ])]);
958
959         $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
960         $resp->assertRedirect('/');
961         $this->assertEquals(1, $client->requestCount());
962         $this->assertTrue(auth()->check());
963     }
964
965     protected function withAutodiscovery(): void
966     {
967         config()->set([
968             'oidc.issuer'                 => OidcJwtHelper::defaultIssuer(),
969             'oidc.discover'               => true,
970             'oidc.authorization_endpoint' => null,
971             'oidc.token_endpoint'         => null,
972             'oidc.userinfo_endpoint'      => null,
973             'oidc.jwt_public_key'         => null,
974         ]);
975     }
976
977     protected function runLogin($claimOverrides = [], $additionalHttpResponses = []): TestResponse
978     {
979         $this->post('/oidc/login');
980         $state = session()->get('oidc_state');
981         $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides), ...$additionalHttpResponses]);
982
983         return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
984     }
985
986     protected function getAutoDiscoveryResponse($responseOverrides = []): Response
987     {
988         return new Response(200, [
989             'Content-Type'  => 'application/json',
990             'Cache-Control' => 'no-cache, no-store',
991             'Pragma'        => 'no-cache',
992         ], json_encode(array_merge([
993             'token_endpoint'         => OidcJwtHelper::defaultIssuer() . '/oidc/token',
994             'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
995             'userinfo_endpoint'      => OidcJwtHelper::defaultIssuer() . '/oidc/userinfo',
996             'jwks_uri'               => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
997             'issuer'                 => OidcJwtHelper::defaultIssuer(),
998             'end_session_endpoint'   => OidcJwtHelper::defaultIssuer() . '/oidc/logout',
999         ], $responseOverrides)));
1000     }
1001
1002     protected function getJwksResponse(): Response
1003     {
1004         return new Response(200, [
1005             'Content-Type'  => 'application/json',
1006             'Cache-Control' => 'no-cache, no-store',
1007             'Pragma'        => 'no-cache',
1008         ], json_encode([
1009             'keys' => [
1010                 OidcJwtHelper::publicJwkKeyArray(),
1011             ],
1012         ]));
1013     }
1014
1015     protected function getMockAuthorizationResponse($claimOverrides = []): Response
1016     {
1017         return new Response(200, [
1018             'Content-Type'  => 'application/json',
1019             'Cache-Control' => 'no-cache, no-store',
1020             'Pragma'        => 'no-cache',
1021         ], json_encode([
1022             'access_token' => 'abc123',
1023             'token_type'   => 'Bearer',
1024             'expires_in'   => 3600,
1025             'id_token'     => OidcJwtHelper::idToken($claimOverrides),
1026         ]));
1027     }
1028 }