SENDLINE open source
open source / oauth4s / testing

Testing

oauth4s-testkit has an HTTP client that answers from a script and remembers what it was asked:

scala
val http: StubHttpClient[IO] =
  StubHttpClient.routes[IO]("https://auth.example.com/token" -> HttpResponse.json("""{"access_token":"a","expires_in":3600}"""))

given HttpClient[IO] = http

val config = OAuthClientConfig(ClientId("client-1"), ClientAuthentication.Public, Endpoints.of(Endpoint("https://auth.example.com/token")))
val client = OAuthClient[IO](config)

val asked: IO[Map[String, String]] =
  client.clientCredentials(Scope.of("read")).map(_ => http.lastForm) // grant_type, scope and client_id, as they were sent

val failing: StubHttpClient[IO]  = StubHttpClient.failing[IO](java.net.ConnectException("connection refused"))
val inOrder: StubHttpClient[IO]  = StubHttpClient.sequence[IO](HttpResponse.json("""{"error":"slow_down"}""", 400), HttpResponse.json("""{"access_token":"a"}"""))
val computed: StubHttpClient[IO] = StubHttpClient[IO](request => IO.pure(HttpResponse.json(s"""{"asked":"${request.url}"}""")))

StubHttpClient.routesBy[IO] { case request if … => … } routes with a partial function. It runs as each request arrives, so a route can answer from something the test learned later, such as the nonce of a flow it has just started. Any request the function does not route gets a 404.

An issuer that signs ID tokens with a key of its own, for testing what your code does with a token:

scala
val issuer: TestIssuer = TestIssuer(Issuer("https://auth.example.com"))

val idToken: IdToken = issuer.idToken(ClientId("client-1"), "user-1", Instant.now(), "email" -> Json.str("ann@example.com"))
val keys: String     = issuer.jwksJson.render // what the provider's jwks_uri would answer

And an authorization server on a loopback port, for testing a sign-in end to end without a container:

scala
val signIn: IO[OidcTokens] =
  for
    oidc   <- OidcClient.discover[IO](server.issuer, server.clientId, ClientAuthentication.SecretBasic(server.clientSecret))
    flow   <- oidc.authorize(redirect, AuthorizationOptions.scoped("email"))
    landed  = server.approve(flow.url) // the user saying yes: the URL the browser would come back to
    tokens <- oidc.complete(flow, AuthorizationCallback.fromUrl(landed))
  yield tokens

FakeAuthorizationServer.start() serves discovery, the code grant with PKCE verified, refresh with rotation, client credentials, the device grant (approveDevice(userCode) is the user typing the code), revocation, introspection, UserInfo, and ID tokens signed with keys it publishes. It checks the client's credentials, refuses a code used twice, and answers with the error documents a real server would.

built from README.md at v0.1.1 edit this page on GitHub