summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/ConfirmEdit/tests/CaptchaPreAuthenticationProviderTest.php
blob: 9606bb56d980fabc4424f7f5a24ed0988ff39b52 (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
<?php

use MediaWiki\Auth\AuthManager;
use MediaWiki\Auth\UsernameAuthenticationRequest;

/**
 * @group Database
 */
class CaptchaPreAuthenticationProviderTest extends MediaWikiTestCase {
	public function setUp() {
		global $wgDisableAuthManager;
		if ( !class_exists( AuthManager::class ) || $wgDisableAuthManager ) {
			$this->markTestSkipped( 'AuthManager is disabled' );
		}

		parent::setUp();
		$this->setMwGlobals( [
			'wgCaptchaClass' => SimpleCaptcha::class,
			'wgCaptchaBadLoginAttempts' => 1,
			'wgCaptchaBadLoginPerUserAttempts' => 1,
			'wgCaptchaStorageClass' => CaptchaHashStore::class,
			'wgMainCacheType' => __METHOD__,
		] );
		CaptchaStore::get()->clearAll();
		ObjectCache::$instances[__METHOD__] = new HashBagOStuff();
	}

	public function tearDown() {
		parent::tearDown();
		// make sure $wgCaptcha resets between tests
		TestingAccessWrapper::newFromClass( 'ConfirmEditHooks' )->instanceCreated = false;
	}

	/**
	 * @dataProvider provideGetAuthenticationRequests
	 */
	public function testGetAuthenticationRequests(
		$action, $username, $triggers, $needsCaptcha, $preTestCallback = null
	) {
		$this->setTriggers( $triggers );
		if ( $preTestCallback ) {
			$fn = array_shift( $preTestCallback );
			call_user_func_array( [ $this, $fn ], $preTestCallback );
		}

		/** @var FauxRequest $request */
		$request = RequestContext::getMain()->getRequest();
		$request->setCookie( 'UserName', $username );

		$provider = new CaptchaPreAuthenticationProvider();
		$provider->setManager( AuthManager::singleton() );
		$reqs = $provider->getAuthenticationRequests( $action, [ 'username' => $username ] );
		if ( $needsCaptcha ) {
			$this->assertCount( 1, $reqs );
			$this->assertInstanceOf( CaptchaAuthenticationRequest::class, $reqs[0] );
		} else {
			$this->assertEmpty( $reqs );
		}
	}

	public function provideGetAuthenticationRequests() {
		return [
			[ AuthManager::ACTION_LOGIN, null, [], false ],
			[ AuthManager::ACTION_LOGIN, null, [ 'badlogin' ], false ],
			[ AuthManager::ACTION_LOGIN, null, [ 'badlogin' ], true, [ 'blockLogin', 'Foo' ] ],
			[ AuthManager::ACTION_LOGIN, null, [ 'badloginperuser' ], false, [ 'blockLogin', 'Foo' ] ],
			[ AuthManager::ACTION_LOGIN, 'Foo', [ 'badloginperuser' ], false, [ 'blockLogin', 'Bar' ] ],
			[ AuthManager::ACTION_LOGIN, 'Foo', [ 'badloginperuser' ], true, [ 'blockLogin', 'Foo' ] ],
			[ AuthManager::ACTION_LOGIN, null, [ 'badloginperuser' ], true, [ 'flagSession' ] ],
			[ AuthManager::ACTION_CREATE, null, [], false ],
			[ AuthManager::ACTION_CREATE, null, [ 'createaccount' ], true ],
			[ AuthManager::ACTION_CREATE, 'UTSysop', [ 'createaccount' ], false ],
			[ AuthManager::ACTION_LINK, null, [], false ],
			[ AuthManager::ACTION_CHANGE, null, [], false ],
			[ AuthManager::ACTION_REMOVE, null, [], false ],
		];
	}

	public function testGetAuthenticationRequests_store() {
		$this->setTriggers( [ 'createaccount' ] );
		$captcha = new SimpleCaptcha();
		$provider = new CaptchaPreAuthenticationProvider();
		$provider->setManager( AuthManager::singleton() );

		$reqs = $provider->getAuthenticationRequests( AuthManager::ACTION_CREATE,
			[ 'username' => 'Foo' ] );

		$this->assertCount( 1, $reqs );
		$this->assertInstanceOf( CaptchaAuthenticationRequest::class, $reqs[0] );

		$id = $reqs[0]->captchaId;
		$data = TestingAccessWrapper::newFromObject( $reqs[0] )->captchaData;
		$this->assertEquals( $captcha->retrieveCaptcha( $id ), $data + [ 'index' => $id ] );
	}

	/**
	 * @dataProvider provideTestForAuthentication
	 */
	public function testTestForAuthentication( $req, $isBadLoginTriggered,
		$isBadLoginPerUserTriggered, $result
	) {
		$this->setMwHook( 'PingLimiter', function ( $user, $action, &$result ) {
			$result = false;
			return false;
		} );
		CaptchaStore::get()->store( '345', [ 'question' => '2+2', 'answer' => '4' ] );
		$captcha = $this->getMock( SimpleCaptcha::class,
			[ 'isBadLoginTriggered', 'isBadLoginPerUserTriggered' ] );
		$captcha->expects( $this->any() )->method( 'isBadLoginTriggered' )
			->willReturn( $isBadLoginTriggered );
		$captcha->expects( $this->any() )->method( 'isBadLoginPerUserTriggered' )
			->willReturn( $isBadLoginPerUserTriggered );
		$this->setMwGlobals( 'wgCaptcha', $captcha );
		TestingAccessWrapper::newFromClass( 'ConfirmEditHooks' )->instanceCreated = true;
		$provider = new CaptchaPreAuthenticationProvider();
		$provider->setManager( AuthManager::singleton() );

		$status = $provider->testForAuthentication( $req ? [ $req ] : [] );
		$this->assertEquals( $result, $status->isGood() );
	}

	public function provideTestForAuthentication() {
		$fallback = new UsernameAuthenticationRequest();
		$fallback->username = 'Foo';
		return [
			// [ auth request, bad login?, bad login per user?, result ]
			'no need to check' => [ $fallback, false, false, true ],
			'badlogin' => [ $fallback, true, false, false ],
			'badloginperuser, no username' => [ null, false, true, true ],
			'badloginperuser' => [ $fallback, false, true, false ],
			'non-existent captcha' => [ $this->getCaptchaRequest( '123', '4' ), true, true, false ],
			'wrong captcha' => [ $this->getCaptchaRequest( '345', '6' ), true, true, false ],
			'correct captcha' => [ $this->getCaptchaRequest( '345', '4' ), true, true, true ],
		];
	}

	/**
	 * @dataProvider provideTestForAccountCreation
	 */
	public function testTestForAccountCreation( $req, $creator, $result, $disableTrigger = false ) {
		$this->setMwHook( 'PingLimiter', function ( &$user, $action, &$result ) {
			$result = false;
			return false;
		} );
		$this->setTriggers( $disableTrigger ? [] : [ 'createaccount' ] );
		CaptchaStore::get()->store( '345', [ 'question' => '2+2', 'answer' => '4' ] );
		$user = User::newFromName( 'Foo' );
		$provider = new CaptchaPreAuthenticationProvider();
		$provider->setManager( AuthManager::singleton() );

		$status = $provider->testForAccountCreation( $user, $creator, $req ? [ $req ] : [] );
		$this->assertEquals( $result, $status->isGood() );
	}

	public function provideTestForAccountCreation() {
		$user = User::newFromName( 'Bar' );
		$sysop = User::newFromName( 'UTSysop' );
		return [
			// [ auth request, creator, result, disable trigger? ]
			'no captcha' => [ null, $user, false ],
			'non-existent captcha' => [ $this->getCaptchaRequest( '123', '4' ), $user, false ],
			'wrong captcha' => [ $this->getCaptchaRequest( '345', '6' ), $user, false ],
			'correct captcha' => [ $this->getCaptchaRequest( '345', '4' ), $user, true ],
			'user is exempt' => [ null, $sysop, true ],
			'disabled' => [ null, $user, true, 'disable' ],
		];
	}

	public function testPostAuthentication() {
		$this->setTriggers( [ 'badlogin', 'badloginperuser' ] );
		$captcha = new SimpleCaptcha();
		$user = User::newFromName( 'Foo' );
		$anotherUser = User::newFromName( 'Bar' );
		$provider = new CaptchaPreAuthenticationProvider();
		$provider->setManager( AuthManager::singleton() );

		$this->assertFalse( $captcha->isBadLoginTriggered() );
		$this->assertFalse( $captcha->isBadLoginPerUserTriggered( $user ) );

		$provider->postAuthentication( $user, \MediaWiki\Auth\AuthenticationResponse::newFail(
			wfMessage( '?' ) ) );

		$this->assertTrue( $captcha->isBadLoginTriggered() );
		$this->assertTrue( $captcha->isBadLoginPerUserTriggered( $user ) );
		$this->assertFalse( $captcha->isBadLoginPerUserTriggered( $anotherUser ) );

		$provider->postAuthentication( $user, \MediaWiki\Auth\AuthenticationResponse::newPass( 'Foo' ) );

		$this->assertFalse( $captcha->isBadLoginPerUserTriggered( $user ) );
	}

	public function testPostAuthentication_disabled() {
		$this->setTriggers( [] );
		$captcha = new SimpleCaptcha();
		$user = User::newFromName( 'Foo' );
		$provider = new CaptchaPreAuthenticationProvider();
		$provider->setManager( AuthManager::singleton() );

		$this->assertFalse( $captcha->isBadLoginTriggered() );
		$this->assertFalse( $captcha->isBadLoginPerUserTriggered( $user ) );

		$provider->postAuthentication( $user, \MediaWiki\Auth\AuthenticationResponse::newFail(
			wfMessage( '?' ) ) );

		$this->assertFalse( $captcha->isBadLoginTriggered() );
		$this->assertFalse( $captcha->isBadLoginPerUserTriggered( $user ) );
	}

	/**
	 * @dataProvider providePingLimiter
	 */
	public function testPingLimiter( array $attempts ) {
		$this->mergeMwGlobalArrayValue( 'wgRateLimits', [ 'badcaptcha' => 1 ] );
		$provider = new CaptchaPreAuthenticationProvider();
		$provider->setManager( AuthManager::singleton() );
		$providerAccess = TestingAccessWrapper::newFromObject( $provider );

		foreach ( $attempts as $attempt ) {
			if ( !empty( $attempts[3] ) ) {
				$this->setMwHook( 'PingLimiter', function ( &$user, $action, &$result ) {
					$result = false;
					return false;
				} );
			} else {
				$this->setMwHook( 'PingLimiter', function () {
				} );
			}

			$captcha = new SimpleCaptcha();
			CaptchaStore::get()->store( '345', [ 'question' => '7+7', 'answer' => '14' ] );
			$success = $providerAccess->verifyCaptcha( $captcha, [ $attempts[0] ], $attempts[1] );
			$this->assertEquals( $attempts[2], $success );
		}
	}

	public function providePingLimiter() {
		$sysop = User::newFromName( 'UTSysop' );
		return [
			// sequence of [ auth request, user, result, disable ping limiter? ]
			'no failure' => [
				[ $this->getCaptchaRequest( '345', '14' ), new User(), true ],
				[ $this->getCaptchaRequest( '345', '14' ), new User(), true ],
			],
			'limited' => [
				[ $this->getCaptchaRequest( '345', '33' ), new User(), false ],
				[ $this->getCaptchaRequest( '345', '14' ), new User(), false ],
			],
			'exempt user' => [
				[ $this->getCaptchaRequest( '345', '33' ), $sysop, false ],
				[ $this->getCaptchaRequest( '345', '14' ), $sysop, true ],
			],
			'pinglimiter disabled' => [
				[ $this->getCaptchaRequest( '345', '33' ), new User(), false, 'disable' ],
				[ $this->getCaptchaRequest( '345', '14' ), new User(), true, 'disable' ],
			],
		];
	}

	protected function getCaptchaRequest( $id, $word, $username = null ) {
		$req = new CaptchaAuthenticationRequest( $id, [ 'question' => '?', 'answer' => $word ] );
		$req->captchaWord = $word;
		$req->username = $username;
		return $req;
	}

	protected function blockLogin( $username ) {
		$captcha = new SimpleCaptcha();
		$captcha->increaseBadLoginCounter( $username );
	}

	protected function flagSession() {
		RequestContext::getMain()->getRequest()->getSession()
			->set( 'ConfirmEdit:loginCaptchaPerUserTriggered', true );
	}

	protected function setTriggers( $triggers ) {
		$types = [ 'edit', 'create', 'sendemail', 'addurl', 'createaccount', 'badlogin',
			'badloginperuser' ];
		$captchaTriggers = array_combine( $types, array_map( function ( $type ) use ( $triggers ) {
			return in_array( $type, $triggers, true );
		}, $types ) );
		$this->setMwGlobals( 'wgCaptchaTriggers', $captchaTriggers );
	}

	/**
	 * Set a $wgHooks handler for a given hook and remove all other handlers (though not ones
	 * set via Hooks::register). The original state will be restored after the test.
	 * @param string $hook Hook name
	 * @param callable $callback Hook method
	 */
	protected function setMwHook( $hook, callable $callback ) {
		$this->mergeMwGlobalArrayValue( 'wgHooks', [ $hook => $callback ] );
	}
}