Merge "Add string length limits"
[lhc/web/wiklou.git] / tests / phpunit / includes / BlockTest.php
1 <?php
2
3 /**
4 * @group Database
5 * @group Blocking
6 */
7 class BlockTest extends MediaWikiLangTestCase {
8
9 /**
10 * @return User
11 */
12 private function getUserForBlocking() {
13 $testUser = $this->getMutableTestUser();
14 $user = $testUser->getUser();
15 $user->addToDatabase();
16 TestUser::setPasswordForUser( $user, 'UTBlockeePassword' );
17 $user->saveSettings();
18 return $user;
19 }
20
21 /**
22 * @param User $user
23 *
24 * @return Block
25 * @throws MWException
26 */
27 private function addBlockForUser( User $user ) {
28 // Delete the last round's block if it's still there
29 $oldBlock = Block::newFromTarget( $user->getName() );
30 if ( $oldBlock ) {
31 // An old block will prevent our new one from saving.
32 $oldBlock->delete();
33 }
34
35 $blockOptions = [
36 'address' => $user->getName(),
37 'user' => $user->getId(),
38 'reason' => 'Parce que',
39 'expiry' => time() + 100500,
40 ];
41 $block = new Block( $blockOptions );
42
43 $block->insert();
44 // save up ID for use in assertion. Since ID is an autoincrement,
45 // its value might change depending on the order the tests are run.
46 // ApiBlockTest insert its own blocks!
47 if ( !$block->getId() ) {
48 throw new MWException( "Failed to insert block for BlockTest; old leftover block remaining?" );
49 }
50
51 $this->addXffBlocks();
52
53 return $block;
54 }
55
56 /**
57 * @covers Block::newFromTarget
58 */
59 public function testINewFromTargetReturnsCorrectBlock() {
60 $user = $this->getUserForBlocking();
61 $block = $this->addBlockForUser( $user );
62
63 $this->assertTrue(
64 $block->equals( Block::newFromTarget( $user->getName() ) ),
65 "newFromTarget() returns the same block as the one that was made"
66 );
67 }
68
69 /**
70 * @covers Block::newFromID
71 */
72 public function testINewFromIDReturnsCorrectBlock() {
73 $user = $this->getUserForBlocking();
74 $block = $this->addBlockForUser( $user );
75
76 $this->assertTrue(
77 $block->equals( Block::newFromID( $block->getId() ) ),
78 "newFromID() returns the same block as the one that was made"
79 );
80 }
81
82 /**
83 * per T28425
84 */
85 public function testBug26425BlockTimestampDefaultsToTime() {
86 $user = $this->getUserForBlocking();
87 $block = $this->addBlockForUser( $user );
88 $madeAt = wfTimestamp( TS_MW );
89
90 // delta to stop one-off errors when things happen to go over a second mark.
91 $delta = abs( $madeAt - $block->mTimestamp );
92 $this->assertLessThan(
93 2,
94 $delta,
95 "If no timestamp is specified, the block is recorded as time()"
96 );
97 }
98
99 /**
100 * CheckUser since being changed to use Block::newFromTarget started failing
101 * because the new function didn't accept empty strings like Block::load()
102 * had. Regression T31116.
103 *
104 * @dataProvider provideBug29116Data
105 * @covers Block::newFromTarget
106 */
107 public function testBug29116NewFromTargetWithEmptyIp( $vagueTarget ) {
108 $user = $this->getUserForBlocking();
109 $initialBlock = $this->addBlockForUser( $user );
110 $block = Block::newFromTarget( $user->getName(), $vagueTarget );
111
112 $this->assertTrue(
113 $initialBlock->equals( $block ),
114 "newFromTarget() returns the same block as the one that was made when "
115 . "given empty vagueTarget param " . var_export( $vagueTarget, true )
116 );
117 }
118
119 public static function provideBug29116Data() {
120 return [
121 [ null ],
122 [ '' ],
123 [ false ]
124 ];
125 }
126
127 /**
128 * @covers Block::prevents
129 */
130 public function testBlockedUserCanNotCreateAccount() {
131 $username = 'BlockedUserToCreateAccountWith';
132 $u = User::newFromName( $username );
133 $u->addToDatabase();
134 $userId = $u->getId();
135 $this->assertNotEquals( 0, $userId, 'sanity' );
136 TestUser::setPasswordForUser( $u, 'NotRandomPass' );
137 unset( $u );
138
139 // Sanity check
140 $this->assertNull(
141 Block::newFromTarget( $username ),
142 "$username should not be blocked"
143 );
144
145 // Reload user
146 $u = User::newFromName( $username );
147 $this->assertFalse(
148 $u->isBlockedFromCreateAccount(),
149 "Our sandbox user should be able to create account before being blocked"
150 );
151
152 // Foreign perspective (blockee not on current wiki)...
153 $blockOptions = [
154 'address' => $username,
155 'user' => $userId,
156 'reason' => 'crosswiki block...',
157 'timestamp' => wfTimestampNow(),
158 'expiry' => $this->db->getInfinity(),
159 'createAccount' => true,
160 'enableAutoblock' => true,
161 'hideName' => true,
162 'blockEmail' => true,
163 'byText' => 'MetaWikiUser',
164 ];
165 $block = new Block( $blockOptions );
166 $block->insert();
167
168 // Reload block from DB
169 $userBlock = Block::newFromTarget( $username );
170 $this->assertTrue(
171 (bool)$block->prevents( 'createaccount' ),
172 "Block object in DB should prevents 'createaccount'"
173 );
174
175 $this->assertInstanceOf(
176 'Block',
177 $userBlock,
178 "'$username' block block object should be existent"
179 );
180
181 // Reload user
182 $u = User::newFromName( $username );
183 $this->assertTrue(
184 (bool)$u->isBlockedFromCreateAccount(),
185 "Our sandbox user '$username' should NOT be able to create account"
186 );
187 }
188
189 /**
190 * @covers Block::insert
191 */
192 public function testCrappyCrossWikiBlocks() {
193 // Delete the last round's block if it's still there
194 $oldBlock = Block::newFromTarget( 'UserOnForeignWiki' );
195 if ( $oldBlock ) {
196 // An old block will prevent our new one from saving.
197 $oldBlock->delete();
198 }
199
200 // Local perspective (blockee on current wiki)...
201 $user = User::newFromName( 'UserOnForeignWiki' );
202 $user->addToDatabase();
203 $userId = $user->getId();
204 $this->assertNotEquals( 0, $userId, 'sanity' );
205
206 // Foreign perspective (blockee not on current wiki)...
207 $blockOptions = [
208 'address' => 'UserOnForeignWiki',
209 'user' => $user->getId(),
210 'reason' => 'crosswiki block...',
211 'timestamp' => wfTimestampNow(),
212 'expiry' => $this->db->getInfinity(),
213 'createAccount' => true,
214 'enableAutoblock' => true,
215 'hideName' => true,
216 'blockEmail' => true,
217 'byText' => 'MetaWikiUser',
218 ];
219 $block = new Block( $blockOptions );
220
221 $res = $block->insert( $this->db );
222 $this->assertTrue( (bool)$res['id'], 'Block succeeded' );
223
224 $user = null; // clear
225
226 $block = Block::newFromID( $res['id'] );
227 $this->assertEquals(
228 'UserOnForeignWiki',
229 $block->getTarget()->getName(),
230 'Correct blockee name'
231 );
232 $this->assertEquals( $userId, $block->getTarget()->getId(), 'Correct blockee id' );
233 $this->assertEquals( 'MetaWikiUser', $block->getBlocker(), 'Correct blocker name' );
234 $this->assertEquals( 'MetaWikiUser', $block->getByName(), 'Correct blocker name' );
235 $this->assertEquals( 0, $block->getBy(), 'Correct blocker id' );
236 }
237
238 protected function addXffBlocks() {
239 static $inited = false;
240
241 if ( $inited ) {
242 return;
243 }
244
245 $inited = true;
246
247 $blockList = [
248 [ 'target' => '70.2.0.0/16',
249 'type' => Block::TYPE_RANGE,
250 'desc' => 'Range Hardblock',
251 'ACDisable' => false,
252 'isHardblock' => true,
253 'isAutoBlocking' => false,
254 ],
255 [ 'target' => '2001:4860:4001::/48',
256 'type' => Block::TYPE_RANGE,
257 'desc' => 'Range6 Hardblock',
258 'ACDisable' => false,
259 'isHardblock' => true,
260 'isAutoBlocking' => false,
261 ],
262 [ 'target' => '60.2.0.0/16',
263 'type' => Block::TYPE_RANGE,
264 'desc' => 'Range Softblock with AC Disabled',
265 'ACDisable' => true,
266 'isHardblock' => false,
267 'isAutoBlocking' => false,
268 ],
269 [ 'target' => '50.2.0.0/16',
270 'type' => Block::TYPE_RANGE,
271 'desc' => 'Range Softblock',
272 'ACDisable' => false,
273 'isHardblock' => false,
274 'isAutoBlocking' => false,
275 ],
276 [ 'target' => '50.1.1.1',
277 'type' => Block::TYPE_IP,
278 'desc' => 'Exact Softblock',
279 'ACDisable' => false,
280 'isHardblock' => false,
281 'isAutoBlocking' => false,
282 ],
283 ];
284
285 foreach ( $blockList as $insBlock ) {
286 $target = $insBlock['target'];
287
288 if ( $insBlock['type'] === Block::TYPE_IP ) {
289 $target = User::newFromName( IP::sanitizeIP( $target ), false )->getName();
290 } elseif ( $insBlock['type'] === Block::TYPE_RANGE ) {
291 $target = IP::sanitizeRange( $target );
292 }
293
294 $block = new Block();
295 $block->setTarget( $target );
296 $block->setBlocker( 'testblocker@global' );
297 $block->mReason = $insBlock['desc'];
298 $block->mExpiry = 'infinity';
299 $block->prevents( 'createaccount', $insBlock['ACDisable'] );
300 $block->isHardblock( $insBlock['isHardblock'] );
301 $block->isAutoblocking( $insBlock['isAutoBlocking'] );
302 $block->insert();
303 }
304 }
305
306 public static function providerXff() {
307 return [
308 [ 'xff' => '1.2.3.4, 70.2.1.1, 60.2.1.1, 2.3.4.5',
309 'count' => 2,
310 'result' => 'Range Hardblock'
311 ],
312 [ 'xff' => '1.2.3.4, 50.2.1.1, 60.2.1.1, 2.3.4.5',
313 'count' => 2,
314 'result' => 'Range Softblock with AC Disabled'
315 ],
316 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.1.1.1, 2.3.4.5',
317 'count' => 2,
318 'result' => 'Exact Softblock'
319 ],
320 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.2.1.1, 50.1.1.1, 2.3.4.5',
321 'count' => 3,
322 'result' => 'Exact Softblock'
323 ],
324 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.2.1.1, 2.3.4.5',
325 'count' => 2,
326 'result' => 'Range Hardblock'
327 ],
328 [ 'xff' => '1.2.3.4, 70.2.1.1, 60.2.1.1, 2.3.4.5',
329 'count' => 2,
330 'result' => 'Range Hardblock'
331 ],
332 [ 'xff' => '50.2.1.1, 60.2.1.1, 2.3.4.5',
333 'count' => 2,
334 'result' => 'Range Softblock with AC Disabled'
335 ],
336 [ 'xff' => '1.2.3.4, 50.1.1.1, 60.2.1.1, 2.3.4.5',
337 'count' => 2,
338 'result' => 'Exact Softblock'
339 ],
340 [ 'xff' => '1.2.3.4, <$A_BUNCH-OF{INVALID}TEXT\>, 60.2.1.1, 2.3.4.5',
341 'count' => 1,
342 'result' => 'Range Softblock with AC Disabled'
343 ],
344 [ 'xff' => '1.2.3.4, 50.2.1.1, 2001:4860:4001:802::1003, 2.3.4.5',
345 'count' => 2,
346 'result' => 'Range6 Hardblock'
347 ],
348 ];
349 }
350
351 /**
352 * @dataProvider providerXff
353 * @covers Block::getBlocksForIPList
354 * @covers Block::chooseBlock
355 */
356 public function testBlocksOnXff( $xff, $exCount, $exResult ) {
357 $user = $this->getUserForBlocking();
358 $this->addBlockForUser( $user );
359
360 $list = array_map( 'trim', explode( ',', $xff ) );
361 $xffblocks = Block::getBlocksForIPList( $list, true );
362 $this->assertEquals( $exCount, count( $xffblocks ), 'Number of blocks for ' . $xff );
363 $block = Block::chooseBlock( $xffblocks, $list );
364 $this->assertEquals( $exResult, $block->mReason, 'Correct block type for XFF header ' . $xff );
365 }
366
367 public function testDeprecatedConstructor() {
368 $this->hideDeprecated( 'Block::__construct with multiple arguments' );
369 $username = 'UnthinkablySecretRandomUsername';
370 $reason = 'being irrational';
371
372 # Set up the target
373 $u = User::newFromName( $username );
374 if ( $u->getId() == 0 ) {
375 $u->addToDatabase();
376 TestUser::setPasswordForUser( $u, 'TotallyObvious' );
377 }
378 unset( $u );
379
380 # Make sure the user isn't blocked
381 $this->assertNull(
382 Block::newFromTarget( $username ),
383 "$username should not be blocked"
384 );
385
386 # Perform the block
387 $block = new Block(
388 /* address */ $username,
389 /* user */ 0,
390 /* by */ 0,
391 /* reason */ $reason,
392 /* timestamp */ 0,
393 /* auto */ false,
394 /* expiry */ 0
395 );
396 $block->insert();
397
398 # Check target
399 $this->assertEquals(
400 $block->getTarget()->getName(),
401 $username,
402 "Target should be set properly"
403 );
404
405 # Check supplied parameter
406 $this->assertEquals(
407 $block->mReason,
408 $reason,
409 "Reason should be non-default"
410 );
411
412 # Check default parameter
413 $this->assertFalse(
414 (bool)$block->prevents( 'createaccount' ),
415 "Account creation should not be blocked by default"
416 );
417 }
418
419 public function testSystemBlocks() {
420 $user = $this->getUserForBlocking();
421 $this->addBlockForUser( $user );
422
423 $blockOptions = [
424 'address' => $user->getName(),
425 'reason' => 'test system block',
426 'timestamp' => wfTimestampNow(),
427 'expiry' => $this->db->getInfinity(),
428 'byText' => 'MetaWikiUser',
429 'systemBlock' => 'test',
430 'enableAutoblock' => true,
431 ];
432 $block = new Block( $blockOptions );
433
434 $this->assertSame( 'test', $block->getSystemBlockType() );
435
436 try {
437 $block->insert();
438 $this->fail( 'Expected exception not thrown' );
439 } catch ( MWException $ex ) {
440 $this->assertSame( 'Cannot insert a system block into the database', $ex->getMessage() );
441 }
442
443 try {
444 $block->doAutoblock( '192.0.2.2' );
445 $this->fail( 'Expected exception not thrown' );
446 } catch ( MWException $ex ) {
447 $this->assertSame( 'Cannot autoblock from a system block', $ex->getMessage() );
448 }
449 }
450
451 }