Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: SystemAdmins receive a token which is valid on the dps-ingest api #2835

Merged
merged 5 commits into from
Sep 14, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@
package org.knora.webapi.responders.v2

import akka.testkit.ImplicitSender
import zio.Exit

import java.time.Instant
import java.util.UUID
import java.util.UUID.randomUUID
import scala.concurrent.duration._
import scala.reflect.ClassTag

import dsp.errors._
import dsp.valueobjects.UuidUtil
Expand Down Expand Up @@ -40,6 +38,7 @@ import org.knora.webapi.store.iiif.errors.SipiException
import org.knora.webapi.store.triplestore.api.TriplestoreService
import org.knora.webapi.store.triplestore.api.TriplestoreService.Queries.Select
import org.knora.webapi.util.MutableTestIri
import org.knora.webapi.util.ZioScalaTestUtil.assertFailsWithA

/**
* Tests [[ValuesResponderV2]].
Expand Down Expand Up @@ -399,11 +398,6 @@ class ValuesResponderV2Spec extends CoreSpec with ImplicitSender {
}
}

private def assertFailsWithA[T <: Throwable: ClassTag](actual: Exit[Throwable, _]) = actual match {
case Exit.Failure(err) => err.squash shouldBe a[T]
case _ => fail(s"Expected Exit.Failure with specific T.")
}

"Load test data" in {
appActor ! GetMappingRequestV2(
mappingIri = "http://rdfh.ch/standoff/mappings/StandardMapping",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package org.knora.webapi.routing

import akka.testkit.ImplicitSender
import org.scalatest.PrivateMethodTester
import zio.ZIO

import dsp.errors.BadCredentialsException
import dsp.errors.BadRequestException
Expand All @@ -18,6 +19,7 @@ import org.knora.webapi.messages.v2.routing.authenticationmessages.KnoraCredenti
import org.knora.webapi.messages.v2.routing.authenticationmessages.KnoraCredentialsV2.KnoraPasswordCredentialsV2
import org.knora.webapi.routing.Authenticator.AUTHENTICATION_INVALIDATION_CACHE_NAME
import org.knora.webapi.sharedtestdata.SharedTestDataADM
import org.knora.webapi.util.ZioScalaTestUtil.assertFailsWithA
import org.knora.webapi.util.cache.CacheUtil

object AuthenticatorSpec {
Expand All @@ -35,29 +37,23 @@ class AuthenticatorSpec extends CoreSpec with ImplicitSender with PrivateMethodT
"During Authentication" when {
"called, the 'getUserADMByEmail' method " should {
"succeed with the correct 'email' " in {
val resF = UnsafeZioRun.runToFuture(
val user = UnsafeZioRun.runOrThrow(
Authenticator.getUserByIdentifier(UserIdentifierADM(maybeEmail = Some(AuthenticatorSpec.rootUserEmail)))
)
resF map { res =>
assert(res == AuthenticatorSpec.rootUser)
}
assert(user == AuthenticatorSpec.rootUser)
}

"fail with the wrong 'email' " in {
val resF = UnsafeZioRun.runToFuture(
Authenticator.getUserByIdentifier(
UserIdentifierADM(maybeEmail = Some("wronguser@example.com"))
)
val actual = UnsafeZioRun.run(
Authenticator.getUserByIdentifier(UserIdentifierADM(maybeEmail = Some("wronguser@example.com")))
)
resF map { _ =>
assertThrows(BadCredentialsException)
}
assertFailsWithA[BadCredentialsException](actual)
}

"fail when not providing anything " in {
a[BadRequestException] should be thrownBy {
throw UnsafeZioRun.run(Authenticator.getUserByIdentifier(UserIdentifierADM())).causeOption.get.squash
}
val actual = UnsafeZioRun.run(ZIO.attempt(UserIdentifierADM()))

assertFailsWithA[BadRequestException](actual)
}
}

Expand All @@ -68,65 +64,58 @@ class AuthenticatorSpec extends CoreSpec with ImplicitSender with PrivateMethodT
UserIdentifierADM(maybeEmail = Some(AuthenticatorSpec.rootUserEmail)),
AuthenticatorSpec.rootUserPassword
)
val resF = UnsafeZioRun.runToFuture(Authenticator.authenticateCredentialsV2(Some(correctPasswordCreds)))
resF map { res => assert(res) }
val isAuthenticated =
UnsafeZioRun.runOrThrow(Authenticator.authenticateCredentialsV2(Some(correctPasswordCreds)))
assert(isAuthenticated)
}
"fail with unknown email" in {
val wrongPasswordCreds =
val invalidEmailCreds =
KnoraPasswordCredentialsV2(UserIdentifierADM(maybeEmail = Some("wrongemail@example.com")), "wrongpassword")
val resF = UnsafeZioRun.runToFuture(Authenticator.authenticateCredentialsV2(Some(wrongPasswordCreds)))
resF map { _ => assertThrows(BadCredentialsException) }
val resF = UnsafeZioRun.run(Authenticator.authenticateCredentialsV2(Some(invalidEmailCreds)))
assertFailsWithA[BadCredentialsException](resF)
}
"fail with wrong password" in {
val wrongPasswordCreds =
val invalidPasswordCreds =
KnoraPasswordCredentialsV2(
UserIdentifierADM(maybeEmail = Some(AuthenticatorSpec.rootUserEmail)),
"wrongpassword"
)
val resF = UnsafeZioRun.runToFuture(Authenticator.authenticateCredentialsV2(Some(wrongPasswordCreds)))
resF map { _ => assertThrows(BadCredentialsException) }
val actual = UnsafeZioRun.run(Authenticator.authenticateCredentialsV2(Some(invalidPasswordCreds)))
assertFailsWithA[BadCredentialsException](actual)
}
"succeed with correct token" in {
val resF = UnsafeZioRun.runToFuture(
val isAuthenticated = UnsafeZioRun.runOrThrow(
for {
token <-
JwtService.createJwt(testUserAdmFromIri("http://rdfh.ch/users/X-T8IkfQTKa86UWuISpbOA")).map(_.jwtString)
tokenCreds = KnoraJWTTokenCredentialsV2(token)
result <- Authenticator.authenticateCredentialsV2(Some(tokenCreds))
} yield result
)
resF map { res => assert(res) }
assert(isAuthenticated)
}
"fail with invalidated token" in {

assertThrows[BadCredentialsException] {
throw UnsafeZioRun
.run(for {
token <-
JwtService.createJwt(testUserAdmFromIri("http://rdfh.ch/users/X-T8IkfQTKa86UWuISpbOA")).map(_.jwtString)
tokenCreds = KnoraJWTTokenCredentialsV2(token)
_ = CacheUtil.put(AUTHENTICATION_INVALIDATION_CACHE_NAME, tokenCreds.jwtToken, tokenCreds.jwtToken)
result <- Authenticator.authenticateCredentialsV2(Some(tokenCreds))
} yield result)
.causeOption
.get
.squash
}
val actual = UnsafeZioRun
.run(for {
token <-
JwtService.createJwt(testUserAdmFromIri("http://rdfh.ch/users/X-T8IkfQTKa86UWuISpbOA")).map(_.jwtString)
tokenCreds = KnoraJWTTokenCredentialsV2(token)
_ = CacheUtil.put(AUTHENTICATION_INVALIDATION_CACHE_NAME, tokenCreds.jwtToken, tokenCreds.jwtToken)
result <- Authenticator.authenticateCredentialsV2(Some(tokenCreds))
} yield result)
assertFailsWithA[BadCredentialsException](actual)
}
"fail with wrong token" in {
val tokenCreds = KnoraJWTTokenCredentialsV2("123456")

assertThrows[BadCredentialsException] {
throw UnsafeZioRun.run(Authenticator.authenticateCredentialsV2(Some(tokenCreds))).causeOption.get.squash
}
val invalidTokenCreds = KnoraJWTTokenCredentialsV2("123456")
val actual = UnsafeZioRun.run(Authenticator.authenticateCredentialsV2(Some(invalidTokenCreds)))
assertFailsWithA[BadCredentialsException](actual)
}
}

"called, the 'calculateCookieName' method" should {
"succeed with generating the name" in {
UnsafeZioRun.runOrThrow(Authenticator.calculateCookieName()) should equal(
"KnoraAuthenticationGAXDALRQFYYDUMZTGMZQ9999"
)
val cookieName = UnsafeZioRun.runOrThrow(Authenticator.calculateCookieName())
cookieName should equal("KnoraAuthenticationGAXDALRQFYYDUMZTGMZQ9999")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,14 @@
package org.knora.webapi.routing

import akka.testkit.ImplicitSender
import pdi.jwt.JwtAlgorithm
import pdi.jwt.JwtSprayJson
import spray.json.JsString
import zio.ZIO

import org.knora.webapi.CoreSpec
import org.knora.webapi.config.JwtConfig
import org.knora.webapi.messages.admin.responder.usersmessages.UserADM
import org.knora.webapi.sharedtestdata.SharedTestDataADM

class JwtServiceSpec extends CoreSpec with ImplicitSender {
Expand All @@ -27,6 +32,25 @@ class JwtServiceSpec extends CoreSpec with ImplicitSender {
UnsafeZioRun.runOrThrow(runZio) should be(Some(SharedTestDataADM.anythingUser1.id))
}

"create a token with dsp-ingest audience for sys admins" in {
val sysAdmin = SharedTestDataADM.rootUser
val audience = createTokenAndExtractAudience(sysAdmin)
UnsafeZioRun.runOrThrow(audience) should contain("http://localhost:3340")
}

def createTokenAndExtractAudience(user: UserADM) = for {
token <- JwtService.createJwt(user)
jwtConfig <- ZIO.service[JwtConfig]
decoded = JwtSprayJson.decodeAll(token.jwtString, jwtConfig.secret, Seq(JwtAlgorithm.HS256))
audience = decoded.toOption.flatMap { case (_, claims, _) => claims.audience }.head
} yield audience

"create a token without dsp-ingest audience for non sys admins" in {
val normalUser = SharedTestDataADM.anythingUser2
val audience = createTokenAndExtractAudience(normalUser)
UnsafeZioRun.runOrThrow(audience) should not contain "http://localhost:3340"
}

"validate a token" in {
val tokenValid = JwtService.validateToken(validToken)
UnsafeZioRun.runOrThrow(tokenValid) should be(true)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package org.knora.webapi.util

import org.scalatest.Assertions
import org.scalatest.matchers.should.Matchers.a
import org.scalatest.matchers.should.Matchers.convertToAnyShouldWrapper
import zio.Exit

import scala.reflect.ClassTag

object ZioScalaTestUtil {

def assertFailsWithA[T <: Throwable: ClassTag](actual: Exit[Throwable, _]) = actual match {
case Exit.Failure(err) => err.squash shouldBe a[T]
case _ => Assertions.fail(s"Expected Exit.Failure with specific T.")
}
}