tapir icon indicating copy to clipboard operation
tapir copied to clipboard

[BUG] Cannot use a body in serverSecurityLogic: causes java.lang.IllegalStateException: This publisher only supports one subscriber

Open samthebest opened this issue 8 months ago • 4 comments

Tapir version: 1.11.9

Scala version: 2.13.15

Suppose we have some security logic, nice and neatly decoupled and deduplicated from the business logic:

val secureBase =
     ...
        .securityIn(extractFromRequest(_.uri))
        .securityIn(extractFromRequest(_.method))
        .securityIn(stringBody)
        .serverSecurityLogic { case (jwt, basic, uri, method, body) => ... Authed(...) }

Then somewhere we try to build on this to add the business logic:

secureBase
  .in(jsonBody[Person])
  .serverLogic(authed => person => ...)

Then hitting this endpoint results in:

java.lang.IllegalStateException: This publisher only supports one subscriber
	at org.playframework.netty.HandlerPublisher.subscribe(HandlerPublisher.java:167)
	at org.playframework.netty.http.DelegateStreamedHttpRequest.subscribe(DelegateStreamedHttpRequest.java:19)
	at sttp.tapir.server.netty.cats.internal.Fs2StreamCompatible$$anon$1.$anonfun$fromPublisher$2(Fs2StreamCompatible.scala:52)
	at flatMap @ fs2.Compiler$Target.flatMap(Compiler.scala:163)
	at flatMap @ fs2.Compiler$Target.flatMap(Compiler.scala:163)
	at flatMap @ fs2.Pull$.fs2$Pull$$interruptGuard$1(Pull.scala:951)
	at flatMap @ fs2.Compiler$Target.flatMap(Compiler.scala:163)
	at flatMap @ fs2.Compiler$Target.flatMap(Compiler.scala:163)
	at flatMap @ fs2.Pull$.fs2$Pull$$interruptGuard$1(Pull.scala:951)
	at flatMap @ fs2.Compiler$Target.flatMap(Compiler.scala:163)
	at flatMap @ fs2.Compiler$Target.flatMap(Compiler.scala:163)
	at flatMap @ fs2.Pull$.fs2$Pull$$interruptGuard$1(Pull.scala:951)
	at async_ @ fs2.interop.reactivestreams.StreamSubscriber$$anon$1.dequeue1(StreamSubscriber.scala:219)

I think what is needed in Tapir to resolve this is to cache the body, so that it can be read for security logic, and also for business logic.

Of course one could argue that an API that uses the body for auth isn't truly RESTful? But still, doesn't seem too naughty.

In the meantime I was hoping there is some neat work around? The only work arounds I've come up with means bypassing the .in(jsonBody part of the DSL 😬 , i.e. by storing the body in Authed then parsing it out later with some sugar:

  implicit class AuthzdEndpointSyntax[INPUT, OUTPUT](endpoint: PSE[INPUT, OUTPUT]) {
    def serverLogicBodyIn[T: Decoder](f: (Authed, INPUT, T) => IO[Either[ErrorInfo, OUTPUT]]) = ...

I was hoping there is a flag somewhere I can set justReadBodyTwicePlease

samthebest avatar Mar 20 '25 13:03 samthebest