MediaWiki  master
CookieSessionProvider.php
Go to the documentation of this file.
1 <?php
24 namespace MediaWiki\Session;
25 
26 use Config;
27 use User;
29 
37 
39  protected $params = [];
40 
42  protected $cookieOptions = [];
43 
57  public function __construct( $params = [] ) {
58  parent::__construct();
59 
60  $params += [
61  'cookieOptions' => [],
62  // @codeCoverageIgnoreStart
63  ];
64  // @codeCoverageIgnoreEnd
65 
66  if ( !isset( $params['priority'] ) ) {
67  throw new \InvalidArgumentException( __METHOD__ . ': priority must be specified' );
68  }
69  if ( $params['priority'] < SessionInfo::MIN_PRIORITY ||
71  ) {
72  throw new \InvalidArgumentException( __METHOD__ . ': Invalid priority' );
73  }
74 
75  if ( !is_array( $params['cookieOptions'] ) ) {
76  throw new \InvalidArgumentException( __METHOD__ . ': cookieOptions must be an array' );
77  }
78 
79  $this->priority = $params['priority'];
80  $this->cookieOptions = $params['cookieOptions'];
81  $this->params = $params;
82  unset( $this->params['priority'] );
83  unset( $this->params['cookieOptions'] );
84  }
85 
86  public function setConfig( Config $config ) {
87  parent::setConfig( $config );
88 
89  // @codeCoverageIgnoreStart
90  $this->params += [
91  // @codeCoverageIgnoreEnd
92  'callUserSetCookiesHook' => false,
93  'sessionName' =>
94  $config->get( 'SessionName' ) ?: $config->get( 'CookiePrefix' ) . '_session',
95  ];
96 
97  // @codeCoverageIgnoreStart
98  $this->cookieOptions += [
99  // @codeCoverageIgnoreEnd
100  'prefix' => $config->get( 'CookiePrefix' ),
101  'path' => $config->get( 'CookiePath' ),
102  'domain' => $config->get( 'CookieDomain' ),
103  'secure' => $config->get( 'CookieSecure' ),
104  'httpOnly' => $config->get( 'CookieHttpOnly' ),
105  ];
106  }
107 
109  $sessionId = $this->getCookie( $request, $this->params['sessionName'], '' );
110  $info = [
111  'provider' => $this,
112  'forceHTTPS' => $this->getCookie( $request, 'forceHTTPS', '', false )
113  ];
114  if ( SessionManager::validateSessionId( $sessionId ) ) {
115  $info['id'] = $sessionId;
116  $info['persisted'] = true;
117  }
118 
119  list( $userId, $userName, $token ) = $this->getUserInfoFromCookies( $request );
120  if ( $userId !== null ) {
121  try {
122  $userInfo = UserInfo::newFromId( $userId );
123  } catch ( \InvalidArgumentException $ex ) {
124  return null;
125  }
126 
127  // Sanity check
128  if ( $userName !== null && $userInfo->getName() !== $userName ) {
129  $this->logger->warning(
130  'Session "{session}" requested with mismatched UserID and UserName cookies.',
131  [
132  'session' => $sessionId,
133  'mismatch' => [
134  'userid' => $userId,
135  'cookie_username' => $userName,
136  'username' => $userInfo->getName(),
137  ],
138  ] );
139  return null;
140  }
141 
142  if ( $token !== null ) {
143  if ( !hash_equals( $userInfo->getToken(), $token ) ) {
144  $this->logger->warning(
145  'Session "{session}" requested with invalid Token cookie.',
146  [
147  'session' => $sessionId,
148  'userid' => $userId,
149  'username' => $userInfo->getName(),
150  ] );
151  return null;
152  }
153  $info['userInfo'] = $userInfo->verified();
154  $info['persisted'] = true; // If we have user+token, it should be
155  } elseif ( isset( $info['id'] ) ) {
156  $info['userInfo'] = $userInfo;
157  } else {
158  // No point in returning, loadSessionInfoFromStore() will
159  // reject it anyway.
160  return null;
161  }
162  } elseif ( isset( $info['id'] ) ) {
163  // No UserID cookie, so insist that the session is anonymous.
164  // Note: this event occurs for several normal activities:
165  // * anon visits Special:UserLogin
166  // * anon browsing after seeing Special:UserLogin
167  // * anon browsing after edit or preview
168  $this->logger->debug(
169  'Session "{session}" requested without UserID cookie',
170  [
171  'session' => $info['id'],
172  ] );
173  $info['userInfo'] = UserInfo::newAnonymous();
174  } else {
175  // No session ID and no user is the same as an empty session, so
176  // there's no point.
177  return null;
178  }
179 
180  return new SessionInfo( $this->priority, $info );
181  }
182 
183  public function persistsSessionId() {
184  return true;
185  }
186 
187  public function canChangeUser() {
188  return true;
189  }
190 
191  public function persistSession( SessionBackend $session, WebRequest $request ) {
192  $response = $request->response();
193  if ( $response->headersSent() ) {
194  // Can't do anything now
195  $this->logger->debug( __METHOD__ . ': Headers already sent' );
196  return;
197  }
198 
199  $user = $session->getUser();
200 
201  $cookies = $this->cookieDataToExport( $user, $session->shouldRememberUser() );
202  $sessionData = $this->sessionDataToExport( $user );
203 
204  // Legacy hook
205  if ( $this->params['callUserSetCookiesHook'] && !$user->isAnon() ) {
206  \Hooks::run( 'UserSetCookies', [ $user, &$sessionData, &$cookies ] );
207  }
208 
210 
211  $forceHTTPS = $session->shouldForceHTTPS() || $user->requiresHTTPS();
212  if ( $forceHTTPS ) {
213  // Don't set the secure flag if the request came in
214  // over "http", for backwards compat.
215  // @todo Break that backwards compat properly.
216  $options['secure'] = $this->config->get( 'CookieSecure' );
217  }
218 
219  $response->setCookie( $this->params['sessionName'], $session->getId(), null,
220  [ 'prefix' => '' ] + $options
221  );
222 
223  foreach ( $cookies as $key => $value ) {
224  if ( $value === false ) {
225  $response->clearCookie( $key, $options );
226  } else {
227  $expirationDuration = $this->getLoginCookieExpiration( $key, $session->shouldRememberUser() );
228  $expiration = $expirationDuration ? $expirationDuration + time() : null;
229  $response->setCookie( $key, (string)$value, $expiration, $options );
230  }
231  }
232 
233  $this->setForceHTTPSCookie( $forceHTTPS, $session, $request );
234  $this->setLoggedOutCookie( $session->getLoggedOutTimestamp(), $request );
235 
236  if ( $sessionData ) {
237  $session->addData( $sessionData );
238  }
239  }
240 
241  public function unpersistSession( WebRequest $request ) {
242  $response = $request->response();
243  if ( $response->headersSent() ) {
244  // Can't do anything now
245  $this->logger->debug( __METHOD__ . ': Headers already sent' );
246  return;
247  }
248 
249  $cookies = [
250  'UserID' => false,
251  'Token' => false,
252  ];
253 
254  $response->clearCookie(
255  $this->params['sessionName'], [ 'prefix' => '' ] + $this->cookieOptions
256  );
257 
258  foreach ( $cookies as $key => $value ) {
259  $response->clearCookie( $key, $this->cookieOptions );
260  }
261 
262  $this->setForceHTTPSCookie( false, null, $request );
263  }
264 
271  protected function setForceHTTPSCookie(
272  $set, SessionBackend $backend = null, WebRequest $request
273  ) {
274  $response = $request->response();
275  if ( $set ) {
276  if ( $backend->shouldRememberUser() ) {
277  $expirationDuration = $this->getLoginCookieExpiration(
278  'forceHTTPS',
279  true
280  );
281  $expiration = $expirationDuration ? $expirationDuration + time() : null;
282  } else {
283  $expiration = null;
284  }
285  $response->setCookie( 'forceHTTPS', 'true', $expiration,
286  [ 'prefix' => '', 'secure' => false ] + $this->cookieOptions );
287  } else {
288  $response->clearCookie( 'forceHTTPS',
289  [ 'prefix' => '', 'secure' => false ] + $this->cookieOptions );
290  }
291  }
292 
298  protected function setLoggedOutCookie( $loggedOut, WebRequest $request ) {
299  if ( $loggedOut + 86400 > time() &&
300  $loggedOut !== (int)$this->getCookie( $request, 'LoggedOut', $this->cookieOptions['prefix'] )
301  ) {
302  $request->response()->setCookie( 'LoggedOut', $loggedOut, $loggedOut + 86400,
303  $this->cookieOptions );
304  }
305  }
306 
307  public function getVaryCookies() {
308  return [
309  // Vary on token and session because those are the real authn
310  // determiners. UserID and UserName don't matter without those.
311  $this->cookieOptions['prefix'] . 'Token',
312  $this->cookieOptions['prefix'] . 'LoggedOut',
313  $this->params['sessionName'],
314  'forceHTTPS',
315  ];
316  }
317 
319  $name = $this->getCookie( $request, 'UserName', $this->cookieOptions['prefix'] );
320  if ( $name !== null ) {
321  $name = User::getCanonicalName( $name, 'usable' );
322  }
323  return $name === false ? null : $name;
324  }
325 
331  protected function getUserInfoFromCookies( $request ) {
332  $prefix = $this->cookieOptions['prefix'];
333  return [
334  $this->getCookie( $request, 'UserID', $prefix ),
335  $this->getCookie( $request, 'UserName', $prefix ),
336  $this->getCookie( $request, 'Token', $prefix ),
337  ];
338  }
339 
348  protected function getCookie( $request, $key, $prefix, $default = null ) {
349  $value = $request->getCookie( $key, $prefix, $default );
350  if ( $value === 'deleted' ) {
351  // PHP uses this value when deleting cookies. A legitimate cookie will never have
352  // this value (usernames start with uppercase, token is longer, other auth cookies
353  // are booleans or integers). Seeing this means that in a previous request we told the
354  // client to delete the cookie, but it has poor cookie handling. Pretend the cookie is
355  // not there to avoid invalidating the session.
356  return null;
357  }
358  return $value;
359  }
360 
367  protected function cookieDataToExport( $user, $remember ) {
368  if ( $user->isAnon() ) {
369  return [
370  'UserID' => false,
371  'Token' => false,
372  ];
373  } else {
374  return [
375  'UserID' => $user->getId(),
376  'UserName' => $user->getName(),
377  'Token' => $remember ? (string)$user->getToken() : false,
378  ];
379  }
380  }
381 
387  protected function sessionDataToExport( $user ) {
388  // If we're calling the legacy hook, we should populate $session
389  // like User::setCookies() did.
390  if ( !$user->isAnon() && $this->params['callUserSetCookiesHook'] ) {
391  return [
392  'wsUserID' => $user->getId(),
393  'wsToken' => $user->getToken(),
394  'wsUserName' => $user->getName(),
395  ];
396  }
397 
398  return [];
399  }
400 
401  public function whyNoSession() {
402  return wfMessage( 'sessionprovider-nocookies' );
403  }
404 
405  public function getRememberUserDuration() {
406  return min( $this->getLoginCookieExpiration( 'UserID', true ),
407  $this->getLoginCookieExpiration( 'Token', true ) ) ?: null;
408  }
409 
416  protected function getExtendedLoginCookies() {
417  return [ 'UserID', 'UserName', 'Token' ];
418  }
419 
430  protected function getLoginCookieExpiration( $cookieName, $shouldRememberUser ) {
431  $extendedCookies = $this->getExtendedLoginCookies();
432  $normalExpiration = $this->config->get( 'CookieExpiration' );
433 
434  if ( $shouldRememberUser && in_array( $cookieName, $extendedCookies, true ) ) {
435  $extendedExpiration = $this->config->get( 'ExtendedLoginCookieExpiration' );
436 
437  return ( $extendedExpiration !== null ) ? (int)$extendedExpiration : (int)$normalExpiration;
438  } else {
439  return (int)$normalExpiration;
440  }
441  }
442 }
getUser()
Returns the authenticated user for this session.
const MIN_PRIORITY
Minimum allowed priority.
Definition: SessionInfo.php:36
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
This is the actual workhorse for Session.
getLoginCookieExpiration( $cookieName, $shouldRememberUser)
Returns the lifespan of the login cookies, in seconds.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
response()
Return a handle to WebResponse style object, for setting cookies, headers and other stuff...
Definition: WebRequest.php:971
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
$value
cookieDataToExport( $user, $remember)
Return the data to store in cookies.
this hook is for auditing only $response
Definition: hooks.txt:780
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
static newAnonymous()
Create an instance for an anonymous (i.e.
Definition: UserInfo.php:75
static newFromId( $id, $verified=false)
Create an instance for a logged-in user by ID.
Definition: UserInfo.php:85
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid...
Definition: User.php:1246
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 use $formDescriptor instead 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
setForceHTTPSCookie( $set, SessionBackend $backend=null, WebRequest $request)
Set the "forceHTTPS" cookie.
Interface for configuration instances.
Definition: Config.php:28
A SessionProvider provides SessionInfo and support for Session.
sessionDataToExport( $user)
Return extra data to store in the session.
whyNoSession()
Return a Message for why sessions might not be being persisted.
getLoggedOutTimestamp()
Fetch the "logged out" timestamp.
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:1982
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
getId()
Returns the session ID.
getExtendedLoginCookies()
Gets the list of cookies that must be set to the &#39;remember me&#39; duration, if $wgExtendedLoginCookieExp...
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
A CookieSessionProvider persists sessions using cookies.
const MAX_PRIORITY
Maximum allowed priority.
Definition: SessionInfo.php:39
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
setLoggedOutCookie( $loggedOut, WebRequest $request)
Set the "logged out" cookie.
getUserInfoFromCookies( $request)
Fetch the user identity from cookies.
persistSession(SessionBackend $session, WebRequest $request)
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
shouldForceHTTPS()
Whether HTTPS should be forced.
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:2633
static validateSessionId( $id)
Validate a session ID.
addData(array $newData)
Add data to the session.
getCookie( $request, $key, $prefix, $default=null)
Get a cookie.
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
Value object returned by SessionProvider.
Definition: SessionInfo.php:34
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
shouldRememberUser()
Indicate whether the user should be remembered independently of the session ID.