Debian Codegraph @

extensions/AbuseFilter/tests/phpunit/unit/FilterLookupTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\AbuseFilter\Tests\Unit;
4
5 use AbuseFilterRowsAndFiltersTestTrait;
6 use Generator;
7 use MediaWiki\Extension\AbuseFilter\CentralDBManager;
8 use MediaWiki\Extension\AbuseFilter\CentralDBNotAvailableException;
9 use MediaWiki\Extension\AbuseFilter\Filter\ClosestFilterVersionNotFoundException;
10 use MediaWiki\Extension\AbuseFilter\Filter\ExistingFilter;
11 use MediaWiki\Extension\AbuseFilter\Filter\Filter;
12 use MediaWiki\Extension\AbuseFilter\Filter\FilterNotFoundException;
13 use MediaWiki\Extension\AbuseFilter\Filter\FilterVersionNotFoundException;
14 use MediaWiki\Extension\AbuseFilter\Filter\Flags;
15 use MediaWiki\Extension\AbuseFilter\Filter\HistoryFilter;
16 use MediaWiki\Extension\AbuseFilter\Filter\LastEditInfo;
17 use MediaWiki\Extension\AbuseFilter\Filter\Specs;
18 use MediaWiki\Extension\AbuseFilter\FilterLookup;
19 use MediaWikiUnitTestCase;
20 use stdClass;
21 use Wikimedia\ObjectCache\HashBagOStuff;
22 use Wikimedia\ObjectCache\WANObjectCache;
23 use Wikimedia\Rdbms\FakeResultWrapper;
24 use Wikimedia\Rdbms\IDatabase;
25 use Wikimedia\Rdbms\ILoadBalancer;
26 use Wikimedia\Rdbms\LBFactory;
27 use Wikimedia\Rdbms\SelectQueryBuilder;
28
29 /**
30 * @group Test
31 * @group AbuseFilter
32 * @covers \MediaWiki\Extension\AbuseFilter\FilterLookup
33 * @todo Some integration tests with a real DB might be helpful
34 */
35 class FilterLookupTest extends MediaWikiUnitTestCase {
36 use AbuseFilterRowsAndFiltersTestTrait;
37
38 /**
39 * @param IDatabase|null $db
40 * @param string|false $centralDB
41 * @param WANObjectCache|null $cache
42 * @param bool $filterIsCentral
43 * @return FilterLookup
44 */
45 private function getLookup(
46 ?IDatabase $db = null,
47 $centralDB = false,
48 ?WANObjectCache $cache = null,
49 bool $filterIsCentral = false
50 ): FilterLookup {
51 $lb = $this->createMock( ILoadBalancer::class );
52 $lb->method( 'getConnection' )
53 ->willReturn( $db ?? $this->createMock( IDatabase::class ) );
54
55 $lbFactory = $this->createMock( LBFactory::class );
56 $lbFactory->method( 'getMainLB' )->willReturnCallback(
57 static function ( $domain ) use ( $lb, $centralDB ) {
58 // Return null for sanity
59 return $domain === $centralDB ? $lb : null;
60 }
61 );
62 $centralDBManager = new CentralDBManager( $lbFactory, $centralDB, $filterIsCentral );
63 return new FilterLookup(
64 $lb,
65 // Cannot use mocks because final methods aren't mocked and they would error out
66 $cache ?? new WANObjectCache( [ 'cache' => new HashBagOStuff() ] ),
67 $centralDBManager
68 );
69 }
70
71 /**
72 * Hacky helper to set up the database
73 * @param stdClass[] $filterRows abuse_filter or abuse_filter_history
74 * @param stdClass[] $actionRows
75 * @return IDatabase
76 */
77 private function getDBWithMockRows( array $filterRows, array $actionRows = [] ): IDatabase {
78 $db = $this->createMock( IDatabase::class );
79 $db->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $db ) );
80 $db->method( 'selectRow' )->willReturnCallback( static function ( $table ) use ( $filterRows ) {
81 $tables = (array)$table;
82 return array_intersect( $tables, [ 'abuse_filter', 'abuse_filter_history' ] ) ? $filterRows[0] : false;
83 } );
84 $db->method( 'select' )->willReturnCallback(
85 static function ( $table, $_, $where ) use ( $filterRows, $actionRows ) {
86 $tables = (array)$table;
87 $ret = [];
88 if ( in_array( 'abuse_filter_action', $tables ) ) {
89 foreach ( $actionRows as $row ) {
90 if ( $row->afa_filter === $where['afa_filter'] ) {
91 $ret[] = $row;
92 }
93 }
94 } elseif ( array_intersect( $tables, [ 'abuse_filter', 'abuse_filter_history' ] ) ) {
95 $ret = $filterRows;
96 }
97 return new FakeResultWrapper( $ret );
98 }
99 );
100 return $db;
101 }
102
103 /**
104 * @param int $version
105 * @param stdClass $dbRow
106 * @param HistoryFilter $expected
107 * @dataProvider provideFilterVersions
108 */
109 public function testGetFilterVersion( int $version, stdClass $dbRow, HistoryFilter $expected ) {
110 $db = $this->getDBWithMockRows( [ $dbRow ] );
111 $filterLookup = $this->getLookup( $db );
112 $this->assertEquals( $expected, $filterLookup->getFilterVersion( $version ) );
113 }
114
115 /**
116 * @return Generator
117 */
118 public static function provideFilterVersions(): Generator {
119 $version = 163;
120 $filters = [
121 'no actions' => new HistoryFilter(
122 new Specs(
123 'false',
124 'X',
125 'Y',
126 [],
127 'default'
128 ),
129 new Flags(
130 true,
131 true,
132 true,
133 true
134 ),
135 [],
136 new LastEditInfo(
137 42,
138 'FilterManager',
139 '20180706142932'
140 ),
141 1,
142 $version
143 ),
144 'with actions' => new HistoryFilter(
145 new Specs(
146 'the_answer := 42; the_answer === 6*9',
147 'Some comments',
148 'My filter',
149 [ 'degroup', 'disallow' ],
150 'default'
151 ),
152 new Flags(
153 true,
154 false,
155 true,
156 false
157 ),
158 [ 'degroup' => [], 'disallow' => [] ],
159 new LastEditInfo(
160 42,
161 'FilterManager',
162 '20180706142932'
163 ),
164 1,
165 $version
166 ),
167 ];
168
169 foreach ( $filters as $filter ) {
170 $flags = [];
171 foreach ( [ 'enabled', 'deleted', 'hidden', 'protected', 'global' ] as $flag ) {
172 $method = 'is' . ucfirst( $flag );
173 if ( $filter->$method() ) {
174 $flags[] = $flag;
175 }
176 }
177 $historyRow = (object)[
178 'afh_id' => $version,
179 'afh_filter' => $filter->getID(),
180 'afh_user' => $filter->getUserID(),
181 'afh_user_text' => $filter->getUserName(),
182 'afh_timestamp' => $filter->getTimestamp(),
183 'afh_pattern' => $filter->getRules(),
184 'afh_comments' => $filter->getComments(),
185 'afh_flags' => implode( ',', $flags ),
186 'afh_public_comments' => $filter->getName(),
187 'afh_actions' => serialize( array_fill_keys( $filter->getActionsNames(), [] ) ),
188 'afh_deleted' => 0,
189 'afh_changed_fields' => 'actions',
190 'afh_group' => $filter->getGroup()
191 ];
192 yield [ $version, $historyRow, $filter ];
193 }
194 }
195
196 public function testGetFilterVersion_notfound() {
197 $db = $this->createMock( IDatabase::class );
198 $db->method( 'selectRow' )->willReturn( false );
199 $db->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $db ) );
200 $filterLookup = $this->getLookup( $db );
201 $this->expectException( FilterVersionNotFoundException::class );
202 $filterLookup->getFilterVersion( 42 );
203 }
204
205 public function testGetLastHistoryVersion() {
206 // Reuse this data provider for conveniency
207 [ , $historyRow, $filter ] = $this->provideFilterVersions()->current();
208 $db = $this->getDBWithMockRows( [ $historyRow ] );
209 $filterLookup = $this->getLookup( $db );
210 $this->assertEquals( $filter, $filterLookup->getLastHistoryVersion( $filter->getID() ) );
211 }
212
213 public function testGetLastHistoryVersion_notfound() {
214 $db = $this->createMock( IDatabase::class );
215 $db->method( 'selectRow' )->willReturn( false );
216 $db->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $db ) );
217 $filterLookup = $this->getLookup( $db );
218 $this->expectException( FilterNotFoundException::class );
219 $filterLookup->getLastHistoryVersion( 42 );
220 }
221
222 public function testGetClosestVersion() {
223 // Reuse this data provider for conveniency
224 [ , $historyRow, $filter ] = $this->provideFilterVersions()->current();
225 $db = $this->getDBWithMockRows( [ $historyRow ] );
226 $filterLookup = $this->getLookup( $db );
227 $this->assertEquals( $filter, $filterLookup->getClosestVersion( 1, 42, FilterLookup::DIR_NEXT ) );
228 }
229
230 public function testGetClosestVersion_notfound() {
231 $db = $this->createMock( IDatabase::class );
232 $db->method( 'selectRow' )->willReturn( false );
233 $db->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $db ) );
234 $filterLookup = $this->getLookup( $db );
235 $this->expectException( ClosestFilterVersionNotFoundException::class );
236 $filterLookup->getClosestVersion( 42, 42, FilterLookup::DIR_PREV );
237 }
238
239 public function testGetFirstFilterVersionID() {
240 $versionID = 1234;
241 $db = $this->createMock( IDatabase::class );
242 $db->method( 'selectField' )->willReturn( $versionID );
243 $db->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $db ) );
244 $filterLookup = $this->getLookup( $db );
245 $this->assertSame( $versionID, $filterLookup->getFirstFilterVersionID( 42 ) );
246 }
247
248 public function testGetFirstFilterVersionID_notfound() {
249 $db = $this->createMock( IDatabase::class );
250 $db->method( 'selectField' )->willReturn( false );
251 $db->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $db ) );
252 $filterLookup = $this->getLookup( $db );
253 $this->expectException( FilterNotFoundException::class );
254 $filterLookup->getFirstFilterVersionID( 42 );
255 }
256
257 public function testLocalCache() {
258 $row = $this->getRowsAndFilters()['no actions']['row'];
259 $db = $this->createMock( IDatabase::class );
260 $db->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $db ) );
261 $db->expects( $this->once() )->method( 'selectRow' )->willReturn( $row );
262 $filterLookup = $this->getLookup( $db );
263
264 // Warm-up cache
265 $filterLookup->getFilter( 42, false );
266 // This should fail the soft assertion of once()
267 $filterLookup->getFilter( 42, false );
268 }
269
270 public function testClearLocalCache() {
271 $row = $this->getRowsAndFilters()['no actions']['row'];
272 $db = $this->createMock( IDatabase::class );
273 $db->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $db ) );
274 $db->expects( $this->exactly( 2 ) )->method( 'selectRow' )->willReturn( $row );
275 $filterLookup = $this->getLookup( $db );
276
277 // Both calls should result in a query
278 $filterLookup->getFilter( 42, false );
279 $filterLookup->clearLocalCache();
280 $filterLookup->getFilter( 42, false );
281 }
282
283 /**
284 * Provider to account for central vs non-central filter DB
285 * @return array
286 */
287 public static function provideIsCentral() {
288 return [
289 'central' => [ true ],
290 'not central' => [ false ]
291 ];
292 }
293
294 /**
295 * @param bool $isCentral
296 * @dataProvider provideIsCentral
297 */
298 public function testGlobalCache( bool $isCentral ) {
299 $row = $this->getRowsAndFilters()['no actions']['row'];
300 $db = $this->createMock( IDatabase::class );
301 $db->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $db ) );
302 // Should be called twice: once for the filter, once for the actions
303 $db->expects( $this->exactly( 2 ) )->method( 'select' )
304 ->willReturnOnConsecutiveCalls(
305 new FakeResultWrapper( [ $row ] ),
306 new FakeResultWrapper( [] )
307 );
308 $filterLookup = $this->getLookup( $db, 'foobar', null, $isCentral );
309
310 // WAN cache is only used for global filters
311 $global = true;
312 $group = 'foo';
313
314 // Warm-up cache: the following calls must not fail the soft assertion of once()
315 $filterLookup->getAllActiveFiltersInGroup( $group, $global );
316
317 // This is covered by the internal cache
318 $filterLookup->getAllActiveFiltersInGroup( $group, $global );
319 $filterLookup->clearLocalCache();
320 // This is covered by the network cache
321 $filterLookup->getAllActiveFiltersInGroup( $group, $global );
322 }
323
324 public function testFilterLookupClearNetworkCache() {
325 $row = $this->getRowsAndFilters()['no actions']['row'];
326 $db = $this->createMock( IDatabase::class );
327 $db->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $db ) );
328 // 4 calls: row, actions, row, actions
329 $db->expects( $this->exactly( 4 ) )
330 ->method( 'select' )
331 ->willReturnOnConsecutiveCalls(
332 new FakeResultWrapper( [ $row ] ),
333 new FakeResultWrapper( [] ),
334 new FakeResultWrapper( [ $row ] ),
335 new FakeResultWrapper( [] )
336 );
337 $cache = new WANObjectCache( [ 'cache' => new HashBagOStuff() ] );
338 $filterLookup = $this->getLookup( $db, 'foobar', $cache );
339
340 // WAN cache is only used for global filters
341 $global = true;
342 $group = 'foo';
343
344 // Both calls should result in a query
345 $filterLookup->getAllActiveFiltersInGroup( $group, $global );
346 $filterLookup->clearLocalCache();
347 $filterLookup->purgeGroupWANCache( $group );
348 // Avoid cache hits due to $TINY_POSTIVE (use +10 out of an abundance of caution)
349 $fakeTime = microtime( true ) + 10;
350 $cache->setMockTime( $fakeTime );
351 $filterLookup->getAllActiveFiltersInGroup( $group, $global );
352 }
353
354 public function testValidConstructor() {
355 $this->assertInstanceOf(
356 FilterLookup::class,
357 new FilterLookup(
358 $this->createMock( ILoadBalancer::class ),
359 $this->createMock( WANObjectCache::class ),
360 $this->createMock( CentralDBManager::class )
361 )
362 );
363 }
364
365 /**
366 * @param stdClass $row
367 * @param stdClass[] $actionsRows
368 * @param ExistingFilter $expected
369 * @dataProvider getRowsAndFilters
370 */
371 public function testGetFilter( stdClass $row, array $actionsRows, ExistingFilter $expected ) {
372 $db = $this->getDBWithMockRows( [ $row ], $actionsRows );
373 $filterLookup = $this->getLookup( $db );
374
375 $actual = $filterLookup->getFilter( $row->af_id, false );
376 // Trigger the lazy-load mechanism
377 $actual->getActions();
378 $this->assertEquals( $expected, $actual );
379 }
380
381 /**
382 * @param stdClass $row
383 * @param stdClass[] $actionsRows
384 * @param ExistingFilter $expected
385 * @dataProvider getRowsAndFilters
386 */
387 public function testGetFilter_global( stdClass $row, array $actionsRows, ExistingFilter $expected ) {
388 $db = $this->getDBWithMockRows( [ $row ], $actionsRows );
389 $filterLookup = $this->getLookup( $db, 'central_wiki' );
390
391 $actual = $filterLookup->getFilter( $row->af_id, true );
392 // Trigger the lazy-load mechanism
393 $actual->getActions();
394 $this->assertEquals( $expected, $actual );
395 }
396
397 public function testGetFilter_notfound() {
398 $db = $this->createMock( IDatabase::class );
399 $db->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $db ) );
400 $db->method( 'selectRow' )->willReturn( false );
401 $filterLookup = $this->getLookup( $db );
402
403 $this->expectException( FilterNotFoundException::class );
404 $filterLookup->getFilter( 42, false );
405 }
406
407 public function testGetFilter_globaldisabled() {
408 $filterLookup = $this->getLookup();
409 $this->expectException( CentralDBNotAvailableException::class );
410 $filterLookup->getFilter( 42, true );
411 }
412
413 public function testGetAllActiveFiltersInGroup() {
414 $data = $this->getRowsAndFilters();
415 $db = $this->getDBWithMockRows(
416 array_column( $data, 'row' ),
417 array_merge( ...array_column( $data, 'actions' ) )
418 );
419 $filterLookup = $this->getLookup( $db, false, null );
420
421 $expected = [];
422 /** @var Filter $filter */
423 foreach ( array_column( $data, 'filter' ) as $filter ) {
424 $expected[$filter->getID()] = $filter;
425 }
426
427 $actual = $filterLookup->getAllActiveFiltersInGroup( '_', false );
428 foreach ( $actual as $filter ) {
429 // Trigger the lazy-load mechanism
430 $filter->getActions();
431 }
432
433 $this->assertEquals( $expected, $actual );
434 }
435
436 /**
437 * @param bool $isCentral
438 * @dataProvider provideIsCentral
439 */
440 public function testGetAllActiveFiltersInGroup_global( bool $isCentral ) {
441 $data = $this->getRowsAndFilters();
442 $db = $this->getDBWithMockRows(
443 array_column( $data, 'row' ),
444 array_merge( ...array_column( $data, 'actions' ) )
445 );
446 $filterLookup = $this->getLookup( $db, 'some_db', null, $isCentral );
447
448 $expected = [];
449 /** @var Filter $filter */
450 foreach ( array_column( $data, 'filter' ) as $filter ) {
451 $key = 'global-' . $filter->getID();
452 $expected[$key] = $filter;
453 }
454
455 $actual = $filterLookup->getAllActiveFiltersInGroup( '_', true );
456 foreach ( $actual as $filter ) {
457 // Trigger the lazy-load mechanism
458 $filter->getActions();
459 }
460
461 $this->assertEquals( $expected, $actual );
462 }
463 }