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