MediaWiki  REL1_31
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 
43 
58  public function __construct( $params = [] ) {
59  parent::__construct();
60 
61  $params += [
62  'cookieOptions' => [],
63  // @codeCoverageIgnoreStart
64  ];
65  // @codeCoverageIgnoreEnd
66 
67  if ( !isset( $params['priority'] ) ) {
68  throw new \InvalidArgumentException( __METHOD__ . ': priority must be specified' );
69  }
70  if ( $params['priority'] < SessionInfo::MIN_PRIORITY ||
72  ) {
73  throw new \InvalidArgumentException( __METHOD__ . ': Invalid priority' );
74  }
75 
76  if ( !is_array( $params['cookieOptions'] ) ) {
77  throw new \InvalidArgumentException( __METHOD__ . ': cookieOptions must be an array' );
78  }
79 
80  $this->priority = $params['priority'];
81  $this->cookieOptions = $params['cookieOptions'];
82  $this->params = $params;
83  unset( $this->params['priority'] );
84  unset( $this->params['cookieOptions'] );
85  }
86 
87  public function setConfig( Config $config ) {
88  parent::setConfig( $config );
89 
90  // @codeCoverageIgnoreStart
91  $this->params += [
92  // @codeCoverageIgnoreEnd
93  'callUserSetCookiesHook' => false,
94  'sessionName' =>
95  $config->get( 'SessionName' ) ?: $config->get( 'CookiePrefix' ) . '_session',
96  ];
97 
98  $this->useCrossSiteCookies = strcasecmp( $config->get( 'CookieSameSite' ), 'none' ) === 0;
99 
100  // @codeCoverageIgnoreStart
101  $this->cookieOptions += [
102  // @codeCoverageIgnoreEnd
103  'prefix' => $config->get( 'CookiePrefix' ),
104  'path' => $config->get( 'CookiePath' ),
105  'domain' => $config->get( 'CookieDomain' ),
106  'secure' => $config->get( 'CookieSecure' ) || $this->config->get( 'ForceHTTPS' ),
107  'httpOnly' => $config->get( 'CookieHttpOnly' ),
108  'sameSite' => $config->get( 'CookieSameSite' ),
109  ];
110  }
111 
113  $sessionId = $this->getCookie( $request, $this->params['sessionName'], '' );
114  $info = [
115  'provider' => $this,
116  'forceHTTPS' => $this->getCookie( $request, 'forceHTTPS', '', false )
117  ];
118  if ( SessionManager::validateSessionId( $sessionId ) ) {
119  $info['id'] = $sessionId;
120  $info['persisted'] = true;
121  }
122 
123  list( $userId, $userName, $token ) = $this->getUserInfoFromCookies( $request );
124  if ( $userId !== null ) {
125  try {
126  $userInfo = UserInfo::newFromId( $userId );
127  } catch ( \InvalidArgumentException $ex ) {
128  return null;
129  }
130 
131  // Sanity check
132  if ( $userName !== null && $userInfo->getName() !== $userName ) {
133  $this->logger->warning(
134  'Session "{session}" requested with mismatched UserID and UserName cookies.',
135  [
136  'session' => $sessionId,
137  'mismatch' => [
138  'userid' => $userId,
139  'cookie_username' => $userName,
140  'username' => $userInfo->getName(),
141  ],
142  ] );
143  return null;
144  }
145 
146  if ( $token !== null ) {
147  if ( !hash_equals( $userInfo->getToken(), $token ) ) {
148  $this->logger->warning(
149  'Session "{session}" requested with invalid Token cookie.',
150  [
151  'session' => $sessionId,
152  'userid' => $userId,
153  'username' => $userInfo->getName(),
154  ] );
155  return null;
156  }
157  $info['userInfo'] = $userInfo->verified();
158  $info['persisted'] = true; // If we have user+token, it should be
159  } elseif ( isset( $info['id'] ) ) {
160  $info['userInfo'] = $userInfo;
161  } else {
162  // No point in returning, loadSessionInfoFromStore() will
163  // reject it anyway.
164  return null;
165  }
166  } elseif ( isset( $info['id'] ) ) {
167  // No UserID cookie, so insist that the session is anonymous.
168  // Note: this event occurs for several normal activities:
169  // * anon visits Special:UserLogin
170  // * anon browsing after seeing Special:UserLogin
171  // * anon browsing after edit or preview
172  $this->logger->debug(
173  'Session "{session}" requested without UserID cookie',
174  [
175  'session' => $info['id'],
176  ] );
177  $info['userInfo'] = UserInfo::newAnonymous();
178  } else {
179  // No session ID and no user is the same as an empty session, so
180  // there's no point.
181  return null;
182  }
183 
184  return new SessionInfo( $this->priority, $info );
185  }
186 
187  public function persistsSessionId() {
188  return true;
189  }
190 
191  public function canChangeUser() {
192  return true;
193  }
194 
195  public function persistSession( SessionBackend $session, WebRequest $request ) {
196  $response = $request->response();
197  if ( $response->headersSent() ) {
198  // Can't do anything now
199  $this->logger->debug( __METHOD__ . ': Headers already sent' );
200  return;
201  }
202 
203  $user = $session->getUser();
204 
205  $cookies = $this->cookieDataToExport( $user, $session->shouldRememberUser() );
206  $sessionData = $this->sessionDataToExport( $user );
207 
208  // Legacy hook
209  if ( $this->params['callUserSetCookiesHook'] && !$user->isAnon() ) {
210  \Hooks::run( 'UserSetCookies', [ $user, &$sessionData, &$cookies ] );
211  }
212 
214 
215  $forceHTTPS = $session->shouldForceHTTPS() || $user->requiresHTTPS();
216  if ( $forceHTTPS ) {
217  $options['secure'] = $this->config->get( 'CookieSecure' )
218  || $this->config->get( 'ForceHTTPS' );
219  }
220 
221  $response->setCookie( $this->params['sessionName'], $session->getId(), null,
222  [ 'prefix' => '' ] + $options
223  );
224 
225  foreach ( $cookies as $key => $value ) {
226  if ( $value === false ) {
227  $response->clearCookie( $key, $options );
228  } else {
229  $expirationDuration = $this->getLoginCookieExpiration( $key, $session->shouldRememberUser() );
230  $expiration = $expirationDuration ? $expirationDuration + time() : null;
231  $response->setCookie( $key, (string)$value, $expiration, $options );
232  }
233  }
234 
235  $this->setForceHTTPSCookie( $forceHTTPS, $session, $request );
236  $this->setLoggedOutCookie( $session->getLoggedOutTimestamp(), $request );
237 
238  if ( $sessionData ) {
239  $session->addData( $sessionData );
240  }
241  }
242 
243  public function unpersistSession( WebRequest $request ) {
244  $response = $request->response();
245  if ( $response->headersSent() ) {
246  // Can't do anything now
247  $this->logger->debug( __METHOD__ . ': Headers already sent' );
248  return;
249  }
250 
251  $cookies = [
252  'UserID' => false,
253  'Token' => false,
254  ];
255 
256  $response->clearCookie(
257  $this->params['sessionName'], [ 'prefix' => '' ] + $this->cookieOptions
258  );
259 
260  foreach ( $cookies as $key => $value ) {
261  $response->clearCookie( $key, $this->cookieOptions );
262  }
263 
264  $this->setForceHTTPSCookie( false, null, $request );
265  }
266 
274  protected function setForceHTTPSCookie(
275  $set, SessionBackend $backend = null, WebRequest $request
276  ) {
277  if ( $this->config->get( 'ForceHTTPS' ) ) {
278  // No need to send a cookie if the wiki is always HTTPS (T256095)
279  return;
280  }
281  $response = $request->response();
282  if ( $set ) {
283  if ( $backend->shouldRememberUser() ) {
284  $expirationDuration = $this->getLoginCookieExpiration(
285  'forceHTTPS',
286  true
287  );
288  $expiration = $expirationDuration ? $expirationDuration + time() : null;
289  } else {
290  $expiration = null;
291  }
292  $response->setCookie( 'forceHTTPS', 'true', $expiration,
293  [ 'prefix' => '', 'secure' => false ] + $this->cookieOptions );
294  } else {
295  $response->clearCookie( 'forceHTTPS',
296  [ 'prefix' => '', 'secure' => false ] + $this->cookieOptions );
297  }
298  }
299 
305  protected function setLoggedOutCookie( $loggedOut, WebRequest $request ) {
306  if ( $loggedOut + 86400 > time() &&
307  $loggedOut !== (int)$this->getCookie( $request, 'LoggedOut', $this->cookieOptions['prefix'] )
308  ) {
309  $request->response()->setCookie( 'LoggedOut', $loggedOut, $loggedOut + 86400,
310  $this->cookieOptions );
311  }
312  }
313 
314  public function getVaryCookies() {
315  return [
316  // Vary on token and session because those are the real authn
317  // determiners. UserID and UserName don't matter without those.
318  $this->cookieOptions['prefix'] . 'Token',
319  $this->cookieOptions['prefix'] . 'LoggedOut',
320  $this->params['sessionName'],
321  'forceHTTPS',
322  ];
323  }
324 
326  $name = $this->getCookie( $request, 'UserName', $this->cookieOptions['prefix'] );
327  if ( $name !== null ) {
328  $name = User::getCanonicalName( $name, 'usable' );
329  }
330  return $name === false ? null : $name;
331  }
332 
338  protected function getUserInfoFromCookies( $request ) {
339  $prefix = $this->cookieOptions['prefix'];
340  return [
341  $this->getCookie( $request, 'UserID', $prefix ),
342  $this->getCookie( $request, 'UserName', $prefix ),
343  $this->getCookie( $request, 'Token', $prefix ),
344  ];
345  }
346 
355  protected function getCookie( $request, $key, $prefix, $default = null ) {
356  if ( $this->useCrossSiteCookies ) {
357  $value = $request->getCrossSiteCookie( $key, $prefix, $default );
358  } else {
359  $value = $request->getCookie( $key, $prefix, $default );
360  }
361  if ( $value === 'deleted' ) {
362  // PHP uses this value when deleting cookies. A legitimate cookie will never have
363  // this value (usernames start with uppercase, token is longer, other auth cookies
364  // are booleans or integers). Seeing this means that in a previous request we told the
365  // client to delete the cookie, but it has poor cookie handling. Pretend the cookie is
366  // not there to avoid invalidating the session.
367  return null;
368  }
369  return $value;
370  }
371 
378  protected function cookieDataToExport( $user, $remember ) {
379  if ( $user->isAnon() ) {
380  return [
381  'UserID' => false,
382  'Token' => false,
383  ];
384  } else {
385  return [
386  'UserID' => $user->getId(),
387  'UserName' => $user->getName(),
388  'Token' => $remember ? (string)$user->getToken() : false,
389  ];
390  }
391  }
392 
398  protected function sessionDataToExport( $user ) {
399  // If we're calling the legacy hook, we should populate $session
400  // like User::setCookies() did.
401  if ( !$user->isAnon() && $this->params['callUserSetCookiesHook'] ) {
402  return [
403  'wsUserID' => $user->getId(),
404  'wsToken' => $user->getToken(),
405  'wsUserName' => $user->getName(),
406  ];
407  }
408 
409  return [];
410  }
411 
412  public function whyNoSession() {
413  return wfMessage( 'sessionprovider-nocookies' );
414  }
415 
416  public function getRememberUserDuration() {
417  return min( $this->getLoginCookieExpiration( 'UserID', true ),
418  $this->getLoginCookieExpiration( 'Token', true ) ) ?: null;
419  }
420 
427  protected function getExtendedLoginCookies() {
428  return [ 'UserID', 'UserName', 'Token' ];
429  }
430 
441  protected function getLoginCookieExpiration( $cookieName, $shouldRememberUser ) {
442  $extendedCookies = $this->getExtendedLoginCookies();
443  $normalExpiration = $this->config->get( 'CookieExpiration' );
444 
445  if ( $shouldRememberUser && in_array( $cookieName, $extendedCookies, true ) ) {
446  $extendedExpiration = $this->config->get( 'ExtendedLoginCookieExpiration' );
447 
448  return ( $extendedExpiration !== null ) ? (int)$extendedExpiration : (int)$normalExpiration;
449  } else {
450  return (int)$normalExpiration;
451  }
452  }
453 }
MediaWiki\Session\CookieSessionProvider\canChangeUser
canChangeUser()
Indicate whether the user associated with the request can be changed.
Definition: CookieSessionProvider.php:191
MediaWiki\Session\CookieSessionProvider\getExtendedLoginCookies
getExtendedLoginCookies()
Gets the list of cookies that must be set to the 'remember me' duration, if $wgExtendedLoginCookieExp...
Definition: CookieSessionProvider.php:427
$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:247
MediaWiki\Session\UserInfo\newAnonymous
static newAnonymous()
Create an instance for an anonymous (i.e.
Definition: UserInfo.php:74
MediaWiki\Session\CookieSessionProvider\getCookie
getCookie( $request, $key, $prefix, $default=null)
Get a cookie.
Definition: CookieSessionProvider.php:355
MediaWiki\Session\SessionBackend\shouldRememberUser
shouldRememberUser()
Indicate whether the user should be remembered independently of the session ID.
Definition: SessionBackend.php:331
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
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, unless $wgForceHTTPS prevents it.
Definition: CookieSessionProvider.php:274
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
$response
this hook is for auditing only $response
Definition: hooks.txt:783
MediaWiki\Session\CookieSessionProvider\sessionDataToExport
sessionDataToExport( $user)
Return extra data to store in the session.
Definition: CookieSessionProvider.php:398
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:181
MediaWiki\Session\SessionBackend\getId
getId()
Returns the session ID.
Definition: SessionBackend.php:205
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:37
MediaWiki\Session\CookieSessionProvider\provideSessionInfo
provideSessionInfo(WebRequest $request)
Provide session info for a request.
Definition: CookieSessionProvider.php:112
MediaWiki\Session\CookieSessionProvider\unpersistSession
unpersistSession(WebRequest $request)
Remove any persisted session from a request/response.
Definition: CookieSessionProvider.php:243
Config
Interface for configuration instances.
Definition: Config.php:28
MediaWiki\Session\CookieSessionProvider\getUserInfoFromCookies
getUserInfoFromCookies( $request)
Fetch the user identity from cookies.
Definition: CookieSessionProvider.php:338
MediaWiki\Session\CookieSessionProvider\$useCrossSiteCookies
bool $useCrossSiteCookies
Definition: CookieSessionProvider.php:42
MediaWiki\Session\CookieSessionProvider\persistSession
persistSession(SessionBackend $session, WebRequest $request)
Persist a session into a request/response.
Definition: CookieSessionProvider.php:195
MediaWiki\Session\CookieSessionProvider\whyNoSession
whyNoSession()
Return a Message for why sessions might not be being persisted.
Definition: CookieSessionProvider.php:412
MediaWiki\Session\SessionManager\validateSessionId
static validateSessionId( $id)
Validate a session ID.
Definition: SessionManager.php:371
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:87
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:441
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
$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:2001
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:58
MediaWiki\Session\SessionBackend\shouldForceHTTPS
shouldForceHTTPS()
Whether HTTPS should be forced.
Definition: SessionBackend.php:429
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:314
MediaWiki\Session\SessionInfo
Value object returned by SessionProvider.
Definition: SessionInfo.php:34
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
MediaWiki\Session\CookieSessionProvider\cookieDataToExport
cookieDataToExport( $user, $remember)
Return the data to store in cookies.
Definition: CookieSessionProvider.php:378
MediaWiki\Session\CookieSessionProvider\$cookieOptions
$cookieOptions
Definition: CookieSessionProvider.php:39
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:325
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:1210
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:22
MediaWiki\Session\CookieSessionProvider\getRememberUserDuration
getRememberUserDuration()
Returns the duration (in seconds) for which users will be remembered when Session::setRememberUser() ...
Definition: CookieSessionProvider.php:416
MediaWiki\Session\CookieSessionProvider
A CookieSessionProvider persists sessions using cookies.
Definition: CookieSessionProvider.php:36
$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:2806
MediaWiki\Session\CookieSessionProvider\persistsSessionId
persistsSessionId()
Indicate whether self::persistSession() can save arbitrary session IDs.
Definition: CookieSessionProvider.php:187
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:305
MediaWiki\Session\SessionBackend
This is the actual workhorse for Session.
Definition: SessionBackend.php:49