MediaWiki  1.30.0
CookieSessionProvider.php
Go to the documentation of this file.
1 <?php
24 namespace MediaWiki\Session;
25 
26 use Config;
27 use User;
29 
37 
38  protected $params = [];
39  protected $cookieOptions = [];
40 
54  public function __construct( $params = [] ) {
55  parent::__construct();
56 
57  $params += [
58  'cookieOptions' => [],
59  // @codeCoverageIgnoreStart
60  ];
61  // @codeCoverageIgnoreEnd
62 
63  if ( !isset( $params['priority'] ) ) {
64  throw new \InvalidArgumentException( __METHOD__ . ': priority must be specified' );
65  }
66  if ( $params['priority'] < SessionInfo::MIN_PRIORITY ||
68  ) {
69  throw new \InvalidArgumentException( __METHOD__ . ': Invalid priority' );
70  }
71 
72  if ( !is_array( $params['cookieOptions'] ) ) {
73  throw new \InvalidArgumentException( __METHOD__ . ': cookieOptions must be an array' );
74  }
75 
76  $this->priority = $params['priority'];
77  $this->cookieOptions = $params['cookieOptions'];
78  $this->params = $params;
79  unset( $this->params['priority'] );
80  unset( $this->params['cookieOptions'] );
81  }
82 
83  public function setConfig( Config $config ) {
84  parent::setConfig( $config );
85 
86  // @codeCoverageIgnoreStart
87  $this->params += [
88  // @codeCoverageIgnoreEnd
89  'callUserSetCookiesHook' => false,
90  'sessionName' =>
91  $config->get( 'SessionName' ) ?: $config->get( 'CookiePrefix' ) . '_session',
92  ];
93 
94  // @codeCoverageIgnoreStart
95  $this->cookieOptions += [
96  // @codeCoverageIgnoreEnd
97  'prefix' => $config->get( 'CookiePrefix' ),
98  'path' => $config->get( 'CookiePath' ),
99  'domain' => $config->get( 'CookieDomain' ),
100  'secure' => $config->get( 'CookieSecure' ),
101  'httpOnly' => $config->get( 'CookieHttpOnly' ),
102  ];
103  }
104 
106  $sessionId = $this->getCookie( $request, $this->params['sessionName'], '' );
107  $info = [
108  'provider' => $this,
109  'forceHTTPS' => $this->getCookie( $request, 'forceHTTPS', '', false )
110  ];
111  if ( SessionManager::validateSessionId( $sessionId ) ) {
112  $info['id'] = $sessionId;
113  $info['persisted'] = true;
114  }
115 
116  list( $userId, $userName, $token ) = $this->getUserInfoFromCookies( $request );
117  if ( $userId !== null ) {
118  try {
119  $userInfo = UserInfo::newFromId( $userId );
120  } catch ( \InvalidArgumentException $ex ) {
121  return null;
122  }
123 
124  // Sanity check
125  if ( $userName !== null && $userInfo->getName() !== $userName ) {
126  $this->logger->warning(
127  'Session "{session}" requested with mismatched UserID and UserName cookies.',
128  [
129  'session' => $sessionId,
130  'mismatch' => [
131  'userid' => $userId,
132  'cookie_username' => $userName,
133  'username' => $userInfo->getName(),
134  ],
135  ] );
136  return null;
137  }
138 
139  if ( $token !== null ) {
140  if ( !hash_equals( $userInfo->getToken(), $token ) ) {
141  $this->logger->warning(
142  'Session "{session}" requested with invalid Token cookie.',
143  [
144  'session' => $sessionId,
145  'userid' => $userId,
146  'username' => $userInfo->getName(),
147  ] );
148  return null;
149  }
150  $info['userInfo'] = $userInfo->verified();
151  $info['persisted'] = true; // If we have user+token, it should be
152  } elseif ( isset( $info['id'] ) ) {
153  $info['userInfo'] = $userInfo;
154  } else {
155  // No point in returning, loadSessionInfoFromStore() will
156  // reject it anyway.
157  return null;
158  }
159  } elseif ( isset( $info['id'] ) ) {
160  // No UserID cookie, so insist that the session is anonymous.
161  // Note: this event occurs for several normal activities:
162  // * anon visits Special:UserLogin
163  // * anon browsing after seeing Special:UserLogin
164  // * anon browsing after edit or preview
165  $this->logger->debug(
166  'Session "{session}" requested without UserID cookie',
167  [
168  'session' => $info['id'],
169  ] );
170  $info['userInfo'] = UserInfo::newAnonymous();
171  } else {
172  // No session ID and no user is the same as an empty session, so
173  // there's no point.
174  return null;
175  }
176 
177  return new SessionInfo( $this->priority, $info );
178  }
179 
180  public function persistsSessionId() {
181  return true;
182  }
183 
184  public function canChangeUser() {
185  return true;
186  }
187 
188  public function persistSession( SessionBackend $session, WebRequest $request ) {
189  $response = $request->response();
190  if ( $response->headersSent() ) {
191  // Can't do anything now
192  $this->logger->debug( __METHOD__ . ': Headers already sent' );
193  return;
194  }
195 
196  $user = $session->getUser();
197 
198  $cookies = $this->cookieDataToExport( $user, $session->shouldRememberUser() );
199  $sessionData = $this->sessionDataToExport( $user );
200 
201  // Legacy hook
202  if ( $this->params['callUserSetCookiesHook'] && !$user->isAnon() ) {
203  \Hooks::run( 'UserSetCookies', [ $user, &$sessionData, &$cookies ] );
204  }
205 
207 
208  $forceHTTPS = $session->shouldForceHTTPS() || $user->requiresHTTPS();
209  if ( $forceHTTPS ) {
210  // Don't set the secure flag if the request came in
211  // over "http", for backwards compat.
212  // @todo Break that backwards compat properly.
213  $options['secure'] = $this->config->get( 'CookieSecure' );
214  }
215 
216  $response->setCookie( $this->params['sessionName'], $session->getId(), null,
217  [ 'prefix' => '' ] + $options
218  );
219 
220  foreach ( $cookies as $key => $value ) {
221  if ( $value === false ) {
222  $response->clearCookie( $key, $options );
223  } else {
224  $expirationDuration = $this->getLoginCookieExpiration( $key, $session->shouldRememberUser() );
225  $expiration = $expirationDuration ? $expirationDuration + time() : null;
226  $response->setCookie( $key, (string)$value, $expiration, $options );
227  }
228  }
229 
230  $this->setForceHTTPSCookie( $forceHTTPS, $session, $request );
231  $this->setLoggedOutCookie( $session->getLoggedOutTimestamp(), $request );
232 
233  if ( $sessionData ) {
234  $session->addData( $sessionData );
235  }
236  }
237 
238  public function unpersistSession( WebRequest $request ) {
239  $response = $request->response();
240  if ( $response->headersSent() ) {
241  // Can't do anything now
242  $this->logger->debug( __METHOD__ . ': Headers already sent' );
243  return;
244  }
245 
246  $cookies = [
247  'UserID' => false,
248  'Token' => false,
249  ];
250 
251  $response->clearCookie(
252  $this->params['sessionName'], [ 'prefix' => '' ] + $this->cookieOptions
253  );
254 
255  foreach ( $cookies as $key => $value ) {
256  $response->clearCookie( $key, $this->cookieOptions );
257  }
258 
259  $this->setForceHTTPSCookie( false, null, $request );
260  }
261 
268  protected function setForceHTTPSCookie(
269  $set, SessionBackend $backend = null, WebRequest $request
270  ) {
271  $response = $request->response();
272  if ( $set ) {
273  if ( $backend->shouldRememberUser() ) {
274  $expirationDuration = $this->getLoginCookieExpiration(
275  'forceHTTPS',
276  true
277  );
278  $expiration = $expirationDuration ? $expirationDuration + time() : null;
279  } else {
280  $expiration = null;
281  }
282  $response->setCookie( 'forceHTTPS', 'true', $expiration,
283  [ 'prefix' => '', 'secure' => false ] + $this->cookieOptions );
284  } else {
285  $response->clearCookie( 'forceHTTPS',
286  [ 'prefix' => '', 'secure' => false ] + $this->cookieOptions );
287  }
288  }
289 
295  protected function setLoggedOutCookie( $loggedOut, WebRequest $request ) {
296  if ( $loggedOut + 86400 > time() &&
297  $loggedOut !== (int)$this->getCookie( $request, 'LoggedOut', $this->cookieOptions['prefix'] )
298  ) {
299  $request->response()->setCookie( 'LoggedOut', $loggedOut, $loggedOut + 86400,
300  $this->cookieOptions );
301  }
302  }
303 
304  public function getVaryCookies() {
305  return [
306  // Vary on token and session because those are the real authn
307  // determiners. UserID and UserName don't matter without those.
308  $this->cookieOptions['prefix'] . 'Token',
309  $this->cookieOptions['prefix'] . 'LoggedOut',
310  $this->params['sessionName'],
311  'forceHTTPS',
312  ];
313  }
314 
316  $name = $this->getCookie( $request, 'UserName', $this->cookieOptions['prefix'] );
317  if ( $name !== null ) {
318  $name = User::getCanonicalName( $name, 'usable' );
319  }
320  return $name === false ? null : $name;
321  }
322 
328  protected function getUserInfoFromCookies( $request ) {
329  $prefix = $this->cookieOptions['prefix'];
330  return [
331  $this->getCookie( $request, 'UserID', $prefix ),
332  $this->getCookie( $request, 'UserName', $prefix ),
333  $this->getCookie( $request, 'Token', $prefix ),
334  ];
335  }
336 
345  protected function getCookie( $request, $key, $prefix, $default = null ) {
346  $value = $request->getCookie( $key, $prefix, $default );
347  if ( $value === 'deleted' ) {
348  // PHP uses this value when deleting cookies. A legitimate cookie will never have
349  // this value (usernames start with uppercase, token is longer, other auth cookies
350  // are booleans or integers). Seeing this means that in a previous request we told the
351  // client to delete the cookie, but it has poor cookie handling. Pretend the cookie is
352  // not there to avoid invalidating the session.
353  return null;
354  }
355  return $value;
356  }
357 
364  protected function cookieDataToExport( $user, $remember ) {
365  if ( $user->isAnon() ) {
366  return [
367  'UserID' => false,
368  'Token' => false,
369  ];
370  } else {
371  return [
372  'UserID' => $user->getId(),
373  'UserName' => $user->getName(),
374  'Token' => $remember ? (string)$user->getToken() : false,
375  ];
376  }
377  }
378 
384  protected function sessionDataToExport( $user ) {
385  // If we're calling the legacy hook, we should populate $session
386  // like User::setCookies() did.
387  if ( !$user->isAnon() && $this->params['callUserSetCookiesHook'] ) {
388  return [
389  'wsUserID' => $user->getId(),
390  'wsToken' => $user->getToken(),
391  'wsUserName' => $user->getName(),
392  ];
393  }
394 
395  return [];
396  }
397 
398  public function whyNoSession() {
399  return wfMessage( 'sessionprovider-nocookies' );
400  }
401 
402  public function getRememberUserDuration() {
403  return min( $this->getLoginCookieExpiration( 'UserID', true ),
404  $this->getLoginCookieExpiration( 'Token', true ) ) ?: null;
405  }
406 
413  protected function getExtendedLoginCookies() {
414  return [ 'UserID', 'UserName', 'Token' ];
415  }
416 
427  protected function getLoginCookieExpiration( $cookieName, $shouldRememberUser ) {
428  $extendedCookies = $this->getExtendedLoginCookies();
429  $normalExpiration = $this->config->get( 'CookieExpiration' );
430 
431  if ( $shouldRememberUser && in_array( $cookieName, $extendedCookies, true ) ) {
432  $extendedExpiration = $this->config->get( 'ExtendedLoginCookieExpiration' );
433 
434  return ( $extendedExpiration !== null ) ? (int)$extendedExpiration : (int)$normalExpiration;
435  } else {
436  return (int)$normalExpiration;
437  }
438  }
439 }
MediaWiki\Session\CookieSessionProvider\canChangeUser
canChangeUser()
Indicate whether the user associated with the request can be changed.
Definition: CookieSessionProvider.php:184
MediaWiki\Session\CookieSessionProvider\getExtendedLoginCookies
getExtendedLoginCookies()
Gets the list of cookies that must be set to the 'remember me' duration, if $wgExtendedLoginCookieExp...
Definition: CookieSessionProvider.php:413
MediaWiki\Session\UserInfo\newAnonymous
static newAnonymous()
Create an instance for an anonymous (i.e.
Definition: UserInfo.php:74
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:244
MediaWiki\Session\CookieSessionProvider\getCookie
getCookie( $request, $key, $prefix, $default=null)
Get a cookie.
Definition: CookieSessionProvider.php:345
MediaWiki\Session\SessionBackend\shouldRememberUser
shouldRememberUser()
Indicate whether the user should be remembered independently of the session ID.
Definition: SessionBackend.php:331
MediaWiki\Session\SessionBackend\getUser
getUser()
Returns the authenticated user for this session.
Definition: SessionBackend.php:369
MediaWiki\Session\CookieSessionProvider\setForceHTTPSCookie
setForceHTTPSCookie( $set, SessionBackend $backend=null, WebRequest $request)
Set the "forceHTTPS" cookie.
Definition: CookieSessionProvider.php:268
MediaWiki\Session\CookieSessionProvider\sessionDataToExport
sessionDataToExport( $user)
Return extra data to store in the session.
Definition: CookieSessionProvider.php:384
MediaWiki\Session\SessionBackend\getId
getId()
Returns the session ID.
Definition: SessionBackend.php:205
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
User
User
Definition: All_system_messages.txt:425
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
MediaWiki\Session\CookieSessionProvider\provideSessionInfo
provideSessionInfo(WebRequest $request)
Provide session info for a request.
Definition: CookieSessionProvider.php:105
MediaWiki\Session\CookieSessionProvider\unpersistSession
unpersistSession(WebRequest $request)
Remove any persisted session from a request/response.
Definition: CookieSessionProvider.php:238
Config
Interface for configuration instances.
Definition: Config.php:28
MediaWiki\Session\CookieSessionProvider\getUserInfoFromCookies
getUserInfoFromCookies( $request)
Fetch the user identity from cookies.
Definition: CookieSessionProvider.php:328
MediaWiki\Session\CookieSessionProvider\persistSession
persistSession(SessionBackend $session, WebRequest $request)
Persist a session into a request/response.
Definition: CookieSessionProvider.php:188
MediaWiki\Session\CookieSessionProvider\whyNoSession
whyNoSession()
Return a Message for why sessions might not be being persisted.
Definition: CookieSessionProvider.php:398
MediaWiki\Session\SessionManager\validateSessionId
static validateSessionId( $id)
Validate a session ID.
Definition: SessionManager.php:370
MediaWiki\Session\SessionProvider
A SessionProvider provides SessionInfo and support for Session.
Definition: SessionProvider.php:78
Config\get
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
MediaWiki\Session\CookieSessionProvider\setConfig
setConfig(Config $config)
Set configuration.
Definition: CookieSessionProvider.php:83
MediaWiki\Session\SessionBackend\addData
addData(array $newData)
Add data to the session.
Definition: SessionBackend.php:526
MediaWiki\Session
Definition: BotPasswordSessionProvider.php:24
MediaWiki\Session\CookieSessionProvider\getLoginCookieExpiration
getLoginCookieExpiration( $cookieName, $shouldRememberUser)
Returns the lifespan of the login cookies, in seconds.
Definition: CookieSessionProvider.php:427
string
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
$request
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2581
MediaWiki\Session\SessionInfo\MAX_PRIORITY
const MAX_PRIORITY
Maximum allowed priority.
Definition: SessionInfo.php:39
MediaWiki\Session\CookieSessionProvider\$params
$params
Definition: CookieSessionProvider.php:38
$value
$value
Definition: styleTest.css.php:45
MediaWiki\Session\CookieSessionProvider\__construct
__construct( $params=[])
Definition: CookieSessionProvider.php:54
MediaWiki\Session\SessionBackend\shouldForceHTTPS
shouldForceHTTPS()
Whether HTTPS should be forced.
Definition: SessionBackend.php:429
$response
this hook is for auditing only $response
Definition: hooks.txt:781
MediaWiki\Session\SessionProvider\$config
Config $config
Definition: SessionProvider.php:84
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:38
MediaWiki\Session\CookieSessionProvider\getVaryCookies
getVaryCookies()
Return the list of cookies that need varying on.
Definition: CookieSessionProvider.php:304
MediaWiki\Session\SessionInfo
Value object returned by SessionProvider.
Definition: SessionInfo.php:34
MediaWiki\Session\CookieSessionProvider\cookieDataToExport
cookieDataToExport( $user, $remember)
Return the data to store in cookies.
Definition: CookieSessionProvider.php:364
MediaWiki\Session\CookieSessionProvider\$cookieOptions
$cookieOptions
Definition: CookieSessionProvider.php:39
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1965
MediaWiki\Session\SessionBackend\getLoggedOutTimestamp
getLoggedOutTimestamp()
Fetch the "logged out" timestamp.
Definition: SessionBackend.php:454
MediaWiki\Session\UserInfo\newFromId
static newFromId( $id, $verified=false)
Create an instance for a logged-in user by ID.
Definition: UserInfo.php:84
MediaWiki\Session\CookieSessionProvider\suggestLoginUsername
suggestLoginUsername(WebRequest $request)
Get a suggested username for the login form.
Definition: CookieSessionProvider.php:315
User\getCanonicalName
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid.
Definition: User.php:1092
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
MediaWiki\Session\CookieSessionProvider\getRememberUserDuration
getRememberUserDuration()
Returns the duration (in seconds) for which users will be remembered when Session::setRememberUser() ...
Definition: CookieSessionProvider.php:402
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
MediaWiki\Session\CookieSessionProvider
A CookieSessionProvider persists sessions using cookies.
Definition: CookieSessionProvider.php:36
MediaWiki\Session\CookieSessionProvider\persistsSessionId
persistsSessionId()
Indicate whether self::persistSession() can save arbitrary session IDs.
Definition: CookieSessionProvider.php:180
MediaWiki\Session\SessionInfo\MIN_PRIORITY
const MIN_PRIORITY
Minimum allowed priority.
Definition: SessionInfo.php:36
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
MediaWiki\Session\CookieSessionProvider\setLoggedOutCookie
setLoggedOutCookie( $loggedOut, WebRequest $request)
Set the "logged out" cookie.
Definition: CookieSessionProvider.php:295
MediaWiki\Session\SessionBackend
This is the actual workhorse for Session.
Definition: SessionBackend.php:49