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: 1 addition & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ ThisBuild / organization := "app.softnetwork"

name := "payment"

ThisBuild / version := "0.9.11"
ThisBuild / version := "0.9.12"

ThisBuild / scalaVersion := scala212

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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]]
Expand All @@ -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()
}
Expand Down
Loading