Debian Codegraph @

extensions/AbuseFilter/includes/View/AbuseFilterViewExamine.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\AbuseFilter\View;
4
5 use LogicException;
6 use MediaWiki\Context\IContextSource;
7 use MediaWiki\Extension\AbuseFilter\AbuseFilterChangesList;
8 use MediaWiki\Extension\AbuseFilter\AbuseFilterPermissionManager;
9 use MediaWiki\Extension\AbuseFilter\AbuseLoggerFactory;
10 use MediaWiki\Extension\AbuseFilter\CentralDBNotAvailableException;
11 use MediaWiki\Extension\AbuseFilter\EditBox\EditBoxBuilderFactory;
12 use MediaWiki\Extension\AbuseFilter\Filter\Flags;
13 use MediaWiki\Extension\AbuseFilter\FilterLookup;
14 use MediaWiki\Extension\AbuseFilter\FilterUtils;
15 use MediaWiki\Extension\AbuseFilter\Pager\AbuseFilterExaminePager;
16 use MediaWiki\Extension\AbuseFilter\Special\SpecialAbuseLog;
17 use MediaWiki\Extension\AbuseFilter\VariableGenerator\VariableGeneratorFactory;
18 use MediaWiki\Extension\AbuseFilter\Variables\VariableHolder;
19 use MediaWiki\Extension\AbuseFilter\Variables\VariablesBlobStore;
20 use MediaWiki\Extension\AbuseFilter\Variables\VariablesFormatter;
21 use MediaWiki\Extension\AbuseFilter\Variables\VariablesManager;
22 use MediaWiki\Html\Html;
23 use MediaWiki\HTMLForm\HTMLForm;
24 use MediaWiki\Linker\LinkRenderer;
25 use MediaWiki\Title\Title;
26 use OOUI;
27 use RecentChange;
28 use Wikimedia\Rdbms\LBFactory;
29
30 class AbuseFilterViewExamine extends AbuseFilterView {
31 /**
32 * @var string The rules of the filter we're examining
33 */
34 private $testFilter;
35 /**
36 * @var LBFactory
37 */
38 private $lbFactory;
39 /**
40 * @var FilterLookup
41 */
42 private $filterLookup;
43 /**
44 * @var EditBoxBuilderFactory
45 */
46 private $boxBuilderFactory;
47 /**
48 * @var VariablesBlobStore
49 */
50 private $varBlobStore;
51 /**
52 * @var VariablesFormatter
53 */
54 private $variablesFormatter;
55 /**
56 * @var VariablesManager
57 */
58 private $varManager;
59 /**
60 * @var VariableGeneratorFactory
61 */
62 private $varGeneratorFactory;
63
64 private AbuseLoggerFactory $abuseLoggerFactory;
65
66 /**
67 * @param LBFactory $lbFactory
68 * @param AbuseFilterPermissionManager $afPermManager
69 * @param FilterLookup $filterLookup
70 * @param EditBoxBuilderFactory $boxBuilderFactory
71 * @param VariablesBlobStore $varBlobStore
72 * @param VariablesFormatter $variablesFormatter
73 * @param VariablesManager $varManager
74 * @param VariableGeneratorFactory $varGeneratorFactory
75 * @param AbuseLoggerFactory $abuseLoggerFactory
76 * @param IContextSource $context
77 * @param LinkRenderer $linkRenderer
78 * @param string $basePageName
79 * @param array $params
80 */
81 public function __construct(
82 LBFactory $lbFactory,
83 AbuseFilterPermissionManager $afPermManager,
84 FilterLookup $filterLookup,
85 EditBoxBuilderFactory $boxBuilderFactory,
86 VariablesBlobStore $varBlobStore,
87 VariablesFormatter $variablesFormatter,
88 VariablesManager $varManager,
89 VariableGeneratorFactory $varGeneratorFactory,
90 AbuseLoggerFactory $abuseLoggerFactory,
91 IContextSource $context,
92 LinkRenderer $linkRenderer,
93 string $basePageName,
94 array $params
95 ) {
96 parent::__construct( $afPermManager, $context, $linkRenderer, $basePageName, $params );
97 $this->lbFactory = $lbFactory;
98 $this->filterLookup = $filterLookup;
99 $this->boxBuilderFactory = $boxBuilderFactory;
100 $this->varBlobStore = $varBlobStore;
101 $this->variablesFormatter = $variablesFormatter;
102 $this->variablesFormatter->setMessageLocalizer( $context );
103 $this->varManager = $varManager;
104 $this->varGeneratorFactory = $varGeneratorFactory;
105 $this->abuseLoggerFactory = $abuseLoggerFactory;
106 }
107
108 /**
109 * Shows the page
110 */
111 public function show() {
112 $out = $this->getOutput();
113 $out->setPageTitleMsg( $this->msg( 'abusefilter-examine' ) );
114 $out->addHelpLink( 'Extension:AbuseFilter/Rules format' );
115 if ( $this->afPermManager->canUseTestTools( $this->getAuthority() ) ) {
116 $out->addWikiMsg( 'abusefilter-examine-intro' );
117 } else {
118 $out->addWikiMsg( 'abusefilter-examine-intro-examine-only' );
119 }
120
121 $this->testFilter = $this->getRequest()->getText( 'testfilter' );
122
123 // Check if we've got a subpage
124 if ( count( $this->mParams ) > 1 && is_numeric( $this->mParams[1] ) ) {
125 $this->showExaminerForRC( $this->mParams[1] );
126 } elseif ( count( $this->mParams ) > 2
127 && $this->mParams[1] === 'log'
128 && is_numeric( $this->mParams[2] )
129 ) {
130 $this->showExaminerForLogEntry( $this->mParams[2] );
131 } else {
132 $this->showSearch();
133 }
134 }
135
136 /**
137 * Shows the search form
138 */
139 public function showSearch() {
140 $RCMaxAge = $this->getConfig()->get( 'RCMaxAge' );
141 $min = wfTimestamp( TS_ISO_8601, time() - $RCMaxAge );
142 $max = wfTimestampNow();
143 $formDescriptor = [
144 'SearchUser' => [
145 'label-message' => 'abusefilter-test-user',
146 'type' => 'user',
147 'ipallowed' => true,
148 ],
149 'SearchPeriodStart' => [
150 'label-message' => 'abusefilter-test-period-start',
151 'type' => 'datetime',
152 'min' => $min,
153 'max' => $max,
154 ],
155 'SearchPeriodEnd' => [
156 'label-message' => 'abusefilter-test-period-end',
157 'type' => 'datetime',
158 'min' => $min,
159 'max' => $max,
160 ],
161 ];
162 HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() )
163 ->addHiddenField( 'testfilter', $this->testFilter )
164 ->setWrapperLegendMsg( 'abusefilter-examine-legend' )
165 ->setSubmitTextMsg( 'abusefilter-examine-submit' )
166 ->setSubmitCallback( [ $this, 'showResults' ] )
167 ->showAlways();
168 }
169
170 /**
171 * Show search results, called as submit callback by HTMLForm
172 * @param array $formData
173 * @param HTMLForm $form
174 * @return bool
175 */
176 public function showResults( array $formData, HTMLForm $form ): bool {
177 $changesList = new AbuseFilterChangesList( $this->getContext(), $this->testFilter );
178
179 $dbr = $this->lbFactory->getReplicaDatabase();
180 $conds = $this->buildVisibilityConditions( $dbr, $this->getAuthority() );
181 $conds[] = $this->buildTestConditions( $dbr );
182
183 // Normalise username
184 $userTitle = Title::newFromText( $formData['SearchUser'], NS_USER );
185 $userName = $userTitle ? $userTitle->getText() : '';
186
187 if ( $userName !== '' ) {
188 $rcQuery = RecentChange::getQueryInfo();
189 $conds[$rcQuery['fields']['rc_user_text']] = $userName;
190 }
191
192 $startTS = strtotime( $formData['SearchPeriodStart'] );
193 if ( $startTS ) {
194 $conds[] = $dbr->expr( 'rc_timestamp', '>=', $dbr->timestamp( $startTS ) );
195 }
196 $endTS = strtotime( $formData['SearchPeriodEnd'] );
197 if ( $endTS ) {
198 $conds[] = $dbr->expr( 'rc_timestamp', '<=', $dbr->timestamp( $endTS ) );
199 }
200 $pager = new AbuseFilterExaminePager(
201 $changesList,
202 $this->linkRenderer,
203 $dbr,
204 $this->getTitle( 'examine' ),
205 $conds
206 );
207
208 $output = $changesList->beginRecentChangesList()
209 . $pager->getNavigationBar()
210 . $pager->getBody()
211 . $pager->getNavigationBar()
212 . $changesList->endRecentChangesList();
213
214 $form->addPostHtml( $output );
215 return true;
216 }
217
218 /**
219 * @param int $rcid
220 */
221 public function showExaminerForRC( $rcid ) {
222 // Get data
223 $rc = RecentChange::newFromId( $rcid );
224 $out = $this->getOutput();
225 if ( !$rc ) {
226 $out->addWikiMsg( 'abusefilter-examine-notfound' );
227 return;
228 }
229
230 if ( !$this->afPermManager::hasRCEntryAccess( $rc, $this->getAuthority() ) ) {
231 $out->addWikiMsg( 'abusefilter-log-details-hidden-implicit' );
232 return;
233 }
234
235 $varGenerator = $this->varGeneratorFactory->newRCGenerator( $rc, $this->getUser() );
236 $vars = $varGenerator->getVars() ?: new VariableHolder();
237 $out->addJsConfigVars( [
238 'wgAbuseFilterVariables' => $this->varManager->dumpAllVars( $vars, true ),
239 'abuseFilterExamine' => [ 'type' => 'rc', 'id' => $rcid ]
240 ] );
241
242 $this->showExaminer( $vars );
243 }
244
245 /**
246 * @param int $logid
247 */
248 public function showExaminerForLogEntry( $logid ) {
249 // Get data
250 $dbr = $this->lbFactory->getReplicaDatabase();
251 $performer = $this->getAuthority();
252 $out = $this->getOutput();
253
254 $row = $dbr->newSelectQueryBuilder()
255 ->select( [
256 'afl_deleted',
257 'afl_ip',
258 'afl_var_dump',
259 'afl_rev_id',
260 'afl_filter_id',
261 'afl_global'
262 ] )
263 ->from( 'abuse_filter_log' )
264 ->where( [ 'afl_id' => $logid ] )
265 ->caller( __METHOD__ )
266 ->fetchRow();
267
268 if ( !$row ) {
269 $out->addWikiMsg( 'abusefilter-examine-notfound' );
270 return;
271 }
272
273 try {
274 $privacyLevel = $this->filterLookup->getFilter( $row->afl_filter_id, $row->afl_global )->getPrivacyLevel();
275 } catch ( CentralDBNotAvailableException $_ ) {
276 // Conservatively assume that it's hidden and protected, like in AbuseLogPager::doFormatRow
277 $privacyLevel = Flags::FILTER_HIDDEN | Flags::FILTER_USES_PROTECTED_VARS;
278 }
279 if ( !$this->afPermManager->canSeeLogDetailsForFilter( $performer, $privacyLevel ) ) {
280 $out->addWikiMsg( 'abusefilter-log-cannot-see-details' );
281 return;
282 }
283
284 $visibility = SpecialAbuseLog::getEntryVisibilityForUser( $row, $performer, $this->afPermManager );
285 if ( $visibility !== SpecialAbuseLog::VISIBILITY_VISIBLE ) {
286 if ( $visibility === SpecialAbuseLog::VISIBILITY_HIDDEN ) {
287 $msg = 'abusefilter-log-details-hidden';
288 } elseif ( $visibility === SpecialAbuseLog::VISIBILITY_HIDDEN_IMPLICIT ) {
289 $msg = 'abusefilter-log-details-hidden-implicit';
290 } else {
291 throw new LogicException( "Unexpected visibility $visibility" );
292 }
293 $out->addWikiMsg( $msg );
294 return;
295 }
296
297 $shouldLogProtectedVarAccess = false;
298
299 // Logs that reveal the values of protected variables are gated behind:
300 // 1. the `abusefilter-access-protected-vars` right
301 // 2. agreement to the `abusefilter-protected-vars-view-agreement` preference
302 $userAuthority = $this->getAuthority();
303 $canViewProtectedVars = $this->afPermManager->canViewProtectedVariableValues( $userAuthority );
304 if ( FilterUtils::isProtected( $privacyLevel ) ) {
305 if ( !$canViewProtectedVars ) {
306 $out->addWikiMsg( 'abusefilter-examine-protected-vars-permission' );
307 return;
308 } else {
309 $shouldLogProtectedVarAccess = true;
310 }
311 }
312
313 // If a non-protected filter and a protected filter have overlapping conditions,
314 // it's possible for a hit to contain a protected variable and for that variable
315 // to be dumped and displayed on a detail page that wouldn't be considered
316 // protected (because it caught on the public filter).
317 // We shouldn't block access to the details of an otherwise public filter hit so
318 // instead only check for access to the protected variables and redact them if the
319 // user shouldn't see them.
320 $vars = $this->varBlobStore->loadVarDump( $row );
321 $varsArray = $this->varManager->dumpAllVars( $vars, $this->afPermManager->getProtectedVariables() );
322
323 foreach ( $this->afPermManager->getProtectedVariables() as $protectedVariable ) {
324 if ( isset( $varsArray[$protectedVariable] ) ) {
325 if ( !$canViewProtectedVars ) {
326 $varsArray[$protectedVariable] = '';
327 } else {
328 // Protected variable in protected filters logs access in the general permission check
329 // Log access to non-protected filters that happen to expose protected variables here
330 if ( !FilterUtils::isProtected( $privacyLevel ) ) {
331 $shouldLogProtectedVarAccess = true;
332 }
333 }
334 }
335 }
336 $vars = VariableHolder::newFromArray( $varsArray );
337
338 if ( $shouldLogProtectedVarAccess ) {
339 $logger = $this->abuseLoggerFactory->getProtectedVarsAccessLogger();
340 $logger->logViewProtectedVariableValue(
341 $userAuthority->getUser(),
342 $varsArray['user_name'] ?? $varsArray['accountname']
343 );
344 }
345
346 $out->addJsConfigVars( [
347 'wgAbuseFilterVariables' => $varsArray,
348 'abuseFilterExamine' => [ 'type' => 'log', 'id' => $logid ]
349 ] );
350 $this->showExaminer( $vars );
351 }
352
353 /**
354 * @param VariableHolder|null $vars
355 */
356 public function showExaminer( ?VariableHolder $vars ) {
357 $output = $this->getOutput();
358 $output->enableOOUI();
359
360 if ( !$vars ) {
361 $output->addWikiMsg( 'abusefilter-examine-incompatible' );
362 return;
363 }
364
365 $html = '';
366
367 $output->addModules( 'ext.abuseFilter.examine' );
368
369 // Add test bit
370 if ( $this->afPermManager->canUseTestTools( $this->getAuthority() ) ) {
371 $boxBuilder = $this->boxBuilderFactory->newEditBoxBuilder(
372 $this,
373 $this->getAuthority(),
374 $output
375 );
376
377 $tester = Html::rawElement( 'h2', [], $this->msg( 'abusefilter-examine-test' )->parse() );
378 $tester .= $boxBuilder->buildEditBox( $this->testFilter, false, false, false );
379 $tester .= $this->buildFilterLoader();
380 $html .= Html::rawElement( 'div', [ 'id' => 'mw-abusefilter-examine-editor' ], $tester );
381 $html .= Html::rawElement( 'p',
382 [],
383 new OOUI\ButtonInputWidget(
384 [
385 'label' => $this->msg( 'abusefilter-examine-test-button' )->text(),
386 'id' => 'mw-abusefilter-examine-test',
387 'flags' => [ 'primary', 'progressive' ]
388 ]
389 ) .
390 Html::element( 'div',
391 [
392 'id' => 'mw-abusefilter-syntaxresult',
393 'style' => 'display: none;'
394 ]
395 )
396 );
397 }
398
399 // Variable dump
400 $html .= Html::rawElement(
401 'h2',
402 [],
403 $this->msg( 'abusefilter-examine-vars' )->parse()
404 );
405 $html .= $this->variablesFormatter->buildVarDumpTable( $vars );
406
407 $output->addHTML( $html );
408 }
409
410 }