wiki.techinc.nl/includes/session/ImmutableSessionProviderWithCookie.php

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

180 lines
5.2 KiB
PHP
Raw Normal View History

<?php
/**
* MediaWiki session provider base class
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Session
*/
namespace MediaWiki\Session;
use InvalidArgumentException;
use MediaWiki\MainConfigNames;
use MediaWiki\Request\WebRequest;
/**
* An ImmutableSessionProviderWithCookie doesn't persist the user, but
* optionally can use a cookie to support multiple IDs per session.
*
* As mentioned in the documentation for SessionProvider, many methods that are
* technically "cannot persist ID" could be turned into "can persist ID but
* not changing User" using a session cookie. This class implements such an
* optional session cookie.
*
* @stable to extend
* @ingroup Session
* @since 1.27
*/
abstract class ImmutableSessionProviderWithCookie extends SessionProvider {
/** @var string|null */
protected $sessionCookieName = null;
/** @var mixed[] */
protected $sessionCookieOptions = [];
/**
* @stable to call
* @param array $params Keys include:
* - sessionCookieName: Session cookie name, if multiple sessions per
* client are to be supported.
* - sessionCookieOptions: Options to pass to WebResponse::setCookie().
*/
public function __construct( $params = [] ) {
parent::__construct();
if ( isset( $params['sessionCookieName'] ) ) {
if ( !is_string( $params['sessionCookieName'] ) ) {
throw new InvalidArgumentException( 'sessionCookieName must be a string' );
}
$this->sessionCookieName = $params['sessionCookieName'];
}
if ( isset( $params['sessionCookieOptions'] ) ) {
if ( !is_array( $params['sessionCookieOptions'] ) ) {
throw new InvalidArgumentException( 'sessionCookieOptions must be an array' );
}
$this->sessionCookieOptions = $params['sessionCookieOptions'];
}
}
/**
* Get the session ID from the cookie, if any.
*
* Only call this if $this->sessionCookieName !== null. If
* sessionCookieName is null, do some logic (probably involving a call to
* $this->hashToSessionId()) to create the single session ID corresponding
* to this WebRequest instead of calling this method.
*
* @param WebRequest $request
* @return string|null
*/
protected function getSessionIdFromCookie( WebRequest $request ) {
if ( $this->sessionCookieName === null ) {
throw new \BadMethodCallException(
__METHOD__ . ' may not be called when $this->sessionCookieName === null'
);
}
$prefix = $this->sessionCookieOptions['prefix']
?? $this->getConfig()->get( MainConfigNames::CookiePrefix );
$id = $request->getCookie( $this->sessionCookieName, $prefix );
return SessionManager::validateSessionId( $id ) ? $id : null;
}
/**
* @inheritDoc
* @stable to override
*/
public function persistsSessionId() {
return $this->sessionCookieName !== null;
}
/**
* @inheritDoc
* @stable to override
*/
public function canChangeUser() {
return false;
}
/**
* @inheritDoc
* @stable to override
*/
public function persistSession( SessionBackend $session, WebRequest $request ) {
if ( $this->sessionCookieName === null ) {
return;
}
$response = $request->response();
if ( $response->headersSent() ) {
// Can't do anything now
$this->logger->debug( __METHOD__ . ': Headers already sent' );
return;
}
$options = $this->sessionCookieOptions;
if ( $session->shouldForceHTTPS() || $session->getUser()->requiresHTTPS() ) {
Introduce $wgForceHTTPS Add $wgForceHTTPS. When set to true: * It makes the HTTP to HTTPS redirect unconditional and suppresses the forceHTTPS cookie. * It makes session cookies be secure. * In the Action API, it triggers the existing deprecation warning and avoids more expensive user/session checks. * In login and signup, it suppresses the old hidden form fields for protocol switching. * It hides the prefershttps user preference. Other changes: * Factor out the HTTPS redirect in MediaWiki::main() into maybeDoHttpsRedirect() and shouldDoHttpRedirect(). Improve documentation. * User::requiresHTTPS() reflects $wgForceHTTPS whereas the Session concept of "force HTTPS" does not. The documentation of User::requiresHTTPS() says that it includes configuration, and retaining this definition was beneficial for some callers. Whereas Session::shouldForceHTTPS() was used fairly narrowly as the value of the forceHTTPS cookie, and injecting configuration into it is not so easy or beneficial, so I left it as it was, except for clarifying the documentation. * Deprecate the following hooks: BeforeHttpsRedirect, UserRequiresHTTPS, CanIPUseHTTPS. No known extension uses them, and they're not compatible with the long-term goal of ending support for mixed-protocol wikis. BeforeHttpsRedirect was documented as unstable from its inception. CanIPUseHTTPS was a WMF config hack now superseded by GFOC's SNI sniffing. * For tests which failed with $wgForceHTTPS=true, I mostly split the tests, testing each configuration value separately. * Add ArrayUtils::cartesianProduct() as a helper for generating combinations of boolean options in the session tests. Bug: T256095 Change-Id: Iefb5ba55af35350dfc7c050f9fb8f4e8a79751cb
2020-06-24 00:56:46 +00:00
// Send a cookie unless $wgForceHTTPS is set (T256095)
if ( !$this->getConfig()->get( MainConfigNames::ForceHTTPS ) ) {
Introduce $wgForceHTTPS Add $wgForceHTTPS. When set to true: * It makes the HTTP to HTTPS redirect unconditional and suppresses the forceHTTPS cookie. * It makes session cookies be secure. * In the Action API, it triggers the existing deprecation warning and avoids more expensive user/session checks. * In login and signup, it suppresses the old hidden form fields for protocol switching. * It hides the prefershttps user preference. Other changes: * Factor out the HTTPS redirect in MediaWiki::main() into maybeDoHttpsRedirect() and shouldDoHttpRedirect(). Improve documentation. * User::requiresHTTPS() reflects $wgForceHTTPS whereas the Session concept of "force HTTPS" does not. The documentation of User::requiresHTTPS() says that it includes configuration, and retaining this definition was beneficial for some callers. Whereas Session::shouldForceHTTPS() was used fairly narrowly as the value of the forceHTTPS cookie, and injecting configuration into it is not so easy or beneficial, so I left it as it was, except for clarifying the documentation. * Deprecate the following hooks: BeforeHttpsRedirect, UserRequiresHTTPS, CanIPUseHTTPS. No known extension uses them, and they're not compatible with the long-term goal of ending support for mixed-protocol wikis. BeforeHttpsRedirect was documented as unstable from its inception. CanIPUseHTTPS was a WMF config hack now superseded by GFOC's SNI sniffing. * For tests which failed with $wgForceHTTPS=true, I mostly split the tests, testing each configuration value separately. * Add ArrayUtils::cartesianProduct() as a helper for generating combinations of boolean options in the session tests. Bug: T256095 Change-Id: Iefb5ba55af35350dfc7c050f9fb8f4e8a79751cb
2020-06-24 00:56:46 +00:00
$response->setCookie( 'forceHTTPS', 'true', null,
[ 'prefix' => '', 'secure' => false ] + $options );
}
$options['secure'] = true;
}
$response->setCookie( $this->sessionCookieName, $session->getId(), null, $options );
}
/**
* @inheritDoc
* @stable to override
*/
public function unpersistSession( WebRequest $request ) {
if ( $this->sessionCookieName === null ) {
return;
}
$response = $request->response();
if ( $response->headersSent() ) {
// Can't do anything now
$this->logger->debug( __METHOD__ . ': Headers already sent' );
return;
}
$response->clearCookie( $this->sessionCookieName, $this->sessionCookieOptions );
}
/**
* @inheritDoc
* @stable to override
*/
public function getVaryCookies() {
if ( $this->sessionCookieName === null ) {
return [];
}
$prefix = $this->sessionCookieOptions['prefix'] ??
$this->getConfig()->get( MainConfigNames::CookiePrefix );
return [ $prefix . $this->sessionCookieName ];
}
public function whyNoSession() {
return wfMessage( 'sessionprovider-nocookies' );
}
}