Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 59
0.00% covered (danger)
0.00%
0 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
CentralAuthUtilityService
0.00% covered (danger)
0.00%
0 / 59
0.00% covered (danger)
0.00%
0 / 6
240
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 getKeyValueUponExistence
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
30
 tokenize
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 detokenize
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 autoCreateUser
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 scheduleCreationJobs
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21namespace MediaWiki\Extension\CentralAuth;
22
23use BagOStuff;
24use MediaWiki\Auth\AuthManager;
25use MediaWiki\Config\Config;
26use MediaWiki\Extension\CentralAuth\User\CentralAuthUser;
27use MediaWiki\JobQueue\JobFactory;
28use MediaWiki\JobQueue\JobQueueGroupFactory;
29use MediaWiki\Logger\LoggerFactory;
30use MediaWiki\Permissions\Authority;
31use MediaWiki\Title\TitleFactory;
32use MediaWiki\User\User;
33use MediaWiki\WikiMap\WikiMap;
34use MWCryptRand;
35use Profiler;
36use Psr\Log\LoggerInterface;
37use RequestContext;
38use RuntimeException;
39use StatusValue;
40use Wikimedia\WaitConditionLoop;
41
42/**
43 * Utility services that are useful in many parts of CentralAuth.
44 *
45 * @since 1.36
46 */
47class CentralAuthUtilityService {
48
49    /** @var Config */
50    private $config;
51
52    /** @var AuthManager */
53    private $authManager;
54
55    /** @var TitleFactory */
56    private $titleFactory;
57
58    /** @var JobQueueGroupFactory */
59    private $jobQueueGroupFactory;
60
61    /** @var JobFactory */
62    private $jobFactory;
63
64    /** @var LoggerInterface */
65    private $logger;
66
67    public function __construct(
68        Config $config,
69        AuthManager $authManager,
70        TitleFactory $titleFactory,
71        JobQueueGroupFactory $jobQueueGroupFactory,
72        JobFactory $jobFactory,
73        LoggerInterface $logger
74    ) {
75        $this->config = $config;
76        $this->authManager = $authManager;
77        $this->titleFactory = $titleFactory;
78        $this->jobQueueGroupFactory = $jobQueueGroupFactory;
79        $this->jobFactory = $jobFactory;
80        $this->logger = $logger;
81    }
82
83    /**
84     * Wait for and return the value of a key which is expected to exist from a store
85     *
86     * @param BagOStuff $store
87     * @param string $key A key that will only have one value while it exists
88     * @param int $timeout
89     * @return mixed Key value; false if not found or on error
90     */
91    public function getKeyValueUponExistence( BagOStuff $store, $key, $timeout = 3 ) {
92        $value = false;
93
94        $result = ( new WaitConditionLoop(
95            static function () use ( $store, $key, &$value ) {
96                $store->clearLastError();
97                $value = $store->get( $key );
98                $error = $store->getLastError();
99                if ( $value !== false ) {
100                    return WaitConditionLoop::CONDITION_REACHED;
101                } elseif ( $error === $store::ERR_NONE ) {
102                    return WaitConditionLoop::CONDITION_CONTINUE;
103                } else {
104                    return WaitConditionLoop::CONDITION_ABORTED;
105                }
106            },
107            $timeout
108        ) )->invoke();
109
110        if ( $result === WaitConditionLoop::CONDITION_REACHED ) {
111            $this->logger->info( "Expected key {key} found.", [ 'key' => $key ] );
112        } elseif ( $result === WaitConditionLoop::CONDITION_TIMED_OUT ) {
113            $this->logger->error( "Expected key {key} not found due to timeout.", [ 'key' => $key ] );
114        } else {
115            $this->logger->error( "Expected key {key} not found due to I/O error.", [ 'key' => $key ] );
116        }
117
118        return $value;
119    }
120
121    /**
122     * Store a value for a short time via the shared token store, and return the random key it's
123     * stored under. This can be used to replace an URL parameter (used to pass information between
124     * wikis via redirect chains) with a random placeholder, to avoid sniffing or tampering.
125     * @param string $value The value to store.
126     * @param string $keyPrefix Namespace in the token store.
127     * @param CentralAuthSessionManager $sessionManager
128     * @return string The random key (without the prefix).
129     */
130    public function tokenize(
131        string $value,
132        string $keyPrefix,
133        CentralAuthSessionManager $sessionManager
134    ): string {
135        $tokenStore = $sessionManager->getTokenStore();
136        $token = MWCryptRand::generateHex( 16 );
137        $key = $sessionManager->makeTokenKey( $keyPrefix, $token );
138
139        $tokenStore->set( $key, $value, $tokenStore::TTL_MINUTE );
140        return $token;
141    }
142
143    /**
144     * Recover the value concealed with tokenize().
145     * @param string $token The random key returned by tokenize().
146     * @param string $keyPrefix Namespace in the token store.
147     * @param CentralAuthSessionManager $sessionManager
148     * @return string|false The value, or false if it was not found.
149     */
150    public function detokenize(
151        string $token,
152        string $keyPrefix,
153        CentralAuthSessionManager $sessionManager
154    ) {
155        $key = $sessionManager->makeTokenKey( $keyPrefix, $token );
156
157        return $this->getKeyValueUponExistence( $sessionManager->getTokenStore(), $key );
158    }
159
160    /**
161     * Auto-create an account
162     *
163     * @param User $user User to auto-create
164     * @param bool $log Whether to generate a user creation log entry
165     * @param Authority|null $performer The user performing the creation
166     * @return StatusValue a status value
167     */
168    public function autoCreateUser( User $user, $log = true,
169        ?Authority $performer = null
170    ): StatusValue {
171        // Ignore warnings about primary database connections/writes...hard to avoid here
172
173        Profiler::instance()->getTransactionProfiler()->resetExpectations();
174
175        $source = CentralAuthPrimaryAuthenticationProvider::ID;
176        if ( !$this->authManager->getAuthenticationProvider( $source ) ) {
177            $source = AuthManager::AUTOCREATE_SOURCE_SESSION;
178        }
179        $sv = $this->authManager->autoCreateUser( $user, $source, false, $log, $performer );
180
181        LoggerFactory::getInstance( 'authevents' )->info( 'Central autocreation attempt', [
182            'event' => 'autocreate',
183            'successful' => $sv->isGood(),
184            'status' => ( $sv->getErrorsArray() ?: $sv->getWarningsArray() )[0][0] ?? '-',
185            'extension' => 'CentralAuth',
186        ] );
187        return $sv;
188    }
189
190    /**
191     * Sets up jobs to create and attach a local account for the given user on every wiki listed in
192     * $wgCentralAuthAutoCreateWikis.
193     * @param CentralAuthUser $centralUser
194     */
195    public function scheduleCreationJobs( CentralAuthUser $centralUser ) {
196        $name = $centralUser->getName();
197        $thisWiki = WikiMap::getCurrentWikiId();
198        $session = RequestContext::getMain()->exportSession();
199
200        $title = $this->titleFactory->makeTitleSafe( NS_USER, $name );
201
202        if ( !$title ) {
203            throw new RuntimeException( "Failed to create title for user page of $name" );
204        }
205
206        foreach ( $this->config->get( 'CentralAuthAutoCreateWikis' ) as $wiki ) {
207            if ( $wiki === $thisWiki ) {
208                continue;
209            }
210
211            $job = $this->jobFactory->newJob(
212                'CentralAuthCreateLocalAccountJob',
213                [ 'name' => $name, 'from' => $thisWiki, 'session' => $session ]
214            );
215            $this->jobQueueGroupFactory->makeJobQueueGroup( $wiki )->lazyPush( $job );
216        }
217    }
218}