-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathclass-two-factor-core.php
More file actions
2734 lines (2224 loc) · 97.6 KB
/
Copy pathclass-two-factor-core.php
File metadata and controls
2734 lines (2224 loc) · 97.6 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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Two Factor Core Class Tests.
*
* @package Two_Factor
*/
/**
* Exception thrown when wp_redirect fires, to prevent exit() from terminating the test process.
*/
class Two_Factor_Redirect_Exception extends RuntimeException {}
/**
* Class Test_ClassTwoFactorCore
*
* @package Two_Factor
* @group core
*/
class Test_ClassTwoFactorCore extends WP_UnitTestCase {
/**
* Original User ID set in set_up().
*
* @var int
*/
private $old_user_id;
/**
* Set up error handling before test suite.
*
* @see WP_UnitTestCase_Base::set_up_before_class()
*/
public static function wpSetUpBeforeClass() {
set_error_handler( array( 'Test_ClassTwoFactorCore', 'error_handler' ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler
add_action( 'set_auth_cookie', array( __CLASS__, 'set_auth_cookie' ) );
add_action( 'set_logged_in_cookie', array( __CLASS__, 'set_logged_in_cookie' ) );
}
/**
* Clean up error settings after test suite.
*
* @see WP_UnitTestCase_Base::tear_down_after_class()
*/
public static function wpTearDownAfterClass() {
restore_error_handler();
remove_action( 'set_auth_cookie', array( __CLASS__, 'set_auth_cookie' ) );
remove_action( 'set_logged_in_cookie', array( __CLASS__, 'set_logged_in_cookie' ) );
}
/**
* Cleanup after each test.
*/
public function tearDown(): void {
parent::tearDown();
unset( $_COOKIE[ AUTH_COOKIE ], $_COOKIE[ LOGGED_IN_COOKIE ] );
// Remove the plugin's send_auth_cookies block that filter_authenticate installs,
// so it does not leak into subsequent tests that expect cookies to be settable.
remove_filter( 'send_auth_cookies', '__return_false', PHP_INT_MAX );
}
/**
* Print error messages and return true if error is a notice
*
* @param integer $errno error number.
* @param string $errstr error message text.
*
* @return boolean
*/
public static function error_handler( $errno, $errstr ) {
if ( E_USER_NOTICE !== $errno ) {
echo 'Received a non-notice error: ' . esc_html( $errstr );
return false;
}
return true;
}
/**
* Simulate the auth cookie having being sent.
*
* @param string $auth_cookie Auth cookie value.
*/
public static function set_auth_cookie( $auth_cookie ) {
$_COOKIE[ AUTH_COOKIE ] = $auth_cookie;
}
/**
* Simulate the logged_in cookie having being sent.
*
* @param string $logged_in_cookie Logged in cookie value.
*/
public static function set_logged_in_cookie( $logged_in_cookie ) {
$_COOKIE[ LOGGED_IN_COOKIE ] = $logged_in_cookie;
}
/**
* Get a dummy user object.
*
* @param array $meta_key authentication method.
*
* @return WP_User
*/
public function get_dummy_user( $meta_key = array( 'Two_Factor_Dummy' => 'Two_Factor_Dummy' ) ) {
$user = new WP_User( self::factory()->user->create() );
$this->old_user_id = get_current_user_id();
wp_set_current_user( $user->ID );
$key = '_nonce_user_two_factor_options';
$nonce = wp_create_nonce( 'user_two_factor_options' );
$_POST[ $key ] = $nonce;
$_REQUEST[ $key ] = $nonce;
$_POST[ Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY ] = $meta_key;
Two_Factor_Core::user_two_factor_options_update( $user->ID );
return $user;
}
/**
* Clean up the dummy user object data.
*/
public function clean_dummy_user() {
unset( $_POST[ Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY ] );
$key = '_nonce_user_two_factor_options';
unset( $_REQUEST[ $key ] );
unset( $_POST[ $key ] );
}
/**
* Run a callable that may call wp_safe_redirect() + exit.
*
* Intercepts the redirect via the wp_redirect filter to throw a
* Two_Factor_Redirect_Exception, preventing exit() from terminating the
* test process. Also captures and discards any output produced.
*
* @param callable $callback Code that may trigger a redirect.
* @return string|null The intercepted redirect URL, or null if no redirect occurred.
*/
private function do_redirect_callable( $callback ) {
$intercepted_url = null;
$redirect_filter = function ( $location ) {
throw new Two_Factor_Redirect_Exception( $location ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
};
add_filter( 'wp_redirect', $redirect_filter, PHP_INT_MAX );
ob_start();
try {
$callback();
} catch ( Two_Factor_Redirect_Exception $e ) {
$intercepted_url = $e->getMessage();
} finally {
ob_end_clean();
remove_filter( 'wp_redirect', $redirect_filter, PHP_INT_MAX );
}
return $intercepted_url;
}
/**
* Reset stored profile errors between tests.
*/
private function reset_profile_errors() {
$reflection = new ReflectionClass( Two_Factor_Core::class );
$prop = $reflection->getProperty( 'profile_errors' );
$prop->setAccessible( true );
$prop->setValue( null, array() );
}
/**
* Render the user two-factor settings UI and return the markup.
*
* @param WP_User $user User instance.
* @return string
*/
private function render_user_two_factor_options( WP_User $user ) {
$this->reset_profile_errors();
ob_start();
Two_Factor_Core::user_two_factor_options( $user );
return ob_get_clean();
}
/**
* Verify adding hooks.
*
* @covers Two_Factor_Core::add_hooks
*/
public function test_add_hooks() {
Two_Factor_Core::add_hooks( new Two_Factor_Compat() );
$this->assertGreaterThan(
0,
has_action(
'init',
array( 'Two_Factor_Core', 'get_providers' )
)
);
$this->assertGreaterThan(
0,
has_action(
'login_form_validate_2fa',
array( 'Two_Factor_Core', 'login_form_validate_2fa' )
)
);
}
/**
* Verify provider list is not empty.
*
* @covers Two_Factor_Core::get_providers
*/
public function test_get_providers_not_empty() {
$this->assertNotEmpty( Two_Factor_Core::get_providers() );
}
/**
* Verify provider class exists.
*
* @covers Two_Factor_Core::get_providers
*/
public function test_get_providers_class_exists() {
$result = Two_Factor_Core::get_providers();
foreach ( array_keys( $result ) as $class ) {
$this->assertNotNull( class_exists( $class ) );
}
}
/**
* Test fetching user functionality.
*
* @covers Two_Factor_Core::fetch_user
*/
public function test_fetch_user() {
$this->assertFalse( Two_Factor_Core::fetch_user( null ) );
$logged_in = self::factory()->user->create_and_get();
wp_set_current_user( $logged_in->ID );
$fetched = Two_Factor_Core::fetch_user( null );
$this->assertSame( $logged_in->ID, $fetched->ID );
$logged_out = self::factory()->user->create_and_get();
$fetched = Two_Factor_Core::fetch_user( $logged_out->ID );
$this->assertSame( $logged_out->ID, $fetched->ID );
$fetched = Two_Factor_Core::fetch_user( $logged_out );
$this->assertSame( $logged_out->ID, $fetched->ID );
}
/**
* Verify enabled providers for non-logged-in user.
*
* @covers Two_Factor_Core::get_enabled_providers_for_user
*/
public function test_get_enabled_providers_for_user_not_logged_in() {
$this->assertEmpty( Two_Factor_Core::get_enabled_providers_for_user() );
}
/**
* Verify enabled providers for logged-in user.
*
* @covers Two_Factor_Core::get_enabled_providers_for_user
*/
public function test_get_enabled_providers_for_user_logged_in() {
$user = new WP_User( self::factory()->user->create() );
$old_user_id = get_current_user_id();
wp_set_current_user( $user->ID );
$this->assertEmpty( Two_Factor_Core::get_enabled_providers_for_user() );
wp_set_current_user( $old_user_id );
}
/**
* Verify enabled providers for logged-in user and set provider.
*
* @covers Two_Factor_Core::get_enabled_providers_for_user
* @covers Two_Factor_Core::get_available_providers_for_user
* @covers Two_Factor_Core::user_two_factor_options_update
* @covers Two_Factor_Core::fetch_user
*/
public function test_get_enabled_providers_for_user_logged_in_and_set_provider() {
$user = $this->get_dummy_user();
$this->assertCount( 1, Two_Factor_Core::get_available_providers_for_user( $user->ID ) );
$this->assertCount( 1, Two_Factor_Core::get_enabled_providers_for_user( $user->ID ) );
// Revert back to the previous user.
wp_set_current_user( $this->old_user_id );
// Verify the counts are still correct for that user ID.
$this->assertCount( 1, Two_Factor_Core::get_available_providers_for_user( $user->ID ) );
$this->assertCount( 1, Two_Factor_Core::get_enabled_providers_for_user( $user->ID ) );
$this->clean_dummy_user();
}
/**
* Verify enabled providers for invalid input is empty.
*
* @covers Two_Factor_Core::get_enabled_providers_for_user
* @covers Two_Factor_Core::get_available_providers_for_user
* @covers Two_Factor_Core::user_two_factor_options_update
* @covers Two_Factor_Core::fetch_user
*/
public function test_get_enabled_providers_for_user_bad_input() {
$user = $this->get_dummy_user();
$this->assertCount( 1, Two_Factor_Core::get_available_providers_for_user( $user->ID ) );
$this->assertCount( 1, Two_Factor_Core::get_enabled_providers_for_user( $user->ID ) );
// Check that checking for an invalid input returns 0.
$this->assertCount( 0, Two_Factor_Core::get_available_providers_for_user( 'bad-input' ) );
$this->assertCount( 0, Two_Factor_Core::get_enabled_providers_for_user( 'bad-input' ) );
$this->clean_dummy_user();
}
/**
* Verify enabled providers for logged-in user and set incorrect provider.
*
* @covers Two_Factor_Core::get_enabled_providers_for_user
* @covers Two_Factor_Core::get_available_providers_for_user
* @covers Two_Factor_Core::user_two_factor_options_update
*/
public function test_get_enabled_providers_for_user_logged_in_and_set_provider_bad_enabled() {
$user = $this->get_dummy_user( 'test_badness' );
$this->assertEmpty( Two_Factor_Core::get_available_providers_for_user( $user->ID ) );
$this->assertEmpty( Two_Factor_Core::get_enabled_providers_for_user( $user->ID ) );
wp_set_current_user( $this->old_user_id );
$this->clean_dummy_user();
}
/**
* Verify available providers for not-logged-in user.
*
* @covers Two_Factor_Core::get_available_providers_for_user
*/
public function test_get_available_providers_for_user_not_logged_in() {
$this->assertEmpty( Two_Factor_Core::get_available_providers_for_user() );
}
/**
* Verify available providers for logged-in user.
*
* @covers Two_Factor_Core::get_available_providers_for_user
*/
public function test_get_available_providers_for_user_logged_in() {
$user = new WP_User( self::factory()->user->create() );
$old_user_id = get_current_user_id();
wp_set_current_user( $user->ID );
$this->assertEmpty( Two_Factor_Core::get_available_providers_for_user() );
wp_set_current_user( $old_user_id );
}
/**
* Verify that if a user has a non-existent provider set, that it
* swaps to email instead, rather than treating the user as having
* no methods enabled.
*/
public function test_deprecated_provider_for_user() {
$user = $this->get_dummy_user();
// Set the dummy user with a non-existent provider.
update_user_meta(
$user->ID,
Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY,
array(
'Two_Factor_Deprecated',
)
);
// This should fail back to `Two_Factor_Email` then.
$this->assertEquals(
array(
'Two_Factor_Email',
),
array_keys( Two_Factor_Core::get_available_providers_for_user( $user ) )
);
// Set the dummy user with a non-existent provider and a valid one.
update_user_meta(
$user->ID,
Two_Factor_Core::ENABLED_PROVIDERS_USER_META_KEY,
array(
'Two_Factor_Deprecated',
'Two_Factor_Dummy',
)
);
// This time it should just strip out the invalid one, and not inject a new one.
$this->assertEquals(
array(
'Two_Factor_Dummy',
),
array_keys( Two_Factor_Core::get_available_providers_for_user( $user ) )
);
$this->clean_dummy_user();
}
/**
* Verify primary provider for not-logged-in user.
*
* @covers Two_Factor_Core::get_primary_provider_for_user
*/
public function test_get_primary_provider_for_user_not_logged_in() {
$this->assertEmpty( Two_Factor_Core::get_primary_provider_for_user() );
}
/**
* Verify not-logged-in-user is using two facator.
*
* @covers Two_Factor_Core::is_user_using_two_factor
*/
public function test_is_user_using_two_factor_not_logged_in() {
$this->assertFalse( Two_Factor_Core::is_user_using_two_factor() );
}
/**
* Verify the login URL.
*
* @covers Two_Factor_Core::login_url
*/
public function test_login_url() {
$this->assertStringContainsString( 'wp-login.php', Two_Factor_Core::login_url() );
$this->assertStringContainsString(
'paramencoded=%2F%3D1',
Two_Factor_Core::login_url(
array(
'paramencoded' => '/=1',
)
)
);
}
/**
* Verify user API log is enabled (when disabled by default).
*
* @covers Two_Factor_Core::is_user_api_login_enabled
*/
public function test_user_api_login_is_disabled_by_default() {
$user_id = self::factory()->user->create();
$this->assertFalse( Two_Factor_Core::is_user_api_login_enabled( $user_id ) );
}
/**
* Verify user API log is can be enabled by filter.
*
* @covers Two_Factor_Core::is_user_api_login_enabled
*/
public function test_user_api_login_can_be_enabled_via_filter() {
$user_id_default = self::factory()->user->create();
$user_id_enabled = self::factory()->user->create();
add_filter(
'two_factor_user_api_login_enable',
function ( $enabled, $user_id ) use ( $user_id_enabled ) {
return ( $user_id === $user_id_enabled );
},
10,
2
);
$this->assertTrue(
Two_Factor_Core::is_user_api_login_enabled( $user_id_enabled ),
'Filters allows specific users to enable API login'
);
$this->assertFalse(
Two_Factor_Core::is_user_api_login_enabled( $user_id_default ),
'Filter doesnot impact other users'
);
// Undo all filters.
remove_all_filters( 'two_factor_user_api_login_enable', 10 );
}
/**
* Verify request is not an API request.
*
* @covers Two_Factor_Core::is_api_request
*/
public function test_is_api_request() {
$this->assertFalse( Two_Factor_Core::is_api_request() );
}
/**
* Verify authentication filters.
*
* @covers Two_Factor_Core::filter_authenticate
*/
public function test_filter_authenticate() {
$user_default = new WP_User( self::factory()->user->create() );
$user_2fa_enabled = $this->get_dummy_user(); // User with a dummy two-factor method enabled.
$this->assertFalse( Two_Factor_Core::is_api_request(), 'Is not an API request by default' );
// The WP test framework registers __return_false on send_auth_cookies at priority 10 to
// prevent real cookies from being set during tests. Check for the plugin's specific
// __return_false callback at PHP_INT_MAX (see Two_Factor_Core::filter_authenticate).
$has_plugin_cookie_block = function () {
global $wp_filter;
if (
! isset( $wp_filter['send_auth_cookies'] ) ||
! $wp_filter['send_auth_cookies'] instanceof WP_Hook ||
empty( $wp_filter['send_auth_cookies']->callbacks[ PHP_INT_MAX ] )
) {
return false;
}
foreach ( $wp_filter['send_auth_cookies']->callbacks[ PHP_INT_MAX ] as $cb ) {
if ( '__return_false' === $cb['function'] ) {
return true;
}
}
return false;
};
$this->assertFalse(
$has_plugin_cookie_block(),
'Auth cookie block not registered before the `authenticate` filter has run.'
);
Two_Factor_Core::filter_authenticate( $user_default );
$this->assertFalse(
$has_plugin_cookie_block(),
'User login without 2fa should not block auth cookies.'
);
Two_Factor_Core::filter_authenticate( $user_2fa_enabled );
$this->assertTrue(
$has_plugin_cookie_block(),
'User login with 2fa should block auth cookies.'
);
}
/**
* Verify authentication filters.
*
* @covers Two_Factor_Core::filter_authenticate
* @covers Two_Factor_Core::is_api_request
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function test_filter_authenticate_api() {
$user_default = new WP_User( self::factory()->user->create() );
$user_2fa_enabled = $this->get_dummy_user(); // User with a dummy two-factor method enabled.
// TODO: Get Two_Factor_Core away from static methods to allow mocking this.
// Guard against re-definition if the constant is already set in this process.
if ( ! defined( 'XMLRPC_REQUEST' ) ) {
define( 'XMLRPC_REQUEST', true );
}
$this->assertTrue( Two_Factor_Core::is_api_request(), 'Can detect an API request' );
$this->assertInstanceOf(
WP_User::class,
Two_Factor_Core::filter_authenticate( $user_default ),
'Non-2FA user should be able to authenticate during API requests'
);
$this->assertInstanceOf(
WP_Error::class,
Two_Factor_Core::filter_authenticate( $user_2fa_enabled ),
'2FA user should not be able to authenticate during API requests'
);
}
/**
* Verify destruction of auth session.
*
* @covers Two_Factor_Core::destroy_current_session_for_user
* @covers Two_Factor_Core::collect_auth_cookie_tokens
*/
public function test_can_distroy_auth_sessions() {
$user_id = self::factory()->user->create(
array(
'user_login' => 'username',
'user_pass' => 'password',
)
);
$user = new WP_User( $user_id );
$session_manager = WP_Session_Tokens::get_instance( $user_id );
$this->assertCount( 0, $session_manager->get_all(), 'No user sessions are present first' );
$user_authenticated = wp_signon(
array(
'user_login' => 'username',
'user_password' => 'password',
)
);
$this->assertEquals( $user_authenticated, $user, 'User can authenticate' );
$this->assertCount( 1, $session_manager->get_all(), 'Can fetch the authenticated session' );
// Create one extra session which shouldn't be destroyed.
$session_manager->create( time() + 60 * 60 );
$this->assertCount( 2, $session_manager->get_all(), 'Can fetch active sessions' );
// Now clear all active password-based sessions.
Two_Factor_Core::destroy_current_session_for_user( $user );
$this->assertCount( 1, $session_manager->get_all(), 'All known authentication sessions have been destroyed' );
// Cleanup for the rest.
$session_manager->destroy_all();
}
/**
* Test invalid hash input fails.
*
* @covers Two_Factor_Core::create_login_nonce()
* @covers Two_Factor_Core::hash_login_nonce()
*/
public function test_invalid_hash_input_fails() {
$nonce = Two_Factor_Core::create_login_nonce( NAN );
$this->assertFalse( $nonce );
$this->assertNotEmpty( json_last_error() );
}
/**
* Test create login nonce.
*
* @covers Two_Factor_Core::create_login_nonce()
* @covers Two_Factor_Core::hash_login_nonce()
*/
public function test_create_login_nonce() {
$user = self::factory()->user->create_and_get();
$plain_nonce = Two_Factor_Core::create_login_nonce( $user->ID );
$hashed_nonce = get_user_meta( $user->ID, Two_Factor_Core::USER_META_NONCE_KEY, true );
$plain_key_length = strlen( $plain_nonce['key'] );
$hashed_key_length = strlen( $hashed_nonce['key'] );
$this->assertSame( $user->ID, $plain_nonce['user_id'] );
$this->assertGreaterThan( time() + ( 9 * MINUTE_IN_SECONDS ), $plain_nonce['expiration'] );
$this->assertIsString( $plain_nonce['key'] );
$this->assertTrue( 64 === $plain_key_length || 32 === $plain_key_length );
$this->assertSame( $plain_nonce['expiration'], $hashed_nonce['expiration'] );
$this->assertIsString( $hashed_nonce['key'] );
$this->assertTrue( 32 === $hashed_key_length );
$this->assertNotEquals( $plain_nonce['key'], $hashed_nonce['key'] );
}
/**
* Check if nonce can be verified.
*
* @covers Two_Factor_Core::create_login_nonce()
* @covers Two_Factor_Core::verify_login_nonce()
*/
public function test_can_verify_login_nonce() {
$user_id = 123456;
$nonce = Two_Factor_Core::create_login_nonce( $user_id );
$this->assertNotEmpty( $nonce['key'], 'Nonce key is present' );
$this->assertNotEmpty( $nonce['expiration'], 'Nonce expiration is set' );
$this->assertGreaterThan( time(), $nonce['expiration'], 'Nonce expiration is in the future' );
$this->assertLessThan( time() + ( 10 * MINUTE_IN_SECONDS ) + 1, $nonce['expiration'], 'Nonce expiration is not more than 10 minutes' );
$this->assertTrue(
Two_Factor_Core::verify_login_nonce( $user_id, $nonce['key'] ),
'Can verify login nonce'
);
$this->assertFalse(
Two_Factor_Core::verify_login_nonce( $user_id, '1234' ),
'Invalid nonce is invalid'
);
// Must create a new one since incorrect nonces deletes them.
$nonce = Two_Factor_Core::create_login_nonce( $user_id );
// Mark the nonce as expired.
$nonce_in_meta = get_user_meta( $user_id, Two_Factor_Core::USER_META_NONCE_KEY, true );
$nonce_in_meta['expiration'] = time() - 1;
update_user_meta( $user_id, Two_Factor_Core::USER_META_NONCE_KEY, $nonce_in_meta );
$this->assertFalse(
Two_Factor_Core::verify_login_nonce( $user_id, $nonce['key'] ),
'Expired nonce is invalid'
);
}
/**
* Invalid nonce deletes the valid nonce.
*
* @covers Two_Factor_Core::verify_login_nonce()
*/
public function test_invalid_nonce_deletes_valid_nonce() {
$user_id = 123456;
$nonce = Two_Factor_Core::create_login_nonce( $user_id );
$this->assertFalse(
Two_Factor_Core::verify_login_nonce( $user_id, '1234' ),
'Invalid nonce is invalid'
);
$this->assertFalse(
Two_Factor_Core::verify_login_nonce( $user_id, $nonce['key'] ),
'The correct nonce is not accepted after an invalid has been attempted'
);
}
/**
* Test that the lockout time delay for two factor attempts is respected.
*
* @covers Two_Factor_Core::get_user_time_delay()
*/
public function test_get_user_time_delay() {
$user = $this->get_dummy_user();
// Default values, sans filters.
$rate_limit = 1;
$max_rate_limit = 15 * MINUTE_IN_SECONDS;
// User has never logged in, validate the minimum time delay is in play.
$this->assertEquals( $rate_limit, Two_Factor_Core::get_user_time_delay( $user ) );
// Simulate 5 failed login attempts, and validate that the lockout is as expected.
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 5 );
$this->assertEquals( pow( 2, 5 ) * $rate_limit, Two_Factor_Core::get_user_time_delay( $user ) );
// Simulate 100 failed login attempts, validate that the lockout is not greater than $max_rate_limit.
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 100 );
$this->assertEquals( $max_rate_limit, Two_Factor_Core::get_user_time_delay( $user ) );
}
/**
* Test that the user rate limit functions return as expected.
*
* @covers Two_Factor_Core::is_user_rate_limited()
*/
public function test_is_user_rate_limited() {
$user = $this->get_dummy_user();
// User has never logged in, validate they're not rate limited.
$this->assertFalse( Two_Factor_Core::is_user_rate_limited( $user ) );
// Failed login attempt at time(), user should be rate limited.
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 1 );
update_user_meta( $user->ID, Two_Factor_Core::USER_RATE_LIMIT_KEY, time() );
$this->assertTrue( Two_Factor_Core::is_user_rate_limited( $user ) );
// 8 failed logins a minite ago, user should be rate limited.
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 8 );
update_user_meta( $user->ID, Two_Factor_Core::USER_RATE_LIMIT_KEY, time() - MINUTE_IN_SECONDS );
$this->assertTrue( Two_Factor_Core::is_user_rate_limited( $user ) );
// 8 failed logins an hour ago, user should not be rate limited.
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 8 );
update_user_meta( $user->ID, Two_Factor_Core::USER_RATE_LIMIT_KEY, time() - HOUR_IN_SECONDS );
$this->assertFalse( Two_Factor_Core::is_user_rate_limited( $user ) );
}
/**
* Test that clearing the login rate limit removes the throttle state.
*
* @covers Two_Factor_Core::clear_login_rate_limit
*/
public function test_clear_login_rate_limit() {
$user = $this->get_dummy_user();
// Put the user into a rate-limited state.
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 5 );
update_user_meta( $user->ID, Two_Factor_Core::USER_RATE_LIMIT_KEY, time() );
$this->assertTrue( Two_Factor_Core::is_user_rate_limited( $user ) );
Two_Factor_Core::clear_login_rate_limit( $user );
$this->assertFalse( Two_Factor_Core::is_user_rate_limited( $user ) );
$this->assertEmpty( get_user_meta( $user->ID, Two_Factor_Core::USER_RATE_LIMIT_KEY, true ) );
$this->assertEmpty( get_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, true ) );
// Clearing an already-clean user is a harmless no-op.
Two_Factor_Core::clear_login_rate_limit( $user );
$this->assertFalse( Two_Factor_Core::is_user_rate_limited( $user ) );
}
/**
* Test that the "invalid login attempts have occurred" login notice works as expected.
*
* @covers Two_Factor_Core::maybe_show_last_login_failure_notice()
*/
public function test_maybe_show_last_login_failure_notice() {
$user = $this->get_dummy_user();
// User has never logged in, validate they're not rate limited.
ob_start();
Two_Factor_Core::maybe_show_last_login_failure_notice( $user );
$contents = ob_get_clean();
$this->assertEmpty( $contents );
// A failed login attempts 5 seconds ago.
// Should throw a notice, even though it's the current user, it will only be displayed if there's no other 2FA errors.
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 1 );
update_user_meta( $user->ID, Two_Factor_Core::USER_RATE_LIMIT_KEY, time() - 5 );
ob_start();
Two_Factor_Core::maybe_show_last_login_failure_notice( $user );
$contents = ob_get_clean();
$this->assertNotEmpty( $contents );
$this->assertStringNotContainsString( '1 times', $contents );
$this->assertStringContainsString( 'attempted to login', $contents );
$this->assertStringContainsString( 'without providing a valid two factor token', $contents );
// 5 failed login attempts 5 hours ago - User should be informed.
$five_hours_ago = time() - 5 * HOUR_IN_SECONDS;
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 5 );
update_user_meta( $user->ID, Two_Factor_Core::USER_RATE_LIMIT_KEY, $five_hours_ago );
ob_start();
Two_Factor_Core::maybe_show_last_login_failure_notice( $user );
$contents = ob_get_clean();
$this->assertNotEmpty( $contents );
$this->assertStringContainsString( '5 times', $contents );
$this->assertStringContainsString( human_time_diff( $five_hours_ago ), $contents );
}
/**
* Test no reset notice when no errors.
*
* @covers Two_Factor_Core::maybe_show_reset_password_notice()
*/
public function test_no_reset_notice_when_no_errors() {
$errors = new WP_Error();
Two_Factor_Core::maybe_show_reset_password_notice( $errors );
$this->assertCount( 0, $errors->get_error_codes() );
}
/**
* Test no reset notice when different error.
*
* @covers Two_Factor_Core::maybe_show_reset_password_notice()
*/
public function test_no_reset_notice_when_different_error() {
$errors = new WP_Error( 'foo_bar', 'Foo Bar' );
Two_Factor_Core::maybe_show_reset_password_notice( $errors );
$this->assertCount( 1, $errors->get_error_codes() );
$this->assertSame( 'foo_bar', $errors->get_error_code() );
}
/**
* Test no reset notice when password not reset.
*
* @covers Two_Factor_Core::maybe_show_reset_password_notice()
*/
public function test_no_reset_notice_when_password_not_reset() {
$user = self::factory()->user->create_and_get();
$errors = new WP_Error( 'incorrect_password', 'Incorrect password' );
$_POST['log'] = $user->user_login;
Two_Factor_Core::maybe_show_reset_password_notice( $errors );
$this->assertCount( 1, $errors->get_error_codes() );
$this->assertSame( 'incorrect_password', $errors->get_error_code() );
}
/**
* Test reset notice when password was reset.
*
* @covers Two_Factor_Core::maybe_show_reset_password_notice()
*/
public function test_reset_notice_when_password_was_reset() {
$user = self::factory()->user->create_and_get();
$errors = new WP_Error( 'incorrect_password', 'Incorrect password' );
$_POST['log'] = $user->user_login;
update_user_meta( $user->ID, Two_Factor_Core::USER_PASSWORD_WAS_RESET_KEY, true );
Two_Factor_Core::maybe_show_reset_password_notice( $errors );
$this->assertCount( 1, $errors->get_error_codes() );
$this->assertSame( 'two_factor_password_reset', $errors->get_error_code() );
}
/**
* Test no reset notice when _wpnonce is present but invalid.
*
* @covers Two_Factor_Core::maybe_show_reset_password_notice()
*/
public function test_no_reset_notice_when_wpnonce_invalid() {
$user = self::factory()->user->create_and_get();
$errors = new WP_Error( 'incorrect_password', 'Incorrect password' );
$_POST['log'] = $user->user_login;
$_POST['_wpnonce'] = 'invalid-nonce';
update_user_meta( $user->ID, Two_Factor_Core::USER_PASSWORD_WAS_RESET_KEY, true );
Two_Factor_Core::maybe_show_reset_password_notice( $errors );
$this->assertCount( 1, $errors->get_error_codes() );
$this->assertSame( 'incorrect_password', $errors->get_error_code() );
unset( $_POST['_wpnonce'] );
}
/**
* Test reset notice when _wpnonce is present and valid for log-in.
*
* @covers Two_Factor_Core::maybe_show_reset_password_notice()
*/
public function test_reset_notice_when_wpnonce_valid() {
$user = self::factory()->user->create_and_get();
$errors = new WP_Error( 'incorrect_password', 'Incorrect password' );
$_POST['log'] = $user->user_login;
$_POST['_wpnonce'] = wp_create_nonce( 'log-in' );
update_user_meta( $user->ID, Two_Factor_Core::USER_PASSWORD_WAS_RESET_KEY, true );
Two_Factor_Core::maybe_show_reset_password_notice( $errors );
$this->assertCount( 1, $errors->get_error_codes() );
$this->assertSame( 'two_factor_password_reset', $errors->get_error_code() );
unset( $_POST['_wpnonce'] );
}
/**
* Test clear password reset notice.
*
* @covers Two_Factor_Core::clear_password_reset_notice()
*/
public function test_clear_password_reset_notice() {
$user = self::factory()->user->create_and_get();
update_user_meta( $user->ID, Two_Factor_Core::USER_PASSWORD_WAS_RESET_KEY, true );
Two_Factor_Core::clear_password_reset_notice( $user );
$this->assertEmpty( get_user_meta( $user->ID, Two_Factor_Core::USER_PASSWORD_WAS_RESET_KEY, true ) );
}
/**
* Test should reset password.
*
* @covers Two_Factor_Core::should_reset_password()
*/
public function test_should_reset_password() {
$user = self::factory()->user->create_and_get();
// Test default limit.
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 29 );
$this->assertFalse( Two_Factor_Core::should_reset_password( $user->ID ) );
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 30 );
$this->assertTrue( Two_Factor_Core::should_reset_password( $user->ID ) );
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 31 );
$this->assertTrue( Two_Factor_Core::should_reset_password( $user->ID ) );
// Test filtered limit.
$strict_limit = function () {
return 7;
};
add_filter( 'two_factor_failed_attempt_limit', $strict_limit );
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 6 );
$this->assertFalse( Two_Factor_Core::should_reset_password( $user->ID ) );
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 7 );
$this->assertTrue( Two_Factor_Core::should_reset_password( $user->ID ) );
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 8 );
$this->assertTrue( Two_Factor_Core::should_reset_password( $user->ID ) );
remove_filter( 'two_factor_failed_attempt_limit', $strict_limit );
}
/**
* Resetting a password should change the password and notify the user and admin.
*
* @covers Two_Factor_Core::reset_compromised_password()
*/
public function test_reset_compromised_password() {
$user = self::factory()->user->create_and_get();
$old_hash = $user->user_pass;
// Simulate entered password but failed 2FA too many times.
Two_Factor_Core::create_login_nonce( $user->ID );
update_user_meta( $user->ID, Two_Factor_Core::USER_RATE_LIMIT_KEY, time() );
update_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, 30 );
Two_Factor_Core::reset_compromised_password( $user );
$user = get_user_by( 'id', $user->ID );
$this->assertNotSame( $old_hash, $user->user_pass );
$this->assertSame( '1', get_user_meta( $user->ID, Two_Factor_Core::USER_PASSWORD_WAS_RESET_KEY, true ) );
$this->assertEmpty( get_user_meta( $user->ID, Two_Factor_Core::USER_META_NONCE_KEY, true ) );
$this->assertEmpty( get_user_meta( $user->ID, Two_Factor_Core::USER_RATE_LIMIT_KEY, false ) );
$this->assertEmpty( get_user_meta( $user->ID, Two_Factor_Core::USER_FAILED_LOGIN_ATTEMPTS_KEY, false ) );
}
/**
* Test both password reset notifications sent.
*
* @covers Two_Factor_Core::send_password_reset_emails()