MediaWiki  1.34.0
CookieSessionProvider.php
Go to the documentation of this file.
1 <?php
24 namespace MediaWiki\Session;
25 
26 use Config;
27 use User;
28 use WebRequest;
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 
108  public function provideSessionInfo( WebRequest $request ) {
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 
209  $options = $this->cookieOptions;
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 
318  public function suggestLoginUsername( WebRequest $request ) {
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 }
MediaWiki\Session\CookieSessionProvider\canChangeUser
canChangeUser()
Indicate whether the user associated with the request can be changed.
Definition: CookieSessionProvider.php:187
MediaWiki\Session\CookieSessionProvider\getExtendedLoginCookies
getExtendedLoginCookies()
Gets the list of cookies that must be set to the 'remember me' duration, if $wgExtendedLoginCookieExp...
Definition: CookieSessionProvider.php:416
MediaWiki\Session\UserInfo\newAnonymous
static newAnonymous()
Create an instance for an anonymous (i.e.
Definition: UserInfo.php:75
MediaWiki\Session\CookieSessionProvider\getCookie
getCookie( $request, $key, $prefix, $default=null)
Get a cookie.
Definition: CookieSessionProvider.php:348
MediaWiki\Session\SessionBackend\shouldRememberUser
shouldRememberUser()
Indicate whether the user should be remembered independently of the session ID.
Definition: SessionBackend.php:353
MediaWiki\Session\SessionBackend\getUser
getUser()
Returns the authenticated user for this session.
Definition: SessionBackend.php:391
MediaWiki\Session\CookieSessionProvider\setForceHTTPSCookie
setForceHTTPSCookie( $set, SessionBackend $backend=null, WebRequest $request)
Set the "forceHTTPS" cookie.
Definition: CookieSessionProvider.php:271
$response
$response
Definition: opensearch_desc.php:38
MediaWiki\Session\CookieSessionProvider\sessionDataToExport
sessionDataToExport( $user)
Return extra data to store in the session.
Definition: CookieSessionProvider.php:387
MediaWiki\Session\SessionBackend\getId
getId()
Returns the session ID.
Definition: SessionBackend.php:225
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1264
MediaWiki\Session\CookieSessionProvider\provideSessionInfo
provideSessionInfo(WebRequest $request)
Provide session info for a request.
Definition: CookieSessionProvider.php:108
MediaWiki\Session\CookieSessionProvider\unpersistSession
unpersistSession(WebRequest $request)
Remove any persisted session from a request/response.
Definition: CookieSessionProvider.php:241
Config
Interface for configuration instances.
Definition: Config.php:28
MediaWiki\Session\CookieSessionProvider\getUserInfoFromCookies
getUserInfoFromCookies( $request)
Fetch the user identity from cookies.
Definition: CookieSessionProvider.php:331
MediaWiki\Session\CookieSessionProvider\persistSession
persistSession(SessionBackend $session, WebRequest $request)
Persist a session into a request/response.
Definition: CookieSessionProvider.php:191
MediaWiki\Session\CookieSessionProvider\whyNoSession
whyNoSession()
Return a Message for why sessions might not be being persisted.
Definition: CookieSessionProvider.php:401
MediaWiki\Session\SessionManager\validateSessionId
static validateSessionId( $id)
Validate a session ID.
Definition: SessionManager.php:365
MediaWiki\Session\SessionProvider
A SessionProvider provides SessionInfo and support for Session.
Definition: SessionProvider.php:78
MediaWiki\Session\CookieSessionProvider\$cookieOptions
mixed[] $cookieOptions
Definition: CookieSessionProvider.php:42
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:86
MediaWiki\Session\SessionBackend\addData
addData(array $newData)
Add data to the session.
Definition: SessionBackend.php:548
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:430
MediaWiki\Session\SessionInfo\MAX_PRIORITY
const MAX_PRIORITY
Maximum allowed priority.
Definition: SessionInfo.php:39
WebRequest\response
response()
Return a handle to WebResponse style object, for setting cookies, headers and other stuff,...
Definition: WebRequest.php:1036
MediaWiki\Session\CookieSessionProvider\__construct
__construct( $params=[])
Definition: CookieSessionProvider.php:57
MediaWiki\Session\SessionBackend\shouldForceHTTPS
shouldForceHTTPS()
Whether HTTPS should be forced.
Definition: SessionBackend.php:451
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:42
MediaWiki\Session\CookieSessionProvider\getVaryCookies
getVaryCookies()
Return the list of cookies that need varying on.
Definition: CookieSessionProvider.php:307
MediaWiki\Session\SessionInfo
Value object returned by SessionProvider.
Definition: SessionInfo.php:34
MediaWiki\Session\CookieSessionProvider\$params
mixed[] $params
Definition: CookieSessionProvider.php:39
MediaWiki\Session\CookieSessionProvider\cookieDataToExport
cookieDataToExport( $user, $remember)
Return the data to store in cookies.
Definition: CookieSessionProvider.php:367
MediaWiki\Session\SessionBackend\getLoggedOutTimestamp
getLoggedOutTimestamp()
Fetch the "logged out" timestamp.
Definition: SessionBackend.php:476
MediaWiki\Session\UserInfo\newFromId
static newFromId( $id, $verified=false)
Create an instance for a logged-in user by ID.
Definition: UserInfo.php:85
MediaWiki\Session\CookieSessionProvider\suggestLoginUsername
suggestLoginUsername(WebRequest $request)
Get a suggested username for the login form.
Definition: CookieSessionProvider.php:318
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:1139
MediaWiki\Session\CookieSessionProvider\getRememberUserDuration
getRememberUserDuration()
Returns the duration (in seconds) for which users will be remembered when Session::setRememberUser() ...
Definition: CookieSessionProvider.php:405
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:183
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:51
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:200
MediaWiki\Session\CookieSessionProvider\setLoggedOutCookie
setLoggedOutCookie( $loggedOut, WebRequest $request)
Set the "logged out" cookie.
Definition: CookieSessionProvider.php:298
MediaWiki\Session\SessionBackend
This is the actual workhorse for Session.
Definition: SessionBackend.php:50