From a25131e32734fced46aa2669e3fc9ca20ffa7e11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Manciot?= Date: Wed, 18 Nov 2026 00:16:49 +0100 Subject: [PATCH] fix(testkit): stripe listen forwards the webhook endpoint's events and reads the new secret format The Stripe test kit's `stripe listen` integration broke in two ways, and hid both: - Stripe CLI 1.51.0+ exits at startup when `listen --forward-to` has no event subscription. The kit now passes `--events` with the event types the webhook endpoint subscribes to. `--events` exists in every CLI version (verified on 1.21.0 and 1.55.12); `--all-snapshot` does not. - Stripe changed the CLI signing-secret format from 64 lowercase hex characters to 32 alphanumeric ones. The extraction pattern `whsec_[a-f0-9]+` truncated it (e.g. to `whsec_e`), so every forwarded webhook failed signature verification (HTTP 400). The kit now takes the whole token (`whsec_\S+`) and runs the CLI with `--color off`. - beforeAll no longer carries on silently: it aborts the suite when no secret is printed within 30s, when it looks truncated, or when it was not installed for the webhook route. The secret is masked in the logs. One shared list (`StripeApi.webhookEnabledEvents`) now drives the webhook endpoint's create and update parameters and the test listener's `--events`; a unit test pins it to the previously hard-coded events. Version 0.9.12. Closes #34 Co-Authored-By: Claude Opus 5.5 --- build.sbt | 2 +- .../payment/config/StripeApi.scala | 96 ++++++++----------- .../payment/config/StripeApiSpec.scala | 28 ++++++ .../scalatest/StripePaymentRouteTestKit.scala | 79 ++++++++++++--- 4 files changed, 137 insertions(+), 68 deletions(-) diff --git a/build.sbt b/build.sbt index b864982..f526029 100644 --- a/build.sbt +++ b/build.sbt @@ -18,7 +18,7 @@ ThisBuild / organization := "app.softnetwork" name := "payment" -ThisBuild / version := "0.9.11" +ThisBuild / version := "0.9.12" ThisBuild / scalaVersion := scala212 diff --git a/stripe/src/main/scala/app/softnetwork/payment/config/StripeApi.scala b/stripe/src/main/scala/app/softnetwork/payment/config/StripeApi.scala index ff84fbe..dd19632 100644 --- a/stripe/src/main/scala/app/softnetwork/payment/config/StripeApi.scala +++ b/stripe/src/main/scala/app/softnetwork/payment/config/StripeApi.scala @@ -51,6 +51,46 @@ case class StripeApi( object StripeApi { + /** The Stripe event types the provisioned webhook endpoint subscribes to, on creation and on + * update. The test kit's `stripe listen --events` subscribes to the same list, so the event + * types the tests receive cannot drift from the real endpoint's. + */ + val webhookEnabledEvents: Seq[String] = Seq( + "account.updated", + "person.updated", + "invoice.payment_succeeded", + "invoice.payment_failed", + "customer.subscription.deleted", + "customer.subscription.updated", + "customer.updated", + "payment_method.attached", + "payment_method.detached" + ) + + private[config] lazy val webhookCreateEvents: Seq[WebhookEndpointCreateParams.EnabledEvent] = + webhookEnabledEvents.map { event => + WebhookEndpointCreateParams.EnabledEvent + .values() + .find(_.getValue == event) + .getOrElse( + throw new IllegalStateException( + s"stripe-java has no WebhookEndpointCreateParams.EnabledEvent for '$event'" + ) + ) + } + + private[config] lazy val webhookUpdateEvents: Seq[WebhookEndpointUpdateParams.EnabledEvent] = + webhookEnabledEvents.map { event => + WebhookEndpointUpdateParams.EnabledEvent + .values() + .find(_.getValue == event) + .getOrElse( + throw new IllegalStateException( + s"stripe-java has no WebhookEndpointUpdateParams.EnabledEvent for '$event'" + ) + ) + } + case class Config( override val clientId: String, override val apiKey: String, @@ -158,33 +198,7 @@ object StripeApi { .create( WebhookEndpointCreateParams .builder() - .addEnabledEvent( - WebhookEndpointCreateParams.EnabledEvent.ACCOUNT__UPDATED - ) - .addEnabledEvent( - WebhookEndpointCreateParams.EnabledEvent.PERSON__UPDATED - ) - .addEnabledEvent( - WebhookEndpointCreateParams.EnabledEvent.INVOICE__PAYMENT_SUCCEEDED - ) - .addEnabledEvent( - WebhookEndpointCreateParams.EnabledEvent.INVOICE__PAYMENT_FAILED - ) - .addEnabledEvent( - WebhookEndpointCreateParams.EnabledEvent.CUSTOMER__SUBSCRIPTION__DELETED - ) - .addEnabledEvent( - WebhookEndpointCreateParams.EnabledEvent.CUSTOMER__SUBSCRIPTION__UPDATED - ) - .addEnabledEvent( - WebhookEndpointCreateParams.EnabledEvent.CUSTOMER__UPDATED - ) - .addEnabledEvent( - WebhookEndpointCreateParams.EnabledEvent.PAYMENT_METHOD__ATTACHED - ) - .addEnabledEvent( - WebhookEndpointCreateParams.EnabledEvent.PAYMENT_METHOD__DETACHED - ) + .addAllEnabledEvent(webhookCreateEvents.asJava) .setUrl(url) .setApiVersion(WebhookEndpointCreateParams.ApiVersion.VERSION_2024_06_20) // connect=true -> events from connected accounts only; connect=false -> events from @@ -236,33 +250,7 @@ object StripeApi { endpoint.update( WebhookEndpointUpdateParams .builder() - .addEnabledEvent( - WebhookEndpointUpdateParams.EnabledEvent.ACCOUNT__UPDATED - ) - .addEnabledEvent( - WebhookEndpointUpdateParams.EnabledEvent.PERSON__UPDATED - ) - .addEnabledEvent( - WebhookEndpointUpdateParams.EnabledEvent.INVOICE__PAYMENT_SUCCEEDED - ) - .addEnabledEvent( - WebhookEndpointUpdateParams.EnabledEvent.INVOICE__PAYMENT_FAILED - ) - .addEnabledEvent( - WebhookEndpointUpdateParams.EnabledEvent.CUSTOMER__SUBSCRIPTION__DELETED - ) - .addEnabledEvent( - WebhookEndpointUpdateParams.EnabledEvent.CUSTOMER__SUBSCRIPTION__UPDATED - ) - .addEnabledEvent( - WebhookEndpointUpdateParams.EnabledEvent.CUSTOMER__UPDATED - ) - .addEnabledEvent( - WebhookEndpointUpdateParams.EnabledEvent.PAYMENT_METHOD__ATTACHED - ) - .addEnabledEvent( - WebhookEndpointUpdateParams.EnabledEvent.PAYMENT_METHOD__DETACHED - ) + .addAllEnabledEvent(webhookUpdateEvents.asJava) .setUrl(url) .build(), requestOptions diff --git a/stripe/src/test/scala/app/softnetwork/payment/config/StripeApiSpec.scala b/stripe/src/test/scala/app/softnetwork/payment/config/StripeApiSpec.scala index 6a1d6a8..32afc25 100644 --- a/stripe/src/test/scala/app/softnetwork/payment/config/StripeApiSpec.scala +++ b/stripe/src/test/scala/app/softnetwork/payment/config/StripeApiSpec.scala @@ -2,6 +2,7 @@ package app.softnetwork.payment.config import app.softnetwork.payment.model.SoftPayAccount.Client import app.softnetwork.security.sha256 +import com.stripe.param.{WebhookEndpointCreateParams, WebhookEndpointUpdateParams} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec @@ -14,5 +15,32 @@ class StripeApiSpec extends AnyWordSpec with Matchers { StripeApi() should not be null StripeApi.webHookSecret(sha256(provider.clientId)).isDefined shouldBe true } + + "subscribe the webhook endpoint to the same events on create and update" in { + // The events the endpoint subscribed to before the shared list existed, in the same order. + StripeApi.webhookCreateEvents shouldBe Seq( + WebhookEndpointCreateParams.EnabledEvent.ACCOUNT__UPDATED, + WebhookEndpointCreateParams.EnabledEvent.PERSON__UPDATED, + WebhookEndpointCreateParams.EnabledEvent.INVOICE__PAYMENT_SUCCEEDED, + WebhookEndpointCreateParams.EnabledEvent.INVOICE__PAYMENT_FAILED, + WebhookEndpointCreateParams.EnabledEvent.CUSTOMER__SUBSCRIPTION__DELETED, + WebhookEndpointCreateParams.EnabledEvent.CUSTOMER__SUBSCRIPTION__UPDATED, + WebhookEndpointCreateParams.EnabledEvent.CUSTOMER__UPDATED, + WebhookEndpointCreateParams.EnabledEvent.PAYMENT_METHOD__ATTACHED, + WebhookEndpointCreateParams.EnabledEvent.PAYMENT_METHOD__DETACHED + ) + StripeApi.webhookUpdateEvents shouldBe Seq( + WebhookEndpointUpdateParams.EnabledEvent.ACCOUNT__UPDATED, + WebhookEndpointUpdateParams.EnabledEvent.PERSON__UPDATED, + WebhookEndpointUpdateParams.EnabledEvent.INVOICE__PAYMENT_SUCCEEDED, + WebhookEndpointUpdateParams.EnabledEvent.INVOICE__PAYMENT_FAILED, + WebhookEndpointUpdateParams.EnabledEvent.CUSTOMER__SUBSCRIPTION__DELETED, + WebhookEndpointUpdateParams.EnabledEvent.CUSTOMER__SUBSCRIPTION__UPDATED, + WebhookEndpointUpdateParams.EnabledEvent.CUSTOMER__UPDATED, + WebhookEndpointUpdateParams.EnabledEvent.PAYMENT_METHOD__ATTACHED, + WebhookEndpointUpdateParams.EnabledEvent.PAYMENT_METHOD__DETACHED + ) + StripeApi.webhookEnabledEvents.distinct shouldBe StripeApi.webhookEnabledEvents + } } } diff --git a/testkit/src/main/scala/app/softnetwork/payment/scalatest/StripePaymentRouteTestKit.scala b/testkit/src/main/scala/app/softnetwork/payment/scalatest/StripePaymentRouteTestKit.scala index 5a02d1d..3350d0d 100644 --- a/testkit/src/main/scala/app/softnetwork/payment/scalatest/StripePaymentRouteTestKit.scala +++ b/testkit/src/main/scala/app/softnetwork/payment/scalatest/StripePaymentRouteTestKit.scala @@ -20,9 +20,9 @@ import org.scalatest.Suite import java.time.Instant import scala.concurrent.Await import java.util.concurrent.CountDownLatch +import java.util.concurrent.atomic.AtomicReference import scala.concurrent.duration._ import scala.sys.process.{Process, ProcessLogger} -import scala.sys.process.{Process, ProcessLogger} import scala.util.{Failure, Success, Try} trait StripePaymentRouteTestKit[SD <: SessionData with SessionDataDecorator[SD]] @@ -45,27 +45,80 @@ trait StripePaymentRouteTestKit[SD <: SessionData with SessionDataDecorator[SD]] val serverPort = binding.localAddress.getPort val hash = sha256(clientId) val secretLatch = new CountDownLatch(1) - val secretPattern = "webhook signing secret is (whsec_[a-f0-9]+)".r + val cliSecret = new AtomicReference[String]() + val installFailure = new AtomicReference[Throwable]() + // Stripe has changed this secret's format before (64 lowercase hex characters, later 32 + // alphanumeric ones), so take everything up to the next whitespace instead of a character class. + val secretPattern = "webhook signing secret is (whsec_\\S+)".r def processLine(line: String): Unit = { - log.info(line) + // never write the signing secret itself to the test logs + log.info(line.replaceAll("whsec_\\S+", "whsec_***")) secretPattern.findFirstMatchIn(line).foreach { m => - val cliSecret = m.group(1) - StripeApi.overrideWebHookSecret(hash, cliSecret) - log.info(s"Stripe CLI webhook secret saved for hash $hash") + val secret = m.group(1) + cliSecret.set(secret) + Try(StripeApi.overrideWebHookSecret(hash, secret)) match { + case Success(_) => + log.info(s"Stripe CLI webhook secret saved for hash $hash (${secret.length} chars)") + case Failure(f) => installFailure.set(f) + } secretLatch.countDown() } } - stripeCLi = Process( - s"stripe listen --forward-to ${providerConfig.hooksBaseUrl.replace("9000", s"$serverPort").replace("localhost", interface)}?hash=$hash" - ).run(ProcessLogger(processLine, processLine)) - // Wait for the CLI to output its secret (max 30 seconds) - secretLatch.await(30, java.util.concurrent.TimeUnit.SECONDS) + val forwardTo = + s"${providerConfig.hooksBaseUrl.replace("9000", s"$serverPort").replace("localhost", interface)}?hash=$hash" + // Since Stripe CLI 1.51.0, `listen --forward-to` without an event subscription exits at startup. + // `--events` exists in every CLI version (`--all-snapshot` only from 1.51.0); subscribing to the + // webhook endpoint's own event types keeps the test listener's events aligned with the endpoint. + // `--color off`: with colours forced, the CLI wraps the secret in ANSI codes the pattern misses. + val command = Seq( + "stripe", + "listen", + "--color", + "off", + "--events", + StripeApi.webhookEnabledEvents.mkString(","), + "--forward-to", + forwardTo + ) + stripeCLi = Process(command).run(ProcessLogger(processLine, processLine)) + // Wait for the CLI to output its secret (max 30 seconds), then check it really took effect: + // without it no webhook passes signature verification, and every webhook-driven test would + // fail later with a misleading timeout. + val secretPrinted = secretLatch.await(30, java.util.concurrent.TimeUnit.SECONDS) + // `whsec_` plus at least 16 characters: Stripe's CLI secrets have been 64 or 32 characters long. + val minWebhookSecretLength = 22 + val problem: Option[String] = + if (!secretPrinted) { + val state = + if (stripeCLi.isAlive()) "still running" else s"exited with code ${stripeCLi.exitValue()}" + Some(s"the Stripe CLI printed no webhook signing secret within 30s ($state)") + } else if (installFailure.get != null) { + Some(s"installing the Stripe CLI webhook signing secret failed: ${installFailure.get}") + } else if (cliSecret.get.length < minWebhookSecretLength) { + Some( + s"the Stripe CLI webhook signing secret looks truncated (${cliSecret.get.length} chars)" + ) + } else if (!StripeApi.webHookSecret(hash).contains(cliSecret.get)) { + Some( + "the Stripe CLI webhook signing secret was not installed for the webhook route " + + "(StripeApi.overrideWebHookSecret only accepts sk_test_ keys)" + ) + } else None + problem.foreach { reason => + // Stop the CLI now so it cannot outlive the suite; ScalaTest still runs afterAll, which + // unbinds the HTTP server. + if (stripeCLi.isAlive()) stripeCLi.destroy() + throw new IllegalStateException( + s"Cannot forward Stripe webhooks to the tests: $reason. The Stripe CLI output is logged above " + + s"(command: ${command.take(2).mkString(" ")} --events ... --forward-to ...).", + installFailure.get + ) + } } override def afterAll(): Unit = { log.info("Shutting down Stripe CLI and HTTP server") - if (stripeCLi.isAlive()) - stripeCLi.destroy() + Option(stripeCLi).filter(_.isAlive()).foreach(_.destroy()) webhookBinding.foreach(b => Await.result(b.unbind(), 5.seconds)) super.afterAll() }