Debian Codegraph @

tests/phpunit/includes/filerepo/AuthenticatedFileEntryPointTest.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\Context\RequestContext;
4 use MediaWiki\FileRepo\AuthenticatedFileEntryPoint;
5 use MediaWiki\MainConfigNames;
6 use MediaWiki\Request\FauxRequest;
7 use MediaWiki\Tests\FileRepo\TestRepoTrait;
8 use MediaWiki\Tests\MockEnvironment;
9 use MediaWiki\Title\Title;
10
11 /**
12 * @covers \MediaWiki\FileRepo\AuthenticatedFileEntryPoint
13 * @group Database
14 */
15 class AuthenticatedFileEntryPointTest extends MediaWikiIntegrationTestCase {
16 use TestRepoTrait;
17
18 private const PNG_MAGIC = "\x89\x50\x4e\x47";
19 private const JPEG_MAGIC = "\xff\xd8\xff\xe0";
20
21 private const IMAGES_DIR = __DIR__ . '/../../data/media';
22
23 private ?MockEnvironment $environment = null;
24
25 /**
26 * will be called only once per test class
27 */
28 public function addDBDataOnce() {
29 // Set a named user account for the request context as the default,
30 // so that these tests do not fail with temp accounts enabled
31 RequestContext::getMain()->setUser( $this->getTestUser()->getUser() );
32
33 // Create mock repo with test files
34 $this->initTestRepoGroup();
35
36 $this->importFileToTestRepo( self::IMAGES_DIR . '/greyscale-png.png', 'Test.png' );
37 $this->importFileToTestRepo( self::IMAGES_DIR . '/test.jpg', 'Icon.jpg' );
38
39 // Create a second version of Test.png and Icon.jpg
40 $this->importFileToTestRepo( self::IMAGES_DIR . '/greyscale-na-png.png', 'Test.png' );
41 $this->importFileToTestRepo( self::IMAGES_DIR . '/portrait-rotated.jpg', 'Icon.jpg' );
42
43 // Create a thumbnail
44 $this->copyFileToTestBackend(
45 self::IMAGES_DIR . '/greyscale-na-png.png',
46 '/thumb/Test.png'
47 );
48
49 // Create a redirect
50 $title = Title::makeTitle( NS_FILE, 'Redirect_to_Test.png' );
51 $this->editPage( $title, '#REDIRECT [[File:Test.png]]' );
52
53 // Suppress the old version of Icon
54 $file = $this->getTestRepo()->newFile( 'Icon.jpg' );
55 $history = $file->getHistory();
56 $oldFile = $history[0];
57
58 $this->getDb()->newUpdateQueryBuilder()
59 ->table( 'oldimage' )
60 ->set( [ 'oi_deleted' => 1 ] )
61 ->where( [ 'oi_archive_name' => $oldFile->getArchiveName() ] )
62 ->caller( __METHOD__ )
63 ->execute();
64 }
65
66 protected function setUp(): void {
67 parent::setUp();
68 $this->overrideConfigValue(
69 MainConfigNames::ImgAuthDetails,
70 true
71 );
72 $this->overrideConfigValue(
73 MainConfigNames::ForeignFileRepos,
74 []
75 );
76 $this->overrideConfigValue(
77 MainConfigNames::UseInstantCommons,
78 false
79 );
80 $this->overrideConfigValue(
81 MainConfigNames::ImgAuthUrlPathMap,
82 [ '/testing' => 'mwstore://test/test-thumb/' ]
83 );
84 $this->overrideConfigValue(
85 MainConfigNames::ImgAuthPath,
86 '/img_auth/'
87 );
88 $this->installTestRepoGroup();
89 }
90
91 private function recordHeader( string $header ) {
92 $this->environment->getFauxResponse()->header( $header );
93 }
94
95 private function getFileUrlPath( string $name, string $prefix = '' ): string {
96 if ( $prefix !== '' && !str_ends_with( $prefix, '/' ) ) {
97 $prefix = $prefix . '/';
98 }
99
100 if ( !str_starts_with( $prefix, '/' ) ) {
101 // Unauthenticated path
102 $prefix = '/w/images/' . $prefix;
103 }
104
105 $file = $this->getTestRepo()->newFile( $name );
106 if ( $file ) {
107 $name = $file->getRel();
108 }
109
110 return $prefix . $name;
111 }
112
113 /**
114 * @param FauxRequest|string|array|null $request
115 *
116 * @return MockEnvironment
117 */
118 private function makeEnvironment( $request ): MockEnvironment {
119 if ( !$request ) {
120 $request = new FauxRequest();
121 }
122
123 if ( is_string( $request ) ) {
124 $url = $request;
125 $request = new FauxRequest();
126 $request->setRequestURL( $url );
127 }
128
129 if ( is_array( $request ) ) {
130 $request = new FauxRequest( $request );
131 }
132
133 $this->environment = new MockEnvironment( $request );
134 return $this->environment;
135 }
136
137 /**
138 * @param MockEnvironment|null $environment
139 * @param FauxRequest|RequestContext|string|array|null $request
140 *
141 * @return AuthenticatedFileEntryPoint
142 */
143 private function getEntryPoint( ?MockEnvironment $environment = null, $request = null ) {
144 if ( !$request && $environment ) {
145 $request = $environment->getFauxRequest();
146 }
147
148 if ( $request instanceof RequestContext ) {
149 $context = $request;
150 $request = $context->getRequest();
151 } else {
152 $context = new RequestContext();
153 $context->setRequest( $request );
154 $context->setUser( $this->getTestUser()->getUser() );
155 }
156
157 if ( !$environment ) {
158 $environment = $this->makeEnvironment( $request );
159 }
160
161 $entryPoint = new AuthenticatedFileEntryPoint(
162 $context,
163 $environment,
164 $this->getServiceContainer()
165 );
166
167 $entryPoint->enableOutputCapture();
168 return $entryPoint;
169 }
170
171 public static function provideGetRequestPathSuffix() {
172 yield [ '/upload', '/upload/file', 'file' ];
173 yield [ '/upload', '/upload/file?q=x', 'file' ];
174 yield [ '/upload', '/upload/x%25y', 'x%y' ];
175 yield [ '/foo', '/upload/file', false ];
176 }
177
178 /**
179 * @dataProvider provideGetRequestPathSuffix
180 *
181 * @param string $basePath
182 * @param string $requestURL
183 * @param string|false $expected
184 *
185 * @covers \MediaWiki\MediaWikiEntryPoint::getRequestPathSuffix
186 */
187 public function testGetRequestPathSuffix( string $basePath, string $requestURL, $expected ) {
188 $entryPoint = $this->getEntryPoint( $this->makeEnvironment( $requestURL ) );
189 $this->assertSame( $expected, $entryPoint->getRequestPathSuffix( $basePath ) );
190 }
191
192 public static function provideStreamFile() {
193 yield 'public wiki' => [
194 '',
195 ];
196
197 yield 'private wiki' => [
198 '',
199 [
200 '*' => [],
201 'user' => [ 'read' => true ],
202 ],
203 [],
204 [],
205 [
206 'cache-control' => 'private',
207 'vary' => 'Cookie',
208 ]
209 ];
210
211 yield 'range' => [
212 '',
213 [],
214 [],
215 [ 'HTTP_RANGE' => 'bytes=0-99' ],
216 [ 'content-range' => 'bytes 0-99/365', 'content-length' => '100' ],
217 206
218 ];
219
220 yield 'download' => [
221 '',
222 [],
223 [ 'download' => 1 ],
224 [],
225 [ 'content-disposition' => 'attachment' ]
226 ];
227
228 yield 'thumb zone' => [
229 // Path under /w/images/
230 'thumb',
231 ];
232
233 yield 'mapped prefix' => [
234 // Path under /w/images/
235 'testing', // per ImgAuthUrlPathMap
236 ];
237
238 yield 'use ImgAuthPath' => [
239 // If the prefix starts with a "/" it's the full path.
240 '/img_auth/', // per ImgAuthPath
241 ];
242 }
243
244 /**
245 * @dataProvider provideStreamFile
246 *
247 * @param string $prefix
248 * @param array $permissions
249 * @param array $requestData
250 * @param array $serverInfo
251 * @param array $expectedHeaders
252 * @param int $expectedCode
253 *
254 * @throws Exception
255 */
256 public function testStreamFile(
257 string $prefix,
258 array $permissions = [],
259 array $requestData = [],
260 array $serverInfo = [],
261 array $expectedHeaders = [],
262 int $expectedCode = 200
263 ) {
264 if ( !isset( $permissions['*'] ) ) {
265 // public wiki
266 $permissions['*'] = [ 'read' => true ];
267 }
268
269 $this->overrideConfigValue( MainConfigNames::GroupPermissions, $permissions );
270
271 $name = 'Test.png';
272 $url = $this->getFileUrlPath( $name, $prefix );
273 $request = new FauxRequest( $requestData );
274 $request->setRequestURL( $url );
275 $env = $this->makeEnvironment( $request );
276
277 foreach ( $serverInfo as $key => $value ) {
278 $env->setServerInfo( $key, $value );
279 }
280
281 $entryPoint = $this->getEntryPoint( $env );
282 $entryPoint->run();
283 $data = $entryPoint->getCapturedOutput();
284
285 $env->assertStatusCode( $expectedCode, $data );
286
287 $this->assertStringStartsWith(
288 self::PNG_MAGIC,
289 $data
290 );
291
292 $env->assertHeaderValue( 'image/png', 'Content-Type' );
293 foreach ( $expectedHeaders as $name => $exp ) {
294 $env->assertHeaderValue( $exp, $name );
295 }
296 }
297
298 public function testStreamFile_archive() {
299 $this->overrideConfigValue(
300 MainConfigNames::GroupPermissions,
301 [ '*' => [ 'read' => true ] ]
302 );
303
304 $name = 'Test.png';
305 $file = $this->getTestRepo()->newFile( $name );
306 $history = $file->getHistory();
307 $oldFile = $history[0];
308 $url = '/img_auth/' . $oldFile->getArchiveRel() . '/' . $oldFile->getArchiveName();
309
310 $env = $this->makeEnvironment( $url );
311
312 $entryPoint = $this->getEntryPoint( $env );
313 $entryPoint->run();
314 $data = $entryPoint->getCapturedOutput();
315
316 $env->assertStatusCode( 200, $data );
317 }
318
319 public function testNotModified() {
320 $this->overrideConfigValue(
321 MainConfigNames::GroupPermissions,
322 [ '*' => [ 'read' => true ] ]
323 );
324
325 $url = $this->getFileUrlPath( 'Test.png' );
326 $env = $this->makeEnvironment( $url );
327 $env->setServerInfo( 'HTTP_IF_MODIFIED_SINCE', '25250101001122' );
328
329 $entryPoint = $this->getEntryPoint( $env );
330 $entryPoint->run();
331
332 // Not modified
333 $env->assertStatusCode( 304 );
334 }
335
336 public function testAccessDenied_deleted() {
337 $this->overrideConfigValue(
338 MainConfigNames::GroupPermissions,
339 [ '*' => [ 'read' => true ] ]
340 );
341
342 $name = 'Icon.jpg';
343 $file = $this->getTestRepo()->newFile( $name );
344 $history = $file->getHistory();
345
346 // This old revision is marked as deleted (supressed) in the database
347 $oldFile = $history[0];
348 $url = '/img_auth/' . $oldFile->getArchiveRel() . '/' . $oldFile->getArchiveName();
349 $env = $this->makeEnvironment( $url );
350
351 $entryPoint = $this->getEntryPoint( $env );
352 $entryPoint->run();
353 $data = $entryPoint->getCapturedOutput();
354
355 $env->assertStatusCode( 403, $data );
356 }
357
358 public static function provideAccessDenied() {
359 yield 'no prefix' => [ '' ];
360 yield 'thumb zone' => [ 'thumb' ];
361 yield 'mapped prefix' => [ 'testing' ];
362 }
363
364 /**
365 * @dataProvider provideAccessDenied
366 */
367 public function testAccessDenied(
368 string $prefix,
369 string $expected = 'User does not have access to read'
370 ) {
371 $this->overrideConfigValue(
372 MainConfigNames::GroupPermissions,
373 [ '*' => [], 'user' => [], ]
374 );
375
376 $env = $this->makeEnvironment( $this->getFileUrlPath( 'Test.png', $prefix ) );
377
378 $entryPoint = $this->getEntryPoint( $env );
379 $entryPoint->run();
380 $output = $entryPoint->getCapturedOutput();
381
382 $env->assertStatusCode( 403 );
383 $env->assertHeaderValue( 'no-cache', 'cache-control' );
384 $this->assertStringContainsString( '<h1>Access denied</h1>', $output );
385 $this->assertStringContainsString( $expected, $output );
386 }
387
388 public function testAccessDenied_hook() {
389 $this->setUserLang( 'qqx' );
390
391 $this->overrideConfigValue(
392 MainConfigNames::GroupPermissions,
393 [ '*' => [], 'user' => [ 'read' => true ], ]
394 );
395
396 $this->setTemporaryHook(
397 'ImgAuthBeforeStream',
398 static function ( $title, $path, $name, ?array &$result ) {
399 $result = [ 'test-title', 'test-detail' ];
400 return false;
401 }
402 );
403
404 $env = $this->makeEnvironment( $this->getFileUrlPath( 'Test.png' ) );
405
406 $entryPoint = $this->getEntryPoint( $env );
407 $entryPoint->run();
408 $output = $entryPoint->getCapturedOutput();
409
410 $env->assertStatusCode( 403 );
411 $env->assertHeaderValue( 'no-cache', 'cache-control' );
412 $this->assertStringContainsString( '<h1>⧼test-title⧽</h1>', $output );
413 $this->assertStringContainsString( '<p>⧼test-detail⧽</p>', $output );
414 }
415
416 public static function provideNotFOund() {
417 yield 'no prefix, missing file' =>
418 [ 'No-such-file.png', '' ];
419
420 yield 'no prefix, bad title' =>
421 [ '_<>_', '' ];
422
423 yield 'thumb zone' =>
424 [ 'No-such-file.png', 'thumb' ];
425
426 yield 'mapped prefix' =>
427 [ 'No-such-file.png', 'testing' ];
428
429 yield 'unrecognized base path' =>
430 [
431 'No-such-file.png',
432 '/bad/base/path',
433 'Requested path is not in the configured',
434 ];
435 }
436
437 /**
438 * @dataProvider provideNotFOund
439 */
440 public function testNotFound( string $name, string $prefix, $expected = 'does not exist' ) {
441 $this->overrideConfigValue(
442 MainConfigNames::GroupPermissions,
443 [
444 '*' => [ 'read' => 'true' ],
445 ]
446 );
447
448 $env = $this->makeEnvironment( $this->getFileUrlPath( $name, $prefix ) );
449
450 $entryPoint = $this->getEntryPoint( $env );
451 $entryPoint->run();
452 $output = $entryPoint->getCapturedOutput();
453
454 // Missing files are also "forbidden"
455 $env->assertStatusCode( 403 );
456 $env->assertHeaderValue( 'no-cache', 'cache-control' );
457 $this->assertStringContainsString(
458 '<h1>Access denied</h1>',
459 $output
460 );
461 $this->assertStringContainsString(
462 $expected,
463 $output
464 );
465 }
466
467 }