File: RestAuthorizeTrait.php

package info (click to toggle)
mediawiki 1%3A1.43.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 417,464 kB
  • sloc: php: 1,062,949; javascript: 664,290; sql: 9,714; python: 5,458; xml: 3,489; sh: 1,131; makefile: 64
file content (89 lines) | stat: -rw-r--r-- 2,055 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php

namespace MediaWiki\Rest\Handler\Helper;

use MediaWiki\Page\PageIdentity;
use MediaWiki\Permissions\Authority;
use MediaWiki\Permissions\PermissionStatus;
use MediaWiki\Rest\HttpException;
use Wikimedia\Message\MessageValue;

trait RestAuthorizeTrait {
	use RestStatusTrait;

	/**
	 * Authorize an action
	 *
	 * @see Authroity::authorizeWrite
	 * @throws HttpException
	 */
	private function authorizeActionOrThrow(
		Authority $authority,
		string $action
	): void {
		$status = PermissionStatus::newEmpty();
		if ( !$authority->authorizeAction( $action, $status ) ) {
			$this->handleStatus( $status );
		}
	}

	/**
	 * Authorize a read operation
	 *
	 * @see Authroity::authorizeWrite
	 * @throws HttpException
	 */
	private function authorizeReadOrThrow(
		Authority $authority,
		string $action,
		PageIdentity $target
	): void {
		$status = PermissionStatus::newEmpty();
		if ( !$authority->authorizeRead( $action, $target, $status ) ) {
			$this->handleStatus( $status );
		}
	}

	/**
	 * Authorize a write operation
	 *
	 * @see Authroity::authorizeWrite
	 * @throws HttpException
	 */
	private function authorizeWriteOrThrow(
		Authority $authority,
		string $action,
		PageIdentity $target
	): void {
		$status = PermissionStatus::newEmpty();
		if ( !$authority->authorizeWrite( $action, $target, $status ) ) {
			$this->handleStatus( $status );
		}
	}

	/**
	 * Throw an exception if the status contains an error.
	 *
	 * @throws HttpException
	 * @return never
	 */
	private function handleStatus( PermissionStatus $status ): void {
		// The permission name should always be set, but don't explode if it isn't.
		$permission = $status->getPermission() ?: '(unknown)';

		if ( $status->isRateLimitExceeded() ) {
			$this->throwExceptionForStatus(
				$status,
				MessageValue::new( 'rest-rate-limit-exceeded', [ $permission ] ),
				429 // See https://www.rfc-editor.org/rfc/rfc6585#section-4
			);
		}

		$this->throwExceptionForStatus(
			$status,
			MessageValue::new( 'rest-permission-error', [ $permission ] ),
			403
		);
	}

}