-
-
Notifications
You must be signed in to change notification settings - Fork 622
Expand file tree
/
Copy pathElevatedSessionTest.php
More file actions
608 lines (505 loc) · 19.8 KB
/
ElevatedSessionTest.php
File metadata and controls
608 lines (505 loc) · 19.8 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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
<?php
namespace Tests\Auth;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Mockery;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\Test;
use Statamic\Contracts\Auth\Passkey;
use Statamic\Facades\User;
use Statamic\Facades\WebAuthn;
use Statamic\Http\Middleware\CP\RequireElevatedSession;
use Statamic\Notifications\ElevatedSessionVerificationCode;
use Tests\ElevatesSessions;
use Tests\PreventSavingStacheItemsToDisk;
use Tests\TestCase;
#[Group('elevated-session')]
class ElevatedSessionTest extends TestCase
{
use ElevatesSessions;
use PreventSavingStacheItemsToDisk;
private $user;
protected function setUp(): void
{
parent::setUp();
$this->freezeTime();
$this->user = User::make()->email('foo@bar.com')->makeSuper()->password('secret');
$this->user->save();
}
protected function resolveApplicationConfiguration($app)
{
parent::resolveApplicationConfiguration($app);
$app->booted(function () {
Route::get('/requires-elevated-session', function () {
return 'ok';
})->middleware(RequireElevatedSession::class);
});
}
#[Test]
public function it_can_get_status_of_elevated_session()
{
config(['statamic.users.elevated_session_duration' => 15]);
$this
->withElevatedSession(now()->subMinutes(5))
->actingAs($this->user)
->get('/cp/elevated-session')
->assertOk()
->assertJson([
'elevated' => true,
'expiry' => now()->addMinutes(10)->timestamp,
'method' => 'password_confirmation',
]);
}
#[Test]
public function it_can_get_status_of_elevated_session_when_session_key_does_not_exist()
{
$this
->actingAs($this->user)
->get('/cp/elevated-session')
->assertOk()
->assertJson([
'elevated' => false,
'expiry' => null,
'method' => 'password_confirmation',
]);
}
#[Test]
public function it_can_get_status_of_elevated_session_when_session_has_expired()
{
config(['statamic.users.elevated_session_duration' => 15]);
$this
->withElevatedSession(now()->subMinutes(20))
->actingAs($this->user)
->get('/cp/elevated-session')
->assertOk()
->assertJson([
'elevated' => false,
'expiry' => now()->subMinutes(5)->timestamp,
'method' => 'password_confirmation',
]);
}
#[Test]
public function it_can_get_status_of_elevated_session_when_session_has_expired_and_user_doesnt_have_a_password()
{
Notification::fake();
Str::createRandomStringsUsing(fn () => 'abc');
$user = tap(User::make()->email('foo@bar.com')->makeSuper())->save();
config(['statamic.users.elevated_session_duration' => 15]);
$this
->withElevatedSession(now()->subMinutes(20))
->actingAs($user)
->get('/cp/elevated-session')
->assertOk()
->assertJson([
'elevated' => false,
'expiry' => now()->subMinutes(5)->timestamp,
'method' => 'verification_code',
])
->assertSessionHas('statamic_elevated_session_verification_code', [
'code' => 'abc',
'generated_at' => now()->timestamp,
]);
Notification::assertSentTo($user, ElevatedSessionVerificationCode::class, function ($notification, $channels) {
return $notification->verificationCode === 'abc';
});
}
#[Test]
public function when_getting_status_for_user_without_password_it_only_sends_notification_once()
{
Notification::fake();
Str::createRandomStringsUsing(fn () => 'abc');
$user = tap(User::make()->email('foo@bar.com')->makeSuper())->save();
config(['statamic.users.elevated_session_duration' => 15]);
$request = function () use ($user) {
return $this
->withElevatedSession(now()->subMinutes(20))
->actingAs($user)
->get('/cp/elevated-session');
};
$request(); // Sent.
$request(); // Within 5-minute window. Not sent.
$this->travel(30)->seconds();
$request(); // Still within 5-minute window. Not sent.
$this->travel(5)->minute();
$request(); // Outside 5 minutes. Sent.
Notification::assertCount(2);
}
#[Test]
public function it_can_start_elevated_session()
{
redirect()->setIntendedUrl('/cp/target-url');
$this
->actingAs($this->user)
->post('/cp/elevated-session', ['password' => 'secret'])
->assertRedirect('/cp/target-url')
->assertSessionHas('statamic_elevated_session', now()->timestamp);
}
#[Test]
public function it_can_start_elevated_session_via_json()
{
$this
->actingAs($this->user)
->postJson('/cp/elevated-session', ['password' => 'secret'])
->assertOk()
->assertJsonStructure(['elevated', 'expiry'])
->assertSessionHas('statamic_elevated_session', now()->timestamp);
}
#[Test]
public function it_cannot_start_elevated_session_with_incorrect_password()
{
$this
->actingAs($this->user)
->post('/cp/elevated-session', ['password' => 'incorrect-password'])
->assertSessionHasErrors('password')
->assertSessionMissing('statamic_elevated_session');
}
#[Test]
#[DataProvider('invalidPasswordPayloads')]
public function it_rejects_invalid_password_payloads(array $payload): void
{
$this
->actingAs($this->user)
->postJson('/cp/elevated-session', $payload)
->assertStatus(422)
->assertJsonValidationErrors('password')
->assertSessionMissing('statamic_elevated_session');
}
public static function invalidPasswordPayloads(): array
{
return [
'no fields' => [[]],
'string zero' => [['password' => '0']],
'integer zero' => [['password' => 0]],
'false' => [['password' => false]],
'empty string' => [['password' => '']],
'null' => [['password' => null]],
];
}
#[Test]
#[DataProvider('invalidVerificationCodePayloads')]
public function it_rejects_invalid_verification_code_payloads(array $payload): void
{
$this
->actingAs($this->user)
->postJson('/cp/elevated-session', $payload)
->assertStatus(422)
->assertJsonValidationErrors('verification_code')
->assertSessionMissing('statamic_elevated_session');
}
public static function invalidVerificationCodePayloads(): array
{
return [
'no fields' => [[]],
'string zero' => [['verification_code' => '0']],
'integer zero' => [['verification_code' => 0]],
'false' => [['verification_code' => false]],
'empty string' => [['verification_code' => '']],
'null' => [['verification_code' => null]],
];
}
#[Test]
#[DataProvider('invalidPasskeyPayloads')]
public function it_handles_invalid_passkey_payloads(array $payload, bool $expectsValidationError): void
{
if ($expectsValidationError) {
$this
->actingAs($this->user)
->postJson('/cp/elevated-session', $payload)
->assertStatus(422)
->assertJsonValidationErrors('id')
->assertSessionMissing('statamic_elevated_session');
return;
}
WebAuthn::shouldReceive('validateAssertion')->once()->andThrow(new \RuntimeException('Invalid assertion'));
$this
->actingAs($this->user)
->postJson('/cp/elevated-session', array_merge($payload, ['rawId' => 'raw-id', 'response' => [], 'type' => 'public-key']))
->assertStatus(500)
->assertSessionMissing('statamic_elevated_session');
}
public static function invalidPasskeyPayloads(): array
{
return [
'no fields' => [[], true],
'string zero' => [['id' => '0'], false],
'integer zero' => [['id' => 0], false],
'false' => [['id' => false], false],
'empty string' => [['id' => ''], true],
'null' => [['id' => null], true],
];
}
#[Test]
public function middleware_allows_request()
{
$this->actingAs($this->user);
$this
->withElevatedSession()
->get('/requires-elevated-session')
->assertOk()
->assertSee('ok');
}
#[Test]
public function middleware_denies_request_when_elevated_session_has_expired()
{
$this->actingAs($this->user);
$this
->withElevatedSession(now()->subMinutes(16))
->get('/requires-elevated-session')
->assertRedirect('/cp/auth/confirm-password');
}
#[Test]
public function middleware_denies_request_when_elevated_session_has_expired_via_json()
{
$this->actingAs($this->user);
$this
->withElevatedSession(now()->subMinutes(16))
->getJson('/requires-elevated-session')
->assertStatus(403)
->assertJson(['message' => __('Requires an elevated session.')]);
}
#[Test]
public function middleware_does_not_require_elevated_session_when_elevated_session_is_disabled()
{
config(['statamic.users.elevated_sessions_enabled' => false]);
$this->actingAs($this->user);
$this
->get('/requires-elevated-session')
->assertOk()
->assertSee('ok');
}
#[Test]
public function middleware_does_not_require_elevated_session_when_elevated_session_is_disabled_even_if_session_expired()
{
config(['statamic.users.elevated_sessions_enabled' => false]);
$this->actingAs($this->user);
$this
->withElevatedSession(now()->subMinutes(16))
->get('/requires-elevated-session')
->assertOk()
->assertSee('ok');
}
#[Test]
public function middleware_does_not_require_elevated_session_when_elevated_session_is_disabled_via_json()
{
config(['statamic.users.elevated_sessions_enabled' => false]);
$this->actingAs($this->user);
$this
->withElevatedSession(now()->subMinutes(16))
->getJson('/requires-elevated-session')
->assertOk()
->assertSee('ok');
}
#[Test]
public function the_session_is_elevated_upon_login()
{
$this
->post(cp_route('login'), [
'email' => 'foo@bar.com',
'password' => 'secret',
])
->assertRedirectToRoute('statamic.cp.index');
$this
->get('/requires-elevated-session')
->assertOk();
}
#[Test]
public function the_session_is_elevated_upon_login_with_oauth()
{
$this->markTestIncomplete('Implementation is done but is missing a test.');
}
#[Test]
public function the_verification_code_will_be_sent_for_passwordless_user_when_loading_the_form()
{
Notification::fake();
Str::createRandomStringsUsing(fn () => 'abc');
$this
->actingAs($user = tap(User::make()->email('foo@bar.com')->makeSuper())->save())
->get(cp_route('confirm-password'))
->assertSessionHas('statamic_elevated_session_verification_code', [
'code' => 'abc',
'generated_at' => now()->timestamp,
]);
Notification::assertSentTo($user, ElevatedSessionVerificationCode::class, function ($notification, $channels) {
return $notification->verificationCode === 'abc';
});
}
#[Test]
public function the_verification_code_will_be_sent_for_passwordless_user_when_loading_the_form_once()
{
Notification::fake();
Str::createRandomStringsUsing(fn () => 'abc');
$user = tap(User::make()->email('foo@bar.com')->makeSuper())->save();
$request = function () use ($user) {
return $this
->actingAs($user)
->get(cp_route('confirm-password'));
};
$request(); // Sent.
$request(); // Within 5-minute window. Not sent.
$this->travel(30)->seconds();
$request(); // Still within 5-minute window. Not sent.
$this->travel(5)->minute();
$request(); // Outside 5 minutes. Sent.
Notification::assertCount(2);
}
#[Test]
public function the_verification_code_can_be_resent()
{
Notification::fake();
Str::createRandomStringsUsing(fn () => 'abc');
$this
->actingAs($user = User::make()->email('foo@bar.com')->makeSuper())
->from('/original')
->get(cp_route('elevated-session.resend-code'))
->assertRedirect('/original')
->assertSessionHas('success')
->assertSessionHas('statamic_elevated_session_verification_code', [
'code' => 'abc',
'generated_at' => now()->timestamp,
]);
Notification::assertSentTo($user, ElevatedSessionVerificationCode::class, function ($notification, $channels) {
return $notification->verificationCode === 'abc';
});
}
#[Test]
public function resending_code_is_rate_limited()
{
Notification::fake();
$user = User::make()->email('foo@bar.com')->makeSuper();
$request = function () use ($user) {
return $this
->actingAs($user)
->from('/original')
->get(cp_route('elevated-session.resend-code'));
};
$request()->assertRedirect('/original')->assertSessionHas('success');
$request()->assertRedirect('/original')->assertSessionHas('error', 'Try again in a minute.');
$this->travel(30)->seconds();
$request()->assertRedirect('/original')->assertSessionHas('error', 'Try again in a minute.');
$this->travel(1)->minute();
$request()->assertRedirect('/original')->assertSessionHas('success');
Notification::assertCount(2);
}
#[Test]
public function the_verification_code_will_not_be_sent_if_the_user_has_a_password()
{
Notification::fake();
Str::createRandomStringsUsing(fn () => 'abc');
$this
->actingAs($this->user)
->from('/original')
->get(cp_route('elevated-session.resend-code'))
->assertSessionHasErrors(['method' => 'Resend code is only available for verification code method'])
->assertSessionMissing('statamic_elevated_session_verification_code');
Notification::assertNothingSent();
}
#[Test]
public function it_returns_passkey_method_when_config_is_false_and_user_has_passkeys()
{
config(['statamic.webauthn.allow_password_login_with_passkey' => false]);
$mockPasskey = Mockery::mock(Passkey::class);
$mockCollection = collect(['passkey-123' => $mockPasskey]);
$user = tap(User::make()->email('foo@bar.com')->makeSuper()->password('secret'))->save();
// Use reflection to set the passkeys property
$reflection = new \ReflectionClass($user);
$property = $reflection->getProperty('passkeys');
$property->setValue($user, $mockCollection);
$this->assertEquals('passkey', $user->getElevatedSessionMethod());
}
#[Test]
public function it_returns_password_confirmation_method_when_config_is_true_even_with_passkeys()
{
config(['statamic.webauthn.allow_password_login_with_passkey' => true]);
$mockPasskey = Mockery::mock(Passkey::class);
$mockCollection = collect(['passkey-123' => $mockPasskey]);
$user = tap(User::make()->email('foo@bar.com')->makeSuper()->password('secret'))->save();
// Use reflection to set the passkeys property
$reflection = new \ReflectionClass($user);
$property = $reflection->getProperty('passkeys');
$property->setValue($user, $mockCollection);
$this->assertEquals('password_confirmation', $user->getElevatedSessionMethod());
}
#[Test]
public function it_returns_password_confirmation_when_user_has_no_passkeys_regardless_of_config()
{
config(['statamic.webauthn.allow_password_login_with_passkey' => false]);
$this->assertEquals('password_confirmation', $this->user->getElevatedSessionMethod());
}
#[Test]
public function it_returns_verification_code_when_no_password_and_no_passkeys()
{
config(['statamic.webauthn.allow_password_login_with_passkey' => false]);
$user = tap(User::make()->email('foo@bar.com')->makeSuper())->save();
$this->assertEquals('verification_code', $user->getElevatedSessionMethod());
}
#[Test]
public function it_can_get_passkey_options_for_elevated_session()
{
config(['statamic.webauthn.allow_password_login_with_passkey' => false]);
$mockPasskey = Mockery::mock(Passkey::class);
$mockCollection = collect(['passkey-123' => $mockPasskey]);
$user = $this->user;
// Use reflection to set the passkeys property
$reflection = new \ReflectionClass($user);
$property = $reflection->getProperty('passkeys');
$property->setValue($user, $mockCollection);
$response = $this
->actingAs($user)
->get(cp_route('elevated-session.passkey-options'))
->assertOk();
$data = $response->json();
$this->assertArrayHasKey('challenge', $data);
$this->assertNotNull(session('webauthn.challenge'));
}
#[Test]
public function it_can_start_elevated_session_with_passkey()
{
config(['statamic.webauthn.allow_password_login_with_passkey' => false]);
$mockPasskey = Mockery::mock(Passkey::class);
$mockCollection = collect(['passkey-123' => $mockPasskey]);
$user = $this->user;
// Use reflection to set the passkeys property
$reflection = new \ReflectionClass($user);
$property = $reflection->getProperty('passkeys');
$property->setValue($user, $mockCollection);
$credentials = [
'id' => 'credential-id',
'rawId' => 'raw-id',
'response' => [],
'type' => 'public-key',
];
WebAuthn::shouldReceive('validateAssertion')
->once()
->with($user, $credentials)
->andReturnTrue();
$this
->actingAs($user)
->postJson('/cp/elevated-session', $credentials)
->assertOk()
->assertJsonStructure(['elevated', 'expiry'])
->assertSessionHas('statamic_elevated_session', now()->timestamp);
}
#[Test]
public function status_endpoint_returns_passkey_method()
{
config(['statamic.webauthn.allow_password_login_with_passkey' => false]);
$mockPasskey = Mockery::mock(Passkey::class);
$mockCollection = collect(['passkey-123' => $mockPasskey]);
$user = $this->user;
// Use reflection to set the passkeys property
$reflection = new \ReflectionClass($user);
$property = $reflection->getProperty('passkeys');
$property->setValue($user, $mockCollection);
$this
->actingAs($user)
->get('/cp/elevated-session')
->assertOk()
->assertJson([
'elevated' => false,
'expiry' => null,
'method' => 'passkey',
]);
}
}