Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions config/nightwatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
'deployment' => env('NIGHTWATCH_DEPLOY'),
'server' => env('NIGHTWATCH_SERVER', (string) gethostname()),
'capture_exception_source_code' => env('NIGHTWATCH_CAPTURE_EXCEPTION_SOURCE_CODE', true),
'capture_request_payload' => env('NIGHTWATCH_CAPTURE_REQUEST_PAYLOAD', false),
'redact_payload_fields' => explode(',', env('NIGHTWATCH_REDACT_PAYLOAD_FIELDS', '_token,password,password_confirmation')),
'redact_headers' => explode(',', env('NIGHTWATCH_REDACT_HEADERS', 'Authorization,Cookie,Proxy-Authorization,X-XSRF-TOKEN')),

'sampling' => [
Expand Down
4 changes: 4 additions & 0 deletions src/NightwatchServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ final class NightwatchServiceProvider extends ServiceProvider
* server?: string,
* ingest?: array{ uri?: string, timeout?: float|int, connection_timeout?: float|int, event_buffer?: int },
* capture_exception_source_code?: bool,
* capture_request_payload?: bool,
* redact_payload_fields?: string[],
* redact_headers?: string[],
* }
*/
Expand Down Expand Up @@ -252,6 +254,8 @@ private function buildAndRegisterCore(): void
publicPath: $this->app->publicPath(),
),
captureExceptionSourceCode: (bool) ($this->nightwatchConfig['capture_exception_source_code'] ?? true),
captureRequestPayload: (bool) ($this->nightwatchConfig['capture_request_payload'] ?? false),
redactPayloadFields: $this->nightwatchConfig['redact_payload_fields'] ?? ['_token', 'password', 'password_confirmation'],
redactHeaders: $this->nightwatchConfig['redact_headers'] ?? ['Authorization', 'Cookie', 'Proxy-Authorization', 'X-XSRF-TOKEN'],
config: $this->config,
),
Expand Down
4 changes: 4 additions & 0 deletions src/Records/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace Laravel\Nightwatch\Records;

use Symfony\Component\HttpFoundation\FileBag;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\InputBag;

final class Request
{
Expand All @@ -23,6 +25,8 @@ public function __construct(
public readonly int $requestSize,
public readonly int $responseSize,
public HeaderBag $headers,
public InputBag $payload,
public FileBag $files,
) {
//
}
Expand Down
5 changes: 5 additions & 0 deletions src/SensorManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,16 @@ final class SensorManager
public $commandSensor;

/**
* @param list<string> $redactPayloadFields
* @param list<string> $redactHeaders
*/
public function __construct(
private RequestState|CommandState $executionState,
private Clock $clock,
public Location $location,
private bool $captureExceptionSourceCode,
private bool $captureRequestPayload,
private array $redactPayloadFields,
private array $redactHeaders,
private Repository $config,
) {
Expand All @@ -158,6 +161,8 @@ public function request(Request $request, Response $response): array
{
$sensor = $this->requestSensor ??= new RequestSensor(
requestState: $this->executionState, // @phpstan-ignore argument.type
capturePayload: $this->captureRequestPayload,
redactPayloadFields: $this->redactPayloadFields,
redactHeaders: $this->redactHeaders,
);

Expand Down
88 changes: 87 additions & 1 deletion src/Sensors/RequestSensor.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Support\Arr;
use Laravel\Nightwatch\Concerns\RecordsContext;
use Laravel\Nightwatch\Concerns\RedactsHeaders;
use Laravel\Nightwatch\ExecutionStage;
Expand All @@ -12,12 +13,17 @@
use Laravel\Nightwatch\State\RequestState;
use Laravel\Nightwatch\Types\Str;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

use function array_map;
use function array_sum;
use function assert;
use function hash;
use function implode;
use function in_array;
use function is_array;
use function is_int;
use function is_numeric;
use function is_string;
Expand All @@ -36,10 +42,13 @@ final class RequestSensor
use RedactsHeaders;

/**
* @param list<string> $redactPayloadFields
* @param list<string> $redactHeaders
*/
public function __construct(
private RequestState $requestState,
private bool $capturePayload,
private array $redactPayloadFields,
private array $redactHeaders,
) {
//
Expand Down Expand Up @@ -93,8 +102,10 @@ public function __invoke(Request $request, Response $response): array
$headers->remove('php-auth-pw');
$headers->remove('php-auth-digest');
}),
payload: clone $request->request,
files: clone $request->files,
),
function () use ($record) {
function () use ($request, $response, $record) {
return [
'v' => 1,
't' => 'request',
Expand Down Expand Up @@ -149,6 +160,7 @@ static function ($e) {
return false;
},
),
'payload' => $this->serializePayload($request, $response, $record),
];
},
];
Expand Down Expand Up @@ -179,4 +191,78 @@ private function parseResponseSize(Response $response): int
// streamed response, e.g., echo Nightwatch::streaming($content);
return 0;
}

private function serializePayload(Request $request, Response $response, RequestRecord $record): string
{
if ($response->getStatusCode() !== 500) {
return '';
}

if (in_array($request->getMethod(), ['GET', 'HEAD', 'OPTIONS', 'TRACE'], true) && $record->payload->count() === 0 && $record->files->count() === 0) {
return '';
}

if (! $this->capturePayload) {
return '{"_nightwatch_error":"NOT_ENABLED"}';
}

if (! $this->isSupportedContentType($request) && $record->payload->count() === 0 && $record->files->count() === 0) {
return '{"_nightwatch_error":"UNSUPPORTED_CONTENT_TYPE"}';
}

return Str::text(rescue(
fn () => json_encode([
...$this->redactRecursively($record->payload->all()),
'_nightwatch_files' => $this->mapUploadedFilesRecursively($record->files->all()),
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION),
'{"_nightwatch_error":"SERIALIZATION_FAILED"}',
static function ($e) {
Nightwatch::unrecoverableExceptionOccurred($e);

return false;
}
));
}

private function isSupportedContentType(Request $request): bool
{
return $request->isJson()
|| in_array($request->headers->get('content-type'), ['application/x-www-form-urlencoded', 'multipart/form-data'], true);
}

/**
* @param array<mixed> $array
* @return array<mixed>
*/
private function redactRecursively(array $array): array
{
return Arr::map($array, function ($value, $key) {
if (is_array($value)) {
return $this->redactRecursively($value);
}

return ! in_array($key, $this->redactPayloadFields, true) || ! is_string($value) ? $value : '['.strlen($value).' bytes redacted]';
});
}

/**
* @param array<mixed> $files
* @return array<mixed>
*/
private function mapUploadedFilesRecursively(array $files): array
{
return array_map(function ($file) {
if (is_array($file)) {
return $this->mapUploadedFilesRecursively($file);
}

assert($file instanceof UploadedFile);

return [
'originalName' => $file->getClientOriginalName(),
'size' => $file->getSize(),
'error' => $file->getError(),
];
}, $files);
}
}
Loading