-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
AuthManager.php
2473 lines (2246 loc) 路 83.9 KB
/
AuthManager.php
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
/**
* Authentication (and possibly Authorization in the future) system entry point
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Auth
*/
namespace MediaWiki\Auth;
use Config;
use MediaWiki\MediaWikiServices;
use MediaWiki\Permissions\PermissionManager;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Status;
use StatusValue;
use User;
use WebRequest;
use Wikimedia\ObjectFactory;
/**
* This serves as the entry point to the authentication system.
*
* In the future, it may also serve as the entry point to the authorization
* system.
*
* If you are looking at this because you are working on an extension that creates its own
* login or signup page, then 1) you really shouldn't do that, 2) if you feel you absolutely
* have to, subclass AuthManagerSpecialPage or build it on the client side using the clientlogin
* or the createaccount API. Trying to call this class directly will very likely end up in
* security vulnerabilities or broken UX in edge cases.
*
* If you are working on an extension that needs to integrate with the authentication system
* (e.g. by providing a new login method, or doing extra permission checks), you'll probably
* need to write an AuthenticationProvider.
*
* If you want to create a "reserved" user programmatically, User::newSystemUser() might be what
* you are looking for. If you want to change user data, use User::changeAuthenticationData().
* Code that is related to some SessionProvider or PrimaryAuthenticationProvider can
* create a (non-reserved) user by calling AuthManager::autoCreateUser(); it is then the provider's
* responsibility to ensure that the user can authenticate somehow (see especially
* PrimaryAuthenticationProvider::autoCreatedAccount()). The same functionality can also be used
* from Maintenance scripts such as createAndPromote.php.
* If you are writing code that is not associated with such a provider and needs to create accounts
* programmatically for real users, you should rethink your architecture. There is no good way to
* do that as such code has no knowledge of what authentication methods are enabled on the wiki and
* cannot provide any means for users to access the accounts it would create.
*
* The two main control flows when using this class are as follows:
* * Login, user creation or account linking code will call getAuthenticationRequests(), populate
* the requests with data (by using them to build a HTMLForm and have the user fill it, or by
* exposing a form specification via the API, so that the client can build it), and pass them to
* the appropriate begin* method. That will return either a success/failure response, or more
* requests to fill (either by building a form or by redirecting the user to some external
* provider which will send the data back), in which case they need to be submitted to the
* appropriate continue* method and that step has to be repeated until the response is a success
* or failure response. AuthManager will use the session to maintain internal state during the
* process.
* * Code doing an authentication data change will call getAuthenticationRequests(), select
* a single request, populate it, and pass it to allowsAuthenticationDataChange() and then
* changeAuthenticationData(). If the data change is user-initiated, the whole process needs
* to be preceded by a call to securitySensitiveOperationStatus() and aborted if that returns
* a non-OK status.
*
* @ingroup Auth
* @since 1.27
* @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
*/
class AuthManager implements LoggerAwareInterface {
/** Log in with an existing (not necessarily local) user */
public const ACTION_LOGIN = 'login';
/** Continue a login process that was interrupted by the need for user input or communication
* with an external provider
*/
public const ACTION_LOGIN_CONTINUE = 'login-continue';
/** Create a new user */
public const ACTION_CREATE = 'create';
/** Continue a user creation process that was interrupted by the need for user input or
* communication with an external provider
*/
public const ACTION_CREATE_CONTINUE = 'create-continue';
/** Link an existing user to a third-party account */
public const ACTION_LINK = 'link';
/** Continue a user linking process that was interrupted by the need for user input or
* communication with an external provider
*/
public const ACTION_LINK_CONTINUE = 'link-continue';
/** Change a user's credentials */
public const ACTION_CHANGE = 'change';
/** Remove a user's credentials */
public const ACTION_REMOVE = 'remove';
/** Like ACTION_REMOVE but for linking providers only */
public const ACTION_UNLINK = 'unlink';
/** Security-sensitive operations are ok. */
public const SEC_OK = 'ok';
/** Security-sensitive operations should re-authenticate. */
public const SEC_REAUTH = 'reauth';
/** Security-sensitive should not be performed. */
public const SEC_FAIL = 'fail';
/** Auto-creation is due to SessionManager */
public const AUTOCREATE_SOURCE_SESSION = \MediaWiki\Session\SessionManager::class;
/** Auto-creation is due to a Maintenance script */
public const AUTOCREATE_SOURCE_MAINT = '::Maintenance::';
/** @var AuthManager|null */
private static $instance = null;
/** @var WebRequest */
private $request;
/** @var Config */
private $config;
/** @var LoggerInterface */
private $logger;
/** @var AuthenticationProvider[] */
private $allAuthenticationProviders = [];
/** @var PreAuthenticationProvider[] */
private $preAuthenticationProviders = null;
/** @var PrimaryAuthenticationProvider[] */
private $primaryAuthenticationProviders = null;
/** @var SecondaryAuthenticationProvider[] */
private $secondaryAuthenticationProviders = null;
/** @var CreatedAccountAuthenticationRequest[] */
private $createdAccountAuthenticationRequests = [];
/**
* Get the global AuthManager
* @return AuthManager
*/
public static function singleton() {
if ( self::$instance === null ) {
self::$instance = new self(
\RequestContext::getMain()->getRequest(),
MediaWikiServices::getInstance()->getMainConfig()
);
}
return self::$instance;
}
/**
* @param WebRequest $request
* @param Config $config
*/
public function __construct( WebRequest $request, Config $config ) {
$this->request = $request;
$this->config = $config;
$this->setLogger( \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' ) );
}
/**
* @param LoggerInterface $logger
*/
public function setLogger( LoggerInterface $logger ) {
$this->logger = $logger;
}
/**
* @return WebRequest
*/
public function getRequest() {
return $this->request;
}
/**
* Force certain PrimaryAuthenticationProviders
* @deprecated For backwards compatibility only
* @param PrimaryAuthenticationProvider[] $providers
* @param string $why
*/
public function forcePrimaryAuthenticationProviders( array $providers, $why ) {
$this->logger->warning( "Overriding AuthManager primary authn because $why" );
if ( $this->primaryAuthenticationProviders !== null ) {
$this->logger->warning(
'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
);
$this->allAuthenticationProviders = array_diff_key(
$this->allAuthenticationProviders,
$this->primaryAuthenticationProviders
);
$session = $this->request->getSession();
$session->remove( 'AuthManager::authnState' );
$session->remove( 'AuthManager::accountCreationState' );
$session->remove( 'AuthManager::accountLinkState' );
$this->createdAccountAuthenticationRequests = [];
}
$this->primaryAuthenticationProviders = [];
foreach ( $providers as $provider ) {
if ( !$provider instanceof PrimaryAuthenticationProvider ) {
throw new \RuntimeException(
'Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got ' .
get_class( $provider )
);
}
$provider->setLogger( $this->logger );
$provider->setManager( $this );
$provider->setConfig( $this->config );
$id = $provider->getUniqueId();
if ( isset( $this->allAuthenticationProviders[$id] ) ) {
throw new \RuntimeException(
"Duplicate specifications for id $id (classes " .
get_class( $provider ) . ' and ' .
get_class( $this->allAuthenticationProviders[$id] ) . ')'
);
}
$this->allAuthenticationProviders[$id] = $provider;
$this->primaryAuthenticationProviders[$id] = $provider;
}
}
/**
* This used to call a legacy AuthPlugin method, if necessary. Since that code has
* been removed, it now just returns the $return parameter.
*
* @codeCoverageIgnore
* @deprecated For backwards compatibility only, should be avoided in new code
* @param string $method AuthPlugin method to call
* @param array $params Parameters to pass
* @param mixed $return Return value if AuthPlugin wasn't called
* @return mixed Return value from the AuthPlugin method, or $return
*/
public static function callLegacyAuthPlugin( $method, array $params, $return = null ) {
wfDeprecated( __METHOD__, '1.33' );
return $return;
}
/**
* @name Authentication
* @{
*/
/**
* Indicate whether user authentication is possible
*
* It may not be if the session is provided by something like OAuth
* for which each individual request includes authentication data.
*
* @return bool
*/
public function canAuthenticateNow() {
return $this->request->getSession()->canSetUser();
}
/**
* Start an authentication flow
*
* In addition to the AuthenticationRequests returned by
* $this->getAuthenticationRequests(), a client might include a
* CreateFromLoginAuthenticationRequest from a previous login attempt to
* preserve state.
*
* Instead of the AuthenticationRequests returned by
* $this->getAuthenticationRequests(), a client might pass a
* CreatedAccountAuthenticationRequest from an account creation that just
* succeeded to log in to the just-created account.
*
* @param AuthenticationRequest[] $reqs
* @param string $returnToUrl Url that REDIRECT responses should eventually
* return to.
* @return AuthenticationResponse See self::continueAuthentication()
*/
public function beginAuthentication( array $reqs, $returnToUrl ) {
$session = $this->request->getSession();
if ( !$session->canSetUser() ) {
// Caller should have called canAuthenticateNow()
$session->remove( 'AuthManager::authnState' );
throw new \LogicException( 'Authentication is not possible now' );
}
$guessUserName = null;
foreach ( $reqs as $req ) {
$req->returnToUrl = $returnToUrl;
// @codeCoverageIgnoreStart
if ( $req->username !== null && $req->username !== '' ) {
if ( $guessUserName === null ) {
$guessUserName = $req->username;
} elseif ( $guessUserName !== $req->username ) {
$guessUserName = null;
break;
}
}
// @codeCoverageIgnoreEnd
}
// Check for special-case login of a just-created account
$req = AuthenticationRequest::getRequestByClass(
$reqs, CreatedAccountAuthenticationRequest::class
);
if ( $req ) {
if ( !in_array( $req, $this->createdAccountAuthenticationRequests, true ) ) {
throw new \LogicException(
'CreatedAccountAuthenticationRequests are only valid on ' .
'the same AuthManager that created the account'
);
}
$user = User::newFromName( $req->username );
// @codeCoverageIgnoreStart
if ( !$user ) {
throw new \UnexpectedValueException(
"CreatedAccountAuthenticationRequest had invalid username \"{$req->username}\""
);
} elseif ( $user->getId() != $req->id ) {
throw new \UnexpectedValueException(
"ID for \"{$req->username}\" was {$user->getId()}, expected {$req->id}"
);
}
// @codeCoverageIgnoreEnd
$this->logger->info( 'Logging in {user} after account creation', [
'user' => $user->getName(),
] );
$ret = AuthenticationResponse::newPass( $user->getName() );
$this->setSessionDataForUser( $user );
$this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
$session->remove( 'AuthManager::authnState' );
\Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName(), [] ] );
return $ret;
}
$this->removeAuthenticationSessionData( null );
foreach ( $this->getPreAuthenticationProviders() as $provider ) {
$status = $provider->testForAuthentication( $reqs );
if ( !$status->isGood() ) {
$this->logger->debug( 'Login failed in pre-authentication by ' . $provider->getUniqueId() );
$ret = AuthenticationResponse::newFail(
Status::wrap( $status )->getMessage()
);
$this->callMethodOnProviders( 7, 'postAuthentication',
[ User::newFromName( $guessUserName ) ?: null, $ret ]
);
\Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, null, $guessUserName, [] ] );
return $ret;
}
}
$state = [
'reqs' => $reqs,
'returnToUrl' => $returnToUrl,
'guessUserName' => $guessUserName,
'primary' => null,
'primaryResponse' => null,
'secondary' => [],
'maybeLink' => [],
'continueRequests' => [],
];
// Preserve state from a previous failed login
$req = AuthenticationRequest::getRequestByClass(
$reqs, CreateFromLoginAuthenticationRequest::class
);
if ( $req ) {
$state['maybeLink'] = $req->maybeLink;
}
$session = $this->request->getSession();
$session->setSecret( 'AuthManager::authnState', $state );
$session->persist();
return $this->continueAuthentication( $reqs );
}
/**
* Continue an authentication flow
*
* Return values are interpreted as follows:
* - status FAIL: Authentication failed. If $response->createRequest is
* set, that may be passed to self::beginAuthentication() or to
* self::beginAccountCreation() to preserve state.
* - status REDIRECT: The client should be redirected to the contained URL,
* new AuthenticationRequests should be made (if any), then
* AuthManager::continueAuthentication() should be called.
* - status UI: The client should be presented with a user interface for
* the fields in the specified AuthenticationRequests, then new
* AuthenticationRequests should be made, then
* AuthManager::continueAuthentication() should be called.
* - status RESTART: The user logged in successfully with a third-party
* service, but the third-party credentials aren't attached to any local
* account. This could be treated as a UI or a FAIL.
* - status PASS: Authentication was successful.
*
* @param AuthenticationRequest[] $reqs
* @return AuthenticationResponse
*/
public function continueAuthentication( array $reqs ) {
$session = $this->request->getSession();
try {
if ( !$session->canSetUser() ) {
// Caller should have called canAuthenticateNow()
// @codeCoverageIgnoreStart
throw new \LogicException( 'Authentication is not possible now' );
// @codeCoverageIgnoreEnd
}
$state = $session->getSecret( 'AuthManager::authnState' );
if ( !is_array( $state ) ) {
return AuthenticationResponse::newFail(
wfMessage( 'authmanager-authn-not-in-progress' )
);
}
$state['continueRequests'] = [];
$guessUserName = $state['guessUserName'];
foreach ( $reqs as $req ) {
$req->returnToUrl = $state['returnToUrl'];
}
// Step 1: Choose an primary authentication provider, and call it until it succeeds.
if ( $state['primary'] === null ) {
// We haven't picked a PrimaryAuthenticationProvider yet
// @codeCoverageIgnoreStart
$guessUserName = null;
foreach ( $reqs as $req ) {
if ( $req->username !== null && $req->username !== '' ) {
if ( $guessUserName === null ) {
$guessUserName = $req->username;
} elseif ( $guessUserName !== $req->username ) {
$guessUserName = null;
break;
}
}
}
$state['guessUserName'] = $guessUserName;
// @codeCoverageIgnoreEnd
$state['reqs'] = $reqs;
foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
$res = $provider->beginPrimaryAuthentication( $reqs );
switch ( $res->status ) {
case AuthenticationResponse::PASS;
$state['primary'] = $id;
$state['primaryResponse'] = $res;
$this->logger->debug( "Primary login with $id succeeded" );
break 2;
case AuthenticationResponse::FAIL;
$this->logger->debug( "Login failed in primary authentication by $id" );
if ( $res->createRequest || $state['maybeLink'] ) {
$res->createRequest = new CreateFromLoginAuthenticationRequest(
$res->createRequest, $state['maybeLink']
);
}
$this->callMethodOnProviders( 7, 'postAuthentication',
[ User::newFromName( $guessUserName ) ?: null, $res ]
);
$session->remove( 'AuthManager::authnState' );
\Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName, [] ] );
return $res;
case AuthenticationResponse::ABSTAIN;
// Continue loop
break;
case AuthenticationResponse::REDIRECT;
case AuthenticationResponse::UI;
$this->logger->debug( "Primary login with $id returned $res->status" );
$this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $guessUserName );
$state['primary'] = $id;
$state['continueRequests'] = $res->neededRequests;
$session->setSecret( 'AuthManager::authnState', $state );
return $res;
// @codeCoverageIgnoreStart
default:
throw new \DomainException(
get_class( $provider ) . "::beginPrimaryAuthentication() returned $res->status"
);
// @codeCoverageIgnoreEnd
}
}
if ( $state['primary'] === null ) {
$this->logger->debug( 'Login failed in primary authentication because no provider accepted' );
$ret = AuthenticationResponse::newFail(
wfMessage( 'authmanager-authn-no-primary' )
);
$this->callMethodOnProviders( 7, 'postAuthentication',
[ User::newFromName( $guessUserName ) ?: null, $ret ]
);
$session->remove( 'AuthManager::authnState' );
return $ret;
}
} elseif ( $state['primaryResponse'] === null ) {
$provider = $this->getAuthenticationProvider( $state['primary'] );
if ( !$provider instanceof PrimaryAuthenticationProvider ) {
// Configuration changed? Force them to start over.
// @codeCoverageIgnoreStart
$ret = AuthenticationResponse::newFail(
wfMessage( 'authmanager-authn-not-in-progress' )
);
$this->callMethodOnProviders( 7, 'postAuthentication',
[ User::newFromName( $guessUserName ) ?: null, $ret ]
);
$session->remove( 'AuthManager::authnState' );
return $ret;
// @codeCoverageIgnoreEnd
}
$id = $provider->getUniqueId();
$res = $provider->continuePrimaryAuthentication( $reqs );
switch ( $res->status ) {
case AuthenticationResponse::PASS;
$state['primaryResponse'] = $res;
$this->logger->debug( "Primary login with $id succeeded" );
break;
case AuthenticationResponse::FAIL;
$this->logger->debug( "Login failed in primary authentication by $id" );
if ( $res->createRequest || $state['maybeLink'] ) {
$res->createRequest = new CreateFromLoginAuthenticationRequest(
$res->createRequest, $state['maybeLink']
);
}
$this->callMethodOnProviders( 7, 'postAuthentication',
[ User::newFromName( $guessUserName ) ?: null, $res ]
);
$session->remove( 'AuthManager::authnState' );
\Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName, [] ] );
return $res;
case AuthenticationResponse::REDIRECT;
case AuthenticationResponse::UI;
$this->logger->debug( "Primary login with $id returned $res->status" );
$this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $guessUserName );
$state['continueRequests'] = $res->neededRequests;
$session->setSecret( 'AuthManager::authnState', $state );
return $res;
default:
throw new \DomainException(
get_class( $provider ) . "::continuePrimaryAuthentication() returned $res->status"
);
}
}
$res = $state['primaryResponse'];
if ( $res->username === null ) {
$provider = $this->getAuthenticationProvider( $state['primary'] );
if ( !$provider instanceof PrimaryAuthenticationProvider ) {
// Configuration changed? Force them to start over.
// @codeCoverageIgnoreStart
$ret = AuthenticationResponse::newFail(
wfMessage( 'authmanager-authn-not-in-progress' )
);
$this->callMethodOnProviders( 7, 'postAuthentication',
[ User::newFromName( $guessUserName ) ?: null, $ret ]
);
$session->remove( 'AuthManager::authnState' );
return $ret;
// @codeCoverageIgnoreEnd
}
if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK &&
$res->linkRequest &&
// don't confuse the user with an incorrect message if linking is disabled
$this->getAuthenticationProvider( ConfirmLinkSecondaryAuthenticationProvider::class )
) {
$state['maybeLink'][$res->linkRequest->getUniqueId()] = $res->linkRequest;
$msg = 'authmanager-authn-no-local-user-link';
} else {
$msg = 'authmanager-authn-no-local-user';
}
$this->logger->debug(
"Primary login with {$provider->getUniqueId()} succeeded, but returned no user"
);
$ret = AuthenticationResponse::newRestart( wfMessage( $msg ) );
$ret->neededRequests = $this->getAuthenticationRequestsInternal(
self::ACTION_LOGIN,
[],
$this->getPrimaryAuthenticationProviders() + $this->getSecondaryAuthenticationProviders()
);
if ( $res->createRequest || $state['maybeLink'] ) {
$ret->createRequest = new CreateFromLoginAuthenticationRequest(
$res->createRequest, $state['maybeLink']
);
$ret->neededRequests[] = $ret->createRequest;
}
$this->fillRequests( $ret->neededRequests, self::ACTION_LOGIN, null, true );
$session->setSecret( 'AuthManager::authnState', [
'reqs' => [], // Will be filled in later
'primary' => null,
'primaryResponse' => null,
'secondary' => [],
'continueRequests' => $ret->neededRequests,
] + $state );
return $ret;
}
// Step 2: Primary authentication succeeded, create the User object
// (and add the user locally if necessary)
$user = User::newFromName( $res->username, 'usable' );
if ( !$user ) {
$provider = $this->getAuthenticationProvider( $state['primary'] );
throw new \DomainException(
get_class( $provider ) . " returned an invalid username: {$res->username}"
);
}
if ( $user->getId() === 0 ) {
// User doesn't exist locally. Create it.
$this->logger->info( 'Auto-creating {user} on login', [
'user' => $user->getName(),
] );
$status = $this->autoCreateUser( $user, $state['primary'], false );
if ( !$status->isGood() ) {
$ret = AuthenticationResponse::newFail(
Status::wrap( $status )->getMessage( 'authmanager-authn-autocreate-failed' )
);
$this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
$session->remove( 'AuthManager::authnState' );
\Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName(), [] ] );
return $ret;
}
}
// Step 3: Iterate over all the secondary authentication providers.
$beginReqs = $state['reqs'];
foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
if ( !isset( $state['secondary'][$id] ) ) {
// This provider isn't started yet, so we pass it the set
// of reqs from beginAuthentication instead of whatever
// might have been used by a previous provider in line.
$func = 'beginSecondaryAuthentication';
$res = $provider->beginSecondaryAuthentication( $user, $beginReqs );
} elseif ( !$state['secondary'][$id] ) {
$func = 'continueSecondaryAuthentication';
$res = $provider->continueSecondaryAuthentication( $user, $reqs );
} else {
continue;
}
switch ( $res->status ) {
case AuthenticationResponse::PASS;
$this->logger->debug( "Secondary login with $id succeeded" );
// fall through
case AuthenticationResponse::ABSTAIN;
$state['secondary'][$id] = true;
break;
case AuthenticationResponse::FAIL;
$this->logger->debug( "Login failed in secondary authentication by $id" );
$this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $res ] );
$session->remove( 'AuthManager::authnState' );
\Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $res, $user, $user->getName(), [] ] );
return $res;
case AuthenticationResponse::REDIRECT;
case AuthenticationResponse::UI;
$this->logger->debug( "Secondary login with $id returned " . $res->status );
$this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $user->getName() );
$state['secondary'][$id] = false;
$state['continueRequests'] = $res->neededRequests;
$session->setSecret( 'AuthManager::authnState', $state );
return $res;
// @codeCoverageIgnoreStart
default:
throw new \DomainException(
get_class( $provider ) . "::{$func}() returned $res->status"
);
// @codeCoverageIgnoreEnd
}
}
// Step 4: Authentication complete! Set the user in the session and
// clean up.
$this->logger->info( 'Login for {user} succeeded from {clientip}', [
'user' => $user->getName(),
'clientip' => $this->request->getIP(),
] );
/** @var RememberMeAuthenticationRequest $req */
$req = AuthenticationRequest::getRequestByClass(
$beginReqs, RememberMeAuthenticationRequest::class
);
$this->setSessionDataForUser( $user, $req && $req->rememberMe );
$ret = AuthenticationResponse::newPass( $user->getName() );
$this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
$session->remove( 'AuthManager::authnState' );
$this->removeAuthenticationSessionData( null );
\Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName(), [] ] );
return $ret;
} catch ( \Exception $ex ) {
$session->remove( 'AuthManager::authnState' );
throw $ex;
}
}
/**
* Whether security-sensitive operations should proceed.
*
* A "security-sensitive operation" is something like a password or email
* change, that would normally have a "reenter your password to confirm"
* box if we only supported password-based authentication.
*
* @param string $operation Operation being checked. This should be a
* message-key-like string such as 'change-password' or 'change-email'.
* @return string One of the SEC_* constants.
*/
public function securitySensitiveOperationStatus( $operation ) {
$status = self::SEC_OK;
$this->logger->debug( __METHOD__ . ": Checking $operation" );
$session = $this->request->getSession();
$aId = $session->getUser()->getId();
if ( $aId === 0 ) {
// User isn't authenticated. DWIM?
$status = $this->canAuthenticateNow() ? self::SEC_REAUTH : self::SEC_FAIL;
$this->logger->info( __METHOD__ . ": Not logged in! $operation is $status" );
return $status;
}
if ( $session->canSetUser() ) {
$id = $session->get( 'AuthManager:lastAuthId' );
$last = $session->get( 'AuthManager:lastAuthTimestamp' );
if ( $id !== $aId || $last === null ) {
$timeSinceLogin = PHP_INT_MAX; // Forever ago
} else {
$timeSinceLogin = max( 0, time() - $last );
}
$thresholds = $this->config->get( 'ReauthenticateTime' );
if ( isset( $thresholds[$operation] ) ) {
$threshold = $thresholds[$operation];
} elseif ( isset( $thresholds['default'] ) ) {
$threshold = $thresholds['default'];
} else {
throw new \UnexpectedValueException( '$wgReauthenticateTime lacks a default' );
}
if ( $threshold >= 0 && $timeSinceLogin > $threshold ) {
$status = self::SEC_REAUTH;
}
} else {
$timeSinceLogin = -1;
$pass = $this->config->get( 'AllowSecuritySensitiveOperationIfCannotReauthenticate' );
if ( isset( $pass[$operation] ) ) {
$status = $pass[$operation] ? self::SEC_OK : self::SEC_FAIL;
} elseif ( isset( $pass['default'] ) ) {
$status = $pass['default'] ? self::SEC_OK : self::SEC_FAIL;
} else {
throw new \UnexpectedValueException(
'$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default'
);
}
}
\Hooks::run( 'SecuritySensitiveOperationStatus', [
&$status, $operation, $session, $timeSinceLogin
] );
// If authentication is not possible, downgrade from "REAUTH" to "FAIL".
if ( !$this->canAuthenticateNow() && $status === self::SEC_REAUTH ) {
$status = self::SEC_FAIL;
}
$this->logger->info( __METHOD__ . ": $operation is $status for '{user}'",
[
'user' => $session->getUser()->getName(),
'clientip' => $this->getRequest()->getIP(),
]
);
return $status;
}
/**
* Determine whether a username can authenticate
*
* This is mainly for internal purposes and only takes authentication data into account,
* not things like blocks that can change without the authentication system being aware.
*
* @param string $username MediaWiki username
* @return bool
*/
public function userCanAuthenticate( $username ) {
foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
if ( $provider->testUserCanAuthenticate( $username ) ) {
return true;
}
}
return false;
}
/**
* Provide normalized versions of the username for security checks
*
* Since different providers can normalize the input in different ways,
* this returns an array of all the different ways the name might be
* normalized for authentication.
*
* The returned strings should not be revealed to the user, as that might
* leak private information (e.g. an email address might be normalized to a
* username).
*
* @param string $username
* @return string[]
*/
public function normalizeUsername( $username ) {
$ret = [];
foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
$normalized = $provider->providerNormalizeUsername( $username );
if ( $normalized !== null ) {
$ret[$normalized] = true;
}
}
return array_keys( $ret );
}
/** @} */
/**
* @name Authentication data changing
* @{
*/
/**
* Revoke any authentication credentials for a user
*
* After this, the user should no longer be able to log in.
*
* @param string $username
*/
public function revokeAccessForUser( $username ) {
$this->logger->info( 'Revoking access for {user}', [
'user' => $username,
] );
$this->callMethodOnProviders( 6, 'providerRevokeAccessForUser', [ $username ] );
}
/**
* Validate a change of authentication data (e.g. passwords)
* @param AuthenticationRequest $req
* @param bool $checkData If false, $req hasn't been loaded from the
* submission so checks on user-submitted fields should be skipped. $req->username is
* considered user-submitted for this purpose, even if it cannot be changed via
* $req->loadFromSubmission.
* @return Status
*/
public function allowsAuthenticationDataChange( AuthenticationRequest $req, $checkData = true ) {
$any = false;
$providers = $this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders();
foreach ( $providers as $provider ) {
$status = $provider->providerAllowsAuthenticationDataChange( $req, $checkData );
if ( !$status->isGood() ) {
return Status::wrap( $status );
}
$any = $any || $status->value !== 'ignored';
}
if ( !$any ) {
$status = Status::newGood( 'ignored' );
$status->warning( 'authmanager-change-not-supported' );
return $status;
}
return Status::newGood();
}
/**
* Change authentication data (e.g. passwords)
*
* If $req was returned for AuthManager::ACTION_CHANGE, using $req should
* result in a successful login in the future.
*
* If $req was returned for AuthManager::ACTION_REMOVE, using $req should
* no longer result in a successful login.
*
* This method should only be called if allowsAuthenticationDataChange( $req, true )
* returned success.
*
* @param AuthenticationRequest $req
* @param bool $isAddition Set true if this represents an addition of
* credentials rather than a change. The main difference is that additions
* should not invalidate BotPasswords. If you're not sure, leave it false.
*/
public function changeAuthenticationData( AuthenticationRequest $req, $isAddition = false ) {
$this->logger->info( 'Changing authentication data for {user} class {what}', [
'user' => is_string( $req->username ) ? $req->username : '<no name>',
'what' => get_class( $req ),
] );
$this->callMethodOnProviders( 6, 'providerChangeAuthenticationData', [ $req ] );
// When the main account's authentication data is changed, invalidate
// all BotPasswords too.
if ( !$isAddition ) {
\BotPassword::invalidateAllPasswordsForUser( $req->username );
}
}
/** @} */
/**
* @name Account creation
* @{
*/
/**
* Determine whether accounts can be created
* @return bool
*/
public function canCreateAccounts() {
foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
switch ( $provider->accountCreationType() ) {
case PrimaryAuthenticationProvider::TYPE_CREATE:
case PrimaryAuthenticationProvider::TYPE_LINK:
return true;
}
}
return false;
}
/**
* Determine whether a particular account can be created
* @param string $username MediaWiki username
* @param array $options
* - flags: (int) Bitfield of User:READ_* constants, default User::READ_NORMAL
* - creating: (bool) For internal use only. Never specify this.
* @return Status
*/
public function canCreateAccount( $username, $options = [] ) {
// Back compat
if ( is_int( $options ) ) {
$options = [ 'flags' => $options ];
}
$options += [
'flags' => User::READ_NORMAL,
'creating' => false,
];
$flags = $options['flags'];
if ( !$this->canCreateAccounts() ) {
return Status::newFatal( 'authmanager-create-disabled' );
}
if ( $this->userExists( $username, $flags ) ) {
return Status::newFatal( 'userexists' );
}
$user = User::newFromName( $username, 'creatable' );
if ( !is_object( $user ) ) {
return Status::newFatal( 'noname' );
} else {
$user->load( $flags ); // Explicitly load with $flags, auto-loading always uses READ_NORMAL
if ( $user->getId() !== 0 ) {
return Status::newFatal( 'userexists' );
}
}
// Denied by providers?
$providers = $this->getPreAuthenticationProviders() +
$this->getPrimaryAuthenticationProviders() +
$this->getSecondaryAuthenticationProviders();
foreach ( $providers as $provider ) {
$status = $provider->testUserForCreation( $user, false, $options );
if ( !$status->isGood() ) {
return Status::wrap( $status );
}
}
return Status::newGood();
}
/**
* Basic permissions checks on whether a user can create accounts
* @param User $creator User doing the account creation
* @return Status
*/
public function checkAccountCreatePermissions( User $creator ) {
// Wiki is read-only?
if ( wfReadOnly() ) {
return Status::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
}
// This is awful, this permission check really shouldn't go through Title.
$permErrors = \SpecialPage::getTitleFor( 'CreateAccount' )
->getUserPermissionsErrors(