Debian Codegraph @

includes/user/TempUser/TempUserCreator.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\User\TempUser;
4
5 use MediaWiki\Auth\AuthManager;
6 use MediaWiki\Auth\Throttler;
7 use MediaWiki\Permissions\Authority;
8 use MediaWiki\Registration\ExtensionRegistry;
9 use MediaWiki\Request\WebRequest;
10 use MediaWiki\Session\Session;
11 use MediaWiki\User\CentralId\CentralIdLookup;
12 use MediaWiki\User\UserFactory;
13 use MediaWiki\User\UserRigorOptions;
14 use MediaWiki\Utils\MWTimestamp;
15 use UnexpectedValueException;
16 use Wikimedia\ObjectFactory\ObjectFactory;
17 use Wikimedia\Rdbms\IExpression;
18 use Wikimedia\Rdbms\IReadableDatabase;
19
20 /**
21 * Service for temporary user creation. For convenience this also proxies the
22 * TempUserConfig methods.
23 *
24 * This is separate from TempUserConfig to avoid dependency loops. Special pages
25 * and actions are free to use this class, but services should take it as a
26 * constructor parameter only if necessary.
27 *
28 * @since 1.39
29 */
30 class TempUserCreator implements TempUserConfig {
31 private RealTempUserConfig $config;
32 private UserFactory $userFactory;
33 private AuthManager $authManager;
34 private CentralIdLookup $centralIdLookup;
35 private Throttler $tempAccountCreationThrottler;
36 private Throttler $tempAccountNameAcquisitionThrottler;
37 private array $serialProviderConfig;
38 private array $serialMappingConfig;
39 private ObjectFactory $objectFactory;
40 private ?SerialProvider $serialProvider;
41 private ?SerialMapping $serialMapping;
42
43 /** ObjectFactory specs for the core serial providers */
44 private const SERIAL_PROVIDERS = [
45 'local' => [
46 'class' => LocalSerialProvider::class,
47 'services' => [ 'DBLoadBalancer' ],
48 ]
49 ];
50
51 /** ObjectFactory specs for the core serial maps */
52 private const SERIAL_MAPPINGS = [
53 'plain-numeric' => [
54 'class' => PlainNumericSerialMapping::class,
55 ],
56 'localized-numeric' => [
57 'class' => LocalizedNumericSerialMapping::class,
58 'services' => [ 'LanguageFactory' ],
59 ],
60 'filtered-radix' => [
61 'class' => FilteredRadixSerialMapping::class,
62 ],
63 'scramble' => [
64 'class' => ScrambleMapping::class,
65 ]
66 ];
67
68 public function __construct(
69 RealTempUserConfig $config,
70 ObjectFactory $objectFactory,
71 UserFactory $userFactory,
72 AuthManager $authManager,
73 CentralIdLookup $centralIdLookup,
74 Throttler $tempAccountCreationThrottler,
75 Throttler $tempAccountNameAcquisitionThrottler
76 ) {
77 $this->config = $config;
78 $this->objectFactory = $objectFactory;
79 $this->userFactory = $userFactory;
80 $this->authManager = $authManager;
81 $this->centralIdLookup = $centralIdLookup;
82 $this->tempAccountCreationThrottler = $tempAccountCreationThrottler;
83 $this->tempAccountNameAcquisitionThrottler = $tempAccountNameAcquisitionThrottler;
84 $this->serialProviderConfig = $config->getSerialProviderConfig();
85 $this->serialMappingConfig = $config->getSerialMappingConfig();
86 }
87
88 /**
89 * Acquire a serial number, create the corresponding user and log in.
90 *
91 * @param string|null $name Previously acquired name
92 * @param WebRequest $request Request details, used for throttling
93 * @return CreateStatus
94 */
95 public function create( ?string $name, WebRequest $request ): CreateStatus {
96 $status = new CreateStatus;
97
98 // Check name acquisition rate limits first.
99 if ( $name === null ) {
100 $name = $this->acquireName( $request->getIP() );
101 if ( $name === null ) {
102 // If the $name remains null after calling ::acquireName, then
103 // we cannot generate a username and therefore cannot create a user.
104 // This could also happen if acquiring the name was rate limited
105 // In this case return a CreateStatus indicating no user was created.
106 // TODO: Create a custom message to support workflows related to T357802
107 return CreateStatus::newFatal( 'temp-user-unable-to-acquire' );
108 }
109 }
110
111 // Check temp account creation rate limits.
112 // TODO: This is duplicated from ThrottlePreAuthenticationProvider
113 // and should be factored out, see T261744
114 $result = $this->tempAccountCreationThrottler->increase(
115 null, $request->getIP(), 'TempUserCreator' );
116 if ( $result ) {
117 // TODO: Use a custom message here (T357777, T357802)
118 $message = wfMessage( 'acct_creation_throttle_hit' )->params( $result['count'] )
119 ->durationParams( $result['wait'] );
120 $status->fatal( $message );
121 return $status;
122 }
123
124 $createStatus = $this->attemptAutoCreate( $name );
125
126 if ( $createStatus->isOK() ) {
127 // The temporary account name didn't already exist, so now attempt to login
128 // using ::attemptAutoCreate as there isn't a public method to just login.
129 $this->attemptAutoCreate( $name, true );
130 }
131 return $createStatus;
132 }
133
134 public function isEnabled() {
135 return $this->config->isEnabled();
136 }
137
138 public function isKnown() {
139 return $this->config->isKnown();
140 }
141
142 public function isAutoCreateAction( string $action ) {
143 return $this->config->isAutoCreateAction( $action );
144 }
145
146 public function shouldAutoCreate( Authority $authority, string $action ) {
147 return $this->config->shouldAutoCreate( $authority, $action );
148 }
149
150 public function isTempName( string $name ) {
151 return $this->config->isTempName( $name );
152 }
153
154 public function isReservedName( string $name ) {
155 return $this->config->isReservedName( $name );
156 }
157
158 public function getPlaceholderName(): string {
159 return $this->config->getPlaceholderName();
160 }
161
162 public function getMatchPattern(): Pattern {
163 return $this->config->getMatchPattern();
164 }
165
166 public function getMatchPatterns(): array {
167 return $this->config->getMatchPatterns();
168 }
169
170 public function getMatchCondition( IReadableDatabase $db, string $field, string $op ): IExpression {
171 return $this->config->getMatchCondition( $db, $field, $op );
172 }
173
174 public function getExpireAfterDays(): ?int {
175 return $this->config->getExpireAfterDays();
176 }
177
178 public function getNotifyBeforeExpirationDays(): ?int {
179 return $this->config->getNotifyBeforeExpirationDays();
180 }
181
182 /**
183 * Attempts to auto create a temporary user using
184 * AuthManager::autoCreateUser, and optionally log them
185 * in if $login is true.
186 *
187 * @param string $name
188 * @param bool $login Whether to also log the user in to this temporary account.
189 * @return CreateStatus
190 */
191 private function attemptAutoCreate( string $name, bool $login = false ): CreateStatus {
192 $createStatus = new CreateStatus;
193 // Verify the $name is usable.
194 $user = $this->userFactory->newFromName( $name, UserRigorOptions::RIGOR_USABLE );
195 if ( !$user ) {
196 $createStatus->fatal( 'internalerror_info',
197 'Unable to create user with automatically generated name' );
198 return $createStatus;
199 }
200 $status = $this->authManager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_TEMP, $login );
201 $createStatus->merge( $status );
202 // If a userexists warning is a part of the status, then
203 // add the fatal error temp-user-unable-to-acquire.
204 if ( $createStatus->hasMessage( 'userexists' ) ) {
205 $createStatus->fatal( 'temp-user-unable-to-acquire' );
206 }
207 if ( $createStatus->isOK() ) {
208 $createStatus->value = $user;
209 }
210 return $createStatus;
211 }
212
213 /**
214 * Acquire a new username and return it. Permanently reserve the ID in
215 * the database.
216 *
217 * @param string $ip The IP address associated with this name acquisition request.
218 * @return string|null The username, or null if the auto-generated username is
219 * already in use, or if the attempt trips the TempAccountNameAcquisitionThrottle limits.
220 */
221 private function acquireName( string $ip ): ?string {
222 if ( $this->tempAccountNameAcquisitionThrottler->increase(
223 null, $ip, 'TempUserCreator'
224 ) ) {
225 return null;
226 }
227 $year = null;
228 if ( $this->serialProviderConfig['useYear'] ?? false ) {
229 $year = MWTimestamp::getInstance()->format( 'Y' );
230 }
231 // Check if the temporary account name is already in use as the ID provided
232 // may not be properly collision safe (T353390)
233 $index = $this->getSerialProvider()->acquireIndex( (int)$year );
234 $serialId = $this->getSerialMapping()->getSerialIdForIndex( $index );
235 $username = $this->config->getGeneratorPattern()->generate( $serialId, $year );
236
237 // Because the ::acquireIndex method may not always return a unique index,
238 // make sure that the temporary account name does not already exist. This
239 // is needed because of the problems discussed in T353390.
240 // The problems discussed at that task should not require the use of a primary lookup.
241 $centralId = $this->centralIdLookup->centralIdFromName(
242 $username,
243 CentralIdLookup::AUDIENCE_RAW
244 );
245 if ( !$centralId ) {
246 // If no user exists with this name centrally, then return the $username.
247 return $username;
248 }
249 return null;
250 }
251
252 /**
253 * Get the serial provider
254 * @return SerialProvider
255 */
256 private function getSerialProvider(): SerialProvider {
257 if ( !isset( $this->serialProvider ) ) {
258 $this->serialProvider = $this->createSerialProvider();
259 }
260 return $this->serialProvider;
261 }
262
263 /**
264 * Create the serial provider
265 * @return SerialProvider
266 */
267 private function createSerialProvider(): SerialProvider {
268 $type = $this->serialProviderConfig['type'];
269 if ( isset( self::SERIAL_PROVIDERS[$type] ) ) {
270 $spec = self::SERIAL_PROVIDERS[$type];
271 } else {
272 $extensionProviders = ExtensionRegistry::getInstance()
273 ->getAttribute( 'TempUserSerialProviders' );
274 if ( isset( $extensionProviders[$type] ) ) {
275 $spec = $extensionProviders[$type];
276 } else {
277 throw new UnexpectedValueException( __CLASS__ . ": unknown serial provider \"$type\"" );
278 }
279 }
280
281 /** @noinspection PhpIncompatibleReturnTypeInspection */
282 // @phan-suppress-next-line PhanTypeInvalidCallableArrayKey
283 return $this->objectFactory->createObject(
284 $spec,
285 [
286 'assertClass' => SerialProvider::class,
287 'extraArgs' => [ $this->serialProviderConfig ]
288 ]
289 );
290 }
291
292 /**
293 * Get the serial mapping
294 * @return SerialMapping
295 */
296 private function getSerialMapping(): SerialMapping {
297 if ( !isset( $this->serialMapping ) ) {
298 $this->serialMapping = $this->createSerialMapping();
299 }
300 return $this->serialMapping;
301 }
302
303 /**
304 * Create the serial map
305 * @return SerialMapping
306 */
307 private function createSerialMapping(): SerialMapping {
308 $type = $this->serialMappingConfig['type'];
309 if ( isset( self::SERIAL_MAPPINGS[$type] ) ) {
310 $spec = self::SERIAL_MAPPINGS[$type];
311 } else {
312 $extensionMappings = ExtensionRegistry::getInstance()
313 ->getAttribute( 'TempUserSerialMappings' );
314 if ( isset( $extensionMappings[$type] ) ) {
315 $spec = $extensionMappings[$type];
316 } else {
317 throw new UnexpectedValueException( __CLASS__ . ": unknown serial mapping \"$type\"" );
318 }
319 }
320 /** @noinspection PhpIncompatibleReturnTypeInspection */
321 // @phan-suppress-next-line PhanTypeInvalidCallableArrayKey
322 return $this->objectFactory->createObject(
323 $spec,
324 [
325 'assertClass' => SerialMapping::class,
326 'extraArgs' => [ $this->serialMappingConfig ]
327 ]
328 );
329 }
330
331 /**
332 * Permanently acquire a username, stash it in a session, and return it.
333 * Do not create the user.
334 *
335 * If this method was called before with the same session ID, return the
336 * previously stashed username instead of acquiring a new one.
337 *
338 * @param Session $session
339 * @return string|null The username, or null if no username could be acquired
340 */
341 public function acquireAndStashName( Session $session ) {
342 $name = $session->get( 'TempUser:name' );
343 if ( $name !== null ) {
344 return $name;
345 }
346 $name = $this->acquireName( $session->getRequest()->getIP() );
347 if ( $name !== null ) {
348 $session->set( 'TempUser:name', $name );
349 $session->save();
350 }
351 return $name;
352 }
353
354 /**
355 * Return a possible acquired and stashed username in a session.
356 * Do not acquire or create the user.
357 *
358 * If this method is called with the same session ID as function acquireAndStashName(),
359 * it returns the previously stashed username.
360 *
361 * @since 1.41
362 * @param Session $session
363 * @return ?string The username, if it was already acquired
364 */
365 public function getStashedName( Session $session ): ?string {
366 return $session->get( 'TempUser:name' );
367 }
368 }