Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Exceptions/Handler.php
7432 views
1
<?php
2
3
namespace Pterodactyl\Exceptions;
4
5
use Exception;
6
use Illuminate\Support\Arr;
7
use Illuminate\Support\Str;
8
use Illuminate\Http\JsonResponse;
9
use Illuminate\Support\Collection;
10
use Illuminate\Container\Container;
11
use Illuminate\Database\Connection;
12
use Illuminate\Http\RedirectResponse;
13
use Illuminate\Foundation\Application;
14
use Illuminate\Auth\AuthenticationException;
15
use Illuminate\Session\TokenMismatchException;
16
use Illuminate\Validation\ValidationException;
17
use Symfony\Component\HttpFoundation\Response;
18
use Illuminate\Auth\Access\AuthorizationException;
19
use Illuminate\Database\Eloquent\ModelNotFoundException;
20
use Symfony\Component\HttpKernel\Exception\HttpException;
21
use Symfony\Component\Mailer\Exception\TransportException;
22
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
23
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
24
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
25
26
class Handler extends ExceptionHandler
27
{
28
/**
29
* The validation parser in Laravel formats custom rules using the class name
30
* resulting in some weird rule names. This string will be parsed out and
31
* replaced with 'p_' in the response code.
32
*/
33
private const PTERODACTYL_RULE_STRING = 'pterodactyl\_rules\_';
34
35
/**
36
* A list of the exception types that should not be reported.
37
*/
38
protected $dontReport = [
39
AuthenticationException::class,
40
AuthorizationException::class,
41
HttpException::class,
42
ModelNotFoundException::class,
43
RecordNotFoundException::class,
44
TokenMismatchException::class,
45
ValidationException::class,
46
];
47
48
/**
49
* Maps exceptions to a specific response code. This handles special exception
50
* types that don't have a defined response code.
51
*/
52
protected static array $exceptionResponseCodes = [
53
AuthenticationException::class => 401,
54
AuthorizationException::class => 403,
55
ValidationException::class => 422,
56
];
57
58
/**
59
* A list of the inputs that are never flashed for validation exceptions.
60
*/
61
protected $dontFlash = [
62
'token',
63
'secret',
64
'password',
65
'password_confirmation',
66
];
67
68
/**
69
* Registers the exception handling callbacks for the application. This
70
* will capture specific exception types that we do not want to include
71
* the detailed stack traces for since they could reveal credentials to
72
* whoever can read the logs.
73
*
74
* @noinspection PhpUnusedLocalVariableInspection
75
*/
76
public function register(): void
77
{
78
if (config('app.exceptions.report_all', false)) {
79
$this->dontReport = [];
80
}
81
82
$this->reportable(function (\PDOException $ex) {
83
$ex = $this->generateCleanedExceptionStack($ex);
84
});
85
86
$this->reportable(function (TransportException $ex) {
87
$ex = $this->generateCleanedExceptionStack($ex);
88
});
89
}
90
91
private function generateCleanedExceptionStack(\Throwable $exception): string
92
{
93
$cleanedStack = '';
94
foreach ($exception->getTrace() as $index => $item) {
95
$cleanedStack .= sprintf(
96
"#%d %s(%d): %s%s%s\n",
97
$index,
98
Arr::get($item, 'file'),
99
Arr::get($item, 'line'),
100
Arr::get($item, 'class'),
101
Arr::get($item, 'type'),
102
Arr::get($item, 'function')
103
);
104
}
105
106
$message = sprintf(
107
'%s: %s in %s:%d',
108
class_basename($exception),
109
$exception->getMessage(),
110
$exception->getFile(),
111
$exception->getLine()
112
);
113
114
return $message . "\nStack trace:\n" . trim($cleanedStack);
115
}
116
117
/**
118
* Render an exception into an HTTP response.
119
*
120
* @param \Illuminate\Http\Request $request
121
*
122
* @throws \Throwable
123
*/
124
public function render($request, \Throwable $e): Response
125
{
126
$connections = $this->container->make(Connection::class);
127
128
// If we are currently wrapped up inside a transaction, we will roll all the way
129
// back to the beginning. This needs to happen, otherwise session data does not
130
// get properly persisted.
131
//
132
// This is kind of a hack, and ideally things like this should be handled as
133
// much as possible at the code level, but there are a lot of spots that do a
134
// ton of actions and were written before this bug discovery was made.
135
//
136
// @see https://github.com/pterodactyl/panel/pull/1468
137
if ($connections->transactionLevel()) {
138
$connections->rollBack(0);
139
}
140
141
return parent::render($request, $e);
142
}
143
144
/**
145
* Transform a validation exception into a consistent format to be returned for
146
* calls to the API.
147
*
148
* @param \Illuminate\Http\Request $request
149
*/
150
public function invalidJson($request, ValidationException $exception): JsonResponse
151
{
152
$codes = Collection::make($exception->validator->failed())->mapWithKeys(function ($reasons, $field) {
153
$cleaned = [];
154
foreach ($reasons as $reason => $attrs) {
155
$cleaned[] = Str::snake($reason);
156
}
157
158
return [str_replace('.', '_', $field) => $cleaned];
159
})->toArray();
160
161
$errors = Collection::make($exception->errors())->map(function ($errors, $field) use ($codes, $exception) {
162
$response = [];
163
foreach ($errors as $key => $error) {
164
$meta = [
165
'source_field' => $field,
166
'rule' => str_replace(self::PTERODACTYL_RULE_STRING, 'p_', Arr::get(
167
$codes,
168
str_replace('.', '_', $field) . '.' . $key
169
)),
170
];
171
172
$converted = $this->convertExceptionToArray($exception)['errors'][0];
173
$converted['detail'] = $error;
174
$converted['meta'] = array_merge($converted['meta'] ?? [], $meta);
175
176
$response[] = $converted;
177
}
178
179
return $response;
180
})->flatMap(function ($errors) {
181
return $errors;
182
})->toArray();
183
184
return response()->json(['errors' => $errors], $exception->status);
185
}
186
187
/**
188
* Return the exception as a JSONAPI representation for use on API requests.
189
*/
190
protected function convertExceptionToArray(\Throwable $e, array $override = []): array
191
{
192
$match = self::$exceptionResponseCodes[get_class($e)] ?? null;
193
194
$error = [
195
'code' => class_basename($e),
196
'status' => method_exists($e, 'getStatusCode')
197
? strval($e->getStatusCode())
198
: strval($match ?? '500'),
199
'detail' => $e instanceof HttpExceptionInterface || !is_null($match)
200
? $e->getMessage()
201
: 'An unexpected error was encountered while processing this request, please try again.',
202
];
203
204
if ($e instanceof ModelNotFoundException || $e->getPrevious() instanceof ModelNotFoundException) {
205
// Show a nicer error message compared to the standard "No query results for model"
206
// response that is normally returned. If we are in debug mode this will get overwritten
207
// with a more specific error message to help narrow down things.
208
$error['detail'] = 'The requested resource could not be found on the server.';
209
}
210
211
if (config('app.debug')) {
212
$error = array_merge($error, [
213
'detail' => $e->getMessage(),
214
'source' => [
215
'line' => $e->getLine(),
216
'file' => str_replace(Application::getInstance()->basePath(), '', $e->getFile()),
217
],
218
'meta' => [
219
'trace' => Collection::make($e->getTrace())
220
->map(fn ($trace) => Arr::except($trace, ['args']))
221
->all(),
222
'previous' => Collection::make($this->extractPrevious($e))
223
->map(fn ($exception) => $e->getTrace())
224
->map(fn ($trace) => Arr::except($trace, ['args']))
225
->all(),
226
],
227
]);
228
}
229
230
return ['errors' => [array_merge($error, $override)]];
231
}
232
233
/**
234
* Return an array of exceptions that should not be reported.
235
*/
236
public static function isReportable(\Exception $exception): bool
237
{
238
return (new static(Container::getInstance()))->shouldReport($exception);
239
}
240
241
/**
242
* Convert an authentication exception into an unauthenticated response.
243
*
244
* @param \Illuminate\Http\Request $request
245
*/
246
protected function unauthenticated($request, AuthenticationException $exception): JsonResponse|RedirectResponse
247
{
248
if ($request->expectsJson()) {
249
return new JsonResponse($this->convertExceptionToArray($exception), JsonResponse::HTTP_UNAUTHORIZED);
250
}
251
252
return redirect()->guest('/auth/login');
253
}
254
255
/**
256
* Extracts all the previous exceptions that lead to the one passed into this
257
* function being thrown.
258
*
259
* @return \Throwable[]
260
*/
261
protected function extractPrevious(\Throwable $e): array
262
{
263
$previous = [];
264
while ($value = $e->getPrevious()) {
265
if (!$value instanceof \Throwable) {
266
break;
267
}
268
$previous[] = $value;
269
$e = $value;
270
}
271
272
return $previous;
273
}
274
275
/**
276
* Helper method to allow reaching into the handler to convert an exception
277
* into the expected array response type.
278
*/
279
public static function toArray(\Throwable $e): array
280
{
281
return (new self(app()))->convertExceptionToArray($e);
282
}
283
}
284
285