Debian Codegraph @

tests/phpunit/integration/includes/Rest/Handler/RevisionHTMLHandlerTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Rest\Handler;
4
5 use Exception;
6 use MediaWiki\Config\ServiceOptions;
7 use MediaWiki\Deferred\DeferredUpdates;
8 use MediaWiki\MainConfigNames;
9 use MediaWiki\MainConfigSchema;
10 use MediaWiki\Parser\Parsoid\ParsoidParser;
11 use MediaWiki\Parser\Parsoid\ParsoidParserFactory;
12 use MediaWiki\Rest\Handler\Helper\HtmlOutputRendererHelper;
13 use MediaWiki\Rest\Handler\Helper\PageRestHelperFactory;
14 use MediaWiki\Rest\Handler\Helper\RevisionContentHelper;
15 use MediaWiki\Rest\Handler\RevisionHTMLHandler;
16 use MediaWiki\Rest\LocalizedHttpException;
17 use MediaWiki\Rest\RequestData;
18 use MediaWiki\Revision\RevisionRecord;
19 use MediaWiki\Utils\MWTimestamp;
20 use MediaWikiIntegrationTestCase;
21 use Psr\Http\Message\StreamInterface;
22 use ReflectionClass;
23 use Wikimedia\Message\MessageValue;
24 use Wikimedia\ObjectCache\HashBagOStuff;
25 use Wikimedia\Parsoid\Core\ClientError;
26 use Wikimedia\Parsoid\Core\ResourceLimitExceededException;
27 use Wikimedia\Parsoid\Parsoid;
28 use Wikimedia\Stats\StatsFactory;
29
30 /**
31 * @covers \MediaWiki\Rest\Handler\RevisionHTMLHandler
32 * @group Database
33 */
34 class RevisionHTMLHandlerTest extends MediaWikiIntegrationTestCase {
35 use HandlerTestTrait;
36 use HTMLHandlerTestTrait;
37
38 private const WIKITEXT = 'Hello \'\'\'World\'\'\'';
39
40 private const HTML = '>World<';
41
42 private HashBagOStuff $parserCacheBagOStuff;
43
44 /** @var int */
45 private static $uuidCounter = 0;
46
47 protected function setUp(): void {
48 parent::setUp();
49
50 $this->parserCacheBagOStuff = new HashBagOStuff();
51 }
52
53 /**
54 * @return RevisionHTMLHandler
55 */
56 private function newHandler(): RevisionHTMLHandler {
57 $services = $this->getServiceContainer();
58 $config = [
59 MainConfigNames::RightsUrl => 'https://example.com/rights',
60 MainConfigNames::RightsText => 'some rights',
61 MainConfigNames::ParsoidCacheConfig =>
62 MainConfigSchema::getDefaultValue( MainConfigNames::ParsoidCacheConfig )
63 ];
64
65 $helperFactory = $this->createNoOpMock(
66 PageRestHelperFactory::class,
67 [ 'newRevisionContentHelper', 'newHtmlOutputRendererHelper' ]
68 );
69
70 $helperFactory->method( 'newRevisionContentHelper' )
71 ->willReturn( new RevisionContentHelper(
72 new ServiceOptions( RevisionContentHelper::CONSTRUCTOR_OPTIONS, $config ),
73 $services->getRevisionLookup(),
74 $services->getTitleFormatter(),
75 $services->getPageStore(),
76 $services->getTitleFactory(),
77 $services->getConnectionProvider(),
78 $services->getChangeTagsStore()
79 ) );
80
81 $parsoidOutputStash = $this->getParsoidOutputStash();
82 $helperFactory->method( 'newHtmlOutputRendererHelper' )
83 ->willReturnCallback( static function ( $page, $parameters, $authority, $revision, $lenientRevHandling ) use ( $services, $parsoidOutputStash ) {
84 return new HtmlOutputRendererHelper(
85 $parsoidOutputStash,
86 StatsFactory::newNull(),
87 $services->getParserOutputAccess(),
88 $services->getPageStore(),
89 $services->getRevisionLookup(),
90 $services->getRevisionRenderer(),
91 $services->getParsoidSiteConfig(),
92 $services->getHtmlTransformFactory(),
93 $services->getContentHandlerFactory(),
94 $services->getLanguageFactory(),
95 $page,
96 $parameters,
97 $authority,
98 $revision,
99 $lenientRevHandling
100 );
101 } );
102
103 $handler = new RevisionHTMLHandler(
104 $helperFactory
105 );
106
107 return $handler;
108 }
109
110 private function getExistingPageWithRevisions( $name ) {
111 $page = $this->getNonexistingTestPage( $name );
112
113 $this->editPage( $page, self::WIKITEXT );
114 $revisions['first'] = $page->getRevisionRecord();
115
116 $this->editPage( $page, 'DEAD BEEF' );
117 $revisions['latest'] = $page->getRevisionRecord();
118
119 return [ $page, $revisions ];
120 }
121
122 public function testExecuteWithHtml() {
123 [ $page, $revisions ] = $this->getExistingPageWithRevisions( __METHOD__ );
124 $this->assertStatusGood( $this->editPage( $page, self::WIKITEXT ),
125 'Edited a page'
126 );
127
128 $request = new RequestData(
129 [ 'pathParams' => [ 'id' => $revisions['first']->getId() ] ]
130 );
131
132 $handler = $this->newHandler();
133 $data = $this->executeHandlerAndGetBodyData( $handler, $request, [
134 'format' => 'with_html'
135 ] );
136
137 $this->assertResponseData( $revisions['first'], $data );
138 $this->assertStringContainsString( '<!DOCTYPE html>', $data['html'] );
139 $this->assertStringContainsString( '<html', $data['html'] );
140 $this->assertStringContainsString( self::HTML, $data['html'] );
141 }
142
143 public function testExecuteHtmlOnly() {
144 [ $page, $revisions ] = $this->getExistingPageWithRevisions( __METHOD__ );
145 $this->assertStatusGood( $this->editPage( $page, self::WIKITEXT ),
146 'Edited a page'
147 );
148
149 $request = new RequestData(
150 [ 'pathParams' => [ 'id' => $revisions['first']->getId() ] ]
151 );
152
153 $handler = $this->newHandler();
154 $response = $this->executeHandler( $handler, $request, [
155 'format' => 'html'
156 ] );
157
158 $htmlResponse = (string)$response->getBody();
159 $this->assertStringContainsString( '<!DOCTYPE html>', $htmlResponse );
160 $this->assertStringContainsString( '<html', $htmlResponse );
161 $this->assertStringContainsString( self::HTML, $htmlResponse );
162 }
163
164 public function testEtagLastModified() {
165 $time = time();
166 MWTimestamp::setFakeTime( $time );
167
168 [ $page, $revisions ] = $this->getExistingPageWithRevisions( __METHOD__ );
169 $request = new RequestData(
170 [ 'pathParams' => [ 'id' => $revisions['first']->getId() ] ]
171 );
172
173 // First, test it works if nothing was cached yet.
174 // Make some time pass since page was created:
175 MWTimestamp::setFakeTime( $time + 10 );
176 $handler = $this->newHandler();
177 $response = $this->executeHandler( $handler, $request, [
178 'format' => 'html'
179 ] );
180 $this->assertArrayHasKey( 'ETag', $response->getHeaders() );
181 $this->assertArrayHasKey( 'Last-Modified', $response->getHeaders() );
182 $this->assertSame( MWTimestamp::convert( TS_RFC2822, $time + 10 ),
183 $response->getHeaderLine( 'Last-Modified' ) );
184
185 $etag = $response->getHeaderLine( 'ETag' );
186
187 // Now, test that headers work when getting from cache too.
188 MWTimestamp::setFakeTime( $time + 20 );
189 $handler = $this->newHandler();
190 $response = $this->executeHandler( $handler, $request, [
191 'format' => 'html'
192 ] );
193 $this->assertArrayHasKey( 'ETag', $response->getHeaders() );
194 $this->assertSame( $etag, $response->getHeaderLine( 'ETag' ) );
195 $this->assertArrayHasKey( 'Last-Modified', $response->getHeaders() );
196 $this->assertSame( MWTimestamp::convert( TS_RFC2822, $time + 10 ),
197 $response->getHeaderLine( 'Last-Modified' ) );
198
199 // Now, expire the cache, and assert we are getting a new timestamp back
200 MWTimestamp::setFakeTime( $time + 10000 );
201 $this->assertTrue(
202 $page->getTitle()->invalidateCache( MWTimestamp::convert( TS_MW, $time ) ),
203 'Can invalidate cache'
204 );
205 DeferredUpdates::doUpdates();
206
207 $handler = $this->newHandler();
208 $response = $this->executeHandler( $handler, $request, [
209 'format' => 'html'
210 ] );
211 $this->assertArrayHasKey( 'ETag', $response->getHeaders() );
212 $this->assertNotSame( $etag, $response->getHeaderLine( 'ETag' ) );
213 $this->assertArrayHasKey( 'Last-Modified', $response->getHeaders() );
214 $this->assertSame( MWTimestamp::convert( TS_RFC2822, $time + 10000 ),
215 $response->getHeaderLine( 'Last-Modified' ) );
216 }
217
218 public static function provideHandlesParsoidError() {
219 yield 'ClientError' => [
220 new ClientError( 'TEST_TEST' ),
221 new LocalizedHttpException(
222 new MessageValue( 'rest-html-backend-error' ),
223 400,
224 [
225 'reason' => 'TEST_TEST'
226 ]
227 )
228 ];
229 yield 'ResourceLimitExceededException' => [
230 new ResourceLimitExceededException( 'TEST_TEST' ),
231 new LocalizedHttpException(
232 new MessageValue( 'rest-resource-limit-exceeded' ),
233 413,
234 [
235 'reason' => 'TEST_TEST'
236 ]
237 )
238 ];
239 }
240
241 /**
242 * @dataProvider provideHandlesParsoidError
243 */
244 public function testHandlesParsoidError(
245 Exception $parsoidException,
246 Exception $expectedException
247 ) {
248 [ $page, $revisions ] = $this->getExistingPageWithRevisions( __METHOD__ );
249 $request = new RequestData(
250 [ 'pathParams' => [ 'id' => $revisions['first']->getId() ] ]
251 );
252
253 $services = $this->getServiceContainer();
254 $parsoidParser = $services->getParsoidParserFactory()->create();
255
256 // Mock Parsoid
257 $mockParsoid = $this->createNoOpMock( Parsoid::class, [ 'wikitext2html' ] );
258 $mockParsoid->expects( $this->once() )
259 ->method( 'wikitext2html' )
260 ->willThrowException( $parsoidException );
261
262 // Install it in the ParsoidParser object
263 $reflector = new ReflectionClass( ParsoidParser::class );
264 $prop = $reflector->getProperty( 'parsoid' );
265 $prop->setValue( $parsoidParser, $mockParsoid );
266 $this->assertEquals( $prop->getValue( $parsoidParser ), $mockParsoid );
267
268 // Create a mock Parsoid factory that returns the ParsoidParser object
269 // with the mocked Parsoid object.
270 $mockParsoidParserFactory = $this->createNoOpMock( ParsoidParserFactory::class, [ 'create' ] );
271 $mockParsoidParserFactory->expects( $this->once() )
272 ->method( 'create' )
273 ->willReturn( $parsoidParser );
274
275 // Ensure WiktiextContentHandler has the mock ParsoidParserFactory
276 $wtHandler = $services->getContentHandlerFactory()->getContentHandler( 'wikitext' );
277 $reflector = new ReflectionClass( 'WikitextContentHandler' );
278 $prop = $reflector->getProperty( 'parsoidParserFactory' );
279 $prop->setValue( $wtHandler, $mockParsoidParserFactory );
280 $this->assertEquals( $prop->getValue( $wtHandler ), $mockParsoidParserFactory );
281
282 $handler = $this->newHandler();
283 $this->expectExceptionObject( $expectedException );
284 $this->executeHandler( $handler, $request, [
285 'format' => 'html'
286 ] );
287 }
288
289 public function testExecute_missingparam() {
290 $request = new RequestData();
291
292 $this->expectExceptionObject(
293 new LocalizedHttpException(
294 new MessageValue( "paramvalidator-missingparam", [ 'revision' ] ),
295 400
296 )
297 );
298
299 $handler = $this->newHandler();
300 $this->executeHandler( $handler, $request );
301 }
302
303 public function testExecute_error() {
304 $request = new RequestData( [ 'pathParams' => [ 'id' => '2076419894' ] ] );
305
306 $this->expectExceptionObject(
307 new LocalizedHttpException(
308 new MessageValue( "rest-nonexistent-revision", [ 'testing' ] ),
309 404
310 )
311 );
312
313 $handler = $this->newHandler();
314 $this->executeHandler( $handler, $request );
315 }
316
317 /**
318 * @param RevisionRecord $rev
319 * @param array $data
320 */
321 private function assertResponseData( RevisionRecord $rev, array $data ): void {
322 $title = $rev->getPageAsLinkTarget();
323
324 $this->assertSame( $rev->getId(), $data['id'] );
325 $this->assertSame( $rev->getSize(), $data['size'] );
326 $this->assertSame( $rev->isMinor(), $data['minor'] );
327 $this->assertSame(
328 wfTimestampOrNull( TS_ISO_8601, $rev->getTimestamp() ),
329 $data['timestamp']
330 );
331 $this->assertSame( $title->getArticleID(), $data['page']['id'] );
332 $this->assertSame( $title->getDBkey(), $data['page']['key'] ); // assume main namespace
333 $this->assertSame( $title->getText(), $data['page']['title'] ); // assume main namespace
334 $this->assertSame( CONTENT_MODEL_WIKITEXT, $data['content_model'] );
335 $this->assertSame( 'https://example.com/rights', $data['license']['url'] );
336 $this->assertSame( 'some rights', $data['license']['title'] );
337 $this->assertSame( $rev->getComment()->text, $data['comment'] );
338 $this->assertSame( $rev->getUser()->getId(), $data['user']['id'] );
339 $this->assertSame( $rev->getUser()->getName(), $data['user']['name'] );
340 }
341
342 /**
343 * The below 2 request are described as follows;
344 *
345 * Request One:
346 * This request stashes data-parsoid to the parsoid output stash and caches the
347 * stash key in ::cachedStashedKey so that we can use to perform a stash lookup
348 * in the near future.
349 *
350 * Request Two:
351 * This request then uses the request header ETag which is the same as that in
352 * the cached stashed key container because during the second request, no stashing
353 * was done and the page revision is the same. So what is in the output response headers
354 * in the user's browser will be exactly what is in the parsoid output stash.
355 *
356 * NOTE: if we make another request which actually stashes, that cached stash key will
357 * be updated, and we can use it to access the stash's latest entry.
358 */
359 public function testExecuteStashParsoidOutput() {
360 [ /* page */, $revisions ] = $this->getExistingPageWithRevisions( __METHOD__ );
361 $outputStash = $this->getParsoidOutputStash();
362
363 [ /* $html1 */, $etag1, $stashKey1 ] = $this->executeRevisionHTMLRequest(
364 $revisions['first']->getId(),
365 [ 'stash' => true ]
366 );
367 $this->assertNotNull( $outputStash->get( $stashKey1 ) );
368
369 [ /* $html2 */, $etag2, $stashKey2 ] = $this->executeRevisionHTMLRequest(
370 $revisions['first']->getId(),
371 [ 'stash' => false ]
372 );
373
374 // The etags should be different, but the stash key should be identicl
375 $this->assertNotSame( $etag1, $etag2 );
376 $this->assertSame( $stashKey1->getKey(), $stashKey2->getKey() );
377
378 // Ensure nothing has changed with the output stash
379 $this->assertNotNull( $outputStash->get( $stashKey1 ) );
380
381 // Make sure the output for stashed and unstashed doesn't have the same tag,
382 // since it will actually be different!
383 // FIXME: implement flavors
384 }
385
386 public function testETagVariesOnFormat() {
387 $page = $this->getExistingTestPage();
388
389 [ /* $html1 */, $etag1 ] =
390 $this->executeRevisionHTMLRequest( $page->getLatest(), [], [ 'format' => 'html' ] );
391
392 [ /* $html2 */, $etag2 ] =
393 $this->executeRevisionHTMLRequest( $page->getLatest(), [], [ 'format' => 'with_html' ] );
394
395 $this->assertNotSame( $etag1, $etag2 );
396 }
397
398 public function testStashingWithRateLimitExceeded() {
399 // Set the rate limit to 1 request per minute
400 $this->overrideConfigValue(
401 MainConfigNames::RateLimits,
402 [
403 'stashbasehtml' => [
404 '&can-bypass' => false,
405 'ip' => [ 1, 60 ],
406 'newbie' => [ 1, 60 ]
407 ]
408 ]
409 );
410
411 $page = $this->getExistingTestPage();
412
413 $authority = $this->getAuthority();
414 $this->executeRevisionHTMLRequest( $page->getLatest(), [ 'stash' => true ], [], $authority );
415 // In this request, the rate limit has been exceeded, so it should throw.
416 $this->expectException( LocalizedHttpException::class );
417 $this->expectExceptionCode( 429 );
418 $this->executeRevisionHTMLRequest( $page->getLatest(), [ 'stash' => true ], [], $authority );
419 }
420
421 /**
422 * @dataProvider provideExecuteWithVariant
423 */
424 public function testExecuteWithVariant(
425 string $format,
426 callable $bodyHtmlHandler,
427 string $expectedContentLanguage,
428 string $expectedVaryHeader
429 ) {
430 $this->overrideConfigValue( MainConfigNames::UsePigLatinVariant, true );
431 $page = $this->getNonexistingTestPage( __METHOD__ );
432 $this->editPage( $page, '<p>test language conversion</p>', 'Edited a page' );
433 $revRecord = $page->getRevisionRecord();
434
435 $acceptLanguage = 'en-x-piglatin';
436 $request = new RequestData(
437 [
438 'pathParams' => [ 'id' => $revRecord->getId() ],
439 'headers' => [
440 'Accept-Language' => $acceptLanguage
441 ]
442 ]
443 );
444
445 $handler = $this->newHandler();
446 $response = $this->executeHandler( $handler, $request, [
447 'format' => $format
448 ] );
449
450 $responseBody = json_decode( $response->getBody(), true );
451 $htmlBody = $bodyHtmlHandler( $response->getBody() );
452 $contentLanguageHeader = $response->getHeaderLine( 'Content-Language' );
453 $varyHeader = $response->getHeaderLine( 'Vary' );
454
455 // html format doesn't return a response in JSON format
456 if ( $responseBody ) {
457 $this->assertResponseData( $revRecord, $responseBody );
458 }
459 $this->assertStringContainsString( '>esttay anguagelay onversioncay<', $htmlBody );
460 $this->assertEquals( $expectedContentLanguage, $contentLanguageHeader );
461 $this->assertStringContainsStringIgnoringCase( $expectedVaryHeader, $varyHeader );
462 $this->assertStringContainsString( $acceptLanguage, $response->getHeaderLine( 'ETag' ) );
463 }
464
465 public static function provideExecuteWithVariant() {
466 yield 'with_html request should contain accept language but not content language' => [
467 'with_html',
468 static function ( StreamInterface $response ) {
469 return json_decode( $response->getContents(), true )['html'];
470 },
471 '',
472 'accept-language'
473 ];
474 yield 'html request should contain accept and content language' => [
475 'html',
476 static function ( StreamInterface $response ) {
477 return $response->getContents();
478 },
479 'en-x-piglatin',
480 'accept-language'
481 ];
482 }
483 }