MediaWiki  1.27.2
ThrottlerTest.php
Go to the documentation of this file.
1 <?php
2 
3 namespace MediaWiki\Auth;
4 
11 
17  public function testConstructor() {
18  $cache = new \HashBagOStuff();
19  $logger = $this->getMockBuilder( AbstractLogger::class )
20  ->setMethods( [ 'log' ] )
21  ->getMockForAbstractClass();
22 
23  $throttler = new Throttler(
24  [ [ 'count' => 123, 'seconds' => 456 ] ],
25  [ 'type' => 'foo', 'cache' => $cache ]
26  );
27  $throttler->setLogger( $logger );
28  $throttlerPriv = \TestingAccessWrapper::newFromObject( $throttler );
29  $this->assertSame( [ [ 'count' => 123, 'seconds' => 456 ] ], $throttlerPriv->conditions );
30  $this->assertSame( 'foo', $throttlerPriv->type );
31  $this->assertSame( $cache, $throttlerPriv->cache );
32  $this->assertSame( $logger, $throttlerPriv->logger );
33 
34  $throttler = new Throttler( [ [ 'count' => 123, 'seconds' => 456 ] ] );
35  $throttler->setLogger( new NullLogger() );
36  $throttlerPriv = \TestingAccessWrapper::newFromObject( $throttler );
37  $this->assertSame( [ [ 'count' => 123, 'seconds' => 456 ] ], $throttlerPriv->conditions );
38  $this->assertSame( 'custom', $throttlerPriv->type );
39  $this->assertInstanceOf( BagOStuff::class, $throttlerPriv->cache );
40  $this->assertInstanceOf( LoggerInterface::class, $throttlerPriv->logger );
41 
42  $this->setMwGlobals( [ 'wgPasswordAttemptThrottle' => [ [ 'count' => 321,
43  'seconds' => 654 ] ] ] );
44  $throttler = new Throttler();
45  $throttler->setLogger( new NullLogger() );
46  $throttlerPriv = \TestingAccessWrapper::newFromObject( $throttler );
47  $this->assertSame( [ [ 'count' => 321, 'seconds' => 654 ] ], $throttlerPriv->conditions );
48  $this->assertSame( 'password', $throttlerPriv->type );
49  $this->assertInstanceOf( BagOStuff::class, $throttlerPriv->cache );
50  $this->assertInstanceOf( LoggerInterface::class, $throttlerPriv->logger );
51 
52  try {
53  new Throttler( [], [ 'foo' => 1, 'bar' => 2, 'baz' => 3 ] );
54  $this->fail( 'Expected exception not thrown' );
55  } catch ( \InvalidArgumentException $ex ) {
56  $this->assertSame( 'unrecognized parameters: foo, bar, baz', $ex->getMessage() );
57  }
58  }
59 
63  public function testNormalizeThrottleConditions( $condition, $normalized ) {
64  $throttler = new Throttler( $condition );
65  $throttler->setLogger( new NullLogger() );
66  $throttlerPriv = \TestingAccessWrapper::newFromObject( $throttler );
67  $this->assertSame( $normalized, $throttlerPriv->conditions );
68  }
69 
71  return [
72  [
73  [],
74  [],
75  ],
76  [
77  [ 'count' => 1, 'seconds' => 2 ],
78  [ [ 'count' => 1, 'seconds' => 2 ] ],
79  ],
80  [
81  [ [ 'count' => 1, 'seconds' => 2 ], [ 'count' => 2, 'seconds' => 3 ] ],
82  [ [ 'count' => 1, 'seconds' => 2 ], [ 'count' => 2, 'seconds' => 3 ] ],
83  ],
84  ];
85  }
86 
89  $this->assertSame( [], $priv->normalizeThrottleConditions( null ) );
90  $this->assertSame( [], $priv->normalizeThrottleConditions( 'bad' ) );
91  }
92 
93  public function testIncrease() {
94  $cache = new \HashBagOStuff();
95  $throttler = new Throttler( [
96  [ 'count' => 2, 'seconds' => 10, ],
97  [ 'count' => 4, 'seconds' => 15, 'allIPs' => true ],
98  ], [ 'cache' => $cache ] );
99  $throttler->setLogger( new NullLogger() );
100 
101  $result = $throttler->increase( 'SomeUser', '1.2.3.4' );
102  $this->assertFalse( $result, 'should not throttle' );
103 
104  $result = $throttler->increase( 'SomeUser', '1.2.3.4' );
105  $this->assertFalse( $result, 'should not throttle' );
106 
107  $result = $throttler->increase( 'SomeUser', '1.2.3.4' );
108  $this->assertSame( [ 'throttleIndex' => 0, 'count' => 2, 'wait' => 10 ], $result );
109 
110  $result = $throttler->increase( 'OtherUser', '1.2.3.4' );
111  $this->assertFalse( $result, 'should not throttle' );
112 
113  $result = $throttler->increase( 'SomeUser', '2.3.4.5' );
114  $this->assertFalse( $result, 'should not throttle' );
115 
116  $result = $throttler->increase( 'SomeUser', '3.4.5.6' );
117  $this->assertFalse( $result, 'should not throttle' );
118 
119  $result = $throttler->increase( 'SomeUser', '3.4.5.6' );
120  $this->assertSame( [ 'throttleIndex' => 1, 'count' => 4, 'wait' => 15 ], $result );
121  }
122 
123  public function testZeroCount() {
124  $cache = new \HashBagOStuff();
125  $throttler = new Throttler( [ [ 'count' => 0, 'seconds' => 10 ] ], [ 'cache' => $cache ] );
126  $throttler->setLogger( new NullLogger() );
127 
128  $result = $throttler->increase( 'SomeUser', '1.2.3.4' );
129  $this->assertFalse( $result, 'should not throttle, count=0 is ignored' );
130 
131  $result = $throttler->increase( 'SomeUser', '1.2.3.4' );
132  $this->assertFalse( $result, 'should not throttle, count=0 is ignored' );
133 
134  $result = $throttler->increase( 'SomeUser', '1.2.3.4' );
135  $this->assertFalse( $result, 'should not throttle, count=0 is ignored' );
136  }
137 
138  public function testNamespacing() {
139  $cache = new \HashBagOStuff();
140  $throttler1 = new Throttler( [ [ 'count' => 1, 'seconds' => 10 ] ],
141  [ 'cache' => $cache, 'type' => 'foo' ] );
142  $throttler2 = new Throttler( [ [ 'count' => 1, 'seconds' => 10 ] ],
143  [ 'cache' => $cache, 'type' => 'foo' ] );
144  $throttler3 = new Throttler( [ [ 'count' => 1, 'seconds' => 10 ] ],
145  [ 'cache' => $cache, 'type' => 'bar' ] );
146  $throttler1->setLogger( new NullLogger() );
147  $throttler2->setLogger( new NullLogger() );
148  $throttler3->setLogger( new NullLogger() );
149 
150  $throttled = [ 'throttleIndex' => 0, 'count' => 1, 'wait' => 10 ];
151 
152  $result = $throttler1->increase( 'SomeUser', '1.2.3.4' );
153  $this->assertFalse( $result, 'should not throttle' );
154 
155  $result = $throttler1->increase( 'SomeUser', '1.2.3.4' );
156  $this->assertEquals( $throttled, $result, 'should throttle' );
157 
158  $result = $throttler2->increase( 'SomeUser', '1.2.3.4' );
159  $this->assertEquals( $throttled, $result, 'should throttle, same namespace' );
160 
161  $result = $throttler3->increase( 'SomeUser', '1.2.3.4' );
162  $this->assertFalse( $result, 'should not throttle, different namespace' );
163  }
164 
165  public function testExpiration() {
166  $cache = $this->getMock( HashBagOStuff::class, [ 'add' ] );
167  $throttler = new Throttler( [ [ 'count' => 3, 'seconds' => 10 ] ], [ 'cache' => $cache ] );
168  $throttler->setLogger( new NullLogger() );
169 
170  $cache->expects( $this->once() )->method( 'add' )->with( $this->anything(), 1, 10 );
171  $throttler->increase( 'SomeUser' );
172  }
173 
177  public function testException() {
178  $throttler = new Throttler( [ [ 'count' => 3, 'seconds' => 10 ] ] );
179  $throttler->setLogger( new NullLogger() );
180  $throttler->increase();
181  }
182 
183  public function testLog() {
184  $cache = new \HashBagOStuff();
185  $throttler = new Throttler( [ [ 'count' => 1, 'seconds' => 10 ] ], [ 'cache' => $cache ] );
186 
187  $logger = $this->getMockBuilder( AbstractLogger::class )
188  ->setMethods( [ 'log' ] )
189  ->getMockForAbstractClass();
190  $logger->expects( $this->never() )->method( 'log' );
191  $throttler->setLogger( $logger );
192  $result = $throttler->increase( 'SomeUser', '1.2.3.4' );
193  $this->assertFalse( $result, 'should not throttle' );
194 
195  $logger = $this->getMockBuilder( AbstractLogger::class )
196  ->setMethods( [ 'log' ] )
197  ->getMockForAbstractClass();
198  $logger->expects( $this->once() )->method( 'log' )->with( $this->anything(), $this->anything(), [
199  'type' => 'custom',
200  'index' => 0,
201  'ip' => '1.2.3.4',
202  'username' => 'SomeUser',
203  'count' => 1,
204  'expiry' => 10,
205  'method' => 'foo',
206  ] );
207  $throttler->setLogger( $logger );
208  $result = $throttler->increase( 'SomeUser', '1.2.3.4', 'foo' );
209  $this->assertSame( [ 'throttleIndex' => 0, 'count' => 1, 'wait' => 10 ], $result );
210  }
211 
212  public function testClear() {
213  $cache = new \HashBagOStuff();
214  $throttler = new Throttler( [ [ 'count' => 1, 'seconds' => 10 ] ], [ 'cache' => $cache ] );
215  $throttler->setLogger( new NullLogger() );
216 
217  $result = $throttler->increase( 'SomeUser', '1.2.3.4' );
218  $this->assertFalse( $result, 'should not throttle' );
219 
220  $result = $throttler->increase( 'SomeUser', '1.2.3.4' );
221  $this->assertSame( [ 'throttleIndex' => 0, 'count' => 1, 'wait' => 10 ], $result );
222 
223  $result = $throttler->increase( 'OtherUser', '1.2.3.4' );
224  $this->assertFalse( $result, 'should not throttle' );
225 
226  $result = $throttler->increase( 'OtherUser', '1.2.3.4' );
227  $this->assertSame( [ 'throttleIndex' => 0, 'count' => 1, 'wait' => 10 ], $result );
228 
229  $throttler->clear( 'SomeUser', '1.2.3.4' );
230 
231  $result = $throttler->increase( 'SomeUser', '1.2.3.4' );
232  $this->assertFalse( $result, 'should not throttle' );
233 
234  $result = $throttler->increase( 'OtherUser', '1.2.3.4' );
235  $this->assertSame( [ 'throttleIndex' => 0, 'count' => 1, 'wait' => 10 ], $result );
236  }
237 }
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static newFromClass($className)
Allow access to non-public static methods and properties of the class.
AuthManager MediaWiki\Auth\Throttler.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access MediaWiki s design is based around catering to the lowest common denominator Although we support higher end setups as the way many things work by default is tailored toward shared hosting These defaults are unconventional from the point of view of and they certainly aren t ideal for someone who s installing MediaWiki as MediaWiki does not conform to normal Unix filesystem layout Hopefully we ll offer direct support for standard layouts in the but for now *any change to the location of files is unsupported *Moving things and leaving symlinks will *probably *not break anything
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1796
testNormalizeThrottleConditions($condition, $normalized)
provideNormalizeThrottleConditions
$cache
Definition: mcc.php:33
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
static newFromObject($object)
Return the same object, without access restrictions.
setMwGlobals($pairs, $value=null)
testException()
\InvalidArgumentException