MediaWiki  master
CookieSessionProvider.php
Go to the documentation of this file.
1 <?php
24 namespace MediaWiki\Session;
25 
27 use User;
28 use WebRequest;
29 
37 
39  protected $params = [];
40 
42  protected $cookieOptions = [];
43 
46 
61  public function __construct( $params = [] ) {
62  parent::__construct();
63 
64  $params += [
65  'cookieOptions' => [],
66  // @codeCoverageIgnoreStart
67  ];
68  // @codeCoverageIgnoreEnd
69 
70  if ( !isset( $params['priority'] ) ) {
71  throw new \InvalidArgumentException( __METHOD__ . ': priority must be specified' );
72  }
73  if ( $params['priority'] < SessionInfo::MIN_PRIORITY ||
75  ) {
76  throw new \InvalidArgumentException( __METHOD__ . ': Invalid priority' );
77  }
78 
79  if ( !is_array( $params['cookieOptions'] ) ) {
80  throw new \InvalidArgumentException( __METHOD__ . ': cookieOptions must be an array' );
81  }
82 
83  $this->priority = $params['priority'];
84  $this->cookieOptions = $params['cookieOptions'];
85  $this->params = $params;
86  unset( $this->params['priority'] );
87  unset( $this->params['cookieOptions'] );
88  }
89 
90  protected function postInitSetup() {
91  // @codeCoverageIgnoreStart
92  $this->params += [
93  // @codeCoverageIgnoreEnd
94  'callUserSetCookiesHook' => false,
95  'sessionName' =>
96  $this->getConfig()->get( 'SessionName' ) ?: $this->getConfig()->get( 'CookiePrefix' ) . '_session',
97  ];
98 
99  $this->useCrossSiteCookies = strcasecmp( $this->getConfig()->get( 'CookieSameSite' ), 'none' ) === 0;
100 
101  // @codeCoverageIgnoreStart
102  $this->cookieOptions += [
103  // @codeCoverageIgnoreEnd
104  'prefix' => $this->getConfig()->get( 'CookiePrefix' ),
105  'path' => $this->getConfig()->get( 'CookiePath' ),
106  'domain' => $this->getConfig()->get( 'CookieDomain' ),
107  'secure' => $this->getConfig()->get( 'CookieSecure' ) || $this->getConfig()->get( 'ForceHTTPS' ),
108  'httpOnly' => $this->getConfig()->get( 'CookieHttpOnly' ),
109  'sameSite' => $this->getConfig()->get( 'CookieSameSite' ),
110  ];
111  }
112 
113  public function provideSessionInfo( WebRequest $request ) {
114  $sessionId = $this->getCookie( $request, $this->params['sessionName'], '' );
115  $info = [
116  'provider' => $this,
117  'forceHTTPS' => $this->getCookie( $request, 'forceHTTPS', '', false )
118  ];
119  if ( SessionManager::validateSessionId( $sessionId ) ) {
120  $info['id'] = $sessionId;
121  $info['persisted'] = true;
122  }
123 
124  list( $userId, $userName, $token ) = $this->getUserInfoFromCookies( $request );
125  if ( $userId !== null ) {
126  try {
127  $userInfo = UserInfo::newFromId( $userId );
128  } catch ( \InvalidArgumentException $ex ) {
129  return null;
130  }
131 
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  $this->getHookRunner()->onUserSetCookies( $user, $sessionData, $cookies );
211  }
212 
213  $options = $this->cookieOptions;
214 
215  $forceHTTPS = $session->shouldForceHTTPS() || $user->requiresHTTPS();
216  if ( $forceHTTPS ) {
217  $options['secure'] = $this->getConfig()->get( 'CookieSecure' )
218  || $this->getConfig()->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( $set, ?SessionBackend $backend, WebRequest $request ) {
275  if ( $this->getConfig()->get( 'ForceHTTPS' ) ) {
276  // No need to send a cookie if the wiki is always HTTPS (T256095)
277  return;
278  }
279  $response = $request->response();
280  if ( $set ) {
281  if ( $backend->shouldRememberUser() ) {
282  $expirationDuration = $this->getLoginCookieExpiration(
283  'forceHTTPS',
284  true
285  );
286  $expiration = $expirationDuration ? $expirationDuration + time() : null;
287  } else {
288  $expiration = null;
289  }
290  $response->setCookie( 'forceHTTPS', 'true', $expiration,
291  [ 'prefix' => '', 'secure' => false ] + $this->cookieOptions );
292  } else {
293  $response->clearCookie( 'forceHTTPS',
294  [ 'prefix' => '', 'secure' => false ] + $this->cookieOptions );
295  }
296  }
297 
302  protected function setLoggedOutCookie( $loggedOut, WebRequest $request ) {
303  if ( $loggedOut + 86400 > time() &&
304  $loggedOut !== (int)$this->getCookie( $request, 'LoggedOut', $this->cookieOptions['prefix'] )
305  ) {
306  $request->response()->setCookie( 'LoggedOut', $loggedOut, $loggedOut + 86400,
307  $this->cookieOptions );
308  }
309  }
310 
311  public function getVaryCookies() {
312  return [
313  // Vary on token and session because those are the real authn
314  // determiners. UserID and UserName don't matter without those.
315  $this->cookieOptions['prefix'] . 'Token',
316  $this->cookieOptions['prefix'] . 'LoggedOut',
317  $this->params['sessionName'],
318  'forceHTTPS',
319  ];
320  }
321 
322  public function suggestLoginUsername( WebRequest $request ) {
323  $name = $this->getCookie( $request, 'UserName', $this->cookieOptions['prefix'] );
324  if ( $name !== null ) {
325  $name = $this->userNameUtils->getCanonical( $name, UserNameUtils::RIGOR_USABLE );
326  }
327  return $name === false ? null : $name;
328  }
329 
335  protected function getUserInfoFromCookies( $request ) {
336  $prefix = $this->cookieOptions['prefix'];
337  return [
338  $this->getCookie( $request, 'UserID', $prefix ),
339  $this->getCookie( $request, 'UserName', $prefix ),
340  $this->getCookie( $request, 'Token', $prefix ),
341  ];
342  }
343 
352  protected function getCookie( $request, $key, $prefix, $default = null ) {
353  if ( $this->useCrossSiteCookies ) {
354  $value = $request->getCrossSiteCookie( $key, $prefix, $default );
355  } else {
356  $value = $request->getCookie( $key, $prefix, $default );
357  }
358  if ( $value === 'deleted' ) {
359  // PHP uses this value when deleting cookies. A legitimate cookie will never have
360  // this value (usernames start with uppercase, token is longer, other auth cookies
361  // are booleans or integers). Seeing this means that in a previous request we told the
362  // client to delete the cookie, but it has poor cookie handling. Pretend the cookie is
363  // not there to avoid invalidating the session.
364  return null;
365  }
366  return $value;
367  }
368 
375  protected function cookieDataToExport( $user, $remember ) {
376  if ( $user->isAnon() ) {
377  return [
378  'UserID' => false,
379  'Token' => false,
380  ];
381  } else {
382  return [
383  'UserID' => $user->getId(),
384  'UserName' => $user->getName(),
385  'Token' => $remember ? (string)$user->getToken() : false,
386  ];
387  }
388  }
389 
395  protected function sessionDataToExport( $user ) {
396  // If we're calling the legacy hook, we should populate $session
397  // like User::setCookies() did.
398  if ( !$user->isAnon() && $this->params['callUserSetCookiesHook'] ) {
399  return [
400  'wsUserID' => $user->getId(),
401  'wsToken' => $user->getToken(),
402  'wsUserName' => $user->getName(),
403  ];
404  }
405 
406  return [];
407  }
408 
409  public function whyNoSession() {
410  return wfMessage( 'sessionprovider-nocookies' );
411  }
412 
413  public function getRememberUserDuration() {
414  return min( $this->getLoginCookieExpiration( 'UserID', true ),
415  $this->getLoginCookieExpiration( 'Token', true ) ) ?: null;
416  }
417 
424  protected function getExtendedLoginCookies() {
425  return [ 'UserID', 'UserName', 'Token' ];
426  }
427 
438  protected function getLoginCookieExpiration( $cookieName, $shouldRememberUser ) {
439  $extendedCookies = $this->getExtendedLoginCookies();
440  $normalExpiration = $this->getConfig()->get( 'CookieExpiration' );
441 
442  if ( $shouldRememberUser && in_array( $cookieName, $extendedCookies, true ) ) {
443  $extendedExpiration = $this->getConfig()->get( 'ExtendedLoginCookieExpiration' );
444 
445  return ( $extendedExpiration !== null ) ? (int)$extendedExpiration : (int)$normalExpiration;
446  } else {
447  return (int)$normalExpiration;
448  }
449  }
450 }
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:424
MediaWiki\Session\UserInfo\newAnonymous
static newAnonymous()
Create an instance for an anonymous (i.e.
Definition: UserInfo.php:78
MediaWiki\Session\CookieSessionProvider\getCookie
getCookie( $request, $key, $prefix, $default=null)
Get a cookie.
Definition: CookieSessionProvider.php:352
MediaWiki\Session\SessionBackend\shouldRememberUser
shouldRememberUser()
Indicate whether the user should be remembered independently of the session ID.
Definition: SessionBackend.php:380
MediaWiki\Session\SessionBackend\getUser
getUser()
Returns the authenticated user for this session.
Definition: SessionBackend.php:418
MediaWiki\Session\CookieSessionProvider\sessionDataToExport
sessionDataToExport( $user)
Return extra data to store in the session.
Definition: CookieSessionProvider.php:395
MediaWiki\Session\SessionBackend\getId
getId()
Returns the session ID.
Definition: SessionBackend.php:252
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1167
MediaWiki\Session\CookieSessionProvider\provideSessionInfo
provideSessionInfo(WebRequest $request)
Provide session info for a request.
Definition: CookieSessionProvider.php:113
MediaWiki\Session\CookieSessionProvider\unpersistSession
unpersistSession(WebRequest $request)
Remove any persisted session from a request/response.
Definition: CookieSessionProvider.php:243
MediaWiki\Session\CookieSessionProvider\getUserInfoFromCookies
getUserInfoFromCookies( $request)
Fetch the user identity from cookies.
Definition: CookieSessionProvider.php:335
MediaWiki\Session\CookieSessionProvider\$useCrossSiteCookies
bool $useCrossSiteCookies
Definition: CookieSessionProvider.php:45
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.For example, "check whether you're blo...
Definition: CookieSessionProvider.php:409
MediaWiki\Session\SessionManager\validateSessionId
static validateSessionId( $id)
Validate a session ID.
Definition: SessionManager.php:425
MediaWiki\Session\SessionProvider
A SessionProvider provides SessionInfo and support for Session.
Definition: SessionProvider.php:81
MediaWiki\Session\CookieSessionProvider\$cookieOptions
mixed[] $cookieOptions
Definition: CookieSessionProvider.php:42
MediaWiki\Session\SessionBackend\addData
addData(array $newData)
Add data to the session.
Definition: SessionBackend.php:573
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:438
MediaWiki\Session\SessionInfo\MAX_PRIORITY
const MAX_PRIORITY
Maximum allowed priority.
Definition: SessionInfo.php:42
WebRequest\response
response()
Return a handle to WebResponse style object, for setting cookies, headers and other stuff,...
Definition: WebRequest.php:1091
MediaWiki\Session\CookieSessionProvider\__construct
__construct( $params=[])
Definition: CookieSessionProvider.php:61
MediaWiki\Session\CookieSessionProvider\setForceHTTPSCookie
setForceHTTPSCookie( $set, ?SessionBackend $backend, WebRequest $request)
Set the "forceHTTPS" cookie, unless $wgForceHTTPS prevents it.
Definition: CookieSessionProvider.php:274
MediaWiki\Session\SessionBackend\shouldForceHTTPS
shouldForceHTTPS()
Whether HTTPS should be forced.
Definition: SessionBackend.php:478
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:43
MediaWiki\Session\CookieSessionProvider\getVaryCookies
getVaryCookies()
Return the list of cookies that need varying on.
Definition: CookieSessionProvider.php:311
MediaWiki\Session\SessionInfo
Value object returned by SessionProvider.
Definition: SessionInfo.php:37
MediaWiki\Session\CookieSessionProvider\$params
mixed[] $params
Definition: CookieSessionProvider.php:39
MediaWiki\Session\SessionProvider\getConfig
getConfig()
Get the config.
Definition: SessionProvider.php:190
MediaWiki\Session\CookieSessionProvider\cookieDataToExport
cookieDataToExport( $user, $remember)
Return the data to store in cookies.
Definition: CookieSessionProvider.php:375
MediaWiki\Session\SessionBackend\getLoggedOutTimestamp
getLoggedOutTimestamp()
Fetch the "logged out" timestamp.
Definition: SessionBackend.php:503
MediaWiki\User\UserNameUtils
UserNameUtils service.
Definition: UserNameUtils.php:42
MediaWiki\Session\UserInfo\newFromId
static newFromId( $id, $verified=false)
Create an instance for a logged-in user by ID.
Definition: UserInfo.php:88
MediaWiki\Session\CookieSessionProvider\suggestLoginUsername
suggestLoginUsername(WebRequest $request)
Get a suggested username for the login form.
Definition: CookieSessionProvider.php:322
MediaWiki\Session\CookieSessionProvider\getRememberUserDuration
getRememberUserDuration()
Returns the duration (in seconds) for which users will be remembered when Session::setRememberUser() ...
Definition: CookieSessionProvider.php:413
MediaWiki\Session\CookieSessionProvider\postInitSetup
postInitSetup()
A provider can override this to do any necessary setup after init() is called.
Definition: CookieSessionProvider.php:90
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:187
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:67
MediaWiki\Session\SessionInfo\MIN_PRIORITY
const MIN_PRIORITY
Minimum allowed priority.
Definition: SessionInfo.php:39
MediaWiki\Session\CookieSessionProvider\setLoggedOutCookie
setLoggedOutCookie( $loggedOut, WebRequest $request)
Definition: CookieSessionProvider.php:302
MediaWiki\Session\SessionBackend
This is the actual workhorse for Session.
Definition: SessionBackend.php:53
MediaWiki\Session\SessionProvider\getHookRunner
getHookRunner()
Get the HookRunner.
Definition: SessionProvider.php:251