diff --git a/.github/actions/setup-sbt/action.yaml b/.github/actions/setup-sbt/action.yaml new file mode 100644 index 0000000..c1da99d --- /dev/null +++ b/.github/actions/setup-sbt/action.yaml @@ -0,0 +1,71 @@ +# From https://github.com/sbt/setup-sbt +name: "Setup sbt installer" +description: "Sets up sbt runner script" +inputs: + sbt-runner-version: + description: "The runner version (The actual version is controlled via project/build.properties)" + required: true + default: 1.11.7 +runs: + using: "composite" + steps: + - name: Set up cache paths + id: cache-paths + shell: bash + env: + SBT_RUNNER_VERSION: ${{ inputs.sbt-runner-version }} + SBT_CACHE_KEY_VERSION: 1.1.6 + run: | + if [[ "$RUNNER_OS" == "Windows" ]]; then + echo "sbt_toolpath=$RUNNER_TOOL_CACHE\\sbt\\$SBT_RUNNER_VERSION" >> "$GITHUB_OUTPUT" + echo "sbt_downloadpath=$RUNNER_TEMP\\_sbt" >> "$GITHUB_OUTPUT" + else + echo "sbt_toolpath=$RUNNER_TOOL_CACHE/sbt/$SBT_RUNNER_VERSION" >> "$GITHUB_OUTPUT" + echo "sbt_downloadpath=$RUNNER_TEMP/_sbt" >> "$GITHUB_OUTPUT" + fi + echo "sbt_cachekey=$RUNNER_OS-sbt-$SBT_RUNNER_VERSION-$SBT_CACHE_KEY_VERSION" >> "$GITHUB_OUTPUT" + - name: Check Tool Cache + id: cache-tool-dir + shell: bash + env: + SBT_TOOLPATH: "${{ steps.cache-paths.outputs.sbt_toolpath }}" + run: | + if [[ -f "$SBT_TOOLPATH/sbt/bin/sbt" ]]; then + echo "cache-hit=true" >> "$GITHUB_OUTPUT" + else + mkdir -p "$SBT_TOOLPATH" + echo "cache-hit=false" >> "$GITHUB_OUTPUT" + fi + - name: Cache sbt distribution + id: cache-dir + if: steps.cache-tool-dir.outputs.cache-hit != 'true' + uses: actions/cache@9255dc7a253b0ccc959486e2bca901246202afeb # v5.0.1 + with: + path: ${{ steps.cache-paths.outputs.sbt_toolpath }} + key: ${{ steps.cache-paths.outputs.sbt_cachekey }} + - name: "Download and Install sbt" + shell: bash + env: + SBT_RUNNER_VERSION: ${{ inputs.sbt-runner-version }} + SBT_TOOLPATH: "${{ steps.cache-paths.outputs.sbt_toolpath }}" + SBT_DOWNLOADPATH: "${{ steps.cache-paths.outputs.sbt_downloadpath }}" + if: steps.cache-tool-dir.outputs.cache-hit != 'true' && steps.cache-dir.outputs.cache-hit != 'true' + run: | + mkdir -p "$SBT_DOWNLOADPATH" + curl -sL "https://github.com/sbt/sbt/releases/download/v$SBT_RUNNER_VERSION/sbt-$SBT_RUNNER_VERSION.zip" > \ + "$SBT_DOWNLOADPATH/sbt-$SBT_RUNNER_VERSION.zip" + + cd "$SBT_DOWNLOADPATH" + unzip -o "sbt-$SBT_RUNNER_VERSION.zip" -d "$SBT_TOOLPATH" + - name: "Setup PATH" + shell: bash + env: + SBT_TOOLPATH: "${{ steps.cache-paths.outputs.sbt_toolpath }}" + run: | + cd "$SBT_TOOLPATH" + ls sbt/bin/sbt + if [[ "$RUNNER_OS" == "Windows" ]]; then + echo "$PWD\\sbt\\bin" >> "$GITHUB_PATH" + else + echo "$PWD/sbt/bin" >> "$GITHUB_PATH" + fi \ No newline at end of file diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e7bded0..76ec5d6 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -2,20 +2,23 @@ name: Publish on: push: - branches: [ master ] + branches: [ main ] tags: ["*"] jobs: publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Set up JDK 11 - uses: actions/setup-java@v1 + uses: actions/setup-java@v4 with: + distribution: 'temurin' java-version: 11 + - name: Set up SBT + uses: ./.github/actions/setup-sbt - name: Publish env: PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }} diff --git a/.github/workflows/publish_branch.yaml b/.github/workflows/publish_branch.yaml index b1627f3..1701803 100644 --- a/.github/workflows/publish_branch.yaml +++ b/.github/workflows/publish_branch.yaml @@ -8,13 +8,16 @@ jobs: runs-on: ubuntu-latest if: github.ref != 'refs/heads/master' && !startsWith(github.ref, 'refs/tags/') steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Set up JDK 11 - uses: actions/setup-java@v1 + uses: actions/setup-java@v4 with: + distribution: 'temurin' java-version: 11 + - name: Set up SBT + uses: ./.github/actions/setup-sbt - name: Publish env: PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }} diff --git a/.github/workflows/scala.yml b/.github/workflows/scala.yml index 8d7d61c..53146e9 100644 --- a/.github/workflows/scala.yml +++ b/.github/workflows/scala.yml @@ -2,18 +2,21 @@ name: Scala CI on: push: - branches: [ master ] + branches: [ main ] pull_request: - branches: [ master ] + branches: [ main ] jobs: java11: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - java-version: 11 - - name: Run tests - run: sbt scalafmtSbtCheck scalafmtCheckAll +testOnly + - uses: actions/checkout@v5 + - name: Set up JDK 11 + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: 11 + - name: Set up SBT + uses: ./.github/actions/setup-sbt + - name: Run tests + run: sbt scalafmtSbtCheck scalafmtCheckAll +testOnly diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e81f13b..ebf8e23 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -24,4 +24,4 @@ repos: hooks: - id: scalafmt stages: [commit] - args: [-c .scalafmt.conf, -d./bin, -v2.4.2, -oorg.scalameta] + args: [-c .scalafmt.conf, -d./bin, -v3.10.2, -oorg.scalameta] diff --git a/README.md b/README.md index 91642fd..da5a171 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ [![Build Status](https://travis-ci.org/StackVista/akka-http-pac4j.svg?branch=master)](https://travis-ci.org/StackVista/akka-http-pac4j) -## akka-http-pac4j ## +Based on [akka-http-pac4j](https://github.com/StackVista/akka-http-pac4j). + +## pekko-http-pac4j ## A wrapper around pac4j (www.pac4j.org) built using AkkaHTTP ## how to use it ## diff --git a/build.sbt b/build.sbt index 669c6c4..6070002 100644 --- a/build.sbt +++ b/build.sbt @@ -1,65 +1,28 @@ import Dependencies._ -inThisBuild( - List(organization := "com.stackstate", scalaVersion := "2.12.13", crossScalaVersions := Seq(scalaVersion.value, "2.13.5"), libraryDependencies ++= { - // Silencer - val silencerVersion = "1.7.3" - - Seq( - compilerPlugin(("com.github.ghik" %% "silencer-plugin" % silencerVersion).cross(CrossVersion.full)), - ("com.github.ghik" %% "silencer-lib" % silencerVersion % Provided).cross(CrossVersion.full) - ) - }) -) +inThisBuild(List(organization := "io.github.stackvista", scalaVersion := "2.13.13")) lazy val root = (project in file(".")).settings( - name := "akka-http-pac4j", - libraryDependencies ++= Seq(akkaHttp, akkaStream, pac4j, scalaTestCore % Test, scalacheck % Test, akkaHttpTestKit % Test, akkaStreamTestKit % Test), - scalacOptions ++= Seq( - "-encoding", - "UTF-8", - "-explaintypes", - "-unchecked", - "-deprecation", - "-feature", - //"-language:higherKinds", - "-Xlint", - "-g:vars" + name := "pekko-http-pac4j", + libraryDependencies ++= Seq( + pekkoHttp, + pekkoStream, + pac4j, + scalaCompat, + scalaTestCore % Test, + scalacheck % Test, + pekkoHttpTestKit % Test, + pekkoStreamTestKit % Test ), - scalacOptions ++= { - if (scalaBinaryVersion.value == "2.13") { - Seq("-Werror", "-Wnumeric-widen", "-Wdead-code", "-Wvalue-discard", "-Wunused", "-Wmacros:after", "-Woctal-literal", "-Wextra-implicit") - - } else { - Seq( - "-Xfatal-warnings", - "-Ywarn-numeric-widen", - "-Ywarn-dead-code", - "-Ywarn-value-discard", - "-Ywarn-infer-any", - "-Ywarn-unused", - "-Ywarn-unused-import", - "-Ywarn-macros:after" - ) - } - }, - scalacOptions in Test ~= { - _.filterNot(_ == "-Werror") - }, - scalacOptions ++= { - if (scalaBinaryVersion.value == "2.13") { - Seq("-P:silencer:globalFilters=scala.jdk.CollectionConverters") - } else { - Seq.empty - } - }, - scalacOptions in Test += "-P:silencer:globalFilters=discarded\\ non-Unit", - scalacOptions in (Compile, console) ~= { + scalacOptions ++= Seq("-encoding", "UTF-8", "-explaintypes", "-unchecked", "-deprecation", "-feature", "-Xlint", "-g:vars"), + scalacOptions ++= Seq("-Werror", "-Wnumeric-widen", "-Wdead-code", "-Wvalue-discard", "-Wmacros:after", "-Woctal-literal", "-Wextra-implicit"), + Test / scalacOptions := Seq("-Wconf:msg=unused value of type org.scalatest.Assertion:s"), + Compile / console / scalacOptions ~= { _.filterNot { opt => opt.startsWith("-P") || opt.startsWith("-X") || opt.startsWith("-W") } }, - scalacOptions in (Test, console) ~= { + Test / console / scalacOptions ~= { _.filterNot { opt => opt.startsWith("-P") || opt.startsWith("-X") || opt.startsWith("-W") } @@ -72,9 +35,9 @@ pomIncludeRepository := { _ => licenses := Seq("BSD-style" -> url("http://www.opensource.org/licenses/bsd-license.php")) -homepage := Some(url("https://github.com/StackVista/akka-http-pac4j")) +homepage := Some(url("https://github.com/StackVista/pekko-http-pac4j")) -scmInfo := Some(ScmInfo(url("https://github.com/StackVista/akka-http-pac4j"), "scm:git@github.com:StackVista/akka-http-pac4j.git")) +scmInfo := Some(ScmInfo(url("https://github.com/StackVista/pekko-http-pac4j"), "scm:git@github.com:StackVista/pekko-http-pac4j.git")) developers := List( Developer(id = "hierynomus", name = "Jeroen van Erp", email = "jeroen@hierynomus.com", url = url("https://github.com/hierynomus")), diff --git a/project/Dependencies.scala b/project/Dependencies.scala index 16ca9d4..a458869 100644 --- a/project/Dependencies.scala +++ b/project/Dependencies.scala @@ -2,16 +2,17 @@ import sbt._ object Dependencies { val scalacheckVersion = "1.14.3" - val akkaHttpVersion = "10.2.7" - val akkaStreamsVersion = "2.6.18" + val pekkoHttpVersion = "1.0.1" + val pekkoStreamsVersion = "1.0.3" val pac4jVersion = "5.7.7" val scalaTestVersion = "3.2.2" lazy val scalacheck = "org.scalacheck" %% "scalacheck" % scalacheckVersion - lazy val akkaHttp = "com.typesafe.akka" %% "akka-http" % akkaHttpVersion - lazy val akkaHttpTestKit = "com.typesafe.akka" %% "akka-http-testkit" % akkaHttpVersion - lazy val akkaStream = "com.typesafe.akka" %% "akka-stream" % akkaStreamsVersion + lazy val pekkoHttp = "org.apache.pekko" %% "pekko-http" % pekkoHttpVersion + lazy val pekkoHttpTestKit = "org.apache.pekko" %% "pekko-http-testkit" % pekkoHttpVersion + lazy val pekkoStream = "org.apache.pekko" %% "pekko-stream" % pekkoStreamsVersion lazy val pac4j = "org.pac4j" % "pac4j-core" % pac4jVersion lazy val scalaTestCore = "org.scalatest" %% "scalatest" % scalaTestVersion - lazy val akkaStreamTestKit = "com.typesafe.akka" %% "akka-stream-testkit" % akkaStreamsVersion + lazy val pekkoStreamTestKit = "org.apache.pekko" %% "pekko-stream-testkit" % pekkoStreamsVersion + lazy val scalaCompat = "org.scala-lang.modules" %% "scala-collection-compat" % "2.13.0" } diff --git a/project/Scapegoat.scala b/project/Scapegoat.scala index 7060f64..4c66a6a 100644 --- a/project/Scapegoat.scala +++ b/project/Scapegoat.scala @@ -11,7 +11,7 @@ object Scapegoat extends AutoPlugin { import ScapegoatSbtPlugin.autoImport._ override def projectSettings = Seq( - ThisBuild / scapegoatVersion := "1.4.8", + ThisBuild / scapegoatVersion := "2.1.6", scapegoatReports := Seq("text"), // xml in 2.13 require extra dep scapegoatDisabledInspections := Seq("FinalModifierOnCaseClass"), pomPostProcess := { diff --git a/project/build.properties b/project/build.properties index dbae93b..489e0a7 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1 @@ -sbt.version=1.4.9 +sbt.version=1.11.4 diff --git a/project/plugins.sbt b/project/plugins.sbt index 5a8d0b9..4a8b7ef 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,7 +1,7 @@ addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.8") -addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.5.12") +addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.11.2") -addSbtPlugin("com.sksamuel.scapegoat" %% "sbt-scapegoat" % "1.1.0") +addSbtPlugin("com.sksamuel.scapegoat" %% "sbt-scapegoat" % "1.2.13") -addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6") +addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.6") diff --git a/src/main/scala/com/stackstate/pac4j/AuthenticatedRequest.scala b/src/main/scala/com/stackstate/pac4j/AuthenticatedRequest.scala index 983b934..0d8db31 100644 --- a/src/main/scala/com/stackstate/pac4j/AuthenticatedRequest.scala +++ b/src/main/scala/com/stackstate/pac4j/AuthenticatedRequest.scala @@ -6,7 +6,7 @@ import org.pac4j.core.profile.UserProfile * Class which serves as a witness when authentication was successful. This class is private such that the user of this * library cannot mess with it. */ -case class AuthenticatedRequest private[pac4j] (private[pac4j] val webContext: AkkaHttpWebContext, +case class AuthenticatedRequest private[pac4j] (private[pac4j] val webContext: PekkoHttpWebContext, /* * Profiles can be accessed such that the user can inspect data * from the authentication. Should not be empty after authentication diff --git a/src/main/scala/com/stackstate/pac4j/AkkaHttpSecurity.scala b/src/main/scala/com/stackstate/pac4j/PekkoHttpSecurity.scala similarity index 70% rename from src/main/scala/com/stackstate/pac4j/AkkaHttpSecurity.scala rename to src/main/scala/com/stackstate/pac4j/PekkoHttpSecurity.scala index 4419ea2..680d442 100644 --- a/src/main/scala/com/stackstate/pac4j/AkkaHttpSecurity.scala +++ b/src/main/scala/com/stackstate/pac4j/PekkoHttpSecurity.scala @@ -1,39 +1,39 @@ package com.stackstate.pac4j import java.util -import akka.http.scaladsl.common.StrictForm -import akka.http.scaladsl.model.{HttpEntity, HttpHeader, HttpResponse} -import akka.http.scaladsl.server.Directives.{authorize => akkaHttpAuthorize} -import akka.http.scaladsl.server.{Directive, Directive0, Directive1, Route, RouteResult} -import akka.http.scaladsl.model.headers._ -import akka.http.scaladsl.server.RouteResult.Complete -import akka.http.scaladsl.unmarshalling.Unmarshal -import com.stackstate.pac4j.AkkaHttpWebContext.ResponseChanges -import com.stackstate.pac4j.http.AkkaHttpActionAdapter +import org.apache.pekko.http.scaladsl.common.StrictForm +import org.apache.pekko.http.scaladsl.model.{HttpEntity, HttpHeader, HttpResponse} +import org.apache.pekko.http.scaladsl.server.Directives.{authorize => pekkoHttpAuthorize} +import org.apache.pekko.http.scaladsl.server.{Directive, Directive0, Directive1, Route, RouteResult} +import org.apache.pekko.http.scaladsl.model.headers._ +import org.apache.pekko.http.scaladsl.server.RouteResult.Complete +import org.apache.pekko.http.scaladsl.unmarshalling.Unmarshal +import com.stackstate.pac4j.PekkoHttpWebContext.ResponseChanges +import com.stackstate.pac4j.http.PekkoHttpActionAdapter import org.pac4j.core.authorization.authorizer.Authorizer import org.pac4j.core.config.Config import org.pac4j.core.engine._ import org.pac4j.core.http.adapter.HttpActionAdapter import org.pac4j.core.profile.UserProfile -import akka.http.scaladsl.util.FastFuture._ -import akka.stream.Materializer +import org.apache.pekko.http.scaladsl.util.FastFuture._ +import org.apache.pekko.stream.Materializer import com.stackstate.pac4j.store.SessionStorage import org.pac4j.core.context.WebContext import org.pac4j.core.context.session.SessionStore import org.pac4j.core.matching.matcher.DefaultMatchers -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.{ExecutionContext, Future} import scala.collection.immutable import org.pac4j.core.util.Pac4jConstants -object AkkaHttpSecurity { - type AkkaHttpSecurityLogic = SecurityLogic - type AkkaHttpCallbackLogic = CallbackLogic - type AkkaHttpLogoutLogic = LogoutLogic +object PekkoHttpSecurity { + type PekkoHttpSecurityLogic = SecurityLogic + type PekkoHttpCallbackLogic = CallbackLogic + type PekkoHttpLogoutLogic = LogoutLogic def authorize(authorizer: Authorizer)(request: AuthenticatedRequest): Directive0 = - akkaHttpAuthorize(authorizer.isAuthorized(request.webContext, request.webContext.getSessionStore, request.profiles.asJava)) + pekkoHttpAuthorize(authorizer.isAuthorized(request.webContext, request.webContext.getSessionStore, request.profiles.asJava)) private def applyHeadersAndCookiesToResponse(changes: ResponseChanges)(httpResponse: HttpResponse): HttpResponse = { val regularHeaders: List[HttpHeader] = changes.headers @@ -44,7 +44,7 @@ object AkkaHttpSecurity { } /** - * Try to extract authentication credentials from form parameters using Akka's StrictForm unmarshallers. + * Try to extract authentication credentials from form parameters using Pekko's StrictForm unmarshallers. * If that fails, either form encoding is enforced, in which case the request fails, or the request proceeds. * If the request proceeds, other ways (e.g. basic auth) are assumed to be configured in pac4j in order to pass * credentials. @@ -73,14 +73,14 @@ object AkkaHttpSecurity { } } -class AkkaHttpSecurity(config: Config, sessionStorage: SessionStorage, val sessionCookieName: String = AkkaHttpWebContext.DEFAULT_COOKIE_NAME)( +class PekkoHttpSecurity(config: Config, sessionStorage: SessionStorage, val sessionCookieName: String = PekkoHttpWebContext.DEFAULT_COOKIE_NAME)( implicit val executionContext: ExecutionContext ) { - import AkkaHttpSecurity._ + import PekkoHttpSecurity._ @SuppressWarnings(Array("AsInstanceOf")) - private[pac4j] val securityLogic: AkkaHttpSecurityLogic = + private[pac4j] val securityLogic: PekkoHttpSecurityLogic = Option(config.getSecurityLogic) match { case Some(v) => v case None => new DefaultSecurityLogic @@ -90,31 +90,31 @@ class AkkaHttpSecurity(config: Config, sessionStorage: SessionStorage, val sessi private[pac4j] val actionAdapter: HttpActionAdapter = Option(config.getHttpActionAdapter) match { case Some(v) => v - case None => AkkaHttpActionAdapter + case None => PekkoHttpActionAdapter } @SuppressWarnings(Array("AsInstanceOf")) private[pac4j] val callbackLogic: CallbackLogic = Option(config.getCallbackLogic) match { - case Some(v) => v.asInstanceOf[AkkaHttpCallbackLogic] + case Some(v) => v.asInstanceOf[PekkoHttpCallbackLogic] case None => new DefaultCallbackLogic } @SuppressWarnings(Array("AsInstanceOf")) private[pac4j] val logoutLogic: LogoutLogic = Option(config.getLogoutLogic) match { - case Some(v) => v.asInstanceOf[AkkaHttpLogoutLogic] + case Some(v) => v.asInstanceOf[PekkoHttpLogoutLogic] case None => new DefaultLogoutLogic } /** * This directive constructs a pac4j context for a route. This means the request is interpreted into - * an AkkaHttpWebContext and any changes to this context are applied when the route returns (e.g. headers/cookies). + * an PekkoHttpWebContext and any changes to this context are applied when the route returns (e.g. headers/cookies). */ - def withContext(existingContext: Option[AkkaHttpWebContext] = None, formParams: Map[String, String] = Map.empty): Directive1[AkkaHttpWebContext] = - Directive[Tuple1[AkkaHttpWebContext]] { inner => ctx => - val akkaWebContext = existingContext.getOrElse( - new AkkaHttpWebContext( + def withContext(existingContext: Option[PekkoHttpWebContext] = None, formParams: Map[String, String] = Map.empty): Directive1[PekkoHttpWebContext] = + Directive[Tuple1[PekkoHttpWebContext]] { inner => ctx => + val pekkoWebContext = existingContext.getOrElse( + new PekkoHttpWebContext( request = ctx.request, formFields = formParams.toSeq, sessionStorage = sessionStorage, @@ -122,8 +122,8 @@ class AkkaHttpSecurity(config: Config, sessionStorage: SessionStorage, val sessi ) ) - inner(Tuple1(akkaWebContext))(ctx).map[RouteResult] { - case Complete(response) => Complete(applyHeadersAndCookiesToResponse(akkaWebContext.getChanges)(response)) + inner(Tuple1(pekkoWebContext))(ctx).map[RouteResult] { + case Complete(response) => Complete(applyHeadersAndCookiesToResponse(pekkoWebContext.getChanges)(response)) case rejection => rejection } } @@ -143,21 +143,21 @@ class AkkaHttpSecurity(config: Config, sessionStorage: SessionStorage, val sessi @SuppressWarnings(Array("NullAssignment")) def withAuthentication(clients: String = null /* Default null, meaning all defined clients */, authorizers: String = ""): Directive1[AuthenticatedRequest] = - withContext().flatMap { akkaWebContext => + withContext().flatMap { pekkoWebContext => Directive[Tuple1[AuthenticatedRequest]] { inner => ctx => // TODO This is a hack to ensure that any underlying Futures are scheduled (and handled in case of errors) from here // TODO Fix this properly Future.successful({}).flatMap { _ => val securityAccessAdapter: SecurityGrantedAccessAdapter = (context: WebContext, _: SessionStore, profiles: util.Collection[UserProfile], _: AnyRef) => { - val authenticatedRequest = AuthenticatedRequest(context.asInstanceOf[AkkaHttpWebContext], profiles.asScala.toList) + val authenticatedRequest = AuthenticatedRequest(context.asInstanceOf[PekkoHttpWebContext], profiles.asScala.toList) inner(Tuple1(authenticatedRequest))(ctx) } securityLogic .perform( - akkaWebContext, - akkaWebContext.getSessionStore, + pekkoWebContext, + pekkoWebContext.getSessionStore, config, securityAccessAdapter, actionAdapter, @@ -179,16 +179,16 @@ class AkkaHttpSecurity(config: Config, sessionStorage: SessionStorage, val sessi def callback(defaultUrl: String = Pac4jConstants.DEFAULT_URL_VALUE, defaultClient: Option[String] = None, enforceFormEncoding: Boolean = false, - existingContext: Option[AkkaHttpWebContext] = None, + existingContext: Option[PekkoHttpWebContext] = None, setCsrfCookie: Boolean = true): Route = withFormParameters(enforceFormEncoding) { formParams => - withContext(existingContext, formParams) { akkaWebContext => _ => + withContext(existingContext, formParams) { pekkoWebContext => _ => callbackLogic - .perform(akkaWebContext, akkaWebContext.getSessionStore, config, actionAdapter, defaultUrl, true, defaultClient.orNull) + .perform(pekkoWebContext, pekkoWebContext.getSessionStore, config, actionAdapter, defaultUrl, true, defaultClient.orNull) .asInstanceOf[Future[RouteResult]] .map { result => - if (setCsrfCookie) akkaWebContext.addResponseCsrfCookie() - akkaWebContext.addResponseSessionCookie() + if (setCsrfCookie) pekkoWebContext.addResponseCsrfCookie() + pekkoWebContext.addResponseSessionCookie() result } } @@ -199,11 +199,11 @@ class AkkaHttpSecurity(config: Config, sessionStorage: SessionStorage, val sessi localLogout: Boolean = true, destroySession: Boolean = true, centralLogout: Boolean = false): Route = { - withContext() { akkaWebContext => _ => + withContext() { pekkoWebContext => _ => logoutLogic .perform( - akkaWebContext, - akkaWebContext.getSessionStore, + pekkoWebContext, + pekkoWebContext.getSessionStore, config, actionAdapter, defaultUrl, diff --git a/src/main/scala/com/stackstate/pac4j/AkkaHttpWebContext.scala b/src/main/scala/com/stackstate/pac4j/PekkoHttpWebContext.scala similarity index 80% rename from src/main/scala/com/stackstate/pac4j/AkkaHttpWebContext.scala rename to src/main/scala/com/stackstate/pac4j/PekkoHttpWebContext.scala index b0e2f74..fc9b832 100644 --- a/src/main/scala/com/stackstate/pac4j/AkkaHttpWebContext.scala +++ b/src/main/scala/com/stackstate/pac4j/PekkoHttpWebContext.scala @@ -1,35 +1,35 @@ package com.stackstate.pac4j import java.util.{Optional, UUID} -import akka.http.scaladsl.model.HttpHeader.ParsingResult.{Error, Ok} -import akka.http.scaladsl.model.headers.HttpCookie -import akka.http.scaladsl.model.{ContentType, HttpHeader, HttpRequest} +import org.apache.pekko.http.scaladsl.model.HttpHeader.ParsingResult.{Error, Ok} +import org.apache.pekko.http.scaladsl.model.headers.HttpCookie +import org.apache.pekko.http.scaladsl.model.{ContentType, HttpHeader, HttpRequest} import com.stackstate.pac4j.authorizer.CsrfCookieAuthorizer -import com.stackstate.pac4j.http.AkkaHttpSessionStore +import com.stackstate.pac4j.http.PekkoHttpSessionStore import com.stackstate.pac4j.store.SessionStorage import org.pac4j.core.context.{Cookie, WebContext} -import compat.java8.OptionConverters._ -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ +import scala.jdk.OptionConverters._ /** - * The AkkaHttpWebContext is responsible for wrapping an HTTP request + * The PekkoHttpWebContext is responsible for wrapping an HTTP request * and stores changes that are produced by pac4j * and need to be applied to an HTTP response. */ -class AkkaHttpWebContext(val request: HttpRequest, - val formFields: Seq[(String, String)], - private[pac4j] val sessionStorage: SessionStorage, - val sessionCookieName: String) +class PekkoHttpWebContext(val request: HttpRequest, + val formFields: Seq[(String, String)], + private[pac4j] val sessionStorage: SessionStorage, + val sessionCookieName: String) extends WebContext { - import com.stackstate.pac4j.AkkaHttpWebContext._ + import com.stackstate.pac4j.PekkoHttpWebContext._ private var changes = ResponseChanges.empty //Only compute the request cookies once - private lazy val requestCookies = request.cookies.map { akkaCookie => - new Cookie(akkaCookie.name, akkaCookie.value) + private lazy val requestCookies = request.cookies.map { pekkoCookie => + new Cookie(pekkoCookie.name, pekkoCookie.value) }.asJavaCollection //Request parameters are composed of form fields and the query part of the uri. Stored in a lazy val in order to only compute it once @@ -74,7 +74,7 @@ class AkkaHttpWebContext(val request: HttpRequest, override def getRequestCookies: java.util.Collection[Cookie] = requestCookies - private def toAkkaHttpCookie(cookie: Cookie): HttpCookie = { + private def toPekkoHttpCookie(cookie: Cookie): HttpCookie = { HttpCookie( name = cookie.getName, value = cookie.getValue, @@ -89,11 +89,11 @@ class AkkaHttpWebContext(val request: HttpRequest, } override def addResponseCookie(cookie: Cookie): Unit = { - val httpCookie = toAkkaHttpCookie(cookie) + val httpCookie = toPekkoHttpCookie(cookie) changes = changes.copy(cookies = changes.cookies ++ List(httpCookie)) } - lazy val getSessionStore = new AkkaHttpSessionStore() + lazy val getSessionStore = new PekkoHttpSessionStore() override def getRemoteAddr: String = { request.getUri().getHost.address() @@ -109,9 +109,8 @@ class AkkaHttpWebContext(val request: HttpRequest, changes = changes.copy(headers = header :: changes.headers.filter(_.name != name)) } - @com.github.ghik.silencer.silent("mapValues") override def getRequestParameters: java.util.Map[String, Array[String]] = - requestParameters.mapValues(Array(_)).toMap.asJava + requestParameters.view.mapValues(Array(_)).toMap.asJava override def getFullRequestURL: String = { request.getUri().toString @@ -136,11 +135,11 @@ class AkkaHttpWebContext(val request: HttpRequest, } override def getRequestParameter(name: String): Optional[String] = { - requestParameters.get(name).asJava + requestParameters.get(name).toJava } override def getRequestHeader(name: String): Optional[String] = { - request.headers.find(_.name().toLowerCase() == name.toLowerCase).map(_.value).asJava + request.headers.find(_.name().toLowerCase() == name.toLowerCase).map(_.value).toJava } lazy val getScheme: String = request.getUri().getScheme @@ -155,7 +154,7 @@ class AkkaHttpWebContext(val request: HttpRequest, changes = changes.copy(attributes = changes.attributes ++ Map[String, AnyRef](name -> value)) override def getRequestAttribute(name: String): Optional[AnyRef] = - changes.attributes.get(name).asJava + changes.attributes.get(name).toJava def getContentType: Option[ContentType] = changes.contentType @@ -185,13 +184,13 @@ class AkkaHttpWebContext(val request: HttpRequest, } override def getResponseHeader(name: String): Optional[String] = { - changes.headers.find(_.name().toLowerCase() == name.toLowerCase).map(_.value).asJava + changes.headers.find(_.name().toLowerCase() == name.toLowerCase).map(_.value).toJava } } -object AkkaHttpWebContext { - def apply(request: HttpRequest, formFields: Seq[(String, String)], sessionStorage: SessionStorage, sessionCookieName: String): AkkaHttpWebContext = - new AkkaHttpWebContext(request, formFields, sessionStorage, sessionCookieName) +object PekkoHttpWebContext { + def apply(request: HttpRequest, formFields: Seq[(String, String)], sessionStorage: SessionStorage, sessionCookieName: String): PekkoHttpWebContext = + new PekkoHttpWebContext(request, formFields, sessionStorage, sessionCookieName) //This class is where all the HTTP response changes are stored so that they can later be applied to an HTTP Request case class ResponseChanges private (headers: List[HttpHeader], @@ -206,5 +205,5 @@ object AkkaHttpWebContext { } } - private[pac4j] val DEFAULT_COOKIE_NAME = "AkkaHttpPac4jSession" + private[pac4j] val DEFAULT_COOKIE_NAME = "PekkoHttpPac4jSession" } diff --git a/src/main/scala/com/stackstate/pac4j/authorizer/CsrfCookieAuthorizer.scala b/src/main/scala/com/stackstate/pac4j/authorizer/CsrfCookieAuthorizer.scala index 299b84a..3ed35fb 100644 --- a/src/main/scala/com/stackstate/pac4j/authorizer/CsrfCookieAuthorizer.scala +++ b/src/main/scala/com/stackstate/pac4j/authorizer/CsrfCookieAuthorizer.scala @@ -2,7 +2,7 @@ package com.stackstate.pac4j.authorizer import java.util.UUID -import com.stackstate.pac4j.AkkaHttpWebContext +import com.stackstate.pac4j.PekkoHttpWebContext import org.pac4j.core.context.Cookie import scala.concurrent.duration.FiniteDuration @@ -12,7 +12,7 @@ object CsrfCookieAuthorizer { val CookiePath = "/" - def apply(context: AkkaHttpWebContext, maxAge: Option[FiniteDuration]): AkkaHttpWebContext = { + def apply(context: PekkoHttpWebContext, maxAge: Option[FiniteDuration]): PekkoHttpWebContext = { val token = UUID.randomUUID.toString val cookieWithDomain = createCookie(token, maxAge) diff --git a/src/main/scala/com/stackstate/pac4j/http/AkkaHttpActionAdapter.scala b/src/main/scala/com/stackstate/pac4j/http/PekkoHttpActionAdapter.scala similarity index 81% rename from src/main/scala/com/stackstate/pac4j/http/AkkaHttpActionAdapter.scala rename to src/main/scala/com/stackstate/pac4j/http/PekkoHttpActionAdapter.scala index 72b43d0..511b56d 100644 --- a/src/main/scala/com/stackstate/pac4j/http/AkkaHttpActionAdapter.scala +++ b/src/main/scala/com/stackstate/pac4j/http/PekkoHttpActionAdapter.scala @@ -1,19 +1,19 @@ package com.stackstate.pac4j.http -import akka.http.scaladsl.model.StatusCodes._ -import akka.http.scaladsl.model.headers.Location -import akka.http.scaladsl.model._ -import akka.http.scaladsl.server.RouteResult.Complete -import com.stackstate.pac4j.AkkaHttpWebContext +import org.apache.pekko.http.scaladsl.model.StatusCodes._ +import org.apache.pekko.http.scaladsl.model.headers.Location +import org.apache.pekko.http.scaladsl.model._ +import org.apache.pekko.http.scaladsl.server.RouteResult.Complete +import com.stackstate.pac4j.PekkoHttpWebContext import org.pac4j.core.context.{HttpConstants, WebContext} import org.pac4j.core.exception.http._ import org.pac4j.core.http.adapter.HttpActionAdapter import scala.concurrent.Future -object AkkaHttpActionAdapter extends HttpActionAdapter { +object PekkoHttpActionAdapter extends HttpActionAdapter { override def adapt(action: HttpAction, ctx: WebContext): Future[Complete] = { - val context = ctx.asInstanceOf[AkkaHttpWebContext] + val context = ctx.asInstanceOf[PekkoHttpWebContext] Future.successful(Complete(action match { case _: UnauthorizedAction => // XHR requests don't receive a TEMP_REDIRECT but a UNAUTHORIZED. The client can handle this diff --git a/src/main/scala/com/stackstate/pac4j/http/AkkaHttpSessionStore.scala b/src/main/scala/com/stackstate/pac4j/http/PekkoHttpSessionStore.scala similarity index 59% rename from src/main/scala/com/stackstate/pac4j/http/AkkaHttpSessionStore.scala rename to src/main/scala/com/stackstate/pac4j/http/PekkoHttpSessionStore.scala index 587c6de..ed0f712 100644 --- a/src/main/scala/com/stackstate/pac4j/http/AkkaHttpSessionStore.scala +++ b/src/main/scala/com/stackstate/pac4j/http/PekkoHttpSessionStore.scala @@ -1,44 +1,44 @@ package com.stackstate.pac4j.http import java.util.Optional -import compat.java8.OptionConverters._ -import com.stackstate.pac4j.AkkaHttpWebContext +import scala.jdk.OptionConverters._ +import com.stackstate.pac4j.PekkoHttpWebContext import org.pac4j.core.context.WebContext import org.pac4j.core.context.session.SessionStore -class AkkaHttpSessionStore() extends SessionStore { +class PekkoHttpSessionStore() extends SessionStore { override def getSessionId(context: WebContext, createSession: Boolean): Optional[String] = { if (createSession) { - Optional.of(context.asInstanceOf[AkkaHttpWebContext].getOrCreateSessionId()) + Optional.of(context.asInstanceOf[PekkoHttpWebContext].getOrCreateSessionId()) } else { - context.asInstanceOf[AkkaHttpWebContext].getSessionId.asJava + context.asInstanceOf[PekkoHttpWebContext].getSessionId.toJava } } override def get(context: WebContext, key: String): Optional[Object] = - context.asInstanceOf[AkkaHttpWebContext].getSessionId match { - case Some(value) => context.asInstanceOf[AkkaHttpWebContext].sessionStorage.getSessionValue(value, key).asJava + context.asInstanceOf[PekkoHttpWebContext].getSessionId match { + case Some(value) => context.asInstanceOf[PekkoHttpWebContext].sessionStorage.getSessionValue(value, key).toJava case None => Optional.empty() } override def set(context: WebContext, key: String, value: scala.AnyRef): Unit = { context - .asInstanceOf[AkkaHttpWebContext] + .asInstanceOf[PekkoHttpWebContext] .sessionStorage - .setSessionValue(context.asInstanceOf[AkkaHttpWebContext].getOrCreateSessionId(), key, value) + .setSessionValue(context.asInstanceOf[PekkoHttpWebContext].getOrCreateSessionId(), key, value) () } - override def destroySession(context: WebContext): Boolean = context.asInstanceOf[AkkaHttpWebContext].destroySession() + override def destroySession(context: WebContext): Boolean = context.asInstanceOf[PekkoHttpWebContext].destroySession() override def getTrackableSession(context: WebContext): Optional[AnyRef] = - context.asInstanceOf[AkkaHttpWebContext].getSessionId.asInstanceOf[Option[AnyRef]].asJava + context.asInstanceOf[PekkoHttpWebContext].getSessionId.asInstanceOf[Option[AnyRef]].toJava override def buildFromTrackableSession(context: WebContext, trackableSession: scala.Any): Optional[SessionStore] = { trackableSession match { case session: String if session.nonEmpty => - context.asInstanceOf[AkkaHttpWebContext].trackSession(session) + context.asInstanceOf[PekkoHttpWebContext].trackSession(session) Optional.of(this) case _ => @@ -47,7 +47,7 @@ class AkkaHttpSessionStore() extends SessionStore { } override def renewSession(ctx: WebContext): Boolean = { - val context = ctx.asInstanceOf[AkkaHttpWebContext] + val context = ctx.asInstanceOf[PekkoHttpWebContext] context.getSessionId.foreach { sessionId => val sessionValues = context.sessionStorage.getSessionValues(sessionId) destroySession(context) diff --git a/src/test/scala/com/stackstate/pac4j/AkkaHttpActionAdapterTest.scala b/src/test/scala/com/stackstate/pac4j/AkkaHttpActionAdapterTest.scala deleted file mode 100644 index 450c7fc..0000000 --- a/src/test/scala/com/stackstate/pac4j/AkkaHttpActionAdapterTest.scala +++ /dev/null @@ -1,91 +0,0 @@ -package com.stackstate.pac4j - -import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpRequest, HttpResponse} -import org.scalatest.matchers.should.Matchers -import org.scalatest.wordspec.AnyWordSpecLike -import akka.http.scaladsl.model.StatusCodes._ -import akka.http.scaladsl.model.headers.HttpCookie -import akka.util.ByteString -import com.stackstate.pac4j.AkkaHttpActionAdapterTest.ActionInt -import com.stackstate.pac4j.http.AkkaHttpActionAdapter -import com.stackstate.pac4j.store.ForgetfulSessionStorage -import org.pac4j.core.exception.http.{ - BadRequestAction, - ForbiddenAction, - FoundAction, - HttpAction, - NoContentAction, - OkAction, - StatusAction, - UnauthorizedAction -} -import org.scalatest.concurrent.ScalaFutures - -class AkkaHttpActionAdapterTest extends AnyWordSpecLike with Matchers with ScalaFutures { - - lazy val immediatelyExpireCookie: HttpCookie = - HttpCookie.apply(name = AkkaHttpWebContext.DEFAULT_COOKIE_NAME, value = "", maxAge = Some(0), path = Some("/"), httpOnly = true) - - "AkkaHttpActionAdapter" should { - "convert 200 to OK" in withContext { context => - AkkaHttpActionAdapter.adapt(new OkAction(""), context).futureValue.response shouldEqual HttpResponse( - OK, - Nil, - HttpEntity(ContentTypes.`application/octet-stream`, ByteString("")) - ) - } - "convert 401 to Unauthorized for direct clients" in withContext { context => - AkkaHttpActionAdapter.adapt(new UnauthorizedAction, context).futureValue.response shouldEqual HttpResponse(Unauthorized) - context.getChanges.cookies shouldBe List(immediatelyExpireCookie) - } - "convert 401 to Unauthorized for indirect clients" in withContext { context => - context.getSessionStore.set(context, "state", "foo") - AkkaHttpActionAdapter.adapt(new UnauthorizedAction, context).futureValue.response shouldEqual HttpResponse(Unauthorized) - context.getChanges.cookies.map(_.name) shouldBe List(AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - } - "convert 302 to SeeOther (to support login flow) (direct client)" in withContext { context => - val r = AkkaHttpActionAdapter.adapt(new FoundAction("/login"), context).futureValue.response - r.status shouldEqual SeeOther - r.headers.head.value() shouldEqual "/login" - context.getChanges.cookies shouldBe List(immediatelyExpireCookie) - } - "convert 302 to SeeOther (to support login flow) (indirect client)" in withContext { context => - context.getSessionStore.set(context, "state", "foo") - val r = AkkaHttpActionAdapter.adapt(new FoundAction("/login"), context).futureValue.response - r.status shouldEqual SeeOther - r.headers.head.value() shouldEqual "/login" - context.getChanges.cookies.map(_.name) shouldBe List(AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - } - "convert 400 to BadRequest" in withContext { context => - AkkaHttpActionAdapter.adapt(new BadRequestAction, context).futureValue.response shouldEqual HttpResponse(BadRequest) - } - "convert 201 to Created" in withContext { context => - AkkaHttpActionAdapter.adapt(201.action(), context).futureValue.response shouldEqual HttpResponse(Created) - } - "convert 403 to Forbidden" in withContext { context => - AkkaHttpActionAdapter.adapt(new ForbiddenAction, context).futureValue.response shouldEqual HttpResponse(Forbidden) - } - "convert 204 to NoContent" in withContext { context => - AkkaHttpActionAdapter.adapt(NoContentAction.INSTANCE, context).futureValue.response shouldEqual HttpResponse(NoContent) - } - "convert 200 to OK with content set from the context" in withContext { context => - AkkaHttpActionAdapter.adapt(new OkAction("content"), context).futureValue.response shouldEqual HttpResponse - .apply(OK, Nil, HttpEntity(ContentTypes.`application/octet-stream`, ByteString("content"))) - } - "convert 200 to OK with content type set from the context" in withContext { context => - context.setResponseContentType("application/json") - AkkaHttpActionAdapter.adapt(new OkAction(""), context).futureValue.response shouldEqual HttpResponse - .apply(OK, Nil, HttpEntity(ContentTypes.`application/json`, ByteString(""))) - } - } - - def withContext(f: AkkaHttpWebContext => Unit): Unit = { - f(AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME)) - } -} - -object AkkaHttpActionAdapterTest { - implicit class ActionInt(val i: Int) extends AnyVal { - def action(): HttpAction = new StatusAction(i) - } -} diff --git a/src/test/scala/com/stackstate/pac4j/PekkoHttpActionAdapterTest.scala b/src/test/scala/com/stackstate/pac4j/PekkoHttpActionAdapterTest.scala new file mode 100644 index 0000000..535455f --- /dev/null +++ b/src/test/scala/com/stackstate/pac4j/PekkoHttpActionAdapterTest.scala @@ -0,0 +1,91 @@ +package com.stackstate.pac4j + +import org.apache.pekko.http.scaladsl.model.{ContentTypes, HttpEntity, HttpRequest, HttpResponse} +import org.scalatest.matchers.should.Matchers +import org.scalatest.wordspec.AnyWordSpecLike +import org.apache.pekko.http.scaladsl.model.StatusCodes._ +import org.apache.pekko.http.scaladsl.model.headers.HttpCookie +import org.apache.pekko.util.ByteString +import com.stackstate.pac4j.PekkoHttpActionAdapterTest.ActionInt +import com.stackstate.pac4j.http.PekkoHttpActionAdapter +import com.stackstate.pac4j.store.ForgetfulSessionStorage +import org.pac4j.core.exception.http.{ + BadRequestAction, + ForbiddenAction, + FoundAction, + HttpAction, + NoContentAction, + OkAction, + StatusAction, + UnauthorizedAction +} +import org.scalatest.concurrent.ScalaFutures + +class PekkoHttpActionAdapterTest extends AnyWordSpecLike with Matchers with ScalaFutures { + + lazy val immediatelyExpireCookie: HttpCookie = + HttpCookie.apply(name = PekkoHttpWebContext.DEFAULT_COOKIE_NAME, value = "", maxAge = Some(0), path = Some("/"), httpOnly = true) + + "PekkoHttpActionAdapter" should { + "convert 200 to OK" in withContext { context => + PekkoHttpActionAdapter.adapt(new OkAction(""), context).futureValue.response shouldEqual HttpResponse( + OK, + Nil, + HttpEntity(ContentTypes.`application/octet-stream`, ByteString("")) + ) + } + "convert 401 to Unauthorized for direct clients" in withContext { context => + PekkoHttpActionAdapter.adapt(new UnauthorizedAction, context).futureValue.response shouldEqual HttpResponse(Unauthorized) + context.getChanges.cookies shouldBe List(immediatelyExpireCookie) + } + "convert 401 to Unauthorized for indirect clients" in withContext { context => + context.getSessionStore.set(context, "state", "foo") + PekkoHttpActionAdapter.adapt(new UnauthorizedAction, context).futureValue.response shouldEqual HttpResponse(Unauthorized) + context.getChanges.cookies.map(_.name) shouldBe List(PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + } + "convert 302 to SeeOther (to support login flow) (direct client)" in withContext { context => + val r = PekkoHttpActionAdapter.adapt(new FoundAction("/login"), context).futureValue.response + r.status shouldEqual SeeOther + r.headers.head.value() shouldEqual "/login" + context.getChanges.cookies shouldBe List(immediatelyExpireCookie) + } + "convert 302 to SeeOther (to support login flow) (indirect client)" in withContext { context => + context.getSessionStore.set(context, "state", "foo") + val r = PekkoHttpActionAdapter.adapt(new FoundAction("/login"), context).futureValue.response + r.status shouldEqual SeeOther + r.headers.head.value() shouldEqual "/login" + context.getChanges.cookies.map(_.name) shouldBe List(PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + } + "convert 400 to BadRequest" in withContext { context => + PekkoHttpActionAdapter.adapt(new BadRequestAction, context).futureValue.response shouldEqual HttpResponse(BadRequest) + } + "convert 201 to Created" in withContext { context => + PekkoHttpActionAdapter.adapt(201.action(), context).futureValue.response shouldEqual HttpResponse(Created) + } + "convert 403 to Forbidden" in withContext { context => + PekkoHttpActionAdapter.adapt(new ForbiddenAction, context).futureValue.response shouldEqual HttpResponse(Forbidden) + } + "convert 204 to NoContent" in withContext { context => + PekkoHttpActionAdapter.adapt(NoContentAction.INSTANCE, context).futureValue.response shouldEqual HttpResponse(NoContent) + } + "convert 200 to OK with content set from the context" in withContext { context => + PekkoHttpActionAdapter.adapt(new OkAction("content"), context).futureValue.response shouldEqual HttpResponse + .apply(OK, Nil, HttpEntity(ContentTypes.`application/octet-stream`, ByteString("content"))) + } + "convert 200 to OK with content type set from the context" in withContext { context => + context.setResponseContentType("application/json") + PekkoHttpActionAdapter.adapt(new OkAction(""), context).futureValue.response shouldEqual HttpResponse + .apply(OK, Nil, HttpEntity(ContentTypes.`application/json`, ByteString(""))) + } + } + + def withContext(f: PekkoHttpWebContext => Unit): Unit = { + f(PekkoHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME)) + } +} + +object PekkoHttpActionAdapterTest { + implicit class ActionInt(val i: Int) extends AnyVal { + def action(): HttpAction = new StatusAction(i) + } +} diff --git a/src/test/scala/com/stackstate/pac4j/AkkaHttpSecurityTest.scala b/src/test/scala/com/stackstate/pac4j/PekkoHttpSecurityTest.scala similarity index 67% rename from src/test/scala/com/stackstate/pac4j/AkkaHttpSecurityTest.scala rename to src/test/scala/com/stackstate/pac4j/PekkoHttpSecurityTest.scala index 4dd39a4..bc77c41 100644 --- a/src/test/scala/com/stackstate/pac4j/AkkaHttpSecurityTest.scala +++ b/src/test/scala/com/stackstate/pac4j/PekkoHttpSecurityTest.scala @@ -2,14 +2,14 @@ package com.stackstate.pac4j import java.{lang, util} -import akka.http.scaladsl.model._ -import akka.http.scaladsl.model.headers.{HttpCookie, `Set-Cookie`} -import akka.http.scaladsl.server.Directives._ -import akka.http.scaladsl.server.{AuthorizationFailedRejection} -import akka.http.scaladsl.server.RouteResult.Complete -import akka.http.scaladsl.testkit.ScalatestRouteTest -import com.stackstate.pac4j.AkkaHttpSecurity.{AkkaHttpCallbackLogic, AkkaHttpLogoutLogic, AkkaHttpSecurityLogic} -import com.stackstate.pac4j.http.AkkaHttpActionAdapter +import org.apache.pekko.http.scaladsl.model._ +import org.apache.pekko.http.scaladsl.model.headers.{HttpCookie, `Set-Cookie`} +import org.apache.pekko.http.scaladsl.server.Directives._ +import org.apache.pekko.http.scaladsl.server.{AuthorizationFailedRejection} +import org.apache.pekko.http.scaladsl.server.RouteResult.Complete +import org.apache.pekko.http.scaladsl.testkit.ScalatestRouteTest +import com.stackstate.pac4j.PekkoHttpSecurity.{PekkoHttpCallbackLogic, PekkoHttpLogoutLogic, PekkoHttpSecurityLogic} +import com.stackstate.pac4j.http.PekkoHttpActionAdapter import com.stackstate.pac4j.store.{ForgetfulSessionStorage, InMemorySessionStorage} import org.pac4j.core.client.{Clients, IndirectClient} import org.pac4j.core.config.Config @@ -28,20 +28,20 @@ import scala.concurrent.Future import scala.concurrent.duration._ import org.pac4j.core.util.Pac4jConstants -class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestRouteTest { +class PekkoHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestRouteTest { - "AkkaHttpSecurity" should { + "PekkoHttpSecurity" should { "set the proper defaults" in { val config = new Config() - val akkaHttpSecurity = new AkkaHttpSecurity(config, new ForgetfulSessionStorage) - akkaHttpSecurity.actionAdapter shouldBe AkkaHttpActionAdapter - akkaHttpSecurity.securityLogic.getClass shouldBe classOf[DefaultSecurityLogic] - akkaHttpSecurity.callbackLogic.getClass shouldBe classOf[DefaultCallbackLogic] + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new ForgetfulSessionStorage) + pekkoHttpSecurity.actionAdapter shouldBe PekkoHttpActionAdapter + pekkoHttpSecurity.securityLogic.getClass shouldBe classOf[DefaultSecurityLogic] + pekkoHttpSecurity.callbackLogic.getClass shouldBe classOf[DefaultCallbackLogic] } } - "AkkaHttpSecurity.withAuthentication" should { + "PekkoHttpSecurity.withAuthentication" should { "uses provided securityLogic and pass the expected parameters" in { val config = new Config() @@ -50,15 +50,15 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } config.setHttpActionAdapter(actionAdapter) - val securityLogic: AkkaHttpSecurityLogic = (_: WebContext, - _: SessionStore, - _: Config, - _: SecurityGrantedAccessAdapter, - httpActionAdapter: HttpActionAdapter, - clients: String, - authorizers: String, - matchers: String, - _: AnyRef) => { + val securityLogic: PekkoHttpSecurityLogic = (_: WebContext, + _: SessionStore, + _: Config, + _: SecurityGrantedAccessAdapter, + httpActionAdapter: HttpActionAdapter, + clients: String, + authorizers: String, + matchers: String, + _: AnyRef) => { clients shouldBe "myclients" matchers shouldBe DefaultMatchers.SECURITYHEADERS matchers should not be empty @@ -69,9 +69,9 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } config.setSecurityLogic(securityLogic) - val akkaHttpSecurity = new AkkaHttpSecurity(config, new ForgetfulSessionStorage) + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new ForgetfulSessionStorage) - Get("/") ~> akkaHttpSecurity.withAuthentication("myclients", authorizers = "myauthorizers") { _ => + Get("/") ~> pekkoHttpSecurity.withAuthentication("myclients", authorizers = "myauthorizers") { _ => complete("problem!") } ~> check { status shouldEqual StatusCodes.OK @@ -83,21 +83,21 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR val config = new Config() val profile = new CommonProfile() - val securityLogic: AkkaHttpSecurityLogic = (context: WebContext, - sessionStore: SessionStore, - _: Config, - securityGrantedAccessAdapter: SecurityGrantedAccessAdapter, - _: HttpActionAdapter, - _: String, - _: String, - _: String, - _: AnyRef) => { + val securityLogic: PekkoHttpSecurityLogic = (context: WebContext, + sessionStore: SessionStore, + _: Config, + securityGrantedAccessAdapter: SecurityGrantedAccessAdapter, + _: HttpActionAdapter, + _: String, + _: String, + _: String, + _: AnyRef) => { securityGrantedAccessAdapter.adapt(context, sessionStore, List[UserProfile](profile).asJava) } config.setSecurityLogic(securityLogic) - val akkaHttpSecurity = new AkkaHttpSecurity(config, new ForgetfulSessionStorage) + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new ForgetfulSessionStorage) val route = - akkaHttpSecurity.withAuthentication() { authenticated => + pekkoHttpSecurity.withAuthentication() { authenticated => { authenticated.profiles.size shouldBe 1 authenticated.profiles.head shouldBe profile @@ -112,12 +112,12 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } } - "AkkaHttpSecurity.withContext" should { + "PekkoHttpSecurity.withContext" should { "sets response headers when they are set in the context" in { val config = new Config() - val akkaHttpSecurity = new AkkaHttpSecurity(config, new ForgetfulSessionStorage) + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new ForgetfulSessionStorage) - Get("/") ~> akkaHttpSecurity.withContext() { context => + Get("/") ~> pekkoHttpSecurity.withContext() { context => context.setResponseHeader("MyHeader", "MyValue") complete("called!") } ~> check { @@ -129,9 +129,9 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR "sets response cookies (deduplicated) when they're set in the context" in { val config = new Config() - val akkaHttpSecurity = new AkkaHttpSecurity(config, new ForgetfulSessionStorage) + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new ForgetfulSessionStorage) - Get("/") ~> akkaHttpSecurity.withContext() { context => + Get("/") ~> pekkoHttpSecurity.withContext() { context => val cookie = new Cookie("MyCookie", "MyValue") cookie.setSecure(true) cookie.setMaxAge(100) @@ -157,12 +157,12 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR "get request parameters from a form" in { val config = new Config() - val akkaHttpSecurity = new AkkaHttpSecurity(config, new ForgetfulSessionStorage) + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new ForgetfulSessionStorage) val postRequest = HttpRequest(HttpMethods.POST, "/", entity = HttpEntity(MediaTypes.`application/x-www-form-urlencoded`, "username=testuser".getBytes)) - postRequest ~> akkaHttpSecurity.withFormParameters(enforceFormEncoding = false) { params => + postRequest ~> pekkoHttpSecurity.withFormParameters(enforceFormEncoding = false) { params => params("username") shouldEqual "testuser" complete("called!") } ~> check { @@ -173,11 +173,11 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR "fail a request when no parameters exist in a form and enforceFormEncoding is enabled" in { val config = new Config() - val akkaHttpSecurity = new AkkaHttpSecurity(config, new ForgetfulSessionStorage) + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new ForgetfulSessionStorage) val postRequest = HttpRequest(HttpMethods.POST, "/", entity = HttpEntity(ContentType(MediaTypes.`application/json`), "".getBytes)) - postRequest ~> akkaHttpSecurity.withFormParameters(enforceFormEncoding = true) { _ => + postRequest ~> pekkoHttpSecurity.withFormParameters(enforceFormEncoding = true) { _ => fail("perform should never be called!") } ~> check { status shouldEqual StatusCodes.InternalServerError @@ -185,7 +185,7 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } } - "AkkaHttpSecurity.callback" should { + "PekkoHttpSecurity.callback" should { "uses provided callbackLogic and pass the expected parameters" in { val config = new Config() @@ -194,7 +194,7 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } config.setHttpActionAdapter(actionAdapter) - config.setCallbackLogic(new AkkaHttpCallbackLogic { + config.setCallbackLogic(new PekkoHttpCallbackLogic { override def perform(webContext: WebContext, sessionStore: SessionStore, config: Config, @@ -212,24 +212,24 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } }) - val akkaHttpSecurity = new AkkaHttpSecurity(config, new ForgetfulSessionStorage) + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new ForgetfulSessionStorage) - Get("/") ~> akkaHttpSecurity.callback("/blaat", Some("Yooo")) ~> check { + Get("/") ~> pekkoHttpSecurity.callback("/blaat", Some("Yooo")) ~> check { status shouldEqual StatusCodes.OK responseAs[String] shouldBe "called!" } } - "run the callbackLogic reusing an akka http context" in { + "run the callbackLogic reusing an pekko http context" in { val config = new Config() - val existingContext = AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME) + val existingContext = PekkoHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME) val actionAdapter = new HttpActionAdapter { override def adapt(action: HttpAction, context: WebContext): AnyRef = ??? } config.setHttpActionAdapter(actionAdapter) - config.setCallbackLogic(new AkkaHttpCallbackLogic { + config.setCallbackLogic(new PekkoHttpCallbackLogic { override def perform(webContext: WebContext, sessionStore: SessionStore, config: Config, @@ -237,7 +237,7 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR defaultUrl: String, renewSession: lang.Boolean, defaultClient: String): AnyRef = { - existingContext.getSessionId shouldBe webContext.asInstanceOf[AkkaHttpWebContext].getSessionId + existingContext.getSessionId shouldBe webContext.asInstanceOf[PekkoHttpWebContext].getSessionId httpActionAdapter shouldBe actionAdapter defaultUrl shouldBe "/blaat" renewSession shouldBe true @@ -247,9 +247,9 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } }) - val akkaHttpSecurity = new AkkaHttpSecurity(config, new ForgetfulSessionStorage) + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new ForgetfulSessionStorage) - Get("/") ~> akkaHttpSecurity + Get("/") ~> pekkoHttpSecurity .callback("/blaat", Some("Yooo"), existingContext = Some(existingContext)) ~> check { status shouldEqual StatusCodes.OK responseAs[String] shouldBe "called!" @@ -258,13 +258,13 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR "run the callbackLogic should not send back a sessionId if the set csrf cookie is false" in { val config = new Config() - val existingContext = AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME) + val existingContext = PekkoHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME) val actionAdapter = new HttpActionAdapter { override def adapt(action: HttpAction, context: WebContext): AnyRef = ??? } config.setHttpActionAdapter(actionAdapter) - config.setCallbackLogic(new AkkaHttpCallbackLogic { + config.setCallbackLogic(new PekkoHttpCallbackLogic { override def perform(webContext: WebContext, sessionStore: SessionStore, config: Config, @@ -276,30 +276,30 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } }) - val akkaHttpSecurity = new AkkaHttpSecurity(config, new ForgetfulSessionStorage) + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new ForgetfulSessionStorage) - Get("/") ~> akkaHttpSecurity + Get("/") ~> pekkoHttpSecurity .callback("/blaat", Some("Yooo"), existingContext = Some(existingContext), setCsrfCookie = false) ~> check { // Session Store is empty so `addResponseSessionCookie` will create a token that will expire immediately - header("Set-Cookie").get.value().contains("AkkaHttpPac4jSession=; Max-Age=0;") shouldBe true + header("Set-Cookie").get.value().contains("PekkoHttpPac4jSession=; Max-Age=0;") shouldBe true } } "run the callbackLogic should send back a sessionId if the csrf cookie is true" in { val config = new Config() - val existingContext = AkkaHttpWebContext( + val existingContext = PekkoHttpWebContext( HttpRequest(uri = "http://test.com"), Seq.empty, new InMemorySessionStorage(3.minutes), - AkkaHttpWebContext.DEFAULT_COOKIE_NAME + PekkoHttpWebContext.DEFAULT_COOKIE_NAME ) val actionAdapter = new HttpActionAdapter { override def adapt(action: HttpAction, context: WebContext): AnyRef = ??? } config.setHttpActionAdapter(actionAdapter) - config.setCallbackLogic(new AkkaHttpCallbackLogic { + config.setCallbackLogic(new PekkoHttpCallbackLogic { override def perform(webContext: WebContext, sessionStore: SessionStore, config: Config, @@ -311,18 +311,18 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } }) - val akkaHttpSecurity = new AkkaHttpSecurity(config, new InMemorySessionStorage(3.minutes)) - Get("http://test.com/") ~> akkaHttpSecurity + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new InMemorySessionStorage(3.minutes)) + Get("http://test.com/") ~> pekkoHttpSecurity .callback("/blaat", Some("Yooo"), existingContext = Some(existingContext), setCsrfCookie = true) ~> check { val localHeaders: Seq[HttpHeader] = headers val threeMinutesInSeconds = 180 // When `addResponseCsrfCookie` is called the method `getOrCreateSessionId` is called which creates a Session // when `addResponseSessionCookie` is called there is already a session so a cookie with value is added. localHeaders.find(_.value().contains("pac4jCsrfToken")).get.value().contains(s"Max-Age=$threeMinutesInSeconds;") shouldBe true - localHeaders.find(_.value().contains("AkkaHttpPac4jSession")).get.value().contains(s"Max-Age=$threeMinutesInSeconds;") shouldBe true + localHeaders.find(_.value().contains("PekkoHttpPac4jSession")).get.value().contains(s"Max-Age=$threeMinutesInSeconds;") shouldBe true val csrfCookies: Seq[HttpCookie] = localHeaders.collect { - case setCookie: `Set-Cookie` if setCookie.cookie.name() == "pac4jCsrfToken" => setCookie.cookie + case setCookie: `Set-Cookie` if setCookie.cookie.name == "pac4jCsrfToken" => setCookie.cookie } // Previous version always added the two cookies. Current version doesn't need domain. // We add the two to keep it backwards compatible. @@ -332,13 +332,13 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } } - "AkkaHttpSecurity.authorize" should { + "PekkoHttpSecurity.authorize" should { "pass the provided authenticationRequest to the authorizer" in { val profile = new CommonProfile() - val context = AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME) + val context = PekkoHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME) val route = - AkkaHttpSecurity.authorize((_: WebContext, _: SessionStore, profiles: util.List[UserProfile]) => { + PekkoHttpSecurity.authorize((_: WebContext, _: SessionStore, profiles: util.List[UserProfile]) => { profiles.size() shouldBe 1 profiles.get(0) shouldBe profile false @@ -350,10 +350,10 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } "reject when authorization fails" in { - val context = AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME) + val context = PekkoHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME) val route = - AkkaHttpSecurity.authorize((_: WebContext, _: SessionStore, _: util.List[UserProfile]) => { + PekkoHttpSecurity.authorize((_: WebContext, _: SessionStore, _: util.List[UserProfile]) => { false })(AuthenticatedRequest(context, List.empty)) { complete("oops!") @@ -363,10 +363,10 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } "succeed when authorization succeeded" in { - val context = AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME) + val context = PekkoHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME) val route = - AkkaHttpSecurity.authorize((_: WebContext, _: SessionStore, _: util.List[UserProfile]) => { + PekkoHttpSecurity.authorize((_: WebContext, _: SessionStore, _: util.List[UserProfile]) => { true })(AuthenticatedRequest(context, List.empty)) { complete("cool!") @@ -379,12 +379,12 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } } - "AkkaHttpSecurity.logout" should { + "PekkoHttpSecurity.logout" should { "run the callbackLogic with the expected parameters" in { val config = new Config() - config.setHttpActionAdapter(AkkaHttpActionAdapter) - config.setLogoutLogic(new AkkaHttpLogoutLogic { + config.setHttpActionAdapter(PekkoHttpActionAdapter) + config.setLogoutLogic(new PekkoHttpLogoutLogic { override def perform(context: WebContext, sessionStore: SessionStore, config: Config, @@ -394,7 +394,7 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR localLogout: lang.Boolean, destroySession: lang.Boolean, centralLogout: lang.Boolean): AnyRef = { - httpActionAdapter shouldBe AkkaHttpActionAdapter + httpActionAdapter shouldBe PekkoHttpActionAdapter defaultUrl shouldBe "/home" logoutUrlPattern shouldBe "*" localLogout shouldBe false @@ -404,9 +404,9 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } }) - val akkaHttpSecurity = new AkkaHttpSecurity(config, new ForgetfulSessionStorage) + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new ForgetfulSessionStorage) - Get("/") ~> akkaHttpSecurity.logout("/home", "*", localLogout = false, destroySession = false) ~> check { + Get("/") ~> pekkoHttpSecurity.logout("/home", "*", localLogout = false, destroySession = false) ~> check { status shouldEqual StatusCodes.OK responseAs[String] shouldBe "logout!" } @@ -429,7 +429,7 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR inputLocalLogout: lang.Boolean, inputDestroySession: lang.Boolean, inputCentralLogout: lang.Boolean): AnyRef = { - val context = ctx.asInstanceOf[AkkaHttpWebContext] + val context = ctx.asInstanceOf[PekkoHttpWebContext] val profiles = new util.HashMap[String, UserProfile]() profiles.put("john", new CommonProfile()) context.sessionStorage.setSessionValue(context.getOrCreateSessionId(), Pac4jConstants.USER_PROFILES, profiles) @@ -453,13 +453,13 @@ class AkkaHttpSecurityTest extends AnyWordSpecLike with Matchers with ScalatestR } } - config.setHttpActionAdapter(AkkaHttpActionAdapter) + config.setHttpActionAdapter(PekkoHttpActionAdapter) config.setLogoutLogic(logoutLogic) config.setClients(new Clients("url", client)) - val akkaHttpSecurity = new AkkaHttpSecurity(config, new InMemorySessionStorage(5000.seconds)) + val pekkoHttpSecurity = new PekkoHttpSecurity(config, new InMemorySessionStorage(5000.seconds)) - Get("/") ~> akkaHttpSecurity.logout("/home", "*") ~> check { + Get("/") ~> pekkoHttpSecurity.logout("/home", "*") ~> check { status shouldEqual StatusCodes.SeeOther header("Location").get.value shouldBe "/home" } diff --git a/src/test/scala/com/stackstate/pac4j/AkkaHttpWebContextTest.scala b/src/test/scala/com/stackstate/pac4j/PekkoHttpWebContextTest.scala similarity index 82% rename from src/test/scala/com/stackstate/pac4j/AkkaHttpWebContextTest.scala rename to src/test/scala/com/stackstate/pac4j/PekkoHttpWebContextTest.scala index fa69e69..73e2bd6 100644 --- a/src/test/scala/com/stackstate/pac4j/AkkaHttpWebContextTest.scala +++ b/src/test/scala/com/stackstate/pac4j/PekkoHttpWebContextTest.scala @@ -2,9 +2,9 @@ package com.stackstate.pac4j import java.util.Optional -import akka.http.scaladsl.model.HttpHeader.ParsingResult.Ok -import akka.http.scaladsl.model.headers.{Cookie, HttpCookie} -import akka.http.scaladsl.model._ +import org.apache.pekko.http.scaladsl.model.HttpHeader.ParsingResult.Ok +import org.apache.pekko.http.scaladsl.model.headers.{Cookie, HttpCookie} +import org.apache.pekko.http.scaladsl.model._ import com.stackstate.pac4j.store.SessionStorage._ import com.stackstate.pac4j.store.{ForgetfulSessionStorage, SessionStorage} @@ -13,13 +13,13 @@ import org.scalatest.wordspec.AnyWordSpecLike import scala.collection.JavaConverters._ import scala.concurrent.duration._ -import akka.http.scaladsl.model.headers.Location +import org.apache.pekko.http.scaladsl.model.headers.Location -class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { +class PekkoHttpWebContextTest extends AnyWordSpecLike with Matchers { lazy val cookie = ("cookieName", "cookieValue") val uuidRegex = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" - "AkkaHttpWebContext" should { + "PekkoHttpWebContext" should { "get/set request cookies" in withContext(cookies = List(Cookie("cookieName", "cookieValue"))) { webContext => val contextCookie = webContext.getRequestCookies contextCookie.asScala.map(cookie => (cookie.getName, cookie.getValue)) shouldEqual Seq(cookie) @@ -111,9 +111,9 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { }) { webContext => val sessionId = webContext.getOrCreateSessionId() webContext.addResponseSessionCookie() - webContext.getChanges.cookies.find(_.name == AkkaHttpWebContext.DEFAULT_COOKIE_NAME) shouldBe Some( + webContext.getChanges.cookies.find(_.name == PekkoHttpWebContext.DEFAULT_COOKIE_NAME) shouldBe Some( HttpCookie( - name = AkkaHttpWebContext.DEFAULT_COOKIE_NAME, + name = PekkoHttpWebContext.DEFAULT_COOKIE_NAME, value = sessionId, expires = None, maxAge = Some(3), @@ -129,11 +129,11 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { "don't add a cookie when the session was expired" in withContext(sessionStorage = new ForgetfulSessionStorage { override def renewSession(session: SessionKey): Boolean = false }) { webContext => - webContext.getChanges.cookies.find(_.name == AkkaHttpWebContext.DEFAULT_COOKIE_NAME) shouldBe None + webContext.getChanges.cookies.find(_.name == PekkoHttpWebContext.DEFAULT_COOKIE_NAME) shouldBe None } "don't add a cookie when the session is empty" in withContext(sessionStorage = new ForgetfulSessionStorage {}) { webContext => - webContext.getChanges.cookies.find(_.name == AkkaHttpWebContext.DEFAULT_COOKIE_NAME) shouldBe None + webContext.getChanges.cookies.find(_.name == PekkoHttpWebContext.DEFAULT_COOKIE_NAME) shouldBe None } "make the session cookie secure when running over https" in withContext(scheme = "https", sessionStorage = new ForgetfulSessionStorage { @@ -143,11 +143,11 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { }) { webContext => webContext.getOrCreateSessionId() webContext.addResponseSessionCookie() - webContext.getChanges.cookies.find(_.name == AkkaHttpWebContext.DEFAULT_COOKIE_NAME).get.secure shouldBe true + webContext.getChanges.cookies.find(_.name == PekkoHttpWebContext.DEFAULT_COOKIE_NAME).get.secure shouldBe true } "pick up the session cookie and send it back" in withContext( - cookies = List(Cookie(AkkaHttpWebContext.DEFAULT_COOKIE_NAME, "my_session")), + cookies = List(Cookie(PekkoHttpWebContext.DEFAULT_COOKIE_NAME, "my_session")), sessionStorage = new ForgetfulSessionStorage { override val sessionLifetime = 3.seconds @@ -157,11 +157,11 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { } ) { webContext => webContext.addResponseSessionCookie() - webContext.getChanges.cookies.find(_.name == AkkaHttpWebContext.DEFAULT_COOKIE_NAME).isDefined shouldEqual true + webContext.getChanges.cookies.find(_.name == PekkoHttpWebContext.DEFAULT_COOKIE_NAME).isDefined shouldEqual true } "pick up the session cookie from cookies that are no longer sessions" in withContext( - cookies = List(Cookie(AkkaHttpWebContext.DEFAULT_COOKIE_NAME, "some_session"), Cookie(AkkaHttpWebContext.DEFAULT_COOKIE_NAME, "my_session")), + cookies = List(Cookie(PekkoHttpWebContext.DEFAULT_COOKIE_NAME, "some_session"), Cookie(PekkoHttpWebContext.DEFAULT_COOKIE_NAME, "my_session")), sessionStorage = new ForgetfulSessionStorage { override val sessionLifetime = 3.seconds @@ -173,11 +173,11 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { webContext.trackSession("my_session") // same as set webContext.getSessionStore.set(webContext, "my_session", "foo") webContext.addResponseSessionCookie() - webContext.getChanges.cookies.find(_.name == AkkaHttpWebContext.DEFAULT_COOKIE_NAME).get.value shouldEqual "my_session" + webContext.getChanges.cookies.find(_.name == PekkoHttpWebContext.DEFAULT_COOKIE_NAME).get.value shouldEqual "my_session" } "creates a new sessionId when the cookie was expired" in withContext( - cookies = List(Cookie(AkkaHttpWebContext.DEFAULT_COOKIE_NAME, "my_session")), + cookies = List(Cookie(PekkoHttpWebContext.DEFAULT_COOKIE_NAME, "my_session")), sessionStorage = new ForgetfulSessionStorage { override val sessionLifetime = 3.seconds @@ -190,7 +190,7 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { } "creates a new sessionId when the session was destroyed" in withContext( - cookies = List(Cookie(AkkaHttpWebContext.DEFAULT_COOKIE_NAME, "my_session")), + cookies = List(Cookie(PekkoHttpWebContext.DEFAULT_COOKIE_NAME, "my_session")), sessionStorage = new ForgetfulSessionStorage { override val sessionLifetime = 3.seconds @@ -202,7 +202,7 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { } "stores the trackable session when requested" in withContext( - cookies = List(Cookie(AkkaHttpWebContext.DEFAULT_COOKIE_NAME, "my_session")), + cookies = List(Cookie(PekkoHttpWebContext.DEFAULT_COOKIE_NAME, "my_session")), sessionStorage = new ForgetfulSessionStorage { override val sessionLifetime = 3.seconds @@ -220,7 +220,7 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { } "getOrCreateSessionId return a valid SessionId if an empty string is defined" in withContext( - cookies = List(Cookie(AkkaHttpWebContext.DEFAULT_COOKIE_NAME, "")), + cookies = List(Cookie(PekkoHttpWebContext.DEFAULT_COOKIE_NAME, "")), sessionStorage = new ForgetfulSessionStorage { override val sessionLifetime = 3.seconds @@ -231,7 +231,7 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { } "getOrCreateSessionId return the defined sessionId if its valid" in withContext( - cookies = List(Cookie(AkkaHttpWebContext.DEFAULT_COOKIE_NAME, "validId")), + cookies = List(Cookie(PekkoHttpWebContext.DEFAULT_COOKIE_NAME, "validId")), sessionStorage = new ForgetfulSessionStorage { override val sessionLifetime = 3.seconds @@ -245,14 +245,14 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { override def sessionExists(sessionKey: SessionKey): Boolean = true }) { webContext => val immediatelyExpireCookie: HttpCookie = - HttpCookie.apply(name = AkkaHttpWebContext.DEFAULT_COOKIE_NAME, value = "", maxAge = Some(0), path = Some("/"), httpOnly = true) + HttpCookie.apply(name = PekkoHttpWebContext.DEFAULT_COOKIE_NAME, value = "", maxAge = Some(0), path = Some("/"), httpOnly = true) webContext.addResponseSessionCookie() webContext.getChanges.cookies shouldBe List(immediatelyExpireCookie) } "addResponseSessionCookie with a non-empty session returns a valid cookie" in withContext( - cookies = List(Cookie(AkkaHttpWebContext.DEFAULT_COOKIE_NAME, "validId")), + cookies = List(Cookie(PekkoHttpWebContext.DEFAULT_COOKIE_NAME, "validId")), sessionStorage = new ForgetfulSessionStorage { override val sessionLifetime = 3.seconds @@ -260,14 +260,14 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { } ) { webContext => val validCookie: HttpCookie = - HttpCookie.apply(name = AkkaHttpWebContext.DEFAULT_COOKIE_NAME, value = "validId", maxAge = Some(3), path = Some("/"), httpOnly = true) + HttpCookie.apply(name = PekkoHttpWebContext.DEFAULT_COOKIE_NAME, value = "validId", maxAge = Some(3), path = Some("/"), httpOnly = true) webContext.addResponseSessionCookie() webContext.getChanges.cookies shouldBe List(validCookie) } "when getSessionId is called and the session exists in the store should return it" in withContext( - cookies = List(Cookie(AkkaHttpWebContext.DEFAULT_COOKIE_NAME, "validId")), + cookies = List(Cookie(PekkoHttpWebContext.DEFAULT_COOKIE_NAME, "validId")), sessionStorage = new ForgetfulSessionStorage { override val sessionLifetime = 3.seconds @@ -278,7 +278,7 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { } "when getSessionId is called and the session doesn't exists in the store should return None" in withContext( - cookies = List(Cookie(AkkaHttpWebContext.DEFAULT_COOKIE_NAME, "notValidAnyMore")), + cookies = List(Cookie(PekkoHttpWebContext.DEFAULT_COOKIE_NAME, "notValidAnyMore")), sessionStorage = new ForgetfulSessionStorage { override val sessionLifetime = 3.seconds @@ -296,12 +296,12 @@ class AkkaHttpWebContextTest extends AnyWordSpecLike with Matchers { hostAddress: String = "", hostPort: Int = 0, formFields: Seq[(String, String)] = Seq.empty, - sessionStorage: SessionStorage = new ForgetfulSessionStorage)(f: AkkaHttpWebContext => Unit): Unit = { + sessionStorage: SessionStorage = new ForgetfulSessionStorage)(f: PekkoHttpWebContext => Unit): Unit = { val parsedHeaders: List[HttpHeader] = requestHeaders.map { case (k, v) => HttpHeader.parse(k, v) }.collect { case Ok(header, _) => header } val completeHeaders: List[HttpHeader] = parsedHeaders ++ cookies val uri = Uri(url).withScheme(scheme).withAuthority(hostAddress, hostPort) val request = HttpRequest(uri = uri, headers = completeHeaders) - f(AkkaHttpWebContext(request, formFields, sessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME)) + f(PekkoHttpWebContext(request, formFields, sessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME)) } } diff --git a/src/test/scala/com/stackstate/pac4j/http/AkkaHttpSessionStoreTest.scala b/src/test/scala/com/stackstate/pac4j/http/AkkaHttpSessionStoreTest.scala deleted file mode 100644 index 6925ac5..0000000 --- a/src/test/scala/com/stackstate/pac4j/http/AkkaHttpSessionStoreTest.scala +++ /dev/null @@ -1,94 +0,0 @@ -package com.stackstate.pac4j.http - -import akka.http.scaladsl.model.HttpRequest -import akka.http.scaladsl.testkit.ScalatestRouteTest -import com.stackstate.pac4j.AkkaHttpWebContext -import com.stackstate.pac4j.store.{ForgetfulSessionStorage, InMemorySessionStorage} -import org.scalatest.matchers.should.Matchers -import org.scalatest.wordspec.AnyWordSpecLike - -import java.util.Optional -import scala.concurrent.duration._ - -class AkkaHttpSessionStoreTest extends AnyWordSpecLike with Matchers with ScalatestRouteTest { - "AkkaHttpSessionStore.get" should { - "return the None if nothing exists in the store" in { - val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - new AkkaHttpSessionStore().getSessionId(context, createSession = false) shouldBe Optional.empty() - } - - "return an existing session if one exist" in { - val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - context.trackSession("foo") - new AkkaHttpSessionStore().getSessionId(context, createSession = false) shouldBe Optional.of("foo") - } - } - - "AkkaHttpSessionStore.getOrCreateSessionId" should { - "return a valid session if one doesn't exist" in { - val uuidRegex = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" - val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - new AkkaHttpSessionStore().getSessionId(context, createSession = true).get().matches(uuidRegex) shouldBe true - } - - "return an existing session if one exist" in { - val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - context.trackSession("foo") - new AkkaHttpSessionStore().getSessionId(context, createSession = false).get() shouldBe "foo" - } - } - - "AkkaHttpSessionStore.get" should { - "return null when the data is not available" in { - val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - new AkkaHttpSessionStore().get(context, "mykey") shouldBe Optional.empty() - } - - "return the data when available" in { - val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - new AkkaHttpSessionStore().set(context, "mykey", "yooo") - new AkkaHttpSessionStore().get(context, "mykey") shouldBe Optional.of("yooo") - } - } - - "AkkaHttpSessionStore.destroySession" should { - "result in an empty session" in { - val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - val sessionStore = new AkkaHttpSessionStore() - sessionStore.set(context, "mykey", "yooo") - sessionStore.destroySession(context) - sessionStore.get(context, "mykey") shouldBe Optional.empty() - } - } - - "AkkaHttpSessionStore.getTrackableSession" should { - "return an optional of the current session" in { - val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - context.trackSession("foo") - new AkkaHttpSessionStore().getTrackableSession(context) shouldBe Optional.of("foo") - } - - "return empty when there is no current session" in { - val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - new AkkaHttpSessionStore().getTrackableSession(context) shouldBe Optional.empty() - } - } - - "AkkaHttpSessionStore.renewSession" should { - "result in a non-empty session if a session exists" in { - val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - val sessionStore = new AkkaHttpSessionStore() - sessionStore.set(context, "mykey", "bar") - sessionStore.renewSession(context) - sessionStore.get(context, "mykey") should not be Optional.of("invalid") - sessionStore.get(context, "mykey") shouldBe Optional.of("bar") - } - - "result in a empty session if a session doesn't exists" in { - val context = new AkkaHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), AkkaHttpWebContext.DEFAULT_COOKIE_NAME) - val sessionStore = new AkkaHttpSessionStore() - sessionStore.renewSession(context) - sessionStore.get(context, "mykey") shouldBe Optional.empty() - } - } -} diff --git a/src/test/scala/com/stackstate/pac4j/http/PekkoHttpSessionStoreTest.scala b/src/test/scala/com/stackstate/pac4j/http/PekkoHttpSessionStoreTest.scala new file mode 100644 index 0000000..dee3430 --- /dev/null +++ b/src/test/scala/com/stackstate/pac4j/http/PekkoHttpSessionStoreTest.scala @@ -0,0 +1,94 @@ +package com.stackstate.pac4j.http + +import org.apache.pekko.http.scaladsl.model.HttpRequest +import org.apache.pekko.http.scaladsl.testkit.ScalatestRouteTest +import com.stackstate.pac4j.PekkoHttpWebContext +import com.stackstate.pac4j.store.{ForgetfulSessionStorage, InMemorySessionStorage} +import org.scalatest.matchers.should.Matchers +import org.scalatest.wordspec.AnyWordSpecLike + +import java.util.Optional +import scala.concurrent.duration._ + +class PekkoHttpSessionStoreTest extends AnyWordSpecLike with Matchers with ScalatestRouteTest { + "PekkoHttpSessionStore.get" should { + "return the None if nothing exists in the store" in { + val context = new PekkoHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + new PekkoHttpSessionStore().getSessionId(context, createSession = false) shouldBe Optional.empty() + } + + "return an existing session if one exist" in { + val context = new PekkoHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + context.trackSession("foo") + new PekkoHttpSessionStore().getSessionId(context, createSession = false) shouldBe Optional.of("foo") + } + } + + "PekkoHttpSessionStore.getOrCreateSessionId" should { + "return a valid session if one doesn't exist" in { + val uuidRegex = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" + val context = new PekkoHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + new PekkoHttpSessionStore().getSessionId(context, createSession = true).get().matches(uuidRegex) shouldBe true + } + + "return an existing session if one exist" in { + val context = new PekkoHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + context.trackSession("foo") + new PekkoHttpSessionStore().getSessionId(context, createSession = false).get() shouldBe "foo" + } + } + + "PekkoHttpSessionStore.get" should { + "return null when the data is not available" in { + val context = new PekkoHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + new PekkoHttpSessionStore().get(context, "mykey") shouldBe Optional.empty() + } + + "return the data when available" in { + val context = new PekkoHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + new PekkoHttpSessionStore().set(context, "mykey", "yooo") + new PekkoHttpSessionStore().get(context, "mykey") shouldBe Optional.of("yooo") + } + } + + "PekkoHttpSessionStore.destroySession" should { + "result in an empty session" in { + val context = new PekkoHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + val sessionStore = new PekkoHttpSessionStore() + sessionStore.set(context, "mykey", "yooo") + sessionStore.destroySession(context) + sessionStore.get(context, "mykey") shouldBe Optional.empty() + } + } + + "PekkoHttpSessionStore.getTrackableSession" should { + "return an optional of the current session" in { + val context = new PekkoHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + context.trackSession("foo") + new PekkoHttpSessionStore().getTrackableSession(context) shouldBe Optional.of("foo") + } + + "return empty when there is no current session" in { + val context = new PekkoHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + new PekkoHttpSessionStore().getTrackableSession(context) shouldBe Optional.empty() + } + } + + "PekkoHttpSessionStore.renewSession" should { + "result in a non-empty session if a session exists" in { + val context = new PekkoHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + val sessionStore = new PekkoHttpSessionStore() + sessionStore.set(context, "mykey", "bar") + sessionStore.renewSession(context) + sessionStore.get(context, "mykey") should not be Optional.of("invalid") + sessionStore.get(context, "mykey") shouldBe Optional.of("bar") + } + + "result in a empty session if a session doesn't exists" in { + val context = new PekkoHttpWebContext(HttpRequest(), Seq.empty, new InMemorySessionStorage(30.minutes), PekkoHttpWebContext.DEFAULT_COOKIE_NAME) + val sessionStore = new PekkoHttpSessionStore() + sessionStore.renewSession(context) + sessionStore.get(context, "mykey") shouldBe Optional.empty() + } + } +} diff --git a/src/test/scala/com/stackstate/pac4j/store/InMemorySessionStorageTest.scala b/src/test/scala/com/stackstate/pac4j/store/InMemorySessionStorageTest.scala index 9467f85..082664c 100644 --- a/src/test/scala/com/stackstate/pac4j/store/InMemorySessionStorageTest.scala +++ b/src/test/scala/com/stackstate/pac4j/store/InMemorySessionStorageTest.scala @@ -1,6 +1,6 @@ package com.stackstate.pac4j.store -import akka.http.scaladsl.testkit.ScalatestRouteTest +import org.apache.pekko.http.scaladsl.testkit.ScalatestRouteTest import com.stackstate.pac4j.store.InMemorySessionStorage._ import org.scalatest.matchers.should.Matchers