Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 82
0.00% covered (danger)
0.00%
0 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
CustomBlockedDomainStorage
0.00% covered (danger)
0.00%
0 / 81
0.00% covered (danger)
0.00%
0 / 10
756
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 loadConfig
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 loadComputed
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
30
 validateDomain
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 fetchConfig
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 addDomain
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 removeDomain
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 fetchLatestConfig
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 saveContent
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 getBlockedDomainPage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20namespace MediaWiki\Extension\AbuseFilter\BlockedDomains;
21
22use MediaWiki\CommentStore\CommentStoreComment;
23use MediaWiki\Content\JsonContent;
24use MediaWiki\Json\FormatJson;
25use MediaWiki\Message\Message;
26use MediaWiki\Page\PageIdentity;
27use MediaWiki\Page\WikiPageFactory;
28use MediaWiki\Permissions\Authority;
29use MediaWiki\RecentChanges\RecentChange;
30use MediaWiki\Revision\RevisionLookup;
31use MediaWiki\Revision\SlotRecord;
32use MediaWiki\Title\Title;
33use StatusValue;
34use Wikimedia\ObjectCache\BagOStuff;
35use Wikimedia\Rdbms\DBAccessObjectUtils;
36use Wikimedia\Rdbms\IDBAccessObject;
37
38/**
39 * Hold and update information about blocked external domains
40 *
41 * @ingroup SpecialPage
42 */
43class CustomBlockedDomainStorage implements IBlockedDomainStorage, IDBAccessObject {
44    public const TARGET_PAGE = 'BlockedExternalDomains.json';
45
46    public function __construct(
47        private readonly BagOStuff $cache,
48        private readonly RevisionLookup $revisionLookup,
49        private readonly WikiPageFactory $wikiPageFactory,
50        private readonly BlockedDomainValidator $domainValidator
51    ) {
52    }
53
54    /** @inheritDoc */
55    public function loadConfig( int $flags = 0 ): StatusValue {
56        if ( DBAccessObjectUtils::hasFlags( $flags, IDBAccessObject::READ_LATEST ) ) {
57            return $this->fetchConfig( $flags );
58        }
59
60        // Load configuration from APCU
61        return $this->cache->getWithSetCallback(
62            $this->cache->makeKey( 'abusefilter-blockeddomains-config' ),
63            BagOStuff::TTL_MINUTE * 5,
64            function ( &$ttl ) use ( $flags ) {
65                $result = $this->fetchConfig( $flags );
66                if ( !$result->isGood() ) {
67                    // error should not be cached
68                    $ttl = BagOStuff::TTL_UNCACHEABLE;
69                }
70                return $result;
71            }
72        );
73    }
74
75    /** @inheritDoc */
76    public function loadComputed(): array {
77        return $this->cache->getWithSetCallback(
78            $this->cache->makeKey( 'abusefilter-blockeddomains-computed' ),
79            BagOStuff::TTL_MINUTE * 5,
80            function () {
81                $status = $this->loadConfig();
82                if ( !$status->isGood() ) {
83                    return [];
84                }
85                $computedDomains = [];
86                foreach ( $status->getValue() as $domain ) {
87                    if ( !( $domain['domain'] ?? null ) ) {
88                        continue;
89                    }
90                    $validatedDomain = $this->domainValidator->validateDomain( $domain['domain'] );
91                    if ( $validatedDomain ) {
92                        // It should be a map, benchmark at https://phabricator.wikimedia.org/P48956
93                        $computedDomains[$validatedDomain] = true;
94                    }
95                }
96                return $computedDomains;
97            }
98        );
99    }
100
101    /**
102     * Validate an input domain
103     *
104     * @deprecated since 1.45, use BlockedDomainValidator instead
105     * @see BlockedDomainValidator
106     * @param string|null $domain Domain such as foo.wikipedia.org
107     * @return string|false Parsed domain, or false otherwise
108     */
109    public function validateDomain( $domain ) {
110        // NOTE: Can be called on the deprecated class name, see the class_alias in the bottom
111        wfDeprecated( __METHOD__, '1.45' );
112        if ( !is_string( $domain ) && $domain !== null ) {
113            // cannot be passed to BlockedDomainValidator
114            return false;
115        }
116        return $this->domainValidator->validateDomain( $domain );
117    }
118
119    /**
120     * Fetch the contents of the configuration page, without caching.
121     *
122     * The result is not validated with a config validator.
123     *
124     * @param int $flags bit field, see IDBAccessObject::READ_XXX; do NOT pass READ_UNCACHED
125     * @return StatusValue Status object, with the configuration (as JSON data) on success.
126     */
127    private function fetchConfig( int $flags ): StatusValue {
128        $revision = $this->revisionLookup->getRevisionByTitle( $this->getBlockedDomainPage(), 0,
129            $flags );
130        if ( !$revision ) {
131            // The configuration page does not exist. Pretend it does not configure anything
132            // specific (failure mode and empty-page behaviors are equal).
133            return StatusValue::newGood( [] );
134        }
135        $content = $revision->getContent( SlotRecord::MAIN );
136        if ( !$content instanceof JsonContent ) {
137            return StatusValue::newFatal( 'modeleditnotsupported-text', $content->getModel() );
138        }
139
140        return FormatJson::parse( $content->getText(), FormatJson::FORCE_ASSOC );
141    }
142
143    /** @inheritDoc */
144    public function addDomain( string $domain, string $notes, Authority $authority ): StatusValue {
145        $contentStatus = $this->fetchLatestConfig();
146        if ( !$contentStatus->isOK() ) {
147            return $contentStatus;
148        }
149        $content = $contentStatus->getValue();
150        $content[] = [ 'domain' => $domain, 'notes' => $notes, 'addedBy' => $authority->getUser()->getName() ];
151        $comment = Message::newFromSpecifier( 'abusefilter-blocked-domains-domain-added-comment' )
152            ->params( $domain, $notes )
153            ->plain();
154        return $this->saveContent( $content, $authority, $comment );
155    }
156
157    /** @inheritDoc */
158    public function removeDomain( string $domain, string $notes, Authority $authority ): StatusValue {
159        $contentStatus = $this->fetchLatestConfig();
160        if ( !$contentStatus->isOK() ) {
161            return $contentStatus;
162        }
163        $content = $contentStatus->getValue();
164        foreach ( $content as $key => $value ) {
165            if ( ( $value['domain'] ?? '' ) == $domain ) {
166                unset( $content[$key] );
167            }
168        }
169        $comment = Message::newFromSpecifier( 'abusefilter-blocked-domains-domain-removed-comment' )
170            ->params( $domain, $notes )
171            ->plain();
172        return $this->saveContent( array_values( $content ), $authority, $comment );
173    }
174
175    /**
176     * @return StatusValue<array> Good status wrapping parsed JSON config as an array (empty array
177     *   when the page doesn't exist); error status on invalid JSON
178     */
179    private function fetchLatestConfig(): StatusValue {
180        $configPage = $this->getBlockedDomainPage();
181        $revision = $this->revisionLookup->getRevisionByTitle( $configPage, 0, IDBAccessObject::READ_LATEST );
182        if ( !$revision ) {
183            return StatusValue::newGood( [] );
184        }
185
186        $revContent = $revision->getContent( SlotRecord::MAIN );
187        if ( $revContent instanceof JsonContent ) {
188            return FormatJson::parse( $revContent->getText(), FormatJson::FORCE_ASSOC );
189        }
190        return StatusValue::newFatal( 'modeleditnotsupported-text', $revContent->getModel() );
191    }
192
193    /**
194     * Save the provided content into the page
195     *
196     * @param array[] $content To be turned into JSON
197     * @param Authority $authority Performer
198     * @param string $comment Save comment
199     *
200     * @return StatusValue
201     */
202    private function saveContent( array $content, Authority $authority, string $comment ): StatusValue {
203        $configPage = $this->getBlockedDomainPage();
204        $page = $this->wikiPageFactory->newFromTitle( $configPage );
205        $updater = $page->newPageUpdater( $authority );
206        $updater->setContent( SlotRecord::MAIN, new JsonContent( FormatJson::encode( $content ) ) );
207
208        if ( $authority->isAllowed( 'autopatrol' ) ) {
209            $updater->setRcPatrolStatus( RecentChange::PRC_AUTOPATROLLED );
210        }
211
212        $updater->saveRevision(
213            CommentStoreComment::newUnsavedComment( $comment )
214        );
215        return $updater->getStatus();
216    }
217
218    /**
219     * @return PageIdentity Title of the config JSON page
220     */
221    private function getBlockedDomainPage(): PageIdentity {
222        return Title::makeTitle( NS_MEDIAWIKI, self::TARGET_PAGE );
223    }
224}
225
226// @deprecated since 1.44
227class_alias( CustomBlockedDomainStorage::class, 'MediaWiki\Extension\AbuseFilter\BlockedDomainStorage' );