summaryrefslogtreecommitdiff
blob: 6a5b3121283b8e9be216974a301addca924badf3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
<?php
/**
 * Tests for validating and saving a filter
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 *
 * @license GPL-2.0-or-later
 */

/**
 * @group Test
 * @group AbuseFilter
 * @group AbuseFilterSave
 * @group Database
 *
 * @covers AbuseFilter
 * @covers AbuseFilterViewEdit
 * @covers AbuseFilterParser
 */
class AbuseFilterSaveTest extends MediaWikiTestCase {
	protected static $mUser, $mParameters;

	/**
	 * @var array This tables will be deleted in parent::tearDown
	 */
	protected $tablesUsed = [
		'abuse_filter',
		'abuse_filter_action',
		'abuse_filter_history',
		'abuse_filter_log'
	];

	/**
	 * @see MediaWikiTestCase::setUp
	 */
	protected function setUp() {
		parent::setUp();
		$user = User::newFromName( 'FilterTester' );
		$user->addToDatabase();
		$user->addGroup( 'filterEditor' );
		RequestContext::getMain()->setUser( $user );
		self::$mUser = $user;
		// Make sure that the config we're using is the one we're expecting
		$this->setMwGlobals( [
			'wgUser' => $user,
			'wgAbuseFilterRestrictions' => [
				'degroup' => true
			],
			'wgAbuseFilterIsCentral' => true,
			'wgAbuseFilterActions' => [
				'throttle' => true,
				'warn' => true,
				'disallow' => true,
				'blockautopromote' => true,
				'block' => true,
				'rangeblock' => true,
				'degroup' => true,
				'tag' => true
			],
			'wgAbuseFilterValidGroups' => [
				'default',
				'flow'
			]
		] );
		$this->setGroupPermissions( [
			'filterEditor' => [
				'abusefilter-modify' => true,
				'abusefilter-modify-restricted' => false,
				'abusefilter-modify-global' => false,
			],
			'filterEditorGlobal' => [
				'abusefilter-modify' => true,
				'abusefilter-modify-global' => true,
			]
		] );
	}

	/**
	 * Gets an instance of AbuseFilterViewEdit ready for creating or editing filter
	 *
	 * @param string $filter 'new' for a new filter, its ID otherwise
	 * @return AbuseFilterViewEdit
	 */
	private static function getViewEdit( $filter ) {
		$special = new SpecialAbuseFilter();
		$context = RequestContext::getMain( self::getRequest() );
		$context->setRequest( self::getRequest() );

		$special->setContext( $context );
		$special->mFilter = $filter;
		$viewEdit = new AbuseFilterViewEdit( $special, [ $filter ] );
		// Being a static property, it's not deleted between tests
		$viewEdit::$mLoadedRow = null;

		return $viewEdit;
	}

	/**
	 * Creates a FauxRequest object
	 *
	 * @return FauxRequest
	 */
	private static function getRequest() {
		$params = [
			'wpFilterRules' => self::$mParameters['rules'],
			'wpFilterDescription' => self::$mParameters['description'],
			'wpFilterNotes' => self::$mParameters['notes'],
			'wpFilterGroup' => self::$mParameters['group'],
			'wpFilterEnabled' => self::$mParameters['enabled'],
			'wpFilterHidden' => self::$mParameters['hidden'],
			'wpFilterDeleted' => self::$mParameters['deleted'],
			'wpFilterGlobal' => self::$mParameters['global'],
			'wpFilterActionThrottle' => self::$mParameters['throttleEnabled'],
			'wpFilterThrottleCount' => self::$mParameters['throttleCount'],
			'wpFilterThrottlePeriod' => self::$mParameters['throttlePeriod'],
			'wpFilterThrottleGroups' => self::$mParameters['throttleGroups'],
			'wpFilterActionWarn' => self::$mParameters['warnEnabled'],
			'wpFilterWarnMessage' => self::$mParameters['warnMessage'],
			'wpFilterWarnMessageOther' => self::$mParameters['warnMessageOther'],
			'wpFilterActionDisallow' => self::$mParameters['disallowEnabled'],
			'wpFilterActionBlockautopromote' => self::$mParameters['blockautopromoteEnabled'],
			'wpFilterActionDegroup' => self::$mParameters['degroupEnabled'],
			'wpFilterActionBlock' => self::$mParameters['blockEnabled'],
			'wpFilterBlockTalk' => self::$mParameters['blockTalk'],
			'wpBlockAnonDuration' => self::$mParameters['blockAnons'],
			'wpBlockUserDuration' => self::$mParameters['blockUsers'],
			'wpFilterActionRangeblock' => self::$mParameters['rangeblockEnabled'],
			'wpFilterActionTag' => self::$mParameters['tagEnabled'],
			'wpFilterTags' => self::$mParameters['tagTags'],
		];

		// Checkboxes aren't included at all if they aren't selected. We can remove them
		// this way (instead of iterating a hardcoded list) since they're the only false values
		$params = array_filter( $params, function ( $el ) {
			return $el !== false;
		} );

		$request = new FauxRequest( $params, true );
		return $request;
	}

	/**
	 * Creates $amount new filters, in case we need to test updating an existing one
	 *
	 * @param int $amount How many filters to create
	 */
	private static function createNewFilters( $amount ) {
		$defaultRow = [
			'af_pattern' => '/**/',
			'af_user' => 0,
			'af_user_text' => 'FilterTester',
			'af_timestamp' => wfTimestampNow(),
			'af_enabled' => 1,
			'af_comments' => '',
			'af_public_comments' => 'Mock filter',
			'af_hidden' => 0,
			'af_hit_count' => 0,
			'af_throttled' => 0,
			'af_deleted' => 0,
			'af_actions' => '',
			'af_global' => 0,
			'af_group' => 'default'
		];

		$dbw = wfGetDB( DB_MASTER );
		for ( $i = 1; $i <= $amount; $i++ ) {
			$dbw->replace(
				'abuse_filter',
				[ 'af_id' ],
				$defaultRow,
				__METHOD__
			);
		}
	}

	/**
	 * Validate and save a filter given its parameters
	 *
	 * @param array $args Parameters of the filter and metadata for the test
	 * @covers AbuseFilter::saveFilter
	 * @dataProvider provideFilters
	 */
	public function testSaveFilter( $args ) {
		// Preliminar stuff for the test
		if ( $args['testData']['customUserGroup'] ) {
			self::$mUser->addGroup( $args['testData']['customUserGroup'] );
		}

		if ( $args['testData']['needsOtherFilters'] ) {
			self::createNewFilters( $args['testData']['needsOtherFilters'] );
		}

		$fixedParameters = [
			'id' => 'new',
			'notes' => '',
			'group' => 'default',
			'enabled' => true,
			'hidden' => false,
			'global' => false,
			'deleted' => false,
			'throttled' => 0,
			'throttleEnabled' => false,
			'throttleCount' => 0,
			'throttlePeriod' => 0,
			'throttleGroups' => '',
			'warnEnabled' => false,
			'warnMessage' => 'abusefilter-warning',
			'warnMessageOther' => '',
			'disallowEnabled' => false,
			'blockautopromoteEnabled' => false,
			'degroupEnabled' => false,
			'blockEnabled' => false,
			'blockTalk' => false,
			'blockAnons' => 'infinity',
			'blockUsers' => 'infinity',
			'rangeblockEnabled' => false,
			'tagEnabled' => false,
			'tagTags' => ''
		];

		// Extract parameters from testset and build what we need to save a filter
		// The values specified in the testset will overwrite the fixed ones.
		self::$mParameters = $args['filterParameters'] + $fixedParameters;
		$filter = self::$mParameters['id'];
		$viewEdit = self::getViewEdit( $filter );
		$request = self::getRequest();
		list( $newRow, $actions ) = $viewEdit->loadRequest( $filter );
		self::$mParameters['rowActions'] = implode( ',', array_keys( array_filter( $actions ) ) );

		// Send data for validation and saving
		$status = AbuseFilter::saveFilter( $viewEdit, $filter, $request, $newRow, $actions );

		// Must be removed for the next test
		if ( $args['testData']['customUserGroup'] ) {
			self::$mUser->removeGroup( $args['testData']['customUserGroup'] );
		}

		$shouldFail = $args['testData']['shouldFail'];
		$shouldBeSaved = $args['testData']['shouldBeSaved'];
		$furtherInfo = null;
		$expected = true;
		if ( $shouldFail ) {
			if ( $status->isGood() ) {
				$furtherInfo = 'The filter validation returned a valid status.';
				$result = false;
			} else {
				$result = $status->getErrors();
				$result = $result[0]['message'];
				$expected = $args['testData']['expectedMessage'];
			}
		} else {
			if ( $shouldBeSaved ) {
				$value = $status->getValue();
				$result = $status->isGood() && is_array( $value ) && count( $value ) === 2 &&
					is_numeric( $value[0] ) && is_numeric( $value[1] );
			} else {
				$result = $status->isGood() && $status->getValue() === false;
			}
		}

		$errorMessage = $args['testData']['doingWhat'] . '. Expected: ' .
			$args['testData']['expectedResult'] . '.';
		if ( $furtherInfo ) {
			$errorMessage .= "\nFurther info: " . $furtherInfo;
		}
		$this->assertEquals(
			$expected,
			$result,
			$errorMessage
		);
	}

	/**
	 * Data provider for creating and editing filters.
	 * @return array
	 */
	public function provideFilters() {
		return [
			[
				[
					'filterParameters' => [
						'rules' => '',
						'description' => '',
						'blockautopromoteEnabled' => true,
					],
					'testData' => [
						'doingWhat' => 'Trying to save a filter without description and rules',
						'expectedResult' => 'a "missing required fields" error message',
						'expectedMessage' => 'abusefilter-edit-missingfields',
						'shouldFail' => true,
						'shouldBeSaved' => false,
						'customUserGroup' => '',
						'needsOtherFilters' => false
					]
				]
			],
			[
				[
					'filterParameters' => [
						'rules' => '/* My rules */',
						'description' => 'Some new filter',
						'enabled' => false,
						'deleted' => true,
					],
					'testData' => [
						'doingWhat' => 'Trying to save a filter with only rules and description',
						'expectedResult' => 'the saving to be successful',
						'expectedMessage' => '',
						'shouldFail' => false,
						'shouldBeSaved' => true,
						'customUserGroup' => '',
						'needsOtherFilters' => false
					]
				]
			],
			[
				[
					'filterParameters' => [
						'rules' => 'rlike',
						'description' => 'This syntax aint good',
						'blockEnabled' => true,
						'blockTalk' => true,
						'blockAnons' => '8 hours',
					],
					'testData' => [
						'doingWhat' => 'Trying to save a filter with wrong syntax',
						'expectedResult' => 'a "wrong syntax" error message',
						'expectedMessage' => 'abusefilter-edit-badsyntax',
						'shouldFail' => true,
						'shouldBeSaved' => false,
						'customUserGroup' => '',
						'needsOtherFilters' => false
					]
				]
			],
			[
				[
					'filterParameters' => [
						'rules' => '1==1',
						'description' => 'Enabled and deleted',
						'deleted' => true,
						'blockEnabled' => true,
						'blockTalk' => true,
						'blockAnons' => '8 hours',
					],
					'testData' => [
						'doingWhat' => 'Trying to save a filter marking it both enabled and deleted',
						'expectedResult' => 'an error message',
						'expectedMessage' => 'abusefilter-edit-deleting-enabled',
						'shouldFail' => true,
						'shouldBeSaved' => false,
						'customUserGroup' => '',
						'needsOtherFilters' => false
					]
				]
			],
			[
				[
					'filterParameters' => [
						'rules' => '1==1',
						'description' => 'Reserved tag',
						'notes' => 'Some notes',
						'hidden' => true,
						'tagEnabled' => true,
						'tagTags' => 'mw-undo'
					],
					'testData' => [
						'doingWhat' => 'Trying to save a filter with a reserved tag',
						'expectedResult' => 'an error message saying that the tag cannot be used',
						'expectedMessage' => 'abusefilter-edit-bad-tags',
						'shouldFail' => true,
						'shouldBeSaved' => false,
						'customUserGroup' => '',
						'needsOtherFilters' => false
					]
				]
			],
			[
				[
					'filterParameters' => [
						'rules' => '1==1',
						'description' => 'Invalid tag',
						'notes' => 'Some notes',
						'tagEnabled' => true,
						'tagTags' => 'some|tag'
					],
					'testData' => [
						'doingWhat' => 'Trying to save a filter with an invalid tag',
						'expectedResult' => 'an error message saying that the tag cannot be used',
						'expectedMessage' => 'tags-create-invalid-chars',
						'shouldFail' => true,
						'shouldBeSaved' => false,
						'customUserGroup' => '',
						'needsOtherFilters' => false
					]
				]
			],
			[
				[
					'filterParameters' => [
						'rules' => '1==1',
						'description' => 'Global without perms',
						'global' => true,
						'disallowEnabled' => true,
					],
					'testData' => [
						'doingWhat' => 'Trying to save a global filter without enough rights',
						'expectedResult' => 'an error message saying that I do not have the required rights',
						'expectedMessage' => 'abusefilter-edit-notallowed-global',
						'shouldFail' => true,
						'shouldBeSaved' => false,
						'customUserGroup' => '',
						'needsOtherFilters' => false
					]
				]
			],
			[
				[
					'filterParameters' => [
						'rules' => '1==1',
						'description' => 'Global with invalid warn message',
						'global' => true,
						'warnEnabled' => true,
						'warnMessage' => 'abusefilter-beautiful-warning',
					],
					'testData' => [
						'doingWhat' => 'Trying to save a global filter with a custom warn message',
						'expectedResult' => 'an error message saying that custom warn messages ' .
							'cannot be used for global rules',
						'expectedMessage' => 'abusefilter-edit-notallowed-global-custom-msg',
						'shouldFail' => true,
						'shouldBeSaved' => false,
						'customUserGroup' => 'filterEditorGlobal',
						'needsOtherFilters' => false
					]
				]
			],
			[
				[
					'filterParameters' => [
						'rules' => '1==1',
						'description' => 'Restricted action',
						'degroupEnabled' => true,
					],
					'testData' => [
						'doingWhat' => 'Trying to save a filter with a restricted action',
						'expectedResult' => 'an error message saying that the action is restricted',
						'expectedMessage' => 'abusefilter-edit-restricted',
						'shouldFail' => true,
						'shouldBeSaved' => false,
						'customUserGroup' => '',
						'needsOtherFilters' => false
					]
				]
			],
			[
				[
					'filterParameters' => [
						'id' => '1',
						'rules' => '/**/',
						'description' => 'Mock filter',
					],
					'testData' => [
						'doingWhat' => 'Trying to save a filter without changing anything',
						'expectedResult' => 'the validation to pass without the filter being saved',
						'expectedMessage' => '',
						'shouldFail' => false,
						'shouldBeSaved' => false,
						'customUserGroup' => '',
						'needsOtherFilters' => 1
					]
				]
			],
			[
				[
					'filterParameters' => [
						'rules' => '1==1',
						'description' => 'Invalid throttle groups',
						'notes' => 'Throttle... Again',
						'throttleEnabled' => true,
						'throttleCount' => 11,
						'throttlePeriod' => 111,
						'throttleGroups' => 'user\nfoo'
					],
					'testData' => [
						'doingWhat' => 'Trying to save a filter with invalid throttle groups',
						'expectedResult' => 'an error message saying that throttle groups are invalid',
						'expectedMessage' => 'abusefilter-edit-invalid-throttlegroups',
						'shouldFail' => true,
						'shouldBeSaved' => false,
						'customUserGroup' => '',
						'needsOtherFilters' => false
					]
				]
			]
		];
	}

	/**
	 * Check that our tag validation is working properly. Note that we only need one test
	 *   for each called function. Consistency within ChangeTags functions should be
	 *   assured by tests in core. The test for canAddTagsAccompanyingChange and canCreateTag
	 *   are missing because they won't actually fail, never. Resolving T173917 would
	 *   greatly improve the situation and could help writing better tests.
	 *
	 * @param string $tag The tag to validate
	 * @param string|null $error The expected error message. Null if validations should pass
	 * @covers AbuseFilter::isAllowedTag
	 * @dataProvider provideTags
	 */
	public function testIsAllowedTag( $tag, $error ) {
		$status = AbuseFilter::isAllowedTag( $tag );

		if ( !$status->isGood() ) {
			$actualError = $status->getErrors();
			$actualError = $actualError[0]['message'];
		} else {
			$actualError = null;
			if ( $error !== null ) {
				$this->fail( "Tag validation returned a valid status instead of the expected '$error' error." );
			}
		}

		$this->assertSame(
			$error,
			$actualError,
			"Expected message '$error', got '$actualError' while validating the tag '$tag'."
		);
	}

	/**
	 * Data provider for testIsAllowedTag
	 * @return array
	 */
	public function provideTags() {
		return [
			[ 'a|b', 'tags-create-invalid-chars' ],
			[ 'mw-undo', 'abusefilter-edit-bad-tags' ],
			[ 'abusefilter-condition-limit', 'abusefilter-tag-reserved' ],
			[ 'my_tag', null ],
		];
	}

	/**
	 * Check that throttle parameters validation works fine
	 *
	 * @param array $params Throttle parameters
	 * @param string|null $error The expected error message. Null if validations should pass
	 * @covers AbuseFilter::checkThrottleParameters
	 * @dataProvider provideThrottleParameters
	 */
	public function testCheckThrottleParameters( $params, $error ) {
		$result = AbuseFilter::checkThrottleParameters( $params );
		$this->assertSame( $error, $result, 'Throttle parameter validation does not work as expected.' );
	}

	/**
	 * Data provider for testCheckThrottleParameters
	 * @return array
	 */
	public function provideThrottleParameters() {
		return [
			[ [ '1', '5,23', 'user', 'ip', 'page,range', 'ip,user', 'range,ip' ], null ],
			[ [ '1', '5.3,23', 'user', 'ip' ], 'abusefilter-edit-invalid-throttlecount' ],
			[ [ '1', '-3,23', 'user', 'ip' ], 'abusefilter-edit-invalid-throttlecount' ],
			[ [ '1', '5,2.3', 'user', 'ip' ], 'abusefilter-edit-invalid-throttleperiod' ],
			[ [ '1', '4,-14', 'user', 'ip' ], 'abusefilter-edit-invalid-throttleperiod' ],
			[ [ '1', '3,33' ], 'abusefilter-edit-empty-throttlegroups' ],
			[ [ '1', '3,33', 'user', 'ip,foo,user' ], 'abusefilter-edit-invalid-throttlegroups' ],
			[ [ '1', '3,33', 'foo', 'ip,user' ], 'abusefilter-edit-invalid-throttlegroups' ],
			[ [ '1', '3,33', 'foo', 'ip,user,bar' ], 'abusefilter-edit-invalid-throttlegroups' ],
			[ [ '1', '3,33', 'user', 'ip,page,user' ], null ],
			[
				[ '1', '3,33', 'ip', 'user','user,ip', 'ip,user', 'user,ip,user', 'user', 'ip,ip,user' ],
				'abusefilter-edit-duplicated-throttlegroups'
			],
			[ [ '1', '3,33', 'ip,ip,user' ], 'abusefilter-edit-duplicated-throttlegroups' ],
			[ [ '1', '3,33', 'user,ip', 'ip,user' ], 'abusefilter-edit-duplicated-throttlegroups' ],
		];
	}
}