Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
83.90% covered (warning)
83.90%
99 / 118
40.00% covered (danger)
40.00%
4 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
FilteredActionsHandler
83.90% covered (warning)
83.90%
99 / 118
40.00% covered (danger)
40.00%
4 / 10
31.27
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 onEditFilterMergedContent
66.67% covered (warning)
66.67%
8 / 12
0.00% covered (danger)
0.00%
0 / 1
2.15
 filterEdit
80.77% covered (warning)
80.77%
21 / 26
0.00% covered (danger)
0.00%
0 / 1
7.35
 getApiStatus
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
3
 onTitleMove
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 onPageDelete
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
2.00
 onUploadVerifyUpload
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 onUploadStashFile
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 filterUpload
66.67% covered (warning)
66.67%
14 / 21
0.00% covered (danger)
0.00%
0 / 1
7.33
 onParserOutputStashForEdit
96.00% covered (success)
96.00%
24 / 25
0.00% covered (danger)
0.00%
0 / 1
4
1<?php
2
3namespace MediaWiki\Extension\AbuseFilter\Hooks\Handlers;
4
5use MediaWiki\Api\ApiMessage;
6use MediaWiki\Content\Content;
7use MediaWiki\Context\IContextSource;
8use MediaWiki\Deferred\DeferredUpdates;
9use MediaWiki\Extension\AbuseFilter\BlockedDomains\IBlockedDomainFilter;
10use MediaWiki\Extension\AbuseFilter\EditRevUpdater;
11use MediaWiki\Extension\AbuseFilter\FilterRunnerFactory;
12use MediaWiki\Extension\AbuseFilter\VariableGenerator\VariableGeneratorFactory;
13use MediaWiki\Hook\EditFilterMergedContentHook;
14use MediaWiki\Hook\TitleMoveHook;
15use MediaWiki\Logger\LoggerFactory;
16use MediaWiki\Page\Hook\PageDeleteHook;
17use MediaWiki\Page\ProperPageIdentity;
18use MediaWiki\Permissions\Authority;
19use MediaWiki\Permissions\PermissionManager;
20use MediaWiki\Revision\SlotRecord;
21use MediaWiki\Status\Status;
22use MediaWiki\Storage\Hook\ParserOutputStashForEditHook;
23use MediaWiki\Title\Title;
24use MediaWiki\Title\TitleFactory;
25use MediaWiki\Upload\Hook\UploadStashFileHook;
26use MediaWiki\Upload\Hook\UploadVerifyUploadHook;
27use MediaWiki\Upload\UploadBase;
28use MediaWiki\User\TempUser\TempUserConfig;
29use MediaWiki\User\User;
30use MediaWiki\User\UserFactory;
31use StatusValue;
32use Wikimedia\Stats\StatsFactory;
33use Wikimedia\Timestamp\ConvertibleTimestamp;
34
35/**
36 * Handler for actions that can be filtered
37 */
38class FilteredActionsHandler implements
39    EditFilterMergedContentHook,
40    TitleMoveHook,
41    PageDeleteHook,
42    UploadVerifyUploadHook,
43    UploadStashFileHook,
44    ParserOutputStashForEditHook
45{
46
47    public function __construct(
48        private readonly StatsFactory $statsFactory,
49        private readonly FilterRunnerFactory $filterRunnerFactory,
50        private readonly VariableGeneratorFactory $variableGeneratorFactory,
51        private readonly EditRevUpdater $editRevUpdater,
52        private readonly IBlockedDomainFilter $blockedDomainFilter,
53        private readonly PermissionManager $permissionManager,
54        private readonly TitleFactory $titleFactory,
55        private readonly UserFactory $userFactory,
56        private readonly TempUserConfig $tempUserConfig,
57    ) {
58    }
59
60    /**
61     * @inheritDoc
62     * @param string $slot Slot role for the content, added by Wikibase (T288885)
63     */
64    public function onEditFilterMergedContent(
65        IContextSource $context,
66        Content $content,
67        Status $status,
68        $summary,
69        User $user,
70        $minoredit,
71        string $slot = SlotRecord::MAIN
72    ) {
73        $startTime = ConvertibleTimestamp::hrtime();
74        if ( !$status->isOK() ) {
75            // Investigate what happens if we skip filtering here (T211680)
76            LoggerFactory::getInstance( 'AbuseFilter' )->info(
77                'Status is already not OK',
78                [ 'status' => (string)$status ]
79            );
80        }
81
82        $this->filterEdit( $context, $user, $content, $summary, $slot, $status );
83
84        $this->statsFactory->withComponent( 'AbuseFilter' )
85            ->getTiming( 'filter_run_duration_seconds' )
86            ->setLabel( 'action', 'edit' )
87            ->observeNanoseconds( ConvertibleTimestamp::hrtime() - $startTime );
88
89        return $status->isOK();
90    }
91
92    /**
93     * Implementation for EditFilterMergedContent hook.
94     *
95     * @param IContextSource $context the context of the edit
96     * @param User $user
97     * @param Content $content the new Content generated by the edit
98     * @param string $summary Edit summary for page
99     * @param string $slot slot role for the content
100     * @param Status $status
101     */
102    private function filterEdit(
103        IContextSource $context,
104        User $user,
105        Content $content,
106        string $summary,
107        string $slot,
108        Status $status
109    ): void {
110        $this->editRevUpdater->clearLastEditPage();
111
112        $title = $context->getTitle();
113        $logger = LoggerFactory::getInstance( 'AbuseFilter' );
114        if ( $title === null ) {
115            // T144265: This *should* never happen.
116            $logger->warning( __METHOD__ . ' received a null title.' );
117            return;
118        }
119        if ( !$title->canExist() ) {
120            // This also should be handled in EditPage or whoever is calling the hook.
121            $logger->warning( __METHOD__ . ' received a Title that cannot exist.' );
122            // Note that if the title cannot exist, there's no much point in filtering the edit anyway
123            return;
124        }
125
126        $page = $context->getWikiPage();
127
128        $builder = $this->variableGeneratorFactory->newRunGenerator( $user, $title );
129        $vars = $builder->getEditVars( $content, $summary, $slot, $page );
130        if ( $vars === null ) {
131            // We don't have to filter the edit
132            return;
133        }
134        $runner = $this->filterRunnerFactory->newRunner( $user, $title, $vars, 'default' );
135        $filterResult = $runner->run();
136        if ( !$filterResult->isOK() ) {
137            // Produce a useful error message for API edits
138            $filterResultApi = self::getApiStatus( $filterResult );
139            $status->merge( $filterResultApi );
140            return;
141        }
142
143        $this->editRevUpdater->setLastEditPage( $page );
144
145        if ( $this->permissionManager->userHasRight( $user, 'abusefilter-bypass-blocked-external-domains' ) ) {
146            return;
147        }
148        $blockedDomainFilterResult = $this->blockedDomainFilter->filter( $vars, $user, $title );
149        if ( !$blockedDomainFilterResult->isOK() ) {
150            $status->merge( $blockedDomainFilterResult );
151        }
152    }
153
154    /**
155     * @param Status $status Error message details
156     * @return Status Status containing the same error messages with extra data for the API
157     */
158    private static function getApiStatus( Status $status ): Status {
159        $allActionsTaken = $status->getValue();
160        $statusForApi = Status::newGood();
161
162        foreach ( $status->getMessages() as $msg ) {
163            [ $filterDescription, $filter ] = $msg->getParams();
164            $actionsTaken = $allActionsTaken[ $filter ];
165
166            $code = ( $actionsTaken === [ 'warn' ] ) ? 'abusefilter-warning' : 'abusefilter-disallowed';
167            $data = [
168                'abusefilter' => [
169                    'id' => $filter,
170                    'description' => $filterDescription,
171                    'actions' => $actionsTaken,
172                ],
173            ];
174
175            $message = ApiMessage::create( $msg, $code, $data );
176            $statusForApi->fatal( $message );
177        }
178
179        return $statusForApi;
180    }
181
182    /**
183     * @inheritDoc
184     */
185    public function onTitleMove( Title $old, Title $nt, User $user, $reason, Status &$status ) {
186        $builder = $this->variableGeneratorFactory->newRunGenerator( $user, $old );
187        $vars = $builder->getMoveVars( $nt, $reason );
188        $runner = $this->filterRunnerFactory->newRunner( $user, $old, $vars, 'default' );
189        $result = $runner->run();
190        $status->merge( $result );
191    }
192
193    /**
194     * @inheritDoc
195     */
196    public function onPageDelete(
197        ProperPageIdentity $page, Authority $deleter, string $reason, StatusValue $status, bool $suppress
198    ) {
199        if ( $suppress ) {
200            // Don't filter suppressions, T71617
201            return true;
202        }
203        $user = $this->userFactory->newFromAuthority( $deleter );
204        $title = $this->titleFactory->newFromPageIdentity( $page );
205        $builder = $this->variableGeneratorFactory->newRunGenerator( $user, $title );
206        $vars = $builder->getDeleteVars( $reason );
207        $runner = $this->filterRunnerFactory->newRunner( $user, $title, $vars, 'default' );
208        $filterResult = $runner->run();
209
210        $status->merge( $filterResult );
211
212        return $filterResult->isOK();
213    }
214
215    /**
216     * @inheritDoc
217     */
218    public function onUploadVerifyUpload(
219        UploadBase $upload,
220        User $user,
221        ?array $props,
222        $comment,
223        $pageText,
224        &$error
225    ) {
226        return $this->filterUpload( 'upload', $upload, $user, $props, $comment, $pageText, $error );
227    }
228
229    /**
230     * Filter an upload to stash. If a filter doesn't need to check the page contents or
231     * upload comment, it can use `action='stashupload'` to provide better experience to e.g.
232     * UploadWizard (rejecting files immediately, rather than after the user adds the details).
233     *
234     * @inheritDoc
235     */
236    public function onUploadStashFile( UploadBase $upload, User $user, ?array $props, &$error ) {
237        return $this->filterUpload( 'stashupload', $upload, $user, $props, null, null, $error );
238    }
239
240    /**
241     * Implementation for UploadStashFile and UploadVerifyUpload hooks.
242     *
243     * @param string $action 'upload' or 'stashupload'
244     * @param UploadBase $upload
245     * @param User $user User performing the action
246     * @param array|null $props File properties, as returned by MWFileProps::getPropsFromPath().
247     * @param string|null $summary Upload log comment (also used as edit summary)
248     * @param string|null $text File description page text (only used for new uploads)
249     * @param array|ApiMessage &$error
250     * @return bool
251     */
252    private function filterUpload(
253        string $action,
254        UploadBase $upload,
255        User $user,
256        ?array $props,
257        ?string $summary,
258        ?string $text,
259        &$error
260    ): bool {
261        $title = $upload->getTitle();
262        if ( $title === null ) {
263            // T144265: This could happen for 'stashupload' if the specified title is invalid.
264            // Let UploadBase warn the user about that, and we'll filter later.
265            $logger = LoggerFactory::getInstance( 'AbuseFilter' );
266            $logger->warning( __METHOD__ . " received a null title. Action: $action." );
267            return true;
268        }
269
270        $builder = $this->variableGeneratorFactory->newRunGenerator( $user, $title );
271        $vars = $builder->getUploadVars( $action, $upload, $summary, $text, $props );
272        if ( $vars === null ) {
273            return true;
274        }
275        $runner = $this->filterRunnerFactory->newRunner( $user, $title, $vars, 'default' );
276        $filterResult = $runner->run();
277
278        if ( !$filterResult->isOK() ) {
279            // Produce a useful error message for API edits
280            $filterResultApi = self::getApiStatus( $filterResult );
281            // @todo Return all errors instead of only the first one
282            $error = $filterResultApi->getMessages()[0];
283        } else {
284            if ( $this->permissionManager->userHasRight( $user, 'abusefilter-bypass-blocked-external-domains' ) ) {
285                return true;
286            }
287            $blockedDomainFilterResult = $this->blockedDomainFilter->filter( $vars, $user, $title );
288            if ( !$blockedDomainFilterResult->isOK() ) {
289                $error = $blockedDomainFilterResult->getMessages()[0];
290                return $blockedDomainFilterResult->isOK();
291            }
292        }
293
294        return $filterResult->isOK();
295    }
296
297    /**
298     * @inheritDoc
299     */
300    public function onParserOutputStashForEdit( $page, $content, $output, $summary, $user ) {
301        // If temporary accounts are enabled, we can't reuse stashed filter matches for unregistered
302        // performers, as the actual save attempt would result in a new temporary account being created,
303        // thereby changing some of the input variables and potentially leading to a different outcome.
304        // (T402298)
305        if ( !$user->isRegistered() && $this->tempUserConfig->isEnabled() ) {
306            return;
307        }
308
309        // XXX: This makes the assumption that this method is only ever called for the main slot.
310        // Which right now holds true, but any more fancy MCR stuff will likely break here...
311        $slot = SlotRecord::MAIN;
312
313        // Cache any resulting filter matches.
314        // Do this outside the synchronous stash lock to avoid any chance of slowdown.
315        DeferredUpdates::addCallableUpdate(
316            function () use (
317                $user,
318                $page,
319                $summary,
320                $content,
321                $slot
322            ) {
323                $startTime = ConvertibleTimestamp::hrtime();
324                $generator = $this->variableGeneratorFactory->newRunGenerator( $user, $page->getTitle() );
325                $vars = $generator->getStashEditVars( $content, $summary, $slot, $page );
326                if ( !$vars ) {
327                    return;
328                }
329                $runner = $this->filterRunnerFactory->newRunner( $user, $page->getTitle(), $vars, 'default' );
330                $runner->runForStash();
331                $this->statsFactory->withComponent( 'AbuseFilter' )
332                    ->getTiming( 'filter_run_duration_seconds' )
333                    ->setLabel( 'action', 'stash' )
334                    ->observeNanoseconds( ConvertibleTimestamp::hrtime() - $startTime );
335            },
336            DeferredUpdates::PRESEND
337        );
338    }
339}