Debian Codegraph @

extensions/AbuseFilter/includes/BlockedDomainStorage.php

raw symbols SCIP
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 */
20 namespace MediaWiki\Extension\AbuseFilter;
21
22 use MediaWiki\Api\ApiRawMessage;
23 use MediaWiki\CommentStore\CommentStoreComment;
24 use MediaWiki\Content\JsonContent;
25 use MediaWiki\Json\FormatJson;
26 use MediaWiki\Message\Message;
27 use MediaWiki\Page\WikiPageFactory;
28 use MediaWiki\Permissions\Authority;
29 use MediaWiki\Revision\RevisionLookup;
30 use MediaWiki\Revision\RevisionRecord;
31 use MediaWiki\Revision\SlotRecord;
32 use MediaWiki\Title\TitleValue;
33 use MediaWiki\User\UserFactory;
34 use MediaWiki\User\UserIdentity;
35 use MediaWiki\Utils\UrlUtils;
36 use RecentChange;
37 use StatusValue;
38 use Wikimedia\ObjectCache\BagOStuff;
39 use Wikimedia\Rdbms\DBAccessObjectUtils;
40 use Wikimedia\Rdbms\IDBAccessObject;
41
42 /**
43 * Hold and update information about blocked external domains
44 *
45 * @ingroup SpecialPage
46 */
47 class BlockedDomainStorage implements IDBAccessObject {
48 public const SERVICE_NAME = 'AbuseFilterBlockedDomainStorage';
49 public const TARGET_PAGE = 'BlockedExternalDomains.json';
50
51 private RevisionLookup $revisionLookup;
52 private BagOStuff $cache;
53 private UserFactory $userFactory;
54 private WikiPageFactory $wikiPageFactory;
55 private UrlUtils $urlUtils;
56
57 /**
58 * @param BagOStuff $cache Local-server caching
59 * @param RevisionLookup $revisionLookup
60 * @param UserFactory $userFactory
61 * @param WikiPageFactory $wikiPageFactory
62 * @param UrlUtils $urlUtils
63 */
64 public function __construct(
65 BagOStuff $cache,
66 RevisionLookup $revisionLookup,
67 UserFactory $userFactory,
68 WikiPageFactory $wikiPageFactory,
69 UrlUtils $urlUtils
70 ) {
71 $this->cache = $cache;
72 $this->revisionLookup = $revisionLookup;
73 $this->userFactory = $userFactory;
74 $this->wikiPageFactory = $wikiPageFactory;
75 $this->urlUtils = $urlUtils;
76 }
77
78 /**
79 * @return string
80 */
81 private function makeCacheKey() {
82 return $this->cache->makeKey( 'abusefilter-blocked-domains' );
83 }
84
85 /**
86 * Load the configuration page, with optional local-server caching.
87 *
88 * @param int $flags bit field, see IDBAccessObject::READ_XXX
89 * @return StatusValue The content of the configuration page (as JSON
90 * data in PHP-native format), or a StatusValue on error.
91 */
92 public function loadConfig( int $flags = 0 ): StatusValue {
93 if ( DBAccessObjectUtils::hasFlags( $flags, IDBAccessObject::READ_LATEST ) ) {
94 return $this->fetchConfig( $flags );
95 }
96
97 // Load configuration from APCU
98 return $this->cache->getWithSetCallback(
99 $this->makeCacheKey(),
100 BagOStuff::TTL_MINUTE * 5,
101 function ( &$ttl ) use ( $flags ) {
102 $result = $this->fetchConfig( $flags );
103 if ( !$result->isGood() ) {
104 // error should not be cached
105 $ttl = BagOStuff::TTL_UNCACHEABLE;
106 }
107 return $result;
108 }
109 );
110 }
111
112 /**
113 * Load the computed domain blocklist
114 *
115 * @return array<string,true> Flipped for performance reasons
116 */
117 public function loadComputed(): array {
118 return $this->cache->getWithSetCallback(
119 $this->cache->makeKey( 'abusefilter-blocked-domains-computed' ),
120 BagOStuff::TTL_MINUTE * 5,
121 function () {
122 $status = $this->loadConfig();
123 if ( !$status->isGood() ) {
124 return [];
125 }
126 $computedDomains = [];
127 foreach ( $status->getValue() as $domain ) {
128 if ( !( $domain['domain'] ?? null ) ) {
129 continue;
130 }
131 $validatedDomain = $this->validateDomain( $domain['domain'] );
132 if ( $validatedDomain ) {
133 // It should be a map, benchmark at https://phabricator.wikimedia.org/P48956
134 $computedDomains[$validatedDomain] = true;
135 }
136 }
137 return $computedDomains;
138 }
139 );
140 }
141
142 /**
143 * Validate an input domain
144 *
145 * @param string|null $domain Domain such as foo.wikipedia.org
146 * @return string|false Parsed domain, or false otherwise
147 */
148 public function validateDomain( $domain ) {
149 if ( !$domain ) {
150 return false;
151 }
152
153 $domain = trim( $domain );
154 if ( !str_contains( $domain, '//' ) ) {
155 $domain = 'https://' . $domain;
156 }
157
158 $parsedUrl = $this->urlUtils->parse( $domain );
159 // Parse url returns a valid URL for "foo"
160 if ( !$parsedUrl || !str_contains( $parsedUrl['host'], '.' ) ) {
161 return false;
162 }
163 return $parsedUrl['host'];
164 }
165
166 /**
167 * Fetch the contents of the configuration page, without caching.
168 *
169 * The result is not validated with a config validator.
170 *
171 * @param int $flags bit field, see IDBAccessObject::READ_XXX; do NOT pass READ_UNCACHED
172 * @return StatusValue Status object, with the configuration (as JSON data) on success.
173 */
174 private function fetchConfig( int $flags ): StatusValue {
175 $revision = $this->revisionLookup->getRevisionByTitle( $this->getBlockedDomainPage(), 0, $flags );
176 if ( !$revision ) {
177 // The configuration page does not exist. Pretend it does not configure anything
178 // specific (failure mode and empty-page behaviors are equal).
179 return StatusValue::newGood( [] );
180 }
181 $content = $revision->getContent( SlotRecord::MAIN );
182 if ( !$content instanceof JsonContent ) {
183 return StatusValue::newFatal( new ApiRawMessage(
184 'The configuration title has no content or is not JSON content.',
185 'newcomer-tasks-configuration-loader-content-error' ) );
186 }
187
188 return FormatJson::parse( $content->getText(), FormatJson::FORCE_ASSOC );
189 }
190
191 /**
192 * This doesn't do validation.
193 *
194 * @param string $domain domain to be blocked
195 * @param string $notes User provided notes
196 * @param Authority|UserIdentity $user Performer
197 *
198 * @return RevisionRecord|null Null on failure
199 */
200 public function addDomain( string $domain, string $notes, $user ): ?RevisionRecord {
201 $content = $this->fetchLatestConfig();
202 if ( $content === null ) {
203 return null;
204 }
205 $content[] = [ 'domain' => $domain, 'notes' => $notes, 'addedBy' => $user->getName() ];
206 $comment = Message::newFromSpecifier( 'abusefilter-blocked-domains-domain-added-comment' )
207 ->params( $domain, $notes )
208 ->plain();
209 return $this->saveContent( $content, $user, $comment );
210 }
211
212 /**
213 * This doesn't do validation
214 *
215 * @param string $domain domain to be removed from the blocked list
216 * @param string $notes User provided notes
217 * @param Authority|UserIdentity $user Performer
218 *
219 * @return RevisionRecord|null Null on failure
220 */
221 public function removeDomain( string $domain, string $notes, $user ): ?RevisionRecord {
222 $content = $this->fetchLatestConfig();
223 if ( $content === null ) {
224 return null;
225 }
226 foreach ( $content as $key => $value ) {
227 if ( ( $value['domain'] ?? '' ) == $domain ) {
228 unset( $content[$key] );
229 }
230 }
231 $comment = Message::newFromSpecifier( 'abusefilter-blocked-domains-domain-removed-comment' )
232 ->params( $domain, $notes )
233 ->plain();
234 return $this->saveContent( array_values( $content ), $user, $comment );
235 }
236
237 /**
238 * @return array[]|null Empty array when the page doesn't exist, null on failure
239 */
240 private function fetchLatestConfig(): ?array {
241 $configPage = $this->getBlockedDomainPage();
242 $revision = $this->revisionLookup->getRevisionByTitle( $configPage, 0, IDBAccessObject::READ_LATEST );
243 if ( !$revision ) {
244 return [];
245 }
246
247 $revContent = $revision->getContent( SlotRecord::MAIN );
248 if ( $revContent instanceof JsonContent ) {
249 $status = FormatJson::parse( $revContent->getText(), FormatJson::FORCE_ASSOC );
250 if ( $status->isOK() ) {
251 return $status->getValue();
252 }
253 }
254
255 return null;
256 }
257
258 /**
259 * Save the provided content into the page
260 *
261 * @param array[] $content To be turned into JSON
262 * @param Authority|UserIdentity $user Performer
263 * @param string $comment Save comment
264 *
265 * @return RevisionRecord|null
266 */
267 private function saveContent( array $content, $user, string $comment ): ?RevisionRecord {
268 $configPage = $this->getBlockedDomainPage();
269 $page = $this->wikiPageFactory->newFromLinkTarget( $configPage );
270 $updater = $page->newPageUpdater( $user );
271 $updater->setContent( SlotRecord::MAIN, new JsonContent( FormatJson::encode( $content ) ) );
272
273 if ( $this->userFactory->newFromUserIdentity( $user )->isAllowed( 'autopatrol' ) ) {
274 $updater->setRcPatrolStatus( RecentChange::PRC_AUTOPATROLLED );
275 }
276
277 return $updater->saveRevision(
278 CommentStoreComment::newUnsavedComment( $comment )
279 );
280 }
281
282 /**
283 * @return TitleValue TitleValue of the config JSON page
284 */
285 private function getBlockedDomainPage(): TitleValue {
286 return new TitleValue( NS_MEDIAWIKI, self::TARGET_PAGE );
287 }
288 }