comparison core/modules/image/tests/src/Functional/ImageStylesPathAndUrlTest.php @ 16:c2387f117808

Routine composer update
author Chris Cannam
date Tue, 10 Jul 2018 15:07:59 +0100
parents
children 129ea1e6d783
comparison
equal deleted inserted replaced
15:e200cb7efeb3 16:c2387f117808
1 <?php
2
3 namespace Drupal\Tests\image\Functional;
4
5 use Drupal\image\Entity\ImageStyle;
6 use Drupal\language\Entity\ConfigurableLanguage;
7 use Drupal\Tests\BrowserTestBase;
8 use Drupal\Tests\TestFileCreationTrait;
9
10 /**
11 * Tests the functions for generating paths and URLs for image styles.
12 *
13 * @group image
14 */
15 class ImageStylesPathAndUrlTest extends BrowserTestBase {
16
17 use TestFileCreationTrait {
18 getTestFiles as drupalGetTestFiles;
19 compareFiles as drupalCompareFiles;
20 }
21
22 /**
23 * Modules to enable.
24 *
25 * @var array
26 */
27 public static $modules = ['image', 'image_module_test', 'language'];
28
29 /**
30 * The image style.
31 *
32 * @var \Drupal\image\ImageStyleInterface
33 */
34 protected $style;
35
36 /**
37 * {@inheritdoc}
38 */
39 protected function setUp() {
40 parent::setUp();
41
42 $this->style = ImageStyle::create([
43 'name' => 'style_foo',
44 'label' => $this->randomString(),
45 ]);
46 $this->style->save();
47
48 // Create a new language.
49 ConfigurableLanguage::createFromLangcode('fr')->save();
50 }
51
52 /**
53 * Tests \Drupal\image\ImageStyleInterface::buildUri().
54 */
55 public function testImageStylePath() {
56 $scheme = 'public';
57 $actual = $this->style->buildUri("$scheme://foo/bar.gif");
58 $expected = "$scheme://styles/" . $this->style->id() . "/$scheme/foo/bar.gif";
59 $this->assertEqual($actual, $expected, 'Got the path for a file URI.');
60
61 $actual = $this->style->buildUri('foo/bar.gif');
62 $expected = "$scheme://styles/" . $this->style->id() . "/$scheme/foo/bar.gif";
63 $this->assertEqual($actual, $expected, 'Got the path for a relative file path.');
64 }
65
66 /**
67 * Tests an image style URL using the "public://" scheme.
68 */
69 public function testImageStyleUrlAndPathPublic() {
70 $this->doImageStyleUrlAndPathTests('public');
71 }
72
73 /**
74 * Tests an image style URL using the "private://" scheme.
75 */
76 public function testImageStyleUrlAndPathPrivate() {
77 $this->doImageStyleUrlAndPathTests('private');
78 }
79
80 /**
81 * Tests an image style URL with the "public://" scheme and unclean URLs.
82 */
83 public function testImageStyleUrlAndPathPublicUnclean() {
84 $this->doImageStyleUrlAndPathTests('public', FALSE);
85 }
86
87 /**
88 * Tests an image style URL with the "private://" schema and unclean URLs.
89 */
90 public function testImageStyleUrlAndPathPrivateUnclean() {
91 $this->doImageStyleUrlAndPathTests('private', FALSE);
92 }
93
94 /**
95 * Tests an image style URL with the "public://" schema and language prefix.
96 */
97 public function testImageStyleUrlAndPathPublicLanguage() {
98 $this->doImageStyleUrlAndPathTests('public', TRUE, TRUE, 'fr');
99 }
100
101 /**
102 * Tests an image style URL with the "private://" schema and language prefix.
103 */
104 public function testImageStyleUrlAndPathPrivateLanguage() {
105 $this->doImageStyleUrlAndPathTests('private', TRUE, TRUE, 'fr');
106 }
107
108 /**
109 * Tests an image style URL with a file URL that has an extra slash in it.
110 */
111 public function testImageStyleUrlExtraSlash() {
112 $this->doImageStyleUrlAndPathTests('public', TRUE, TRUE);
113 }
114
115 /**
116 * Tests that an invalid source image returns a 404.
117 */
118 public function testImageStyleUrlForMissingSourceImage() {
119 $non_existent_uri = 'public://foo.png';
120 $generated_url = $this->style->buildUrl($non_existent_uri);
121 $this->drupalGet($generated_url);
122 $this->assertResponse(404, 'Accessing an image style URL with a source image that does not exist provides a 404 error response.');
123 }
124
125 /**
126 * Tests building an image style URL.
127 */
128 public function doImageStyleUrlAndPathTests($scheme, $clean_url = TRUE, $extra_slash = FALSE, $langcode = FALSE) {
129 $this->prepareRequestForGenerator($clean_url);
130
131 // Make the default scheme neither "public" nor "private" to verify the
132 // functions work for other than the default scheme.
133 $this->config('system.file')->set('default_scheme', 'temporary')->save();
134
135 // Create the directories for the styles.
136 $directory = $scheme . '://styles/' . $this->style->id();
137 $status = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
138 $this->assertNotIdentical(FALSE, $status, 'Created the directory for the generated images for the test style.');
139
140 // Override the language to build the URL for the correct language.
141 if ($langcode) {
142 $language_manager = \Drupal::service('language_manager');
143 $language = $language_manager->getLanguage($langcode);
144 $language_manager->setConfigOverrideLanguage($language);
145 }
146
147 // Create a working copy of the file.
148 $files = $this->drupalGetTestFiles('image');
149 $file = array_shift($files);
150 $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
151 // Let the image_module_test module know about this file, so it can claim
152 // ownership in hook_file_download().
153 \Drupal::state()->set('image.test_file_download', $original_uri);
154 $this->assertNotIdentical(FALSE, $original_uri, 'Created the generated image file.');
155
156 // Get the URL of a file that has not been generated and try to create it.
157 $generated_uri = $this->style->buildUri($original_uri);
158 $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
159 $generate_url = $this->style->buildUrl($original_uri, $clean_url);
160
161 // Make sure that language prefix is never added to the image style URL.
162 if ($langcode) {
163 $this->assertTrue(strpos($generate_url, "/$langcode/") === FALSE, 'Langcode was not found in the image style URL.');
164 }
165
166 // Ensure that the tests still pass when the file is generated by accessing
167 // a poorly constructed (but still valid) file URL that has an extra slash
168 // in it.
169 if ($extra_slash) {
170 $modified_uri = str_replace('://', ':///', $original_uri);
171 $this->assertNotEqual($original_uri, $modified_uri, 'An extra slash was added to the generated file URI.');
172 $generate_url = $this->style->buildUrl($modified_uri, $clean_url);
173 }
174 if (!$clean_url) {
175 $this->assertTrue(strpos($generate_url, 'index.php/') !== FALSE, 'When using non-clean URLS, the system path contains the script name.');
176 }
177 // Add some extra chars to the token.
178 $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
179 $this->assertResponse(404, 'Image was inaccessible at the URL with an invalid token.');
180 // Change the parameter name so the token is missing.
181 $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $generate_url));
182 $this->assertResponse(404, 'Image was inaccessible at the URL with a missing token.');
183
184 // Check that the generated URL is the same when we pass in a relative path
185 // rather than a URI. We need to temporarily switch the default scheme to
186 // match the desired scheme before testing this, then switch it back to the
187 // "temporary" scheme used throughout this test afterwards.
188 $this->config('system.file')->set('default_scheme', $scheme)->save();
189 $relative_path = file_uri_target($original_uri);
190 $generate_url_from_relative_path = $this->style->buildUrl($relative_path, $clean_url);
191 $this->assertEqual($generate_url, $generate_url_from_relative_path);
192 $this->config('system.file')->set('default_scheme', 'temporary')->save();
193
194 // Fetch the URL that generates the file.
195 $this->drupalGet($generate_url);
196 $this->assertResponse(200, 'Image was generated at the URL.');
197 $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
198 // assertRaw can't be used with string containing non UTF-8 chars.
199 $this->assertNotEmpty(file_get_contents($generated_uri), 'URL returns expected file.');
200 $image = $this->container->get('image.factory')->get($generated_uri);
201 $this->assertEqual($this->drupalGetHeader('Content-Type'), $image->getMimeType(), 'Expected Content-Type was reported.');
202 $this->assertEqual($this->drupalGetHeader('Content-Length'), $image->getFileSize(), 'Expected Content-Length was reported.');
203
204 // Check that we did not download the original file.
205 $original_image = $this->container->get('image.factory')
206 ->get($original_uri);
207 $this->assertNotEqual($this->drupalGetHeader('Content-Length'), $original_image->getFileSize());
208
209 if ($scheme == 'private') {
210 $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
211 $this->assertNotEqual(strpos($this->drupalGetHeader('Cache-Control'), 'no-cache'), FALSE, 'Cache-Control header contains \'no-cache\' to prevent caching.');
212 $this->assertEqual($this->drupalGetHeader('X-Image-Owned-By'), 'image_module_test', 'Expected custom header has been added.');
213
214 // Make sure that a second request to the already existing derivative
215 // works too.
216 $this->drupalGet($generate_url);
217 $this->assertResponse(200, 'Image was generated at the URL.');
218
219 // Check that the second request also returned the generated image.
220 $this->assertEqual($this->drupalGetHeader('Content-Length'), $image->getFileSize());
221
222 // Check that we did not download the original file.
223 $this->assertNotEqual($this->drupalGetHeader('Content-Length'), $original_image->getFileSize());
224
225 // Make sure that access is denied for existing style files if we do not
226 // have access.
227 \Drupal::state()->delete('image.test_file_download');
228 $this->drupalGet($generate_url);
229 $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');
230
231 // Repeat this with a different file that we do not have access to and
232 // make sure that access is denied.
233 $file_noaccess = array_shift($files);
234 $original_uri_noaccess = file_unmanaged_copy($file_noaccess->uri, $scheme . '://', FILE_EXISTS_RENAME);
235 $generated_uri_noaccess = $scheme . '://styles/' . $this->style->id() . '/' . $scheme . '/' . drupal_basename($original_uri_noaccess);
236 $this->assertFalse(file_exists($generated_uri_noaccess), 'Generated file does not exist.');
237 $generate_url_noaccess = $this->style->buildUrl($original_uri_noaccess);
238
239 $this->drupalGet($generate_url_noaccess);
240 $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');
241 // Verify that images are not appended to the response.
242 // Currently this test only uses PNG images.
243 if (strpos($generate_url, '.png') === FALSE) {
244 $this->fail('Confirming that private image styles are not appended require PNG file.');
245 }
246 else {
247 // Check for PNG-Signature
248 // (cf. http://www.libpng.org/pub/png/book/chapter08.html#png.ch08.div.2)
249 // in the response body.
250 $raw = $this->getSession()->getPage()->getContent();
251 $this->assertFalse(strpos($raw, chr(137) . chr(80) . chr(78) . chr(71) . chr(13) . chr(10) . chr(26) . chr(10)));
252 }
253 }
254 else {
255 $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
256 $this->assertEqual(strpos($this->drupalGetHeader('Cache-Control'), 'no-cache'), FALSE, 'Cache-Control header contains \'no-cache\' to prevent caching.');
257
258 if ($clean_url) {
259 // Add some extra chars to the token.
260 $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
261 $this->assertResponse(200, 'Existing image was accessible at the URL with an invalid token.');
262 }
263 }
264
265 // Allow insecure image derivatives to be created for the remainder of this
266 // test.
267 $this->config('image.settings')
268 ->set('allow_insecure_derivatives', TRUE)
269 ->save();
270
271 // Create another working copy of the file.
272 $files = $this->drupalGetTestFiles('image');
273 $file = array_shift($files);
274 $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
275 // Let the image_module_test module know about this file, so it can claim
276 // ownership in hook_file_download().
277 \Drupal::state()->set('image.test_file_download', $original_uri);
278
279 // Suppress the security token in the URL, then get the URL of a file that
280 // has not been created and try to create it. Check that the security token
281 // is not present in the URL but that the image is still accessible.
282 $this->config('image.settings')->set('suppress_itok_output', TRUE)->save();
283 $generated_uri = $this->style->buildUri($original_uri);
284 $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
285 $generate_url = $this->style->buildUrl($original_uri, $clean_url);
286 $this->assertIdentical(strpos($generate_url, IMAGE_DERIVATIVE_TOKEN . '='), FALSE, 'The security token does not appear in the image style URL.');
287 $this->drupalGet($generate_url);
288 $this->assertResponse(200, 'Image was accessible at the URL with a missing token.');
289
290 // Stop supressing the security token in the URL.
291 $this->config('image.settings')->set('suppress_itok_output', FALSE)->save();
292 // Ensure allow_insecure_derivatives is enabled.
293 $this->assertEqual($this->config('image.settings')
294 ->get('allow_insecure_derivatives'), TRUE);
295 // Check that a security token is still required when generating a second
296 // image derivative using the first one as a source.
297 $nested_url = $this->style->buildUrl($generated_uri, $clean_url);
298 $matches_expected_url_format = (boolean) preg_match('/styles\/' . $this->style->id() . '\/' . $scheme . '\/styles\/' . $this->style->id() . '\/' . $scheme . '/', $nested_url);
299 $this->assertTrue($matches_expected_url_format, "URL for a derivative of an image style matches expected format.");
300 $nested_url_with_wrong_token = str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $nested_url);
301 $this->drupalGet($nested_url_with_wrong_token);
302 $this->assertResponse(404, 'Image generated from an earlier derivative was inaccessible at the URL with a missing token.');
303 // Check that this restriction cannot be bypassed by adding extra slashes
304 // to the URL.
305 $this->drupalGet(substr_replace($nested_url_with_wrong_token, '//styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
306 $this->assertResponse(404, 'Image generated from an earlier derivative was inaccessible at the URL with a missing token, even with an extra forward slash in the URL.');
307 $this->drupalGet(substr_replace($nested_url_with_wrong_token, '////styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
308 $this->assertResponse(404, 'Image generated from an earlier derivative was inaccessible at the URL with a missing token, even with multiple forward slashes in the URL.');
309 // Make sure the image can still be generated if a correct token is used.
310 $this->drupalGet($nested_url);
311 $this->assertResponse(200, 'Image was accessible when a correct token was provided in the URL.');
312
313 // Check that requesting a nonexistent image does not create any new
314 // directories in the file system.
315 $directory = $scheme . '://styles/' . $this->style->id() . '/' . $scheme . '/' . $this->randomMachineName();
316 $this->drupalGet(file_create_url($directory . '/' . $this->randomString()));
317 $this->assertFalse(file_exists($directory), 'New directory was not created in the filesystem when requesting an unauthorized image.');
318 }
319
320 }