Debian Codegraph @

extensions/OATHAuth/src/OATHUserRepository.php

raw symbols SCIP
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
19 namespace MediaWiki\Extension\OATHAuth;
20
21 use ErrorPageError;
22 use InvalidArgumentException;
23 use MediaWiki\Config\ConfigException;
24 use MediaWiki\Context\RequestContext;
25 use MediaWiki\Extension\OATHAuth\Notifications\Manager;
26 use MediaWiki\Json\FormatJson;
27 use MediaWiki\User\CentralId\CentralIdLookupFactory;
28 use MediaWiki\User\UserIdentity;
29 use MWException;
30 use Psr\Log\LoggerAwareInterface;
31 use Psr\Log\LoggerInterface;
32 use Wikimedia\ObjectCache\BagOStuff;
33 use Wikimedia\Rdbms\IConnectionProvider;
34
35 class OATHUserRepository implements LoggerAwareInterface {
36 private IConnectionProvider $dbProvider;
37
38 private BagOStuff $cache;
39
40 private OATHAuthModuleRegistry $moduleRegistry;
41
42 private CentralIdLookupFactory $centralIdLookupFactory;
43
44 private LoggerInterface $logger;
45
46 public function __construct(
47 IConnectionProvider $dbProvider,
48 BagOStuff $cache,
49 OATHAuthModuleRegistry $moduleRegistry,
50 CentralIdLookupFactory $centralIdLookupFactory,
51 LoggerInterface $logger
52 ) {
53 $this->dbProvider = $dbProvider;
54 $this->cache = $cache;
55 $this->moduleRegistry = $moduleRegistry;
56 $this->centralIdLookupFactory = $centralIdLookupFactory;
57 $this->setLogger( $logger );
58 }
59
60 /**
61 * @param LoggerInterface $logger
62 */
63 public function setLogger( LoggerInterface $logger ) {
64 $this->logger = $logger;
65 }
66
67 /**
68 * @param UserIdentity $user
69 * @return OATHUser
70 * @throws ConfigException
71 * @throws MWException
72 */
73 public function findByUser( UserIdentity $user ) {
74 $oathUser = $this->cache->get( $user->getName() );
75 if ( !$oathUser ) {
76 $uid = $this->centralIdLookupFactory->getLookup()
77 ->centralIdFromLocalUser( $user );
78 $oathUser = new OATHUser( $user, $uid );
79 $this->loadKeysFromDatabase( $oathUser );
80
81 $this->cache->set( $user->getName(), $oathUser );
82 }
83 return $oathUser;
84 }
85
86 /**
87 * @param OATHUser $user
88 * @param string|null $clientInfo
89 * @throws ConfigException
90 * @throws MWException
91 */
92 public function persist( OATHUser $user, $clientInfo = null ) {
93 if ( !$clientInfo ) {
94 $clientInfo = RequestContext::getMain()->getRequest()->getIP();
95 }
96 $prevUser = $this->findByUser( $user->getUser() );
97 $userId = $this->centralIdLookupFactory->getLookup()->centralIdFromLocalUser( $user->getUser() );
98
99 $dbw = $this->dbProvider->getPrimaryDatabase( 'virtual-oathauth' );
100 $dbw->startAtomic( __METHOD__ );
101
102 // TODO: only update changed rows
103 $dbw->newDeleteQueryBuilder()
104 ->deleteFrom( 'oathauth_devices' )
105 ->where( [ 'oad_user' => $userId ] )
106 ->caller( __METHOD__ )
107 ->execute();
108
109 foreach ( $user->getKeys() as $key ) {
110 $dbw->newInsertQueryBuilder()
111 ->insertInto( 'oathauth_devices' )
112 ->row( [
113 'oad_user' => $userId,
114 'oad_type' => $this->moduleRegistry->getModuleId( $key->getModule() ),
115 'oad_data' => FormatJson::encode( $key->jsonSerialize() )
116 ] )
117 ->caller( __METHOD__ )
118 ->execute();
119 }
120
121 $dbw->endAtomic( __METHOD__ );
122
123 $this->loadKeysFromDatabase( $user );
124
125 $userName = $user->getUser()->getName();
126 $this->cache->set( $userName, $user );
127
128 if ( $prevUser !== false ) {
129 $this->logger->info( 'OATHAuth updated for {user} from {clientip}', [
130 'user' => $userName,
131 'clientip' => $clientInfo,
132 'oldoathtype' => $prevUser->getModule() ? $prevUser->getModule()->getName() : 'disabled',
133 'newoathtype' => $user->getModule() ? $user->getModule()->getName() : 'disabled'
134 ] );
135 } else {
136 // If findByUser() has returned false, there was no user row or cache entry
137 $this->logger->info( 'OATHAuth enabled for {user} from {clientip}', [
138 'user' => $userName,
139 'clientip' => $clientInfo,
140 'oathtype' => $user->getModule() ? $user->getModule()->getName() : 'disabled',
141 ] );
142 Manager::notifyEnabled( $user );
143 }
144 }
145
146 /**
147 * Persists the given OAuth key in the database.
148 *
149 * @param OATHUser $user
150 * @param IModule $module
151 * @param array $keyData
152 * @param string $clientInfo
153 * @return IAuthKey
154 */
155 public function createKey( OATHUser $user, IModule $module, array $keyData, string $clientInfo ): IAuthKey {
156 $otherEnabledModule = null;
157 foreach ( $user->getKeys() as $key ) {
158 if ( $key->getModule() !== $module->getName() ) {
159 $otherEnabledModule = $this->moduleRegistry->getModuleByKey( $key->getModule() );
160 break;
161 }
162 }
163 if ( $otherEnabledModule ) {
164 throw new ErrorPageError( 'errorpagetitle', 'oathauth-error-multiple-modules',
165 [ $module->getDisplayName(), $otherEnabledModule->getDisplayName() ] );
166 }
167
168 $uid = $user->getCentralId();
169 if ( !$uid ) {
170 throw new InvalidArgumentException( "Can't persist a key for user with no central ID available" );
171 }
172
173 $moduleId = $this->moduleRegistry->getModuleId( $module->getName() );
174
175 $dbw = $this->dbProvider->getPrimaryDatabase( 'virtual-oathauth' );
176 $dbw->newInsertQueryBuilder()
177 ->insertInto( 'oathauth_devices' )
178 ->row( [
179 'oad_user' => $uid,
180 'oad_type' => $moduleId,
181 'oad_data' => FormatJson::encode( $keyData ),
182 'oad_created' => $dbw->timestamp(),
183 ] )
184 ->caller( __METHOD__ )
185 ->execute();
186 $id = $dbw->insertId();
187
188 $hasExistingKey = $user->isTwoFactorAuthEnabled();
189
190 $key = $module->newKey( $keyData + [ 'id' => $id ] );
191 $user->addKey( $key );
192
193 $this->logger->info( 'OATHAuth {oathtype} key {key} added for {user} from {clientip}', [
194 'key' => $id,
195 'user' => $user->getUser()->getName(),
196 'clientip' => $clientInfo,
197 'oathtype' => $module->getName(),
198 ] );
199
200 if ( !$hasExistingKey ) {
201 Manager::notifyEnabled( $user );
202 }
203
204 return $key;
205 }
206
207 /**
208 * Saves an existing key in the database.
209 *
210 * @param OATHUser $user
211 * @param IAuthKey $key
212 * @return void
213 */
214 public function updateKey( OATHUser $user, IAuthKey $key ): void {
215 $keyId = $key->getId();
216 if ( !$keyId ) {
217 throw new InvalidArgumentException( 'updateKey() can only be used with already existing keys' );
218 }
219
220 $dbw = $this->dbProvider->getPrimaryDatabase( 'virtual-oathauth' );
221 $dbw->newUpdateQueryBuilder()
222 ->table( 'oathauth_devices' )
223 ->set( [ 'oad_data' => FormatJson::encode( $key->jsonSerialize() ) ] )
224 ->where( [ 'oad_user' => $user->getCentralId(), 'oad_id' => $keyId ] )
225 ->caller( __METHOD__ )
226 ->execute();
227
228 $this->logger->info( 'OATHAuth key {keyId} updated for {user}', [
229 'keyId' => $keyId,
230 'user' => $user->getUser()->getName(),
231 ] );
232 }
233
234 /**
235 * @param OATHUser $user
236 * @param array $where Conditions to pass to DeleteQueryBuilder::where().
237 * @return void
238 */
239 private function removeSomeKeys( OATHUser $user, array $where ): void {
240 $this->dbProvider->getPrimaryDatabase( 'virtual-oathauth' )
241 ->newDeleteQueryBuilder()
242 ->deleteFrom( 'oathauth_devices' )
243 ->where( [ 'oad_user' => $user->getCentralId() ] )
244 ->where( $where )
245 ->caller( __METHOD__ )
246 ->execute();
247
248 $this->cache->delete( $user->getUser()->getName() );
249 }
250
251 /**
252 * @param OATHUser $user
253 * @param IAuthKey $key
254 * @param string $clientInfo
255 * @param bool $self Whether they disabled it themselves
256 */
257 public function removeKey( OATHUser $user, IAuthKey $key, string $clientInfo, bool $self ) {
258 $keyId = $key->getId();
259 if ( !$keyId ) {
260 throw new InvalidArgumentException( 'A non-persisted key cannot be removed' );
261 }
262
263 $this->removeSomeKeys( $user, [ 'oad_id' => $keyId ] );
264 $user->removeKey( $key );
265
266 $this->logger->info( 'OATHAuth removed {oathtype} key {key} for {user} from {clientip}', [
267 'key' => $keyId,
268 'user' => $user->getUser()->getName(),
269 'clientip' => $clientInfo,
270 'oathtype' => $key->getModule(),
271 ] );
272
273 Manager::notifyDisabled( $user, $self );
274 }
275
276 /**
277 * @param OATHUser $user
278 * @param string $keyType As in IModule::getName()
279 * @param string $clientInfo
280 * @param bool $self Whether they disabled it themselves
281 */
282 public function removeAllOfType( OATHUser $user, string $keyType, string $clientInfo, bool $self ) {
283 $moduleId = $this->moduleRegistry->getModuleId( $keyType );
284 if ( !$moduleId ) {
285 throw new InvalidArgumentException( 'Invalid key type: ' . $keyType );
286 }
287
288 $this->removeSomeKeys( $user, [ 'oad_type' => $moduleId ] );
289 $user->removeKeysForModule( $keyType );
290
291 $this->logger->info( 'OATHAuth removed {oathtype} keys for {user} from {clientip}', [
292 'user' => $user->getUser()->getName(),
293 'clientip' => $clientInfo,
294 'oathtype' => $keyType,
295 ] );
296
297 Manager::notifyDisabled( $user, $self );
298 }
299
300 /**
301 * @param OATHUser $user
302 * @param string $clientInfo
303 * @param bool $self Whether the user disabled the 2FA themselves
304 *
305 * @deprecated since 1.41, use removeAll() instead
306 */
307 public function remove( OATHUser $user, $clientInfo, bool $self ) {
308 $this->removeAll( $user, $clientInfo, $self );
309 }
310
311 /**
312 * @param OATHUser $user
313 * @param string $clientInfo
314 * @param bool $self Whether they disabled it themselves
315 */
316 public function removeAll( OATHUser $user, $clientInfo, bool $self ) {
317 $this->removeSomeKeys( $user, [] );
318
319 $keyTypes = array_unique( array_map(
320 static fn ( IAuthKey $key ) => $key->getModule(),
321 $user->getKeys()
322 ) );
323 $user->disable();
324
325 $this->logger->info( 'OATHAuth disabled for {user} from {clientip}', [
326 'user' => $user->getUser()->getName(),
327 'clientip' => $clientInfo,
328 'oathtype' => implode( ',', $keyTypes ),
329 ] );
330
331 Manager::notifyDisabled( $user, $self );
332 }
333
334 private function loadKeysFromDatabase( OATHUser $user ): void {
335 $uid = $user->getCentralId();
336 if ( !$uid ) {
337 // T379442
338 return;
339 }
340
341 $res = $this->dbProvider
342 ->getReplicaDatabase( 'virtual-oathauth' )
343 ->newSelectQueryBuilder()
344 ->select( [
345 'oad_id',
346 'oad_data',
347 'oat_name',
348 ] )
349 ->from( 'oathauth_devices' )
350 ->join( 'oathauth_types', null, [ 'oat_id = oad_type' ] )
351 ->where( [ 'oad_user' => $uid ] )
352 ->caller( __METHOD__ )
353 ->fetchResultSet();
354
355 // Clear stored key list before loading keys
356 $user->disable();
357
358 foreach ( $res as $row ) {
359 $module = $this->moduleRegistry->getModuleByKey( $row->oat_name );
360 $keyData = FormatJson::decode( $row->oad_data, true );
361 $user->addKey( $module->newKey( $keyData + [ 'id' => (int)$row->oad_id ] ) );
362 }
363 }
364 }