Updated to Drupal 8.6.4, which is PHP 7.3 friendly. Also updated HTMLaw library....
[yaffs-website] / web / core / modules / system / src / Tests / Session / SessionHttpsTest.php
1 <?php
2
3 namespace Drupal\system\Tests\Session;
4
5 use Drupal\simpletest\WebTestBase;
6 use Symfony\Component\HttpFoundation\Request;
7 use Drupal\Component\Utility\Crypt;
8 use Drupal\Core\Session\AccountInterface;
9
10 /**
11  * Ensure that when running under HTTPS two session cookies are generated.
12  *
13  * @group Session
14  */
15 class SessionHttpsTest extends WebTestBase {
16
17   /**
18    * The name of the session cookie when using HTTP.
19    *
20    * @var string
21    */
22   protected $insecureSessionName;
23
24   /**
25    * The name of the session cookie when using HTTPS.
26    *
27    * @var string
28    */
29   protected $secureSessionName;
30
31   /**
32    * Modules to enable.
33    *
34    * @var array
35    */
36   public static $modules = ['session_test'];
37
38   protected function setUp() {
39     parent::setUp();
40
41     $request = Request::createFromGlobals();
42     if ($request->isSecure()) {
43       $this->secureSessionName = $this->getSessionName();
44       $this->insecureSessionName = substr($this->getSessionName(), 1);
45     }
46     else {
47       $this->secureSessionName = 'S' . $this->getSessionName();
48       $this->insecureSessionName = $this->getSessionName();
49     }
50   }
51
52   public function testHttpsSession() {
53     $user = $this->drupalCreateUser(['access administration pages']);
54
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);
58
59     // Test a second concurrent session.
60     $this->curlClose();
61     $this->curlCookies = [];
62     $this->loginHttps($user);
63
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.');
70
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);
75
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);
80
81     // Verify that empty SID cannot be used on the non-secure site.
82     $this->curlClose();
83     $this->curlCookies = [$this->insecureSessionName . '='];
84     $this->drupalGet($this->httpUrl('admin/config'));
85     $this->assertResponse(403);
86
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
89     // test environments.
90     $this->curlClose();
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.');
97
98     // Verify that empty secure SID cannot be used on the secure site.
99     $this->curlClose();
100     $this->curlCookies = [$this->secureSessionName . '='];
101     $this->drupalGet($this->httpsUrl('admin/config'));
102     $this->assertResponse(403);
103
104     // Clear browser cookie jar.
105     $this->cookies = [];
106   }
107
108   /**
109    * Log in a user via HTTP.
110    *
111    * Note that the parents $session_id and $loggedInUser is not updated.
112    */
113   protected function loginHttp(AccountInterface $account) {
114     $this->drupalGet('user/login');
115
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];
121
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;
132
133     // Follow the location header.
134     $path = $this->getPathFromLocationHeader(FALSE);
135     $this->drupalGet($this->httpUrl($path));
136     $this->assertResponse(200);
137   }
138
139   /**
140    * Log in a user via HTTPS.
141    *
142    * Note that the parents $session_id and $loggedInUser is not updated.
143    */
144   protected function loginHttps(AccountInterface $account) {
145     $this->drupalGet('user/login');
146
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];
152
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;
163
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
170     // the HTTPS mock.
171     $this->curlCookies = [$this->secureSessionName . '=' . $this->cookies[$this->secureSessionName]['value']];
172
173     // Follow the location header.
174     $path = $this->getPathFromLocationHeader(TRUE);
175     $this->drupalGet($this->httpsUrl($path));
176     $this->assertResponse(200);
177   }
178
179   /**
180    * Extract internal path from the location header on the response.
181    */
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]);
185     if ($https) {
186       $base_url = str_replace('http://', 'https://', $base_url);
187     }
188     else {
189       $base_url = str_replace('https://', 'http://', $base_url);
190     }
191
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
194     // strip that also.
195     $base_url .= 'index.php/';
196
197     // Extract relative path from location header.
198     $this->assertResponse($response_code);
199     $location = $this->drupalGetHeader('location');
200
201     $this->assertIdentical(strpos($location, $base_url), 0, 'Location header contains expected base URL');
202     return substr($location, strlen($base_url));
203   }
204
205   /**
206    * Test that there exists a session with two specific session IDs.
207    *
208    * @param $sid
209    *   The insecure session ID to search for.
210    * @param $assertion_text
211    *   The text to display when we perform the assertion.
212    *
213    * @return
214    *   The result of assertTrue() that there's a session in the system that
215    *   has the given insecure and secure session IDs.
216    */
217   protected function assertSessionIds($sid, $assertion_text) {
218     $args = [
219       ':sid' => Crypt::hashBase64($sid),
220     ];
221     return $this->assertTrue(db_query('SELECT timestamp FROM {sessions} WHERE sid = :sid', $args)->fetchField(), $assertion_text);
222   }
223
224   /**
225    * Builds a URL for submitting a mock HTTPS request to HTTP test environments.
226    *
227    * @param $url
228    *   A Drupal path such as 'user/login'.
229    *
230    * @return
231    *   URL prepared for the https.php mock front controller.
232    */
233   protected function httpsUrl($url) {
234     return 'core/modules/system/tests/https.php/' . $url;
235   }
236
237   /**
238    * Builds a URL for submitting a mock HTTP request to HTTPS test environments.
239    *
240    * @param $url
241    *   A Drupal path such as 'user/login'.
242    *
243    * @return
244    *   URL prepared for the http.php mock front controller.
245    */
246   protected function httpUrl($url) {
247     return 'core/modules/system/tests/http.php/' . $url;
248   }
249
250 }