Debian Codegraph @

extensions/AbuseFilter/tests/phpunit/integration/ActionVariablesIntegrationTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\AbuseFilter\Tests\Integration;
4
5 use AbuseFilterCreateAccountTestTrait;
6 use Generator;
7 use MediaWiki\Api\ApiUsageException;
8 use MediaWiki\Content\Content;
9 use MediaWiki\Content\JsonContent;
10 use MediaWiki\Content\WikitextContent;
11 use MediaWiki\Extension\AbuseFilter\AbuseFilterServices;
12 use MediaWiki\Extension\AbuseFilter\AbuseLogger;
13 use MediaWiki\Extension\AbuseFilter\AbuseLoggerFactory;
14 use MediaWiki\Extension\AbuseFilter\Consequences\ConsequencesLookup;
15 use MediaWiki\Extension\AbuseFilter\EditRevUpdater;
16 use MediaWiki\Extension\AbuseFilter\EmergencyCache;
17 use MediaWiki\Extension\AbuseFilter\Filter\ExistingFilter;
18 use MediaWiki\Extension\AbuseFilter\Filter\Flags;
19 use MediaWiki\Extension\AbuseFilter\Filter\LastEditInfo;
20 use MediaWiki\Extension\AbuseFilter\Filter\Specs;
21 use MediaWiki\Extension\AbuseFilter\FilterLookup;
22 use MediaWiki\Extension\AbuseFilter\FilterProfiler;
23 use MediaWiki\Extension\AbuseFilter\Hooks\Handlers\FilteredActionsHandler;
24 use MediaWiki\Extension\AbuseFilter\Variables\VariableHolder;
25 use MediaWiki\Extension\AbuseFilter\Watcher\EmergencyWatcher;
26 use MediaWiki\Extension\AbuseFilter\Watcher\UpdateHitCountWatcher;
27 use MediaWiki\Json\FormatJson;
28 use MediaWiki\MainConfigNames;
29 use MediaWiki\MediaWikiServices;
30 use MediaWiki\Tests\Api\ApiTestCase;
31 use MediaWiki\Utils\MWTimestamp;
32 use Wikimedia\Stats\NullStatsdDataFactory;
33
34 /**
35 * @group Database
36 * @group medium
37 * @group AbuseFilter
38 * @group AbuseFilterGeneric
39 */
40 class ActionVariablesIntegrationTest extends ApiTestCase {
41 use AbuseFilterCreateAccountTestTrait;
42
43 private function prepareServices(): void {
44 $this->setService(
45 FilterProfiler::SERVICE_NAME,
46 $this->createMock( FilterProfiler::class )
47 );
48 $this->setService(
49 EmergencyCache::SERVICE_NAME,
50 $this->createMock( EmergencyCache::class )
51 );
52 $this->setService(
53 EmergencyWatcher::SERVICE_NAME,
54 $this->createMock( EmergencyWatcher::class )
55 );
56 $this->setService(
57 UpdateHitCountWatcher::SERVICE_NAME,
58 $this->createMock( UpdateHitCountWatcher::class )
59 );
60 $this->setService(
61 EditRevUpdater::SERVICE_NAME,
62 $this->createMock( EditRevUpdater::class )
63 );
64
65 $this->overrideConfigValues( [
66 MainConfigNames::PageCreationLog => false,
67 'AbuseFilterCentralDB' => false,
68 ] );
69
70 $filter = new ExistingFilter(
71 new Specs( '1 === 1', '', 'Test Filter', [ 'disallow' ], 'default' ),
72 new Flags( true, false, false, false ),
73 [ 'disallow' => [ 'abusefilter-disallow' ] ],
74 new LastEditInfo( 1, 'Filter User', '20220713000000' ),
75 1,
76 0,
77 false
78 );
79 $filterLookup = $this->createMock( FilterLookup::class );
80 $filterLookup->expects( $this->once() )
81 ->method( 'getAllActiveFiltersInGroup' )
82 ->with( 'default', false )
83 ->willReturn( [ $filter ] );
84 $filterLookup->method( 'getFilter' )
85 ->with( 1, false )
86 ->willReturn( $filter );
87 $this->setService( FilterLookup::SERVICE_NAME, $filterLookup );
88
89 $consequencesLookup = $this->createMock( ConsequencesLookup::class );
90 $consequencesLookup->method( 'getConsequencesForFilters' )
91 ->with( $this->logicalOr( [ 1 ], [ '1' ] ) )
92 ->willReturn( [ 1 => $filter->getActions() ] );
93 $this->setService( ConsequencesLookup::SERVICE_NAME, $consequencesLookup );
94 }
95
96 private function setAbuseLoggerFactoryWithEavesdrop( ?VariableHolder &$varHolder = null ): void {
97 $factory = $this->createMock( AbuseLoggerFactory::class );
98 $factory->method( 'newLogger' )
99 ->willReturnCallback( function ( $title, $user, $vars ) use ( &$varHolder ) {
100 $varHolder = $vars;
101 $logger = $this->createMock( AbuseLogger::class );
102 $logger->method( 'addLogEntries' )
103 ->willReturn( [ 'local' => [ 1 ], 'global' => [] ] );
104 return $logger;
105 } );
106 $this->setService( AbuseLoggerFactory::SERVICE_NAME, $factory );
107 }
108
109 private function assertVariables( array $expected, array $export ) {
110 foreach ( $expected as $var => $value ) {
111 $this->assertArrayHasKey( $var, $export, "Variable '$var' not set" );
112
113 $actual = $export[$var];
114 if ( $var === 'new_html' && is_array( $value ) ) {
115 // Special case for new_html: avoid flaky tests, and only check containment
116 $this->assertStringContainsString( 'mw-parser-output', $actual );
117 $this->assertDoesNotMatchRegularExpression( "/<!--\s*NewPP limit/", $actual );
118 $this->assertDoesNotMatchRegularExpression( "/<!--\s*Transclusion/", $actual );
119 foreach ( $value as $needle ) {
120 $this->assertStringContainsString( $needle, $actual, 'Checking new_html' );
121 }
122 } else {
123 $this->assertSame( $value, $actual, $var );
124 }
125 }
126 }
127
128 public static function provideEditVariables(): Generator {
129 $summary = __METHOD__;
130 $new = '[https://a.com Test] foo';
131
132 yield 'create page' => [
133 'expected' => [
134 'action' => 'edit',
135 'old_wikitext' => '',
136 'old_content_model' => '',
137 'new_wikitext' => $new,
138 'new_content_model' => 'wikitext',
139 'summary' => $summary,
140 'new_pst' => $new,
141 'new_text' => "Test foo",
142 'edit_diff' => "@@ -1,0 +1,1 @@\n+$new\n",
143 'edit_diff_pst' => "@@ -1,0 +1,1 @@\n+$new\n",
144 'new_size' => strlen( $new ),
145 'old_size' => 0,
146 'edit_delta' => strlen( $new ),
147 'added_lines' => [ $new ],
148 'removed_lines' => [],
149 'added_lines_pst' => [ $new ],
150 'all_links' => [ 'https://a.com/' ],
151 'old_links' => [],
152 'added_links' => [ 'https://a.com/' ],
153 'removed_links' => [],
154 'page_last_edit_age' => null,
155 ],
156 'params' => [ 'text' => $new, 'summary' => $summary, 'createonly' => true ],
157 ];
158
159 // phpcs:disable Generic.Files.LineLength
160 $old = '[https://a.com Test] foo';
161 $new = "'''Random'''.\nSome ''special'' chars: àèìòù 名探偵コナン.\n[[Help:PST|]] test, [//www.b.com link]";
162
163 yield 'PST and special chars' => [
164 'expected' => [
165 'action' => 'edit',
166 'old_wikitext' => $old,
167 'old_content_model' => 'wikitext',
168 'new_wikitext' => $new,
169 'new_content_model' => 'wikitext',
170 'summary' => $summary,
171 'new_pst' => "'''Random'''.\nSome ''special'' chars: àèìòù 名探偵コナン.\n[[Help:PST|PST]] test, [//www.b.com link]",
172 'new_text' => "Random.\nSome special chars: àèìòù 名探偵コナン.\nPST test, link",
173 'edit_diff' => "@@ -1,1 +1,3 @@\n-[https://a.com Test] foo\n+'''Random'''.\n+Some ''special'' chars: àèìòù 名探偵コナン.\n+[[Help:PST|]] test, [//www.b.com link]\n",
174 'edit_diff_pst' => "@@ -1,1 +1,3 @@\n-[https://a.com Test] foo\n+'''Random'''.\n+Some ''special'' chars: àèìòù 名探偵コナン.\n+[[Help:PST|PST]] test, [//www.b.com link]\n",
175 'new_size' => strlen( $new ),
176 'old_size' => strlen( $old ),
177 'edit_delta' => strlen( $new ) - strlen( $old ),
178 'added_lines' => explode( "\n", $new ),
179 'removed_lines' => [ $old ],
180 'added_lines_pst' => [ "'''Random'''.", "Some ''special'' chars: àèìòù 名探偵コナン.", '[[Help:PST|PST]] test, [//www.b.com link]' ],
181 'old_links' => [ 'https://a.com/' ],
182 'all_links' => [ 'https://www.b.com/' ],
183 'removed_links' => [ 'https://a.com/' ],
184 'added_links' => [ 'https://www.b.com/' ],
185 'page_last_edit_age' => 10,
186 ],
187 'params' => [ 'text' => $new, 'summary' => $summary ],
188 'oldContent' => new WikitextContent( $old ),
189 ];
190
191 $old = "'''Random'''.\nSome ''special'' chars: àèìòù 名探偵コナン.\n[[Help:PST|PST]] test, [//www.b.com link]";
192 $new = '[https://a.com Test] foo';
193
194 yield 'PST and special chars, reverse' => [
195 'expected' => [
196 'action' => 'edit',
197 'old_wikitext' => $old,
198 'old_content_model' => 'wikitext',
199 'new_wikitext' => $new,
200 'new_content_model' => 'wikitext',
201 'summary' => $summary,
202 'new_html' => [ 'Test</a>' ],
203 'new_pst' => '[https://a.com Test] foo',
204 'new_text' => 'Test foo',
205 'edit_diff' => "@@ -1,3 +1,1 @@\n-'''Random'''.\n-Some ''special'' chars: àèìòù 名探偵コナン.\n-[[Help:PST|PST]] test, [//www.b.com link]\n+[https://a.com Test] foo\n",
206 'edit_diff_pst' => "@@ -1,3 +1,1 @@\n-'''Random'''.\n-Some ''special'' chars: àèìòù 名探偵コナン.\n-[[Help:PST|PST]] test, [//www.b.com link]\n+[https://a.com Test] foo\n",
207 'new_size' => strlen( $new ),
208 'old_size' => strlen( $old ),
209 'edit_delta' => strlen( $new ) - strlen( $old ),
210 'added_lines' => [ $new ],
211 'removed_lines' => explode( "\n", $old ),
212 'added_lines_pst' => [ $new ],
213 'old_links' => [ 'https://www.b.com/' ],
214 'all_links' => [ 'https://a.com/' ],
215 'removed_links' => [ 'https://www.b.com/' ],
216 'added_links' => [ 'https://a.com/' ],
217 'page_last_edit_age' => 10,
218 ],
219 'params' => [ 'text' => $new, 'summary' => $summary ],
220 'oldContent' => new WikitextContent( $old ),
221 ];
222 // phpcs:enable Generic.Files.LineLength
223
224 $old = 'This edit will be pretty smal';
225 $new = $old . 'l';
226
227 yield 'Small edit' => [
228 'expected' => [
229 'action' => 'edit',
230 'old_wikitext' => $old,
231 'old_content_model' => 'wikitext',
232 'new_wikitext' => $new,
233 'new_content_model' => 'wikitext',
234 'summary' => $summary,
235 'new_html' => [ "<p>This edit will be pretty small\n</p>" ],
236 'new_pst' => $new,
237 'new_text' => $new,
238 'edit_diff' => "@@ -1,1 +1,1 @@\n-$old\n+$new\n",
239 'edit_diff_pst' => "@@ -1,1 +1,1 @@\n-$old\n+$new\n",
240 'new_size' => strlen( $new ),
241 'old_size' => strlen( $old ),
242 'edit_delta' => 1,
243 'removed_lines' => [ $old ],
244 'added_lines' => [ $new ],
245 'added_lines_pst' => [ $new ],
246 'old_links' => [],
247 'all_links' => [],
248 'removed_links' => [],
249 'added_links' => [],
250 'page_last_edit_age' => 10,
251 ],
252 'params' => [ 'text' => $new, 'summary' => $summary ],
253 'oldContent' => new WikitextContent( $old ),
254 ];
255
256 yield 'content model change to wikitext' => [
257 'expected' => [
258 'action' => 'edit',
259 'old_wikitext' => "{\n\t\"key\": \"value\"\n}",
260 'old_content_model' => 'json',
261 'new_wikitext' => 'new test https://en.wikipedia.org',
262 'new_content_model' => 'wikitext',
263 'old_links' => [],
264 'all_links' => [ 'https://en.wikipedia.org/' ],
265 'page_last_edit_age' => 10,
266 ],
267 'params' => [
268 'text' => 'new test https://en.wikipedia.org',
269 'contentmodel' => 'wikitext',
270 ],
271 'oldContent' => new JsonContent( FormatJson::encode( [ 'key' => 'value' ] ) ),
272 ];
273
274 yield 'content model change from wikitext' => [
275 'expected' => [
276 'action' => 'edit',
277 'old_wikitext' => 'test https://en.wikipedia.org',
278 'old_content_model' => 'wikitext',
279 'new_wikitext' => '{"key": "value"}',
280 'new_content_model' => 'json',
281 'old_links' => [ 'https://en.wikipedia.org/' ],
282 'all_links' => [],
283 'page_last_edit_age' => 10,
284 ],
285 'params' => [
286 'text' => '{"key": "value"}',
287 'contentmodel' => 'json',
288 ],
289 'oldContent' => new WikitextContent( 'test https://en.wikipedia.org' ),
290 ];
291 }
292
293 /**
294 * @dataProvider provideEditVariables
295 * @covers \MediaWiki\Extension\AbuseFilter\Hooks\Handlers\FilteredActionsHandler
296 * @covers \MediaWiki\Extension\AbuseFilter\VariableGenerator\RunVariableGenerator
297 * @covers \MediaWiki\Extension\AbuseFilter\VariableGenerator\VariableGenerator
298 * @covers \MediaWiki\Extension\AbuseFilter\Variables\LazyVariableComputer
299 */
300 public function testEditVariables(
301 array $expected, array $params, ?Content $oldContent = null
302 ) {
303 $time = time();
304 MWTimestamp::setFakeTime( $time );
305
306 $varHolder = null;
307 $this->prepareServices();
308 $this->setAbuseLoggerFactoryWithEavesdrop( $varHolder );
309
310 $title = 'My test page';
311 $page = $this->getNonexistingTestPage( $title );
312 if ( $oldContent ) {
313 $status = $this->editPage( $page, $oldContent, 'Creating test page' );
314 $this->assertStatusGood( $status );
315 }
316
317 $handler = new FilteredActionsHandler(
318 new NullStatsdDataFactory(),
319 AbuseFilterServices::getFilterRunnerFactory(),
320 AbuseFilterServices::getVariableGeneratorFactory(),
321 AbuseFilterServices::getEditRevUpdater(),
322 AbuseFilterServices::getBlockedDomainFilter(),
323 MediaWikiServices::getInstance()->getPermissionManager()
324 );
325 $this->setTemporaryHook(
326 'EditFilterMergedContent',
327 [ $handler, 'onEditFilterMergedContent' ],
328 true
329 );
330
331 MWTimestamp::setFakeTime( $time + 10 );
332 $ex = null;
333 try {
334 $this->doApiRequestWithToken(
335 [ 'action' => 'edit', 'title' => $title ] + $params
336 );
337 } catch ( ApiUsageException $ex ) {
338 }
339 $this->assertNotNull( $ex, 'Exception should be thrown' );
340 $this->assertNotNull( $varHolder, 'Variables should be set' );
341 $export = AbuseFilterServices::getVariablesManager()->dumpAllVars(
342 $varHolder,
343 array_keys( $expected )
344 );
345 $this->assertVariables( $expected, $export );
346 }
347
348 public static function provideAccountCreationVars(): Generator {
349 yield 'create account anonymously' => [
350 'expected' => [
351 'action' => 'createaccount',
352 'accountname' => 'New account',
353 ]
354 ];
355
356 yield 'create account by an existing user' => [
357 'expected' => [
358 'action' => 'createaccount',
359 'accountname' => 'New account',
360 'user_name' => 'Account creator',
361 'user_editcount' => 0,
362 ],
363 'accountName' => 'New account',
364 'autocreate' => false,
365 'creatorName' => 'Account creator'
366 ];
367
368 yield 'autocreate an account' => [
369 'expected' => [
370 'action' => 'autocreateaccount',
371 'accountname' => 'New account',
372 ],
373 'accountName' => 'New account',
374 'autocreate' => true,
375 ];
376 }
377
378 /**
379 * @dataProvider provideAccountCreationVars
380 * @covers \MediaWiki\Extension\AbuseFilter\AbuseFilterPreAuthenticationProvider
381 * @covers \MediaWiki\Extension\AbuseFilter\Hooks\Handlers\FilteredActionsHandler
382 * @covers \MediaWiki\Extension\AbuseFilter\VariableGenerator\RunVariableGenerator
383 * @covers \MediaWiki\Extension\AbuseFilter\VariableGenerator\VariableGenerator
384 */
385 public function testAccountCreationVars(
386 array $expected,
387 string $accountName = 'New account',
388 bool $autocreate = false,
389 ?string $creatorName = null
390 ) {
391 $varHolder = null;
392 $this->prepareServices();
393 $this->setAbuseLoggerFactoryWithEavesdrop( $varHolder );
394
395 $creator = null;
396 if ( $creatorName !== null ) {
397 $creator = $this->getServiceContainer()->getUserFactory()->newFromName( $creatorName );
398 $creator->addToDatabase();
399 }
400 $status = $this->createAccount( $accountName, $autocreate, $creator );
401 $this->assertStatusNotOK( $status );
402 $this->assertNotNull( $varHolder, 'Variables should be set' );
403 $export = AbuseFilterServices::getVariablesManager()->dumpAllVars(
404 $varHolder,
405 array_keys( $expected )
406 );
407 $this->assertVariables( $expected, $export );
408 }
409
410 }