From 65aa619045bfc933a61c46eb4984b89eb68aec3c Mon Sep 17 00:00:00 2001 From: Edgar Jimenez Date: Mon, 22 Aug 2016 12:20:00 +0100 Subject: [PATCH] API-1888 adding authFilter to verify confidence level --- .../userinfo/config/microserviceGlobal.scala | 19 +--- .../userinfo/config/microserviceWiring.scala | 7 +- .../userinfo/connectors/AuthConnector.scala | 48 +++++++++ .../userinfo/domain/package.scala | 1 + .../filters/MicroserviceAuthFilter.scala | 58 +++++++++++ .../userinfo/services/AuthService.scala | 39 ++++++++ conf/application.conf | 62 ++++++++++++ project/MicroserviceBuild.scala | 4 +- .../filters/MicroserviceAuthFilterSpec.scala | 98 +++++++++++++++++++ .../userinfo/services/AuthServiceSpec.scala | 70 +++++++++++++ .../userinfo/WireMockSugar.scala | 56 +++++++++++ .../openidconnect/userinfo/WiremockDSL.scala | 43 ++++++++ .../connectors/AuthConnectorSpec.scala | 61 ++++++++++++ 13 files changed, 540 insertions(+), 26 deletions(-) create mode 100644 app/uk/gov/hmrc/openidconnect/userinfo/connectors/AuthConnector.scala create mode 100644 app/uk/gov/hmrc/openidconnect/userinfo/filters/MicroserviceAuthFilter.scala create mode 100644 app/uk/gov/hmrc/openidconnect/userinfo/services/AuthService.scala create mode 100644 test/uk/gov/hmrc/openidconnect/userinfo/filters/MicroserviceAuthFilterSpec.scala create mode 100644 test/uk/gov/hmrc/openidconnect/userinfo/services/AuthServiceSpec.scala create mode 100644 test/unit/uk/gov/hmrc/openidconnect/userinfo/WireMockSugar.scala create mode 100644 test/unit/uk/gov/hmrc/openidconnect/userinfo/WiremockDSL.scala create mode 100644 test/unit/uk/gov/hmrc/openidconnect/userinfo/connectors/AuthConnectorSpec.scala diff --git a/app/uk/gov/hmrc/openidconnect/userinfo/config/microserviceGlobal.scala b/app/uk/gov/hmrc/openidconnect/userinfo/config/microserviceGlobal.scala index a6971b8..4f0b7ea 100644 --- a/app/uk/gov/hmrc/openidconnect/userinfo/config/microserviceGlobal.scala +++ b/app/uk/gov/hmrc/openidconnect/userinfo/config/microserviceGlobal.scala @@ -24,9 +24,9 @@ import play.api._ import play.api.libs.json.Json import play.api.mvc.Results._ import play.api.mvc.{RequestHeader, Result} +import uk.gov.hmrc.openidconnect.userinfo.filters.MicroserviceAuthFilter import uk.gov.hmrc.play.audit.filters.AuditFilter import uk.gov.hmrc.play.auth.controllers.AuthParamsControllerConfig -import uk.gov.hmrc.play.auth.microservice.filters.AuthorisationFilter import uk.gov.hmrc.play.config.{AppName, ControllerConfig, RunMode} import uk.gov.hmrc.play.http.HeaderCarrier import uk.gov.hmrc.play.http.logging.filters.LoggingFilter @@ -67,23 +67,6 @@ object MicroserviceLoggingFilter extends LoggingFilter { override def controllerNeedsLogging(controllerName: String) = ControllerConfiguration.paramsForController(controllerName).needsLogging } -object MicroserviceAuthFilter extends AuthorisationFilter { - override def apply(next: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = { - super.apply(next)(rh) map { res => - res.header.status - match { - case 401 => Status(ErrorUnauthorized.httpStatusCode)(Json.toJson(ErrorUnauthorized)) - case _ => res - } - } - } - - override lazy val authParamsConfig = AuthParamsControllerConfiguration - override lazy val authConnector = MicroserviceAuthConnector - - override def controllerNeedsAuth(controllerName: String): Boolean = ControllerConfiguration.paramsForController(controllerName).needsAuth -} - object MicroserviceGlobal extends DefaultMicroserviceGlobal with RunMode with ServiceLocatorRegistration { override val auditConnector = MicroserviceAuditConnector diff --git a/app/uk/gov/hmrc/openidconnect/userinfo/config/microserviceWiring.scala b/app/uk/gov/hmrc/openidconnect/userinfo/config/microserviceWiring.scala index 2659d5d..f107de1 100644 --- a/app/uk/gov/hmrc/openidconnect/userinfo/config/microserviceWiring.scala +++ b/app/uk/gov/hmrc/openidconnect/userinfo/config/microserviceWiring.scala @@ -18,8 +18,7 @@ package uk.gov.hmrc.openidconnect.userinfo.config import uk.gov.hmrc.play.audit.http.config.LoadAuditingConfig import uk.gov.hmrc.play.audit.http.connector.AuditConnector -import uk.gov.hmrc.play.auth.microservice.connectors.AuthConnector -import uk.gov.hmrc.play.config.{AppName, RunMode, ServicesConfig} +import uk.gov.hmrc.play.config.{AppName, RunMode} import uk.gov.hmrc.play.http.ws._ object WSHttp extends WSGet with WSPut with WSPost with WSDelete with WSPatch with AppName with RunMode { @@ -29,7 +28,3 @@ object WSHttp extends WSGet with WSPut with WSPost with WSDelete with WSPatch wi object MicroserviceAuditConnector extends AuditConnector with RunMode { override lazy val auditingConfig = LoadAuditingConfig(s"$env.auditing") } - -object MicroserviceAuthConnector extends AuthConnector with ServicesConfig { - override val authBaseUrl = baseUrl("auth") -} diff --git a/app/uk/gov/hmrc/openidconnect/userinfo/connectors/AuthConnector.scala b/app/uk/gov/hmrc/openidconnect/userinfo/connectors/AuthConnector.scala new file mode 100644 index 0000000..c720b2c --- /dev/null +++ b/app/uk/gov/hmrc/openidconnect/userinfo/connectors/AuthConnector.scala @@ -0,0 +1,48 @@ +/* + * Copyright 2016 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.gov.hmrc.openidconnect.userinfo.connectors + +import play.api.Logger +import uk.gov.hmrc.openidconnect.userinfo.config.WSHttp +import uk.gov.hmrc.play.auth.microservice.connectors.ConfidenceLevel._ +import uk.gov.hmrc.play.config.ServicesConfig +import uk.gov.hmrc.play.http.{HeaderCarrier, HttpGet} + +import scala.concurrent.ExecutionContext.Implicits.global +import scala.concurrent.Future + +trait AuthConnector extends uk.gov.hmrc.play.auth.microservice.connectors.AuthConnector { + val authBaseUrl: String + val http: HttpGet + + def confidenceLevel()(implicit hc: HeaderCarrier): Future[Option[Int]] = { + http.GET(s"$authBaseUrl/auth/authority") map { + resp => + val cf = (resp.json \ "confidenceLevel").as[Int] + Some(cf) + } recover { + case e: Throwable => + Logger.error("failed to retrieve auth confidenceLevel", e) + None + } + } +} + +object AuthConnector extends AuthConnector with ServicesConfig { + override lazy val authBaseUrl = baseUrl("auth") + lazy val http = WSHttp +} diff --git a/app/uk/gov/hmrc/openidconnect/userinfo/domain/package.scala b/app/uk/gov/hmrc/openidconnect/userinfo/domain/package.scala index de4275e..7c7b44e 100644 --- a/app/uk/gov/hmrc/openidconnect/userinfo/domain/package.scala +++ b/app/uk/gov/hmrc/openidconnect/userinfo/domain/package.scala @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package uk.gov.hmrc.openidconnect.userinfo import play.api.libs.json._ diff --git a/app/uk/gov/hmrc/openidconnect/userinfo/filters/MicroserviceAuthFilter.scala b/app/uk/gov/hmrc/openidconnect/userinfo/filters/MicroserviceAuthFilter.scala new file mode 100644 index 0000000..c3f3c22 --- /dev/null +++ b/app/uk/gov/hmrc/openidconnect/userinfo/filters/MicroserviceAuthFilter.scala @@ -0,0 +1,58 @@ +/* + * Copyright 2016 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.gov.hmrc.openidconnect.userinfo.filters + +import play.api.Routes +import play.api.mvc.{Filter, RequestHeader, Result, Results} +import uk.gov.hmrc.openidconnect.userinfo.config.{AuthParamsControllerConfiguration, ControllerConfiguration} +import uk.gov.hmrc.openidconnect.userinfo.services.AuthService +import uk.gov.hmrc.play.auth.controllers.{AuthConfig, AuthParamsControllerConfig} +import uk.gov.hmrc.play.http.HeaderCarrier + +import scala.concurrent.ExecutionContext.Implicits.global +import scala.concurrent.Future + +trait MicroserviceAuthFilter extends Filter { + def apply(next: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = { + implicit val hc = HeaderCarrier.fromHeadersAndSession(rh.headers) + + def authConfig(rh: RequestHeader): Option[AuthConfig] = { + rh.tags.get(Routes.ROUTE_CONTROLLER).flatMap { name => + if (controllerNeedsAuth(name)) Some(authParamsConfig.authConfig(name)) + else None + } + } + + authConfig(rh) match { + case Some(authConfig) => authService.isAuthorised().flatMap { + case true => next(rh) + case _ => Future.successful(Results.Unauthorized) + } + case _ => next(rh) + } + } + + val authService: AuthService + val authParamsConfig: AuthParamsControllerConfig + + def controllerNeedsAuth(controllerName: String): Boolean = ControllerConfiguration.paramsForController(controllerName).needsAuth +} + +object MicroserviceAuthFilter extends MicroserviceAuthFilter { + override lazy val authService = AuthService + override lazy val authParamsConfig = AuthParamsControllerConfiguration +} \ No newline at end of file diff --git a/app/uk/gov/hmrc/openidconnect/userinfo/services/AuthService.scala b/app/uk/gov/hmrc/openidconnect/userinfo/services/AuthService.scala new file mode 100644 index 0000000..c453582 --- /dev/null +++ b/app/uk/gov/hmrc/openidconnect/userinfo/services/AuthService.scala @@ -0,0 +1,39 @@ +/* + * Copyright 2016 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.gov.hmrc.openidconnect.userinfo.services + +import uk.gov.hmrc.openidconnect.userinfo.connectors.AuthConnector +import uk.gov.hmrc.play.auth.microservice.connectors.ConfidenceLevel.L200 +import uk.gov.hmrc.play.http.HeaderCarrier +import scala.concurrent.ExecutionContext.Implicits.global + +trait AuthService { + val authConnector: AuthConnector + + def isAuthorised()(implicit hc: HeaderCarrier) = { + authConnector.confidenceLevel().map { result => + result match { + case Some(cf) => cf >= L200.level + case None => false + } + } + } +} + +object AuthService extends AuthService { + override val authConnector = AuthConnector +} diff --git a/conf/application.conf b/conf/application.conf index c6df2af..4a17c5a 100644 --- a/conf/application.conf +++ b/conf/application.conf @@ -117,6 +117,58 @@ metrics { # Microservice specific config +wiremock-port = 22222 +wiremock-port = ${?WIREMOCK_PORT} + +Test { + + auditing { + enabled=true + traceRequests=false + + consumer { + baseUri { + host = ${wiremock-port} + port = 8100 + } + } + } + + microservice { + metrics { + graphite { + host = graphite + port = 2003 + prefix = play.${appName}. + enabled = false + } + } + + services { + + auth { + host=localhost + port=${wiremock-port} + } + + datastream { + host=localhost + port=${wiremock-port} + } + + service-locator { + host=localhost + port=${wiremock-port} + } + + auth { + host = localhost + port = ${wiremock-port} + } + } + } +} + Dev { auditing { @@ -157,6 +209,11 @@ Dev { host=localhost port=9602 } + + auth { + host = localhost + port = 8500 + } } } } @@ -200,6 +257,11 @@ Prod { host=service-locator.service port=80 } + + auth { + host = auth.service + port = 80 + } } } } \ No newline at end of file diff --git a/project/MicroserviceBuild.scala b/project/MicroserviceBuild.scala index 7dc3596..c419775 100644 --- a/project/MicroserviceBuild.scala +++ b/project/MicroserviceBuild.scala @@ -41,10 +41,10 @@ private object AppDependencies { val scalaTestPlus = "org.scalatestplus" %% "play" % "1.2.0" % testScope val scalaHttp = "org.scalaj" %% "scalaj-http" % "1.1.5" val junit = "junit" % "junit" % "4.12" % testScope - val wireMock = "com.github.tomakehurst" % "wiremock" % "1.48" % testScope exclude("org.apache.httpcomponents", "httpclient") exclude("org.apache.httpcomponents", "httpcore") + val wireMock = "com.github.tomakehurst" % "wiremock" % "1.54" % testScope exclude("org.apache.httpcomponents", "httpclient") exclude("org.apache.httpcomponents", "httpcore") val compileDependencies = Seq(microserviceBootStrap, playAuthorisation, playHealth, playUrlBinders, playConfig, playJsonLogger, domain, referenceChecker, scalaCheck, playHmrcApi) - val testDependencies = Seq(hmrcTest, scalaTest, pegDown, playTest, scalaHttp, junit, wireMock) + val testDependencies = Seq(hmrcTest, scalaTest, pegDown, playTest, scalaTestPlus, scalaHttp, junit, wireMock) def apply() = compileDependencies ++ testDependencies } diff --git a/test/uk/gov/hmrc/openidconnect/userinfo/filters/MicroserviceAuthFilterSpec.scala b/test/uk/gov/hmrc/openidconnect/userinfo/filters/MicroserviceAuthFilterSpec.scala new file mode 100644 index 0000000..e604e62 --- /dev/null +++ b/test/uk/gov/hmrc/openidconnect/userinfo/filters/MicroserviceAuthFilterSpec.scala @@ -0,0 +1,98 @@ +/* + * Copyright 2016 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.gov.hmrc.openidconnect.userinfo.filters + +import org.mockito.Matchers._ +import org.mockito.Mockito._ +import org.scalatest.concurrent.ScalaFutures +import org.scalatest.mock.MockitoSugar +import play.api.Routes +import play.api.mvc.RequestHeader +import play.api.mvc.Results._ +import play.api.test.FakeRequest +import uk.gov.hmrc.openidconnect.userinfo.services.AuthService +import uk.gov.hmrc.play.auth.controllers.{AuthConfig, AuthParamsControllerConfig} +import uk.gov.hmrc.play.auth.microservice.connectors.ConfidenceLevel +import uk.gov.hmrc.play.http.HeaderCarrier +import uk.gov.hmrc.play.test.UnitSpec + +import scala.concurrent.Future + +class MicroserviceAuthFilterSpec extends UnitSpec with ScalaFutures with MockitoSugar { + + val sandbox = "sandbox" + val live = "live" + + trait Setup { + + val authFilter = new MicroserviceAuthFilter { + override val authService = mock[AuthService] + override val authParamsConfig = mock[AuthParamsControllerConfig] + + override def controllerNeedsAuth(controllerName: String): Boolean = { + controllerName match { + case `sandbox` => false + case `live` => true + case _ => false + } + } + } + } + + "microserviceAuthFilter" should { + + implicit val hc = HeaderCarrier() + + def nextCall(rh: RequestHeader) = Future.successful(Ok("Success")) + + "call the next filter if authentication is required and the user is authorised" in new Setup { + + when(authFilter.authService.isAuthorised()(any())).thenReturn(Future.successful(true)) + when(authFilter.authParamsConfig.authConfig(live)).thenReturn(AuthConfig(confidenceLevel = ConfidenceLevel.L50)) + + val request = FakeRequest("GET", "/").copy(tags = Map(Routes.ROUTE_CONTROLLER -> live)) + val response = authFilter(nextCall _)(request).futureValue + + response.header.status shouldBe 200 + bodyOf(response) shouldBe "Success" + } + + "return 401 (Unauthorized) if authentication is required and the user is not authorised" in new Setup { + + when(authFilter.authService.isAuthorised()(any())).thenReturn(Future.successful(false)) + when(authFilter.authParamsConfig.authConfig(live)).thenReturn(AuthConfig(confidenceLevel = ConfidenceLevel.L50)) + + val request = FakeRequest("GET", "/").copy(tags = Map(Routes.ROUTE_CONTROLLER -> live)) + val response = authFilter(nextCall _)(request).futureValue + + response.header.status shouldBe 401 + bodyOf(response) shouldBe empty + } + + "call the next filter if authentication is not required" in new Setup { + + val request = FakeRequest("GET", "/").copy(tags = Map(Routes.ROUTE_CONTROLLER -> sandbox)) + + val response = authFilter(nextCall _)(request).futureValue + + response.header.status shouldBe 200 + bodyOf(response) shouldBe "Success" + + verifyZeroInteractions(authFilter.authService, authFilter.authParamsConfig) + } + } +} \ No newline at end of file diff --git a/test/uk/gov/hmrc/openidconnect/userinfo/services/AuthServiceSpec.scala b/test/uk/gov/hmrc/openidconnect/userinfo/services/AuthServiceSpec.scala new file mode 100644 index 0000000..ebde4f4 --- /dev/null +++ b/test/uk/gov/hmrc/openidconnect/userinfo/services/AuthServiceSpec.scala @@ -0,0 +1,70 @@ +/* + * Copyright 2016 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package uk.gov.hmrc.openidconnect.userinfo.services + +import org.scalatest.concurrent.ScalaFutures +import org.scalatest.mock.MockitoSugar +import org.mockito.Mockito._ +import org.mockito.Matchers._ +import uk.gov.hmrc.openidconnect.userinfo.connectors.AuthConnector +import uk.gov.hmrc.play.http.HeaderCarrier +import uk.gov.hmrc.play.test.UnitSpec + +class AuthServiceSpec extends UnitSpec with ScalaFutures with MockitoSugar { + + trait Setup { + implicit val hc = HeaderCarrier() + + val authService = new AuthService { + override val authConnector = mock[AuthConnector] + } + } + + "isAuthorised" should { + "return true if confidenceLevel is 200" in new Setup { + when(authService.authConnector.confidenceLevel()(any())).thenReturn(Some(200)) + + val result = authService.isAuthorised() + + result.futureValue shouldBe true + } + + "return true if confidenceLevel is above 200" in new Setup { + when(authService.authConnector.confidenceLevel()(any())).thenReturn(Some(300)) + + val result = authService.isAuthorised() + + result.futureValue shouldBe true + } + + "return false if confidenceLevel is below 200" in new Setup { + when(authService.authConnector.confidenceLevel()(any())).thenReturn(Some(50)) + + val result = authService.isAuthorised() + + result.futureValue shouldBe false + } + + "return false if no confidenceLevel returned from auth" in new Setup { + when(authService.authConnector.confidenceLevel()(any())).thenReturn(None) + + val result = authService.isAuthorised() + + result.futureValue shouldBe false + } + } +} diff --git a/test/unit/uk/gov/hmrc/openidconnect/userinfo/WireMockSugar.scala b/test/unit/uk/gov/hmrc/openidconnect/userinfo/WireMockSugar.scala new file mode 100644 index 0000000..37541d8 --- /dev/null +++ b/test/unit/uk/gov/hmrc/openidconnect/userinfo/WireMockSugar.scala @@ -0,0 +1,56 @@ +/* + * Copyright 2016 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package unit.uk.gov.hmrc.openidconnect.userinfo + +import java.util.concurrent.TimeUnit + +import com.github.tomakehurst.wiremock.WireMockServer +import com.github.tomakehurst.wiremock.client.WireMock +import com.github.tomakehurst.wiremock.client.WireMock._ +import com.github.tomakehurst.wiremock.core.WireMockConfiguration._ +import org.scalatest.BeforeAndAfterAll +import org.scalatest.concurrent.{Eventually, IntegrationPatience, ScalaFutures} +import org.scalatestplus.play.OneServerPerSuite +import uk.gov.hmrc.play.test.UnitSpec + +import scala.concurrent.duration.FiniteDuration + +trait WireMockSugar extends UnitSpec with OneServerPerSuite with Eventually with ScalaFutures + with IntegrationPatience with BeforeAndAfterAll with WiremockDSL { + + override implicit val defaultTimeout = FiniteDuration(100, TimeUnit.SECONDS) + + val WIREMOCK_PORT = 22222 + val stubHost = "localhost" + + protected val wiremockBaseUrl: String = s"http://$stubHost:$WIREMOCK_PORT" + private val wireMockServer = new WireMockServer(wireMockConfig().port(WIREMOCK_PORT)) + + override def beforeAll() = { + super.beforeAll() + wireMockServer.stop() + wireMockServer.start() + WireMock.configureFor(stubHost, WIREMOCK_PORT) + // the below stub is here so that the application finds the registration endpoint which is called on startup + stubFor(post(urlMatching("/registration")).willReturn(aResponse().withStatus(200))) + } + + override def afterAll() = { + super.afterAll() + wireMockServer.stop() + } +} diff --git a/test/unit/uk/gov/hmrc/openidconnect/userinfo/WiremockDSL.scala b/test/unit/uk/gov/hmrc/openidconnect/userinfo/WiremockDSL.scala new file mode 100644 index 0000000..4d8e005 --- /dev/null +++ b/test/unit/uk/gov/hmrc/openidconnect/userinfo/WiremockDSL.scala @@ -0,0 +1,43 @@ +/* + * Copyright 2016 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package unit.uk.gov.hmrc.openidconnect.userinfo + +import com.github.tomakehurst.wiremock.client.WireMock._ +import com.github.tomakehurst.wiremock.client.{MappingBuilder, UrlMatchingStrategy, WireMock} + +trait WiremockDSL { + + def given() = new Givens() + + class Givens() { + def get(strategy: UrlMatchingStrategy) = new Result(WireMock.get(strategy)) + + class Result(mappingBuilder: MappingBuilder) { + def returns(responseBody: String) = { + stubFor(mappingBuilder.willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(responseBody))) + } + + def returns(statusCode: Int) = { + stubFor(mappingBuilder.willReturn(aResponse() + .withStatus(statusCode))) + } + } + } +} diff --git a/test/unit/uk/gov/hmrc/openidconnect/userinfo/connectors/AuthConnectorSpec.scala b/test/unit/uk/gov/hmrc/openidconnect/userinfo/connectors/AuthConnectorSpec.scala new file mode 100644 index 0000000..30e5ef1 --- /dev/null +++ b/test/unit/uk/gov/hmrc/openidconnect/userinfo/connectors/AuthConnectorSpec.scala @@ -0,0 +1,61 @@ +/* + * Copyright 2016 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package unit.uk.gov.hmrc.openidconnect.userinfo.connectors; + +import com.github.tomakehurst.wiremock.client.WireMock._ +import org.scalatest.mock.MockitoSugar +import uk.gov.hmrc.openidconnect.userinfo.config.WSHttp +import uk.gov.hmrc.openidconnect.userinfo.connectors.AuthConnector +import uk.gov.hmrc.play.auth.microservice.connectors.ConfidenceLevel +import uk.gov.hmrc.play.auth.microservice.connectors.ConfidenceLevel._ +import uk.gov.hmrc.play.http.{HeaderCarrier, HttpGet} +import unit.uk.gov.hmrc.openidconnect.userinfo.WireMockSugar + +class AuthConnectorSpec extends WireMockSugar { + "confidenceLevel" should { + "return the authority's confidence level" in new TestAuthConnector(wiremockBaseUrl) { + given().get(urlPathEqualTo("/auth/authority")).returns(authorityJson(L200)) + confidenceLevel().futureValue shouldBe Some(200) + } + + "return None when authority's confidence level is not in the response" in new TestAuthConnector(wiremockBaseUrl) { + given().get(urlPathEqualTo("/auth/authority")).returns("""{"credentialStrength":"weak"}""") + confidenceLevel().futureValue shouldBe None + } + + "return false when auth request fails" in new TestAuthConnector(wiremockBaseUrl) { + given().get(urlPathEqualTo("/auth/authority")).returns(500) + confidenceLevel().futureValue shouldBe None + } + } +} + +class TestAuthConnector(wiremockBaseUrl: String) extends AuthConnector with MockitoSugar { + implicit val hc = HeaderCarrier() + + override val authBaseUrl: String = wiremockBaseUrl + override val http: HttpGet = WSHttp + + def authorityJson(confidenceLevel: ConfidenceLevel) = { + s""" + |{ + | "credentialStrength":"weak", + | "confidenceLevel": ${confidenceLevel.level} + |} + """.stripMargin + } +} \ No newline at end of file