Skip to content
Open
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
20 changes: 20 additions & 0 deletions config/barstool.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,26 @@
// SensitiveRequest::class,
],

/*
* Query parameter names whose values are replaced with `REDACTED` in the stored URL.
* The outgoing request is not changed. Matching ignores case.
* Use '*' to redact every query value.
*/
'excluded_query_parameters' => [
'access_token',
'api_key',
'api-key',
'apikey',
'client_secret',
'id_token',
'password',
'refresh_token',
'secret',
'sig',
'signature',
'token',
],

/*
* Queue configuration for recording.
* When enabled, recordings will be dispatched as queued jobs
Expand Down
79 changes: 74 additions & 5 deletions src/Barstool.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

namespace Saloon\Barstool;

use GuzzleHttp\Psr7\Uri;
use Saloon\Http\Response;
use GuzzleHttp\Psr7\Query;
use Illuminate\Support\Str;
use Saloon\Http\PendingRequest;
use Psr\Http\Message\UriInterface;
Expand All @@ -20,6 +22,26 @@ class Barstool
{
private const string CONTEXT_KEY = 'barstool:context';

/**
* Query parameter names whose values are credentials.
*
* @var list<string>
*/
private const array DEFAULT_EXCLUDED_QUERY_PARAMETERS = [
'access_token',
'api_key',
'api-key',
'apikey',
'client_secret',
'id_token',
'password',
'refresh_token',
'secret',
'sig',
'signature',
'token',
];

/**
* Merge the given key/value pairs into the Barstool context.
*
Expand Down Expand Up @@ -150,7 +172,7 @@ private static function getRequestData(PendingRequest $request): array
'connector_class' => get_class($request->getConnector()),
'request_class' => get_class($request->getRequest()),
'method' => $request->getMethod()->value,
'url' => $request->getUrl(),
'url' => self::redactUrl($request->getUrl()),
'request_headers' => self::getRequestHeaders($request),
'request_body' => $body,
'successful' => false,
Expand All @@ -169,7 +191,7 @@ private static function getRequestData(PendingRequest $request): array

/**
* @return array{
* url: UriInterface,
* url: string,
* response_headers: array<string, mixed>,
* response_body: string,
* response_status: int,
Expand All @@ -181,7 +203,7 @@ private static function getResponseData(Response $response): array
$responseBody = self::getResponseBody($response);

return [
'url' => $response->getPsrRequest()->getUri(),
'url' => self::redactUrl($response->getPsrRequest()->getUri()),
'response_headers' => self::getResponseHeaders($response),
'response_body' => $responseBody,
'response_status' => $response->status(),
Expand Down Expand Up @@ -219,7 +241,7 @@ public static function getResponseHeaders(Response $response): array

/**
* @return array{
* url: UriInterface,
* url: string,
* response_headers: null,
* response_body: null,
* response_status: null,
Expand All @@ -230,7 +252,7 @@ public static function getResponseHeaders(Response $response): array
private static function getFatalData(FatalRequestException $exception): array
{
return [
'url' => $exception->getPendingRequest()->getUri(),
'url' => self::redactUrl($exception->getPendingRequest()->getUri()),
'response_headers' => null,
'response_body' => null,
'response_status' => null,
Expand Down Expand Up @@ -350,6 +372,53 @@ private static function supportedContentTypes(): array
];
}

/**
* Replace credential query values and URL user info before the URL is stored.
*
* The outgoing request is left unchanged. Names in `excluded_query_parameters`
* are matched without regard to case. `*` redacts every query value.
*/
private static function redactUrl(string|UriInterface $url): string
{
$uri = new Uri((string) $url);
$userInfo = $uri->getUserInfo();

if ($userInfo !== '') {
$uri = str_contains($userInfo, ':')
? $uri->withUserInfo('REDACTED', 'REDACTED')
: $uri->withUserInfo('REDACTED');
}

if ($uri->getQuery() === '') {
return (string) $uri;
}

$excluded = config('barstool.excluded_query_parameters', self::DEFAULT_EXCLUDED_QUERY_PARAMETERS);

if (! is_array($excluded)) {
return (string) $uri;
}

$excluded = array_map(
static fn (mixed $parameter): string => mb_strtolower((string) $parameter),
$excluded,
);
$redactAll = in_array('*', $excluded, true);
$parameters = Query::parse($uri->getQuery());

foreach ($parameters as $name => $value) {
if (! $redactAll && ! in_array(mb_strtolower((string) $name), $excluded, true)) {
continue;
}

$parameters[$name] = is_array($value)
? array_map(static fn (): string => 'REDACTED', $value)
: 'REDACTED';
}

return (string) $uri->withQuery(Query::build($parameters));
}

/**
* @return array<string, string>|null
*/
Expand Down
64 changes: 64 additions & 0 deletions tests/BarstoolTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1260,3 +1260,67 @@

expect(BarstoolRecorder::calculateDuration($pendingRequest))->toBe(1);
});

it('redacts credential query parameters in the stored url', function () {
config()->set('barstool.enabled', true);

$mock = MockClient::global([
SoloUserRequest::class => MockResponse::make(
body: ['data' => 'ok'],
status: 200,
),
]);

$request = new SoloUserRequest;
$request->query()->add('access_token', 'query-access-secret');
$request->query()->add('API_KEY', 'query-api-secret');
$request->query()->add('account_id', 'acc_123');
$request->send();

$url = Barstool::sole()->url;

expect($url)->not->toContain('query-access-secret')
->and($url)->not->toContain('query-api-secret')
->and($url)->toContain('access_token=REDACTED')
->and($url)->toContain('API_KEY=REDACTED')
->and($url)->toContain('account_id=acc_123');

$sent = $mock->getLastPendingRequest();

expect($sent)->not->toBeNull()
->and($sent->query()->get('access_token'))->toBe('query-access-secret')
->and($sent->query()->get('API_KEY'))->toBe('query-api-secret')
->and($sent->query()->get('account_id'))->toBe('acc_123');
});

it('redacts credentials in the stored url user info', function () {
config()->set('barstool.enabled', true);

$pendingRequest = (new SoloUserRequest)->createPendingRequest();
$pendingRequest->setUrl('https://alice:secret-pass@tests.saloon.dev/api/user');

BarstoolRecorder::record($pendingRequest);

$url = Barstool::query()->latest('id')->value('url');

expect($url)->not->toContain('alice')
->and($url)->not->toContain('secret-pass')
->and($url)->toContain('REDACTED:REDACTED@tests.saloon.dev/api/user');
});

it('redacts a credential query parameter when a connection error is recorded', function () {
config()->set('barstool.enabled', true);

$request = new SoloUserRequest;
$request->query()->add('access_token', 'query-access-secret');

$pendingRequest = $request->createPendingRequest();
$connectionError = new FatalRequestException(new RuntimeException('connection refused'), $pendingRequest);

$pendingRequest->executeFatalPipeline($connectionError);

$url = Barstool::query()->latest('id')->value('url');

expect($url)->not->toContain('query-access-secret')
->and($url)->toContain('access_token=REDACTED');
});
Loading