diff --git a/app/Http/Controllers/PaymentGatewayWebHookController.php b/app/Http/Controllers/PaymentGatewayWebHookController.php index d133b25a33..0bc9860155 100644 --- a/app/Http/Controllers/PaymentGatewayWebHookController.php +++ b/app/Http/Controllers/PaymentGatewayWebHookController.php @@ -27,6 +27,7 @@ use models\exceptions\ValidationException; use Exception; use OpenApi\Attributes as OA; +use Stripe\Exception\SignatureVerificationException; /** * Class PaymentGatewayWebHookController @@ -179,6 +180,11 @@ public function genericConfirm($application_type, LaravelRequest $request){ Log::warning($ex); return $this->error412(["error" => 'payload error']); } + catch (SignatureVerificationException $ex){ + // message only: the trace carries the webhook signing secret (verifyHeader() argument) + Log::warning(sprintf("PaymentGatewayWebHookController::genericConfirm application_type %s invalid signature: %s", $application_type, $ex->getMessage())); + return $this->error400(["error" => 'payload error']); + } catch (Exception $ex){ Log::error($ex); return $this->error400(["error" => 'payload error']); @@ -289,6 +295,11 @@ public function confirm($summit_id, $application_type, LaravelRequest $request){ Log::warning($ex); return $this->error412(["error" => 'payload error']); } + catch (SignatureVerificationException $ex){ + // message only: the trace carries the webhook signing secret (verifyHeader() argument) + Log::warning(sprintf("PaymentGatewayWebHookController::confirm summit %s application_type %s invalid signature: %s", $summit_id, $application_type, $ex->getMessage())); + return $this->error400(["error" => 'payload error']); + } catch (Exception $ex){ Log::error($ex); return $this->error400(["error" => 'payload error']); diff --git a/app/Jobs/Payments/CreatePaymentProfileMQJob.php b/app/Jobs/Payments/CreatePaymentProfileMQJob.php index 23504f2153..556bab7f0c 100644 --- a/app/Jobs/Payments/CreatePaymentProfileMQJob.php +++ b/app/Jobs/Payments/CreatePaymentProfileMQJob.php @@ -22,6 +22,7 @@ use Illuminate\Support\Facades\Log; use models\summit\IPaymentConstants; use models\summit\ISummitRepository; +use models\summit\PaymentGatewayProfile; use models\summit\Summit; class CreatePaymentProfileMQJob implements ShouldQueue @@ -67,13 +68,13 @@ public function handle(PaymentsMQJob $job): void{ return; } $response = $this->payments_api->getPaymentProfile($summit_id, $id); - Log::debug("CreatePaymentProfileMQJob::handle", ['response' => $response]); + Log::debug("CreatePaymentProfileMQJob::handle", ['response' => PaymentGatewayProfile::toLogContext($response)]); $summit = $this->summit_repository->getById($summit_id); if($summit instanceof Summit) { // mappings $response['external_id'] = $id; $response['active'] = $response['is_active'] ?? false; - Log::debug("CreatePaymentProfileMQJob::handle creating payment profile", ['response' => $response ]); + Log::debug("CreatePaymentProfileMQJob::handle creating payment profile", ['response' => PaymentGatewayProfile::toLogContext($response)]); $this->service->addPaymentProfile($summit, $response); } $job->delete(); diff --git a/app/Jobs/Payments/UpdatePaymentProfileMQJob.php b/app/Jobs/Payments/UpdatePaymentProfileMQJob.php index d27461846d..44286616de 100644 --- a/app/Jobs/Payments/UpdatePaymentProfileMQJob.php +++ b/app/Jobs/Payments/UpdatePaymentProfileMQJob.php @@ -75,7 +75,7 @@ public function handle(PaymentsMQJob $job): void{ return; } $response = $this->payments_api->getPaymentProfile($summit_id, $id); - Log::debug("UpdatePaymentProfileMQJob::handle", ['response' => $response]); + Log::debug("UpdatePaymentProfileMQJob::handle", ['response' => PaymentGatewayProfile::toLogContext($response)]); $summit = $this->summit_repository->getById($summit_id); $local_payment_profile =$this->payment_gateway_profile_repository->getByExternalId($id); if($summit instanceof Summit) { @@ -90,11 +90,11 @@ public function handle(PaymentsMQJob $job): void{ else{ Log::warning("UpdatePaymentProfileMQJob::handle local profile does not exists ..."); $response = $this->payments_api->getPaymentProfile($summit_id, $id); - Log::debug("UpdatePaymentProfileMQJob::handle get from payment api", ['response' => $response]); + Log::debug("UpdatePaymentProfileMQJob::handle get from payment api", ['response' => PaymentGatewayProfile::toLogContext($response)]); // mappings $response['external_id'] = $id; $response['active'] = $response['is_active'] ?? false; - Log::debug("UpdatePaymentProfileMQJob::handle creating payment profile", ['response' => $response ]); + Log::debug("UpdatePaymentProfileMQJob::handle creating payment profile", ['response' => PaymentGatewayProfile::toLogContext($response)]); $this->service->addPaymentProfile($summit, $response); } } diff --git a/app/Models/Foundation/Summit/Factories/PaymentGatewayProfileFactory.php b/app/Models/Foundation/Summit/Factories/PaymentGatewayProfileFactory.php index 632d339fe3..efbc62bf3b 100644 --- a/app/Models/Foundation/Summit/Factories/PaymentGatewayProfileFactory.php +++ b/app/Models/Foundation/Summit/Factories/PaymentGatewayProfileFactory.php @@ -28,7 +28,7 @@ final class PaymentGatewayProfileFactory */ public static function build(string $provider, array $params): ?PaymentGatewayProfile { - Log::debug("PaymentGatewayProfileFactory::build()", ['provider' => $provider, 'params' => $params]); + Log::debug("PaymentGatewayProfileFactory::build()", ['provider' => $provider, 'params' => PaymentGatewayProfile::toLogContext($params)]); return static::populate(static::create($provider), $params); } diff --git a/app/Models/Foundation/Summit/Registration/Payment/PaymentGatewayProfile.php b/app/Models/Foundation/Summit/Registration/Payment/PaymentGatewayProfile.php index e27ffd214c..056e7138c9 100644 --- a/app/Models/Foundation/Summit/Registration/Payment/PaymentGatewayProfile.php +++ b/app/Models/Foundation/Summit/Registration/Payment/PaymentGatewayProfile.php @@ -328,6 +328,36 @@ public function setTestMode(): void abstract public function buildWebHook(): void; + /** + * Fields of a payment profile payload that can be logged. API keys and webhook secrets + * are never among them. + */ + const LoggableFields = [ + 'id', + 'external_id', + 'provider', + 'application_type', + 'active', + 'is_active', + 'test_mode_enabled', + 'send_email_receipt', + 'set_webhooks', + ]; + + /** + * Returns only the loggable fields of a payment profile payload (as sent by the admin API or + * returned by purchases-api), so the payload can be logged without its keys. Anything that + * is not an array, such as the null PaymentsApi::getPaymentProfile() returns on a 404, gives + * an empty context: logging must never be what makes a caller fail. + * @param mixed $payload + * @return array + */ + public static function toLogContext(mixed $payload): array + { + if (!is_array($payload)) return []; + return array_intersect_key($payload, array_flip(self::LoggableFields)); + } + /** * Deletes at the payment gateway every webhook that this in-memory instance created itself. * Called when the transaction meant to persist the profile fails: the DB rollback cannot diff --git a/app/Models/Foundation/Summit/Registration/Payment/StripePaymentProfile.php b/app/Models/Foundation/Summit/Registration/Payment/StripePaymentProfile.php index 184dad1fde..e095c7186a 100644 --- a/app/Models/Foundation/Summit/Registration/Payment/StripePaymentProfile.php +++ b/app/Models/Foundation/Summit/Registration/Payment/StripePaymentProfile.php @@ -116,7 +116,7 @@ public function getTestWebhookSecretKey(): ?string */ public function setLiveWebHookData(array $webhook_data): void { - Log::debug(sprintf("StripePaymentProfile::setLiveWebHookData payload %s", json_encode($webhook_data))); + Log::debug(sprintf("StripePaymentProfile::setLiveWebHookData id %s", $webhook_data['id'] ?? '')); $this->live_webhook_id = $webhook_data['id']; $this->live_webhook_secret_key = $webhook_data['secret_key']; @@ -127,7 +127,7 @@ public function setLiveWebHookData(array $webhook_data): void */ public function setTestWebHookData(array $webhook_data): void { - Log::debug(sprintf("StripePaymentProfile::setTestWebHookData payload %s", json_encode($webhook_data))); + Log::debug(sprintf("StripePaymentProfile::setTestWebHookData id %s", $webhook_data['id'] ?? '')); $this->test_webhook_id = $webhook_data['id']; $this->test_webhook_secret_key = $webhook_data['secret_key']; } diff --git a/app/Services/Apis/AbstractOAuth2Api.php b/app/Services/Apis/AbstractOAuth2Api.php index 8016c3cd9f..1a34f327df 100644 --- a/app/Services/Apis/AbstractOAuth2Api.php +++ b/app/Services/Apis/AbstractOAuth2Api.php @@ -138,7 +138,7 @@ protected function getAccessToken():?string{ $accessToken = $client->getAccessToken('client_credentials', ['scope' => $scopes]); $token = $accessToken->getToken(); $expires_in = $accessToken->getExpires() - time(); - Log::debug(sprintf("AbstractOAuth2Api::getAccessToken - setting new access token %s expires in %s", $token, $expires_in)); + Log::debug(sprintf("AbstractOAuth2Api::getAccessToken - setting new access token expires in %s", $expires_in)); $ttl = $expires_in - self::SkewTime; if($ttl < 0) $ttl = $expires_in; @@ -156,7 +156,7 @@ protected function getAccessToken():?string{ throw $ex; } } - Log::debug(sprintf("AbstractOAuth2Api::getAccessToken - returning access token %s", $token)); + Log::debug(sprintf("AbstractOAuth2Api::getAccessToken - returning access token (%s)", empty($token) ? 'empty' : 'set')); return $token; } diff --git a/app/Services/Apis/PaymentGateways/LawPayApi.php b/app/Services/Apis/PaymentGateways/LawPayApi.php index 2c855f55d5..d5d02179f2 100644 --- a/app/Services/Apis/PaymentGateways/LawPayApi.php +++ b/app/Services/Apis/PaymentGateways/LawPayApi.php @@ -69,8 +69,11 @@ public function __construct(array $config) ( sprintf ( - "LawPayApi::__construct config %s", - json_encode($config) + "LawPayApi::__construct account_id %s test_mode_enabled %s secret_key %s public_key %s", + $this->account_id, + json_encode($this->test_mode_enabled), + empty($this->secret_key) ? 'not set' : 'set', + empty($this->public_key) ? 'not set' : 'set' ) ); } @@ -93,7 +96,8 @@ public function preProcessOrder(SummitOrder $order): SummitOrder */ public function postProcessOrder(SummitOrder $order, array $payload = []):SummitOrder { - Log::debug(sprintf("LawPayApi::postProcessOrder order %s payload %s", $order->getId(), json_encode($payload))); + // the payload carries the one-time payment token (payment_method_id): log its keys only + Log::debug(sprintf("LawPayApi::postProcessOrder order %s payload keys %s", $order->getId(), implode(',', array_keys($payload)))); $summit_id = $order->getSummitId(); $token_id = $payload['payment_method_id'] ?? null; @@ -164,7 +168,8 @@ public function generatePayment(array $payload): array if (empty($this->public_key)) throw new \InvalidArgumentException(); - Log::debug(sprintf("LawPayApi::generatePayment payload %s ",json_encode($payload))); + // the payload carries the one-time payment token (token_id): leave it out + Log::debug(sprintf("LawPayApi::generatePayment amount %s metadata %s", $payload['amount'] ?? '', json_encode($payload['metadata'] ?? []))); try { ChargeIO::setCredentials(new ChargeIO_Credentials( $this->public_key, diff --git a/app/Services/Apis/PaymentGateways/StripeApi.php b/app/Services/Apis/PaymentGateways/StripeApi.php index 27c8cf5724..40ccffc0bd 100644 --- a/app/Services/Apis/PaymentGateways/StripeApi.php +++ b/app/Services/Apis/PaymentGateways/StripeApi.php @@ -72,13 +72,28 @@ public function __construct(array $config) ( sprintf ( - "StripeApi::__construct secret_key %s webhook_secret_key %s", - $this->secret_key, - $this->webhook_secret_key + "StripeApi::__construct secret_key %s (%s) webhook_secret_key %s", + empty($this->secret_key) ? 'not set' : 'set', + self::keyMode($this->secret_key), + empty($this->webhook_secret_key) ? 'not set' : 'set' ) ); } + /** + * Mode of a Stripe API key, read from its prefix, so logs can tell live from test calls + * without ever printing the key. + * @param string|null $key + * @return string + */ + private static function keyMode(?string $key): string + { + if (empty($key)) return 'none'; + if (str_contains($key, '_live_')) return 'live'; + if (str_contains($key, '_test_')) return 'test'; + return 'unknown'; + } + /** * @param string $webhook_secret_key */ @@ -92,7 +107,7 @@ public function setWebHookSecretKey(string $webhook_secret_key):void{ */ private function extractPaymentMethodInfo(array $stripeObject): array { - Log::debug(sprintf("StripeApi::extractPaymentMethodInfo %s", json_encode($stripeObject))); + Log::debug(sprintf("StripeApi::extractPaymentMethodInfo %s %s", $stripeObject['object'] ?? '', $stripeObject['id'] ?? '')); $isIntent = $stripeObject['object'] === 'payment_intent'; $charge = null; @@ -248,10 +263,10 @@ public function processCallback(LaravelRequest $request): array ( sprintf ( - "StripeApi::processCallback Stripe-Signature %s requestContent %s webHook Secret %s", - $signature, - $requestContent, - $this->webhook_secret_key + "StripeApi::processCallback body %s bytes Stripe-Signature %s webhook_secret_key %s", + strlen($requestContent), + empty($signature) ? 'missing' : 'present', + empty($this->webhook_secret_key) ? 'not set' : 'set' ) ); @@ -262,6 +277,7 @@ public function processCallback(LaravelRequest $request): array ); $event = Event::constructFrom(json_decode($requestContent, true)); + Log::debug(sprintf("StripeApi::processCallback event %s type %s", $event->id, $event->type)); if (!in_array($event->type, ["payment_intent.succeeded", "payment_intent.payment_failed"])) throw new \InvalidArgumentException(); @@ -291,13 +307,11 @@ public function processCallback(LaravelRequest $request): array } throw new ValidationException(sprintf("event type %s not handled!", $event->type)); - } catch (\UnexpectedValueException $e) { - Log::warning($e); - // Invalid payload - throw $e; - } catch (SignatureVerificationException $e) { - Log::warning($e); - // Invalid signature + } catch (\UnexpectedValueException|SignatureVerificationException $e) { + // Invalid payload or signature. Log the message only: the trace of an exception + // thrown by WebhookSignature::verifyHeader() carries its arguments, the webhook + // signing secret among them. + Log::warning(sprintf("StripeApi::processCallback %s: %s", get_class($e), $e->getMessage())); throw $e; } catch (\Exception $e) { Log::warning($e); @@ -475,7 +489,7 @@ public function getCartStatus(string $cart_id): ?string if (is_null($intent)) throw new \InvalidArgumentException(); - Log::debug(sprintf("StripeApi::getCartStatus calling cart_id %s intent %s", $cart_id, json_encode($intent))); + Log::debug(sprintf("StripeApi::getCartStatus cart_id %s intent %s status %s", $cart_id, $intent->id, $intent->status)); return $intent->status; } catch(Exception $ex){ @@ -506,7 +520,8 @@ public function createWebHook(string $webhook_endpoint_url): array ], ]); - Log::debug(sprintf("StripeApi::createWebHook webhook_endpoint_url %s res %s", $webhook_endpoint_url, $res->toJSON())); + // the response carries the endpoint signing secret: log only what identifies the endpoint + Log::debug(sprintf("StripeApi::createWebHook webhook_endpoint_url %s id %s livemode %s", $webhook_endpoint_url, $res->id, json_encode($res->livemode))); return [ 'id' => $res->id, @@ -532,7 +547,7 @@ public function getWebHookById(string $id){ $res = WebhookEndpoint::retrieve($id); if(!is_null($res)) - Log::debug(sprintf("StripeApi::getWebHookById id %s res %s", $id, $res->toJSON())); + Log::debug(sprintf("StripeApi::getWebHookById id %s url %s status %s", $id, $res->url, $res->status)); return $res; } @@ -629,7 +644,7 @@ public function getPaymentDetailsInfo(string $cart_id): ?array if (is_null($intent)) throw new \InvalidArgumentException(); - Log::debug(sprintf("StripeApi::getPaymentDetailsInfo pi %s ", json_encode($intent))); + Log::debug(sprintf("StripeApi::getPaymentDetailsInfo pi %s status %s", $intent->id, $intent->status)); return $this->extractPaymentMethodInfo($intent->toArray()); } diff --git a/app/Services/Auth/OAuth2ClientFactory.php b/app/Services/Auth/OAuth2ClientFactory.php index 3cd063804b..f8a44d6c11 100644 --- a/app/Services/Auth/OAuth2ClientFactory.php +++ b/app/Services/Auth/OAuth2ClientFactory.php @@ -34,7 +34,7 @@ public static function build(array $idpConfig, array $appConfig, string $redirec sprintf( "OAuth2ClientFactory::build client_id %s client_secret %s scopes %s", $client_id, - $client_secret, + empty($client_secret) ? 'not set' : 'set', $scopes ) ); diff --git a/app/Services/Model/Imp/PaymentGatewayProfileService.php b/app/Services/Model/Imp/PaymentGatewayProfileService.php index 0ed94dbc48..fcdd562a0b 100644 --- a/app/Services/Model/Imp/PaymentGatewayProfileService.php +++ b/app/Services/Model/Imp/PaymentGatewayProfileService.php @@ -45,7 +45,7 @@ public function addPaymentProfile(Summit $summit, array $payload): ?PaymentGatew $built_profiles = []; try { $profile = $this->tx_service->transaction(function () use ($summit, $payload, &$built_profiles) { - Log::debug("PaymentGatewayProfileService::addPaymentProfilee", ["summit" => $summit->getId(), 'payload' => $payload]); + Log::debug("PaymentGatewayProfileService::addPaymentProfilee", ["summit" => $summit->getId(), 'payload' => PaymentGatewayProfile::toLogContext($payload)]); $is_active = isset($payload['active']) && boolval($payload['active']) == true; // check before building the profile, so that a rejected one never reaches the gateway if ($is_active) { @@ -128,7 +128,7 @@ public function deletePaymentProfile(Summit $summit, int $child_id): void public function updatePaymentProfile(Summit $summit, int $child_id, array $payload): ?PaymentGatewayProfile { return $this->tx_service->transaction(function () use ($summit, $child_id, $payload) { - Log::debug("PaymentGatewayProfileService::updatePaymentProfile", ["summit" => $summit->getId(), "profile_id" => $child_id, "payload" => $payload]); + Log::debug("PaymentGatewayProfileService::updatePaymentProfile", ["summit" => $summit->getId(), "profile_id" => $child_id, "payload" => PaymentGatewayProfile::toLogContext($payload)]); $profile = $summit->getPaymentProfileById($child_id); if (is_null($profile)) throw new EntityNotFoundException(); diff --git a/tests/Unit/Services/PaymentSecretsLoggingTest.php b/tests/Unit/Services/PaymentSecretsLoggingTest.php new file mode 100644 index 0000000000..f341de9da4 --- /dev/null +++ b/tests/Unit/Services/PaymentSecretsLoggingTest.php @@ -0,0 +1,474 @@ + '0', 'zend.exception_string_param_max_len' => '1000000'] as $name => $value) { + $this->ini[$name] = ini_get($name); + ini_set($name, $value); + } + Facade::clearResolvedInstances(); + $this->app = new Container(); + $this->logger = new class extends AbstractLogger { + public array $lines = []; + + public function log($level, $message, array $context = []): void + { + $this->lines[] = $level . ' ' . (string)$message . ' ' . json_encode($context); + } + }; + $this->app->instance('log', $this->logger); + $this->app->instance('config', new Repository([])); + Container::setInstance($this->app); + Facade::setFacadeApplication($this->app); + } + + protected function tearDown(): void + { + foreach ($this->ini as $name => $value) { + ini_set($name, (string)$value); + } + ApiRequestor::setHttpClient(null); + Facade::setFacadeApplication(null); + Facade::clearResolvedInstances(); + Container::setInstance(null); + Mockery::close(); + parent::tearDown(); + } + + private function assertLogsDoNotContain(string ...$secrets): void + { + $this->assertNotEmpty($this->logger->lines, 'the code path under test logged nothing'); + foreach ($this->logger->lines as $line) { + foreach ($secrets as $secret) { + $this->assertStringNotContainsString($secret, $line, 'a secret was written to the log'); + } + } + } + + private function assertLogsContain(string $needle): void + { + foreach ($this->logger->lines as $line) { + if (str_contains($line, $needle)) { + $this->addToAssertionCount(1); + return; + } + } + $this->fail(sprintf('no log line mentions %s', $needle)); + } + + /** + * Routes the Stripe SDK to an in-memory client that answers every request with $body. + */ + private function fakeStripe(array $body): void + { + ApiRequestor::setHttpClient(new class($body) implements ClientInterface { + public function __construct(private array $body) + { + } + + public function request($method, $absUrl, $headers, $params, $hasFile) + { + return [json_encode($this->body), 200, []]; + } + }); + } + + private function paymentIntent(): array + { + return [ + 'id' => 'pi_leakcheck_intent', + 'object' => 'payment_intent', + 'status' => 'succeeded', + 'client_secret' => self::IntentClientSecret, + 'payment_method' => 'pm_leakcheck', + 'charges' => ['object' => 'list', 'data' => []], + ]; + } + + private function stripeApi(): StripeApi + { + return new StripeApi([ + 'secret_key' => self::StripeSecretKey, + 'webhook_secret_key' => self::StripeWebhookSecret, + ]); + } + + /** + * Payment profile as returned by purchases-api, which the sync jobs and the service receive. + */ + private function profilePayload(): array + { + return [ + 'id' => 5, + 'provider' => IPaymentConstants::ProviderStripe, + 'application_type' => IPaymentConstants::ApplicationTypeRegistration, + 'is_active' => false, + 'test_mode_enabled' => true, + 'live_secret_key' => self::ProfileLiveSecretKey, + 'live_publishable_key' => 'pk_live_public', + 'test_secret_key' => self::ProfileTestSecretKey, + 'test_publishable_key' => 'pk_test_public', + 'live_webhook_secret' => self::StripeWebhookSecret, + 'test_webhook_secret' => self::StripeWebhookSecret, + ]; + } + + public function testStripeApiConstructorDoesNotLogItsKeys(): void + { + $this->stripeApi(); + + $this->assertLogsDoNotContain(self::StripeSecretKey, self::StripeWebhookSecret); + } + + public function testStripeWebhookCallbackDoesNotLogTheSigningSecretNorTheRawEvent(): void + { + $payload = json_encode([ + 'id' => 'evt_leakcheck_event', + 'object' => 'event', + 'type' => 'payment_intent.succeeded', + 'data' => ['object' => $this->paymentIntent()], + ]); + $timestamp = time(); + $signature = hash_hmac('sha256', $timestamp . '.' . $payload, self::StripeWebhookSecret); + $request = Request::create('/confirm', 'POST', [], [], [], [ + 'HTTP_STRIPE_SIGNATURE' => sprintf('t=%s,v1=%s', $timestamp, $signature), + 'CONTENT_TYPE' => 'application/json', + ], $payload); + + $result = $this->stripeApi()->processCallback($request); + + $this->assertSame('pi_leakcheck_intent', $result['cart_id']); + $this->assertLogsDoNotContain(self::StripeSecretKey, self::StripeWebhookSecret, self::IntentClientSecret, $signature); + $this->assertLogsContain('evt_leakcheck_event'); + $this->assertLogsContain('pi_leakcheck_intent'); + } + + /** + * A webhook request whose signature was made with another endpoint's secret, like the + * deliveries of the orphaned summit 70 endpoint. + */ + private function wronglySignedWebhookRequest(): Request + { + $payload = json_encode([ + 'id' => 'evt_leakcheck_event', + 'object' => 'event', + 'type' => 'payment_intent.succeeded', + 'data' => ['object' => $this->paymentIntent()], + ]); + $timestamp = time(); + $signature = hash_hmac('sha256', $timestamp . '.' . $payload, 'whsec_another_endpoint'); + return Request::create('/confirm', 'POST', [], [], [], [ + 'HTTP_STRIPE_SIGNATURE' => sprintf('t=%s,v1=%s', $timestamp, $signature), + 'CONTENT_TYPE' => 'application/json', + ], $payload); + } + + public function testStripeInvalidSignatureDoesNotLogTheSigningSecret(): void + { + $error = null; + try { + $this->stripeApi()->processCallback($this->wronglySignedWebhookRequest()); + } catch (SignatureVerificationException $ex) { + $error = $ex; + } + + $this->assertNotNull($error, 'the invalid signature must still reach the caller'); + $this->assertLogsDoNotContain(self::StripeSecretKey, self::StripeWebhookSecret); + $this->assertLogsContain('No signatures found matching the expected signature'); + } + + public function testWebhookControllerDoesNotLogTheSigningSecretOnAnInvalidSignature(): void + { + $response_factory = Mockery::mock(ResponseFactory::class); + $response_factory->shouldReceive('json')->andReturnUsing(fn ($data, $status) => new JsonResponse($data, $status)); + $this->app->instance(ResponseFactory::class, $response_factory); + $profile = Mockery::mock(PaymentGatewayProfile::class); + $profile->shouldReceive('buildPaymentGatewayApi')->andReturn($this->stripeApi()); + $strategy = Mockery::mock(IBuildDefaultPaymentGatewayProfileStrategy::class); + $strategy->shouldReceive('build')->with(IPaymentConstants::ApplicationTypeRegistration)->andReturn($profile); + $controller = new PaymentGatewayWebHookController( + Mockery::mock(ISummitRepository::class), + Mockery::mock(IResourceServerContext::class), + Mockery::mock(ILocationService::class), + Mockery::mock(ISummitOrderService::class), + $strategy + ); + + $response = $controller->genericConfirm(IPaymentConstants::ApplicationTypeRegistration, $this->wronglySignedWebhookRequest()); + + $this->assertSame(400, $response->getStatusCode()); + $this->assertLogsDoNotContain(self::StripeSecretKey, self::StripeWebhookSecret); + } + + public function testLawPayOrderProcessingDoesNotLogThePaymentToken(): void + { + $order = Mockery::mock(SummitOrder::class); + $order->shouldReceive('getId')->andReturn(1); + $order->shouldReceive('getSummitId')->andReturn(43); + $order->shouldReceive('getFinalAmount')->andReturn(10.0); + // without keys generatePayment() stops before calling LawPay + $api = new LawPayApi(['test_mode_enabled' => true]); + + $error = null; + try { + $api->postProcessOrder($order, ['payment_method_id' => self::LawPayPaymentToken]); + } catch (\InvalidArgumentException $ex) { + $error = $ex; + } + + $this->assertNotNull($error); + $this->assertLogsDoNotContain(self::LawPayPaymentToken); + $this->assertLogsContain('LawPayApi::postProcessOrder order 1'); + } + + public function testStripeWebhookCreationDoesNotLogTheReturnedSigningSecret(): void + { + $this->fakeStripe([ + 'id' => 'we_leakcheck_endpoint', + 'object' => 'webhook_endpoint', + 'secret' => self::StripeCreatedWebhookSecret, + 'livemode' => true, + 'url' => 'https://api.test/confirm', + ]); + + $info = $this->stripeApi()->createWebHook('https://api.test/confirm'); + $this->stripeApi()->getWebHookById('we_leakcheck_endpoint'); + + $this->assertSame(self::StripeCreatedWebhookSecret, $info['secret']); + $this->assertLogsDoNotContain(self::StripeSecretKey, self::StripeWebhookSecret, self::StripeCreatedWebhookSecret); + $this->assertLogsContain('we_leakcheck_endpoint'); + } + + public function testStripePaymentIntentLookupsDoNotLogTheClientSecret(): void + { + $this->fakeStripe($this->paymentIntent()); + + $api = $this->stripeApi(); + $this->assertSame('succeeded', $api->getCartStatus('pi_leakcheck_intent')); + $this->assertNotNull($api->getPaymentDetailsInfo('pi_leakcheck_intent')); + + $this->assertLogsDoNotContain(self::StripeSecretKey, self::IntentClientSecret); + $this->assertLogsContain('pi_leakcheck_intent'); + } + + public function testStripeProfileDoesNotLogWebhookSigningSecrets(): void + { + $profile = new StripePaymentProfile(); + $profile->setLiveWebHookData(['id' => 'we_leakcheck_live', 'secret_key' => self::StripeWebhookSecret]); + $profile->setTestWebHookData(['id' => 'we_leakcheck_test', 'secret_key' => self::StripeWebhookSecret]); + + $this->assertLogsDoNotContain(self::StripeWebhookSecret); + $this->assertLogsContain('we_leakcheck_live'); + } + + public function testLawPayApiConstructorDoesNotLogItsSecretKey(): void + { + new LawPayApi([ + 'secret_key' => self::LawPaySecretKey, + 'public_key' => 'lawpay_public', + 'account_id' => 'lawpay_account', + 'test_mode_enabled' => true, + ]); + + $this->assertLogsDoNotContain(self::LawPaySecretKey); + } + + public function testOAuth2ClientFactoryDoesNotLogTheClientSecret(): void + { + OAuth2ClientFactory::build( + ['authorization_endpoint' => 'https://idp.test/authorize', 'token_endpoint' => 'https://idp.test/token'], + ['client_id' => 'leakcheck_client', 'client_secret' => self::OAuth2ClientSecret, 'scopes' => 'payment-profile/read'] + ); + + $this->assertLogsDoNotContain(self::OAuth2ClientSecret); + $this->assertLogsContain('leakcheck_client'); + } + + public function testOAuth2ApiDoesNotLogTheAccessToken(): void + { + $cache = Mockery::mock(ICacheService::class); + $cache->shouldReceive('getSingleValue')->andReturn(self::OAuth2AccessToken); + $api = new class($cache) extends AbstractOAuth2Api { + public function getAppName(): string + { + return 'LEAKCHECK'; + } + + public function getAppConfig(): array + { + return []; + } + + public function token(): ?string + { + return $this->getAccessToken(); + } + }; + + $this->assertSame(self::OAuth2AccessToken, $api->token()); + $this->assertLogsDoNotContain(self::OAuth2AccessToken); + } + + public function testProfileFactoryDoesNotLogTheProfileKeys(): void + { + PaymentGatewayProfileFactory::build(IPaymentConstants::ProviderStripe, $this->profilePayload() + ['set_webhooks' => true]); + + $this->assertLogsDoNotContain(self::ProfileLiveSecretKey, self::ProfileTestSecretKey, self::StripeWebhookSecret); + } + + public function testProfileServiceDoesNotLogTheProfileKeys(): void + { + $tx_service = Mockery::mock(ITransactionService::class); + $tx_service->shouldReceive('transaction')->andReturnUsing(fn (\Closure $callback) => $callback()); + $summit = Mockery::mock(Summit::class); + $summit->shouldReceive('getId')->andReturn(0); + $summit->shouldReceive('addPaymentProfile'); + $summit->shouldReceive('getPaymentProfileById')->andReturn(new StripePaymentProfile()); + $summit->shouldReceive('getPaymentGateWayProfilePerApp')->andReturn(null); + $service = new PaymentGatewayProfileService($tx_service); + + $service->addPaymentProfile($summit, $this->profilePayload()); + $service->updatePaymentProfile($summit, 1, $this->profilePayload()); + + $this->assertLogsDoNotContain(self::ProfileLiveSecretKey, self::ProfileTestSecretKey, self::StripeWebhookSecret); + } + + private function mqJob(): PaymentsMQJob + { + $job = Mockery::mock(PaymentsMQJob::class); + $job->shouldReceive('payload')->andReturn([ + 'data' => ['id' => 5, 'summit_id' => 70, 'application_type' => IPaymentConstants::ApplicationTypeRegistration], + ]); + $job->shouldReceive('delete')->once(); + return $job; + } + + private function paymentsApi(): IPaymentsApi + { + $payments_api = Mockery::mock(IPaymentsApi::class); + $payments_api->shouldReceive('getPaymentProfile')->with(70, 5)->andReturn($this->profilePayload()); + return $payments_api; + } + + public function testProfileSyncJobsDoNotLogTheProfileKeys(): void + { + $summit_repository = Mockery::mock(ISummitRepository::class); + $summit_repository->shouldReceive('getById')->with(70)->andReturn(null); + $profile_repository = Mockery::mock(IPaymentGatewayProfileRepository::class); + $profile_repository->shouldReceive('getByExternalId')->andReturn(null); + $service = new PaymentGatewayProfileService(Mockery::mock(ITransactionService::class)); + + (new CreatePaymentProfileMQJob($summit_repository, $service, $this->paymentsApi()))->handle($this->mqJob()); + (new UpdatePaymentProfileMQJob($summit_repository, $profile_repository, $service, $this->paymentsApi()))->handle($this->mqJob()); + + $this->assertLogsDoNotContain(self::ProfileLiveSecretKey, self::ProfileTestSecretKey, self::StripeWebhookSecret); + } + + public function testProfileSyncJobsStillDeleteTheEventWhenPurchasesApiReturnsNoProfile(): void + { + // PaymentsApi::getPaymentProfile() returns null on 404 (AbstractOAuth2Api::invokeWithRetry), + // e.g. for an event whose profile was deleted in purchases-api before it was consumed + $payments_api = Mockery::mock(IPaymentsApi::class); + $payments_api->shouldReceive('getPaymentProfile')->andReturn(null); + $summit_repository = Mockery::mock(ISummitRepository::class); + $summit_repository->shouldReceive('getById')->with(70)->andReturn(null); + $profile_repository = Mockery::mock(IPaymentGatewayProfileRepository::class); + $profile_repository->shouldReceive('getByExternalId')->andReturn(null); + $service = new PaymentGatewayProfileService(Mockery::mock(ITransactionService::class)); + + (new CreatePaymentProfileMQJob($summit_repository, $service, $payments_api))->handle($this->mqJob()); + (new UpdatePaymentProfileMQJob($summit_repository, $profile_repository, $service, $payments_api))->handle($this->mqJob()); + + $this->assertSame([], PaymentGatewayProfile::toLogContext(null)); + } +}