3 namespace Drupal\system\Tests\Session;
5 use Drupal\simpletest\WebTestBase;
6 use Symfony\Component\HttpFoundation\Request;
7 use Drupal\Component\Utility\Crypt;
8 use Drupal\Core\Session\AccountInterface;
11 * Ensure that when running under HTTPS two session cookies are generated.
15 class SessionHttpsTest extends WebTestBase {
18 * The name of the session cookie when using HTTP.
22 protected $insecureSessionName;
25 * The name of the session cookie when using HTTPS.
29 protected $secureSessionName;
36 public static $modules = ['session_test'];
38 protected function setUp() {
41 $request = Request::createFromGlobals();
42 if ($request->isSecure()) {
43 $this->secureSessionName = $this->getSessionName();
44 $this->insecureSessionName = substr($this->getSessionName(), 1);
47 $this->secureSessionName = 'S' . $this->getSessionName();
48 $this->insecureSessionName = $this->getSessionName();
52 public function testHttpsSession() {
53 $user = $this->drupalCreateUser(['access administration pages']);
55 // Test HTTPS session handling by altering the form action to submit the
56 // login form through https.php, which creates a mock HTTPS request.
57 $this->loginHttps($user);
59 // Test a second concurrent session.
61 $this->curlCookies = [];
62 $this->loginHttps($user);
64 // Check secure cookie on secure page.
65 $this->assertTrue($this->cookies[$this->secureSessionName]['secure'], 'The secure cookie has the secure attribute');
66 // Check insecure cookie is not set.
67 $this->assertFalse(isset($this->cookies[$this->insecureSessionName]));
68 $ssid = $this->cookies[$this->secureSessionName]['value'];
69 $this->assertSessionIds($ssid, 'Session has a non-empty SID and a correct secure SID.');
71 // Verify that user is logged in on secure URL.
72 $this->drupalGet($this->httpsUrl('admin/config'));
73 $this->assertText(t('Configuration'));
74 $this->assertResponse(200);
76 // Verify that user is not logged in on non-secure URL.
77 $this->drupalGet($this->httpUrl('admin/config'));
78 $this->assertNoText(t('Configuration'));
79 $this->assertResponse(403);
81 // Verify that empty SID cannot be used on the non-secure site.
83 $this->curlCookies = [$this->insecureSessionName . '='];
84 $this->drupalGet($this->httpUrl('admin/config'));
85 $this->assertResponse(403);
87 // Test HTTP session handling by altering the form action to submit the
88 // login form through http.php, which creates a mock HTTP request on HTTPS
91 $this->curlCookies = [];
92 $this->loginHttp($user);
93 $this->drupalGet($this->httpUrl('admin/config'));
94 $this->assertResponse(200);
95 $sid = $this->cookies[$this->insecureSessionName]['value'];
96 $this->assertSessionIds($sid, '', 'Session has the correct SID and an empty secure SID.');
98 // Verify that empty secure SID cannot be used on the secure site.
100 $this->curlCookies = [$this->secureSessionName . '='];
101 $this->drupalGet($this->httpsUrl('admin/config'));
102 $this->assertResponse(403);
104 // Clear browser cookie jar.
109 * Log in a user via HTTP.
111 * Note that the parents $session_id and $loggedInUser is not updated.
113 protected function loginHttp(AccountInterface $account) {
114 $this->drupalGet('user/login');
116 // Alter the form action to submit the login form through http.php, which
117 // creates a mock HTTP request on HTTPS test environments.
118 $form = $this->xpath('//form[@id="user-login-form"]');
119 $form[0]['action'] = $this->httpUrl('user/login');
120 $edit = ['name' => $account->getUsername(), 'pass' => $account->pass_raw];
122 // When posting directly to the HTTP or HTTPS mock front controller, the
123 // location header on the returned response is an absolute URL. That URL
124 // needs to be converted into a request to the respective mock front
125 // controller in order to retrieve the target page. Because the URL in the
126 // location header needs to be modified, it is necessary to disable the
127 // automatic redirects normally performed by parent::curlExec().
128 $maximum_redirects = $this->maximumRedirects;
129 $this->maximumRedirects = 0;
130 $this->drupalPostForm(NULL, $edit, t('Log in'));
131 $this->maximumRedirects = $maximum_redirects;
133 // Follow the location header.
134 $path = $this->getPathFromLocationHeader(FALSE);
135 $this->drupalGet($this->httpUrl($path));
136 $this->assertResponse(200);
140 * Log in a user via HTTPS.
142 * Note that the parents $session_id and $loggedInUser is not updated.
144 protected function loginHttps(AccountInterface $account) {
145 $this->drupalGet('user/login');
147 // Alter the form action to submit the login form through https.php, which
148 // creates a mock HTTPS request on HTTP test environments.
149 $form = $this->xpath('//form[@id="user-login-form"]');
150 $form[0]['action'] = $this->httpsUrl('user/login');
151 $edit = ['name' => $account->getUsername(), 'pass' => $account->pass_raw];
153 // When posting directly to the HTTP or HTTPS mock front controller, the
154 // location header on the returned response is an absolute URL. That URL
155 // needs to be converted into a request to the respective mock front
156 // controller in order to retrieve the target page. Because the URL in the
157 // location header needs to be modified, it is necessary to disable the
158 // automatic redirects normally performed by parent::curlExec().
159 $maximum_redirects = $this->maximumRedirects;
160 $this->maximumRedirects = 0;
161 $this->drupalPostForm(NULL, $edit, t('Log in'));
162 $this->maximumRedirects = $maximum_redirects;
164 // When logging in via the HTTPS mock, the child site will issue a session
165 // cookie with the secure attribute set. While this cookie will be stored in
166 // the curl handle, it will not be used on subsequent requests via the HTTPS
167 // mock, unless when operating in a true HTTPS environment. Therefore it is
168 // necessary to manually collect the session cookie and add it to the
169 // curlCookies property such that it will be used on subsequent requests via
171 $this->curlCookies = [$this->secureSessionName . '=' . $this->cookies[$this->secureSessionName]['value']];
173 // Follow the location header.
174 $path = $this->getPathFromLocationHeader(TRUE);
175 $this->drupalGet($this->httpsUrl($path));
176 $this->assertResponse(200);
180 * Extract internal path from the location header on the response.
182 protected function getPathFromLocationHeader($https = FALSE, $response_code = 303) {
183 // Generate the base_url.
184 $base_url = $this->container->get('url_generator')->generateFromRoute('<front>', [], ['absolute' => TRUE]);
186 $base_url = str_replace('http://', 'https://', $base_url);
189 $base_url = str_replace('https://', 'http://', $base_url);
192 // The mock front controllers (http.php and https.php) add the script name
193 // to $_SERVER['REQUEST_URI'] and friends. Therefore it is necessary to
195 $base_url .= 'index.php/';
197 // Extract relative path from location header.
198 $this->assertResponse($response_code);
199 $location = $this->drupalGetHeader('location');
201 $this->assertIdentical(strpos($location, $base_url), 0, 'Location header contains expected base URL');
202 return substr($location, strlen($base_url));
206 * Test that there exists a session with two specific session IDs.
209 * The insecure session ID to search for.
210 * @param $assertion_text
211 * The text to display when we perform the assertion.
214 * The result of assertTrue() that there's a session in the system that
215 * has the given insecure and secure session IDs.
217 protected function assertSessionIds($sid, $assertion_text) {
219 ':sid' => Crypt::hashBase64($sid),
221 return $this->assertTrue(db_query('SELECT timestamp FROM {sessions} WHERE sid = :sid', $args)->fetchField(), $assertion_text);
225 * Builds a URL for submitting a mock HTTPS request to HTTP test environments.
228 * A Drupal path such as 'user/login'.
231 * URL prepared for the https.php mock front controller.
233 protected function httpsUrl($url) {
234 return 'core/modules/system/tests/https.php/' . $url;
238 * Builds a URL for submitting a mock HTTP request to HTTPS test environments.
241 * A Drupal path such as 'user/login'.
244 * URL prepared for the http.php mock front controller.
246 protected function httpUrl($url) {
247 return 'core/modules/system/tests/http.php/' . $url;