Debian Codegraph @

vendor/wikimedia/shellbox/src/Action/MultipartAction.php

raw
1 <?php
2
3 namespace Shellbox\Action;
4
5 use GuzzleHttp\Psr7\MultipartStream;
6 use GuzzleHttp\Psr7\Stream;
7 use GuzzleHttp\Psr7\Utils;
8 use Psr\Log\LoggerInterface;
9 use Psr\Log\NullLogger;
10 use Shellbox\FileUtils;
11 use Shellbox\Multipart\MultipartReader;
12 use Shellbox\Multipart\MultipartUtils;
13 use Shellbox\Server;
14 use Shellbox\Shellbox;
15 use Shellbox\ShellboxError;
16 use Shellbox\TempDirManager;
17
18 /**
19 * Base class for actions that share a specific input/output protocol.
20 *
21 * @todo Protocol documentation
22 */
23 abstract class MultipartAction {
24 /** @var TempDirManager */
25 protected $tempDirManager;
26 /** @var array */
27 private $structuredData;
28 /** @var string[] */
29 private $binaryData;
30 /** @var Server */
31 private $server;
32 /** @var string[] */
33 private $headers;
34 /** @var LoggerInterface */
35 protected $logger;
36 /** @var string[] */
37 private $inputFiles = [];
38
39 private const COPY_BUFFER_SIZE = 65536;
40
41 /**
42 * @param Server $server
43 */
44 public function __construct( Server $server ) {
45 $this->server = $server;
46 $this->logger = new NullLogger;
47 }
48
49 /**
50 * @param LoggerInterface $logger
51 */
52 public function setLogger( LoggerInterface $logger ) {
53 $this->logger = $logger;
54 }
55
56 /**
57 * The entry point for execution of the action
58 *
59 * @param string[] $pathParts
60 */
61 public function baseExecute( $pathParts ) {
62 try {
63 $this->tempDirManager = Shellbox::createTempDirManager(
64 $this->getConfig( 'tempDir' ) );
65 $this->tempDirManager->setLogger( $this->logger );
66
67 $this->processInput();
68 $this->execute( $pathParts );
69 } finally {
70 if ( $this->tempDirManager ) {
71 $this->tempDirManager->teardown();
72 }
73 }
74 }
75
76 /**
77 * Override this to implement the action.
78 *
79 * @param string[] $pathParts
80 */
81 abstract protected function execute( $pathParts );
82
83 /**
84 * Override this to provide the action name as used in the URL.
85 *
86 * @return string
87 */
88 abstract protected function getActionName();
89
90 /**
91 * Get a parameter from the request, or throw if it isn't present
92 *
93 * @param string $name
94 * @return mixed
95 * @throws ShellboxError
96 */
97 protected function getRequiredParam( $name ) {
98 $nonexistent = new \stdClass;
99 $result = $this->getParam( $name, $nonexistent );
100 if ( $result === $nonexistent ) {
101 $this->error( "The $name parameter is required" );
102 }
103 return $result;
104 }
105
106 /**
107 * Get a parameter from the request. Return the specified default if it
108 * isn't present.
109 *
110 * @param string $name
111 * @param mixed $default
112 * @return mixed
113 */
114 protected function getParam( $name, $default = null ) {
115 return $this->structuredData[$name] ?? $this->binaryData[$name] ?? $default;
116 }
117
118 /**
119 * Get a configuration option, or throw if it doesn't exist.
120 *
121 * @param string $name
122 * @return mixed
123 * @throws ShellboxError
124 */
125 protected function getConfig( $name ) {
126 return $this->server->getConfig( $name );
127 }
128
129 /**
130 * Erase a configuration option
131 *
132 * @param string $name
133 */
134 protected function forgetConfig( $name ) {
135 $this->server->forgetConfig( $name );
136 }
137
138 /**
139 * Get a request header of a given name, or null if there was no such header.
140 *
141 * @param string $name
142 * @return string|null
143 */
144 protected function getHeader( $name ) {
145 if ( $this->headers === null ) {
146 $this->headers = array_change_key_case( getallheaders(), CASE_LOWER );
147 }
148 return $this->headers[strtolower( $name )] ?? null;
149 }
150
151 /**
152 * Throw an error exception
153 *
154 * @param string $message
155 * @param int $code
156 * @throws ShellboxError
157 * @return never
158 */
159 protected function error( $message, $code = 500 ) {
160 throw new ShellboxError( $message, $code );
161 }
162
163 /**
164 * Process the request. Read the POST data, do some generic validation,
165 * create input files and populate the parameter arrays.
166 */
167 private function processInput() {
168 if ( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
169 $this->error( 'The POST method must be used', 405 );
170 }
171 $auth = $this->getHeader( 'Authorization' );
172 if ( $auth === null ) {
173 $this->error( 'An Authorization header is required' );
174 }
175 // Phan doesn't understand functions that always throw, so thinks that
176 // $auth could still be null. Maybe fixable -- see comment in
177 // BlockExitStatusChecker::computeStatusOfCall().
178 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal
179 if ( !preg_match( '/^sha256 ([0-9a-z]+)$/', $auth, $m ) ) {
180 $this->error( 'Invalid Authorization header' );
181 }
182 $authHash = $m[1];
183
184 $ctype = $this->getHeader( 'Content-Type' );
185 if ( !preg_match( '/^multipart\/mixed/i', $ctype, $m ) ) {
186 $this->error( 'The Content-Type must be multipart/mixed', 415 );
187 }
188 $boundary = MultipartUtils::extractBoundary( $ctype );
189 if ( $boundary === false || $boundary === '' ) {
190 $this->error( 'boundary is a required parameter of Content-Type' );
191 }
192
193 $inputFile = FileUtils::openInputFile( 'php://input' );
194 $multipartReader = new MultipartReader(
195 new Stream( $inputFile ),
196 $boundary,
197 $this->getConfig( 'secretKey' ) );
198 $preamble = $multipartReader->readPreamble();
199
200 if ( trim( $preamble ) !== '' ) {
201 $this->error( 'The multipart preamble must be empty, otherwise a ' .
202 'fraudulent boundary with a replayed body could be used to send ' .
203 'unauthorized requests' );
204 }
205
206 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
207 while ( ( $headers = $multipartReader->readPartHeaders() ) !== false ) {
208 if ( !isset( $headers['content-disposition'] ) ) {
209 $this->error( 'Part has no Content-Disposition', 400 );
210 }
211 $disposition = $headers['content-disposition'];
212 if ( $disposition['type'] === 'json-data' ) {
213 $this->structuredData = $multipartReader->readPartAsJson( $headers );
214 } elseif ( $disposition['type'] === 'form-data' ) {
215 if ( !isset( $disposition['name'] ) ) {
216 $this->error( "multipart form-data requires name" );
217 }
218 $name = $disposition['name'];
219 $this->binaryData[$name] = $multipartReader->readPartAsString();
220 } elseif ( $disposition['type'] === 'attachment' ) {
221 $this->processFile( $multipartReader, $headers );
222 } else {
223 $this->error( "Unknown content disposition type" );
224 }
225 }
226 $multipartReader->readEpilogue();
227
228 if ( $this->getRequiredParam( 'action' ) !== $this->getActionName() ) {
229 $this->error( "The URL action must match the HMAC-verified parameter" );
230 }
231
232 if ( !hash_equals( $multipartReader->getHash(), $authHash ) ) {
233 $this->error( "HMAC signature verification failed" );
234 }
235 }
236
237 /**
238 * Extract a single file from the MultipartReader
239 *
240 * @param MultipartReader $multipartReader
241 * @param array $headers The part headers
242 */
243 private function processFile( $multipartReader, $headers ) {
244 if ( !isset( $headers['content-disposition']['filename'] ) ) {
245 $this->error( 'Part has no filename' );
246 }
247 $fileName = Shellbox::normalizePath( $headers['content-disposition']['filename'] );
248 $path = $this->tempDirManager->preparePath( $fileName );
249 $file = FileUtils::openOutputFile( $path );
250 $multipartReader->copyPartToStream( Utils::streamFor( $file ) );
251 $this->inputFiles[] = $fileName;
252 }
253
254 /**
255 * Write a standard result
256 *
257 * @param array $structuredData JSON serializable data
258 * @param string[] $binaryData An array of strings to be sent as multipart
259 * parts
260 * @param string[] $files The names of the output files relative to the
261 * working directory
262 */
263 protected function writeResult( $structuredData, $binaryData = [], $files = [] ) {
264 $boundary = Shellbox::getUniqueString();
265 header( "Content-Type: multipart/mixed; boundary=\"$boundary\"" );
266 $parts = [];
267
268 $structuredData['log'] = $this->server->flushLogBuffer();
269 $parts[] = [
270 'name' => 'json-data',
271 'headers' => [
272 'Content-Type' => 'application/json',
273 'Content-Disposition' => 'json-data',
274 ],
275 'contents' => Shellbox::jsonEncode( $structuredData )
276 ];
277 foreach ( $binaryData as $name => $value ) {
278 $parts[] = [
279 'name' => $name,
280 'contents' => $value
281 ];
282 }
283 foreach ( $files as $name ) {
284 // phpcs:ignore Generic.PHP.NoSilencedErrors
285 $stream = @fopen( $this->tempDirManager->getPath( $name ), 'r' );
286 if ( $stream ) {
287 $parts[] = [
288 'name' => $name,
289 'headers' => [
290 'Content-Type' => 'application/octet-stream',
291 'Content-Disposition' => "attachment; name=\"$name\""
292 ],
293 'contents' => Utils::streamFor( $stream )
294 ];
295 }
296 }
297 $multipartStream = new MultipartStream( $parts, $boundary );
298 while ( !$multipartStream->eof() ) {
299 echo $multipartStream->read( self::COPY_BUFFER_SIZE );
300 }
301 }
302
303 /**
304 * Get the names of the received files, relative to the temporary directory
305 *
306 * @return string[]
307 */
308 protected function getReceivedFileNames() {
309 return $this->inputFiles;
310 }
311 }