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

MTDSA-21543 - remove hard-coded version objects #480

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/definition/BsasApiDefinitionFactory.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ package definition

import shared.config.AppConfig
import shared.definition._
import shared.routing.{Version3, Version4, Version5, Version6}
import routing.Versions._

import javax.inject.{Inject, Singleton}

Expand Down
3 changes: 2 additions & 1 deletion app/routing/BsasVersionRoutingMap.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ package routing

import play.api.routing.Router
import shared.config.AppConfig
import shared.routing.{Version, Version3, Version4, Version5, Version6, VersionRoutingMap}
import shared.routing.{Version, VersionRoutingMap}
import Versions._

import javax.inject.{Inject, Singleton}

Expand Down
29 changes: 29 additions & 0 deletions app/routing/Versions.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2023 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 routing

import shared.routing.Version

object Versions {

val Version1: Version = Version("1.0")
val Version2: Version = Version("2.0")
val Version3: Version = Version("3.0")
val Version4: Version = Version("4.0")
val Version5: Version = Version("5.0")
val Version6: Version = Version("6.0")
}
47 changes: 47 additions & 0 deletions app/shared/routing/Version.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright 2024 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 shared.routing

import play.api.http.HeaderNames.ACCEPT
import play.api.libs.json._
import play.api.mvc.{Headers, RequestHeader}

final case class Version(name: String) {
override def toString: String = name
}

object Version {

implicit val versionWrites: Writes[Version] = implicitly[Writes[String]].contramap[Version](_.name)

implicit val versionReads: Reads[Version] = implicitly[Reads[String]].map(Version(_))

private val versionRegex = """application/vnd.hmrc.(\d.\d)\+json""".r

def apply(request: RequestHeader): Version =
getFromRequest(request).getOrElse(throw new Exception("Missing or unsupported version found in request accept header"))

def getFromRequest(request: RequestHeader): Either[GetFromRequestError, Version] =
getFrom(request.headers).map(Version(_))

private def getFrom(headers: Headers): Either[GetFromRequestError, String] =
headers.get(ACCEPT).collect { case versionRegex(value) => value }.toRight(left = InvalidHeader)

}

sealed trait GetFromRequestError
case object InvalidHeader extends GetFromRequestError
21 changes: 9 additions & 12 deletions app/shared/routing/VersionRoutingRequestHandler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@
package shared.routing

import play.api.http.{DefaultHttpRequestHandler, HttpConfiguration, HttpErrorHandler, HttpFilters}
import play.api.mvc.{DefaultActionBuilder, Handler, RequestHeader, Results}
import play.api.mvc.Results.Status
import play.api.mvc.{DefaultActionBuilder, Handler, RequestHeader}
import play.api.routing.Router
import play.core.DefaultWebCommands
import shared.config.AppConfig
import shared.models.errors.{InvalidAcceptHeaderError, UnsupportedVersionError}
import shared.models.errors.{InvalidAcceptHeaderError, MtdError, UnsupportedVersionError}

import javax.inject.{Inject, Singleton}

Expand All @@ -41,29 +42,25 @@ class VersionRoutingRequestHandler @Inject() (versionRoutingMap: VersionRoutingM
filters = filters.filters
) {

private val unsupportedVersionAction = action(Results.NotFound(UnsupportedVersionError.asJson))

private val invalidAcceptHeaderError = action(Results.NotAcceptable(InvalidAcceptHeaderError.asJson))
private def errorAction(error: MtdError) = action(Status(error.httpStatus)(error.asJson))

override def routeRequest(request: RequestHeader): Option[Handler] = {

def documentHandler: Option[Handler] = routeWith(versionRoutingMap.defaultRouter)(request)

def apiHandler: Option[Handler] =
Versions.getFromRequest(request) match {
case Left(InvalidHeader) => Some(invalidAcceptHeaderError)
case Left(VersionNotFound) => Some(unsupportedVersionAction)
Version.getFromRequest(request) match {
case Left(InvalidHeader) => Some(errorAction(InvalidAcceptHeaderError))

case Right(version) =>
versionRoutingMap.versionRouter(version) match {
case Some(versionRouter) if config.endpointsEnabled(version) =>
routeWith(versionRouter)(request)
case _ =>
Some(unsupportedVersionAction)
case Some(versionRouter) if config.endpointsEnabled(version) => routeWith(versionRouter)(request)
case _ => Some(errorAction(UnsupportedVersionError))
}
}

documentHandler orElse apiHandler

}

private def routeWith(router: Router)(request: RequestHeader): Option[Handler] =
Expand Down
130 changes: 0 additions & 130 deletions app/shared/routing/Versions.scala

This file was deleted.

4 changes: 2 additions & 2 deletions app/shared/utils/ErrorHandler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import play.api.http.Status._
import play.api.mvc.Results._
import play.api.mvc._
import shared.models.errors._
import shared.routing.Versions
import shared.routing.Version
import uk.gov.hmrc.auth.core.AuthorisationException
import uk.gov.hmrc.http._
import uk.gov.hmrc.play.audit.http.connector.AuditConnector
Expand Down Expand Up @@ -85,7 +85,7 @@ class ErrorHandler @Inject() (
}
}

private def versionIfSpecified(request: RequestHeader): String = Versions.getFromRequest(request).map(_.name).getOrElse("<unspecified>")
private def versionIfSpecified(request: RequestHeader): String = Version.getFromRequest(request).map(_.name).getOrElse("<unspecified>")

override def onServerError(request: RequestHeader, ex: Throwable): Future[Result] = {
implicit val headerCarrier: HeaderCarrier = HeaderCarrierConverter.fromRequestAndSession(request, request.session)
Expand Down
7 changes: 3 additions & 4 deletions it/shared/endpoints/DocumentationControllerISpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import play.api.http.Status.OK
import play.api.libs.json.Json
import play.api.libs.ws.WSResponse
import shared.config.AppConfig
import shared.routing.{Version, Versions}
import shared.routing.Version
import support.IntegrationBaseSpec

import scala.util.Try
Expand All @@ -34,9 +34,8 @@ class DocumentationControllerISpec extends IntegrationBaseSpec {

private lazy val enabledVersions: Seq[Version] =
(1 to 99).collect {
case num if config.safeEndpointsEnabled(s"$num.0") =>
Versions.getFrom(s"$num.0").toOption
}.flatten
case num if config.safeEndpointsEnabled(s"$num.0") => Version(s"$num.0")
}

"GET /api/definition" should {
"return a 200 with the correct response body" in {
Expand Down
2 changes: 1 addition & 1 deletion test/definition/BsasApiDefinitionFactorySpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import shared.config.{ConfidenceLevelConfig, MockAppConfig}
import shared.definition.APIStatus.BETA
import shared.definition._
import shared.mocks.MockHttpClient
import shared.routing.{Version3, Version4, Version5, Version6}
import routing.Versions._
import shared.utils.UnitSpec
import uk.gov.hmrc.auth.core.ConfidenceLevel

Expand Down
14 changes: 7 additions & 7 deletions test/shared/controllers/ControllerBaseSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import shared.config.MockAppConfig
import shared.models.audit.{AuditError, AuditEvent, AuditResponse, GenericAuditDetail}
import shared.models.domain.Nino
import shared.models.errors.{BadRequestError, ErrorWrapper, MtdError}
import shared.routing.{Version, Version9}
import shared.routing.Version
import shared.services.{MockAuditService, MockEnrolmentsAuthService, MockMtdIdLookupService}
import shared.utils.{MockIdGenerator, UnitSpec}
import uk.gov.hmrc.http.HeaderCarrier
Expand All @@ -44,16 +44,16 @@ abstract class ControllerBaseSpec
with ControllerSpecHateoasSupport
with MockAppConfig {

protected val apiVersion: Version = Version9
protected val apiVersion: Version = Version("9.9")

lazy val fakeRequest: FakeRequest[AnyContentAsEmpty.type] =
FakeRequest().withHeaders(HeaderNames.ACCEPT -> s"application/vnd.hmrc.${apiVersion.name}+json")
lazy val fakeRequest: FakeRequest[AnyContentAsEmpty.type] = FakeRequest().withHeaders(
HeaderNames.AUTHORIZATION -> "Bearer Token",
HeaderNames.ACCEPT -> s"application/vnd.hmrc.${apiVersion.name}+json"
)

lazy val cc: ControllerComponents = stubControllerComponents()

lazy val fakeGetRequest: FakeRequest[AnyContentAsEmpty.type] = fakeRequest.withHeaders(
HeaderNames.AUTHORIZATION -> "Bearer Token"
)
lazy val fakeGetRequest: FakeRequest[AnyContentAsEmpty.type] = fakeRequest

def fakePostRequest[T](body: T): FakeRequest[T] = fakeRequest.withBody(body)
}
Expand Down
7 changes: 2 additions & 5 deletions test/shared/controllers/DocumentationControllerSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import play.api.{Configuration, Environment}
import shared.config.rewriters._
import shared.config.{AppConfig, MockAppConfig}
import shared.definition._
import shared.routing.{Version, Versions}
import shared.routing.Version
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.bootstrap.config.ServicesConfig

Expand All @@ -35,10 +35,7 @@ class DocumentationControllerSpec extends ControllerBaseSpec with MockAppConfig

private val apiVersionName = s"$latestEnabledApiVersion.0"

override protected val apiVersion: Version =
Versions
.getFrom(apiVersionName)
.getOrElse(fail(s"Matching Version object not found for $apiVersionName"))
override protected val apiVersion: Version = Version(apiVersionName)

private val apiTitle = "Business Source Adjustable Summary (MTD)"

Expand Down
Loading