Skip to content

Commit

Permalink
Merge pull request #69 from hmrc/GG-5001
Browse files Browse the repository at this point in the history
GG-5001: added static code analysis tools
  • Loading branch information
ShaneTN authored Sep 16, 2020
2 parents 799701a + b247731 commit 5b220a9
Show file tree
Hide file tree
Showing 38 changed files with 356 additions and 305 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ import com.typesafe.config.{Config, ConfigObject}

import collection.JavaConverters._

case class APIAccessConfig(version: String, status: String, accessType: String, endpointsEnabled: Boolean, whiteListedApplicationIds : List[String])
case class APIAccessConfig(version: String, status: String, accessType: String, endpointsEnabled: Boolean, whiteListedApplicationIds: List[String])

case class APIAccessVersions(versionConfigs: Option[ConfigObject]) {
def findAPIs(versions : List[String], config: Config) = {
def findAPIs(versions: List[String], config: Config) = {
versions.map { version =>
val value = config.getConfig(version)

Expand Down
12 changes: 6 additions & 6 deletions app/uk/gov/hmrc/openidconnect/userinfo/config/AppContext.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@ import play.api.{Configuration, Environment}
import uk.gov.hmrc.play.bootstrap.config.{RunMode, ServicesConfig}

@Singleton
class AppContext @Inject()(val runModeConfiguration: Configuration, environment: Environment, runMode: RunMode) extends ServicesConfig(runModeConfiguration,runMode) {
class AppContext @Inject() (val runModeConfiguration: Configuration, environment: Environment, runMode: RunMode) extends ServicesConfig(runModeConfiguration, runMode) {
protected def mode: Mode = environment.mode

lazy val appName : String = runModeConfiguration.getString("appName").getOrElse(throw new RuntimeException("appName is not configured"))
lazy val appUrl : String = runModeConfiguration.getString("appUrl").getOrElse(throw new RuntimeException("appUrl is not configured"))
lazy val authUrl : String = baseUrl("auth")
lazy val thirdPartyDelegatedAuthorityUrl : String = baseUrl("third-party-delegated-authority")
lazy val appName: String = runModeConfiguration.getString("appName").getOrElse(throw new RuntimeException("appName is not configured"))
lazy val appUrl: String = runModeConfiguration.getString("appUrl").getOrElse(throw new RuntimeException("appUrl is not configured"))
lazy val authUrl: String = baseUrl("auth")
lazy val thirdPartyDelegatedAuthorityUrl: String = baseUrl("third-party-delegated-authority")
lazy val access: Option[ConfigObject] = runModeConfiguration.getObject("api.access.version")
lazy val desEnvironment: String = runModeConfiguration.getString(s"$runMode.env.microservice.services.des.environment").getOrElse(throw new RuntimeException(s"$runMode.env.microservice.services.des.environment is not configured"))
lazy val desBearerToken: String = runModeConfiguration.getString(s"$runMode.env.microservice.services.des.bearer-token").getOrElse(throw new RuntimeException(s"$runMode.env.microservice.services.des.bearer-token is not configured"))
lazy val desBearerToken: String = runModeConfiguration.getString(s"$runMode.env.microservice.services.des.bearer-token").getOrElse(throw new RuntimeException(s"$runMode.env.microservice.services.des.bearer-token is not configured"))
lazy val logUserInfoResponsePayload: Boolean = runModeConfiguration.underlying.getBoolean("log-user-info-response-payload")
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package uk.gov.hmrc.openidconnect.userinfo.config

case class FeatureSwitch(name: String, isEnabled: Boolean)


object FeatureSwitch {

def forName(name: String) = FeatureSwitch(name, java.lang.Boolean.getBoolean(systemPropertyName(name)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class GuiceModule(val environment: Environment, val configuration: Configuration
bind(classOf[HttpGet]).to(classOf[DefaultHttpClient])
bind(classOf[ControllerConfig]).toInstance {
new ControllerConfig {
def controllerConfigs: Config = configuration.underlying.getConfig("controllers")
def controllerConfigs: Config = configuration.underlying.getConfig("controllers")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ abstract class AuthConnector extends PlayAuthConnector with AuthorisedFunctions

val appContext: AppContext
val http: CorePost
val serviceUrl : String = appContext.authUrl
val serviceUrl: String = appContext.authUrl

override def authConnector: AuthConnector = this

Expand All @@ -47,13 +47,13 @@ abstract class AuthConnector extends PlayAuthConnector with AuthorisedFunctions
def fetchAuthority()(implicit headerCarrier: HeaderCarrier): Future[Option[Authority]] = {
authorised().retrieve(Retrievals.credentials and Retrievals.nino) {
case credentials ~ nino => Future.successful(Some(Authority(credentials.providerId, nino)))
case _ => Future.successful(None)
case _ => Future.successful(None)
}.recover {
case e: NotFoundException => None
}
}

def fetchUserDetails()(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[Option[UserDetails]] = self.fetchDetails()(hc,ec)
def fetchUserDetails()(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[Option[UserDetails]] = self.fetchDetails()(hc, ec)

def fetchDesUserInfo()(implicit hc: HeaderCarrier): Future[Option[DesUserInfo]] = {
val nothing = Future.successful(None)
Expand All @@ -68,7 +68,7 @@ abstract class AuthConnector extends PlayAuthConnector with AuthorisedFunctions
}

@Singleton
class AuthConnectorV1 @Inject() (val appContext: AppContext, val http: CorePost)(implicit val executionContext: ExecutionContext) extends AuthConnector with AuthV1UserDetailsFetcher
class AuthConnectorV1 @Inject() (val appContext: AppContext, val http: CorePost)(implicit val executionContext: ExecutionContext) extends AuthConnector with AuthV1UserDetailsFetcher

@Singleton
class AuthConnectorV2 @Inject() (val appContext: AppContext, val http: CorePost)(implicit val executionContext: ExecutionContext) extends AuthConnector with AuthV2UserDetailsFetcher
class AuthConnectorV2 @Inject() (val appContext: AppContext, val http: CorePost)(implicit val executionContext: ExecutionContext) extends AuthConnector with AuthV2UserDetailsFetcher
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,18 @@ import uk.gov.hmrc.openidconnect.userinfo.domain.UserDetails
import scala.concurrent.{ExecutionContext, Future}

trait AuthV1UserDetailsFetcher extends UserDetailsFetcher {
self : AuthorisedFunctions =>
self: AuthorisedFunctions =>

def fetchDetails()(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[Option[UserDetails]] = {
authorised().retrieve(Retrievals.allUserDetails and Retrievals.mdtpInformation and Retrievals.gatewayInformation) {
case credentials ~ name ~ birthDate ~ postCode ~ email ~ affinityGroup ~ agentCode ~ agentInformation ~
credentialRole ~ description ~ groupId ~ unreadMessageCount ~ mdtp ~ gatewayInformation =>
Future.successful(Some(UserDetails(authProviderId = Some(credentials.providerId), authProviderType = Some(credentials.providerType),
name = name.name, lastName = name.lastName, dateOfBirth = birthDate, postCode = postCode, email = email,
affinityGroup = affinityGroup.map(_.toString()), agentCode = agentCode,
agentFriendlyName = agentInformation.agentFriendlyName, credentialRole = credentialRole.map(_.toString),
description = description, groupIdentifier = groupId, agentId = agentInformation.agentId,
gatewayInformation = gatewayInformation, mdtpInformation = mdtp, unreadMessageCount = unreadMessageCount, None, None)))
Future.successful(Some(UserDetails(authProviderId = Some(credentials.providerId), authProviderType = Some(credentials.providerType),
name = name.name, lastName = name.lastName, dateOfBirth = birthDate, postCode = postCode, email = email,
affinityGroup = affinityGroup.map(_.toString()), agentCode = agentCode,
agentFriendlyName = agentInformation.agentFriendlyName, credentialRole = credentialRole.map(_.toString),
description = description, groupIdentifier = groupId, agentId = agentInformation.agentId,
gatewayInformation = gatewayInformation, mdtpInformation = mdtp, unreadMessageCount = unreadMessageCount, None, None)))
case _ => Future.successful(None)
}.recover {
case e: NotFoundException => None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,19 @@ import uk.gov.hmrc.openidconnect.userinfo.domain.UserDetails
import scala.concurrent.{ExecutionContext, Future}

trait AuthV2UserDetailsFetcher extends UserDetailsFetcher {
self : AuthorisedFunctions =>
self: AuthorisedFunctions =>

def fetchDetails()(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[Option[UserDetails]] = {
authorised().retrieve(Retrievals.allUserDetails and Retrievals.mdtpInformation and Retrievals.gatewayInformation and Retrievals.profile and Retrievals.groupProfile) {
case credentials ~ maybeName ~ birthDate ~ postCode ~ email ~ affinityGroup ~ agentCode ~ agentInformation ~
credentialRole ~ description ~ groupId ~ unreadMessageCount ~ mdtp ~ gatewayInformation ~ profile ~ groupProfile =>
Future.successful(Some(UserDetails(authProviderId = credentials.map(_.providerId), authProviderType = credentials.map(_.providerType),
name = maybeName.flatMap(_.name), lastName = maybeName.flatMap(_.lastName), dateOfBirth = birthDate, postCode = postCode, email = email,
affinityGroup = affinityGroup.map(_.toString()), agentCode = agentCode,
agentFriendlyName = agentInformation.agentFriendlyName, credentialRole = credentialRole.map(_.toString),
description = description, groupIdentifier = groupId, agentId = agentInformation.agentId,
gatewayInformation = gatewayInformation, mdtpInformation = mdtp, unreadMessageCount = unreadMessageCount, profile = profile,
groupProfile = groupProfile)))
Future.successful(Some(UserDetails(authProviderId = credentials.map(_.providerId), authProviderType = credentials.map(_.providerType),
name = maybeName.flatMap(_.name), lastName = maybeName.flatMap(_.lastName), dateOfBirth = birthDate, postCode = postCode, email = email,
affinityGroup = affinityGroup.map(_.toString()), agentCode = agentCode,
agentFriendlyName = agentInformation.agentFriendlyName, credentialRole = credentialRole.map(_.toString),
description = description, groupIdentifier = groupId, agentId = agentInformation.agentId,
gatewayInformation = gatewayInformation, mdtpInformation = mdtp, unreadMessageCount = unreadMessageCount, profile = profile,
groupProfile = groupProfile)))
case _ => Future.successful(None)
}.recover {
case e: NotFoundException => None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ import uk.gov.hmrc.openidconnect.userinfo.views._
import scala.language.dynamics

@Singleton
class DocumentationController @Inject() (errorHandler:HttpErrorHandler, appContext: AppContext, assets: Assets, cc:ControllerComponents)
extends uk.gov.hmrc.api.controllers.DocumentationController(cc, assets,errorHandler) {
class DocumentationController @Inject() (errorHandler: HttpErrorHandler, appContext: AppContext, assets: Assets, cc: ControllerComponents)
extends uk.gov.hmrc.api.controllers.DocumentationController(cc, assets, errorHandler) {

override def definition(): Action[AnyContent] = Action {
val versions = APIAccessVersions(appContext.access)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ package uk.gov.hmrc.openidconnect.userinfo.controllers
import play.mvc.Http.Status._

sealed abstract class ErrorResponse(val httpStatusCode: Int,
val errorCode: String,
val message: String)
val errorCode: String,
val message: String)

case class ErrorUnauthorized(msg: String = "Bearer token is missing or not authorized") extends ErrorResponse(UNAUTHORIZED, "UNAUTHORIZED", msg)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,19 @@ case object Version_1_0 extends Version
case object Version_1_1 extends Version

object Version {
def fromAcceptHeader(header: Option[String]) : Version = {
def fromAcceptHeader(header: Option[String]): Version = {
header match {
case Some("application/vnd.hmrc.1.0+json") => Version_1_0
case Some("application/vnd.hmrc.1.1+json") => Version_1_1
case _ => throw new IllegalArgumentException("Valid version not supplied")
case _ => throw new IllegalArgumentException("Valid version not supplied")
}
}
}

trait UserInfoController extends BackendBaseController with HeaderValidator {
val service: UserInfoService
val appContext: AppContext
implicit val executionContext:ExecutionContext
implicit val executionContext: ExecutionContext
override val validateVersion: String => Boolean = version => (version == "1.0") | (version == "1.1")

val responseLogger = Logger("userInfoResponsePayloadLogger")
Expand All @@ -55,16 +55,16 @@ trait UserInfoController extends BackendBaseController with HeaderValidator {
service.fetchUserInfo(Version.fromAcceptHeader(request.headers.get(ACCEPT))) map { userInfo =>
val json = Json.toJson(userInfo)

if(appContext.logUserInfoResponsePayload){
if (appContext.logUserInfoResponsePayload) {
responseLogger.debug(s"Returning user info payload: $json")
}

Ok(json)
} recover {
case Upstream4xxResponse(msg, 401, _, _) => Unauthorized(Json.toJson(ErrorUnauthorized()))
case Upstream4xxResponse(msg4xx, _, _ , _) => BadGateway(Json.toJson(ErrorBadGateway(msg4xx)))
case Upstream5xxResponse(msg5xx, _, _,_) => BadGateway(Json.toJson(ErrorBadGateway(msg5xx)))
case bex: BadRequestException => BadRequest(Json.toJson(ErrorBadRequest(bex.getMessage)))
case Upstream4xxResponse(msg, 401, _, _) => Unauthorized(Json.toJson(ErrorUnauthorized()))
case Upstream4xxResponse(msg4xx, _, _, _) => BadGateway(Json.toJson(ErrorBadGateway(msg4xx)))
case Upstream5xxResponse(msg5xx, _, _, _) => BadGateway(Json.toJson(ErrorBadGateway(msg5xx)))
case bex: BadRequestException => BadRequest(Json.toJson(ErrorBadRequest(bex.getMessage)))
}
}
}
Expand All @@ -77,7 +77,7 @@ class SandboxUserInfoController @Inject() (@Named("sandbox") val service: UserIn
}

@Singleton
class LiveUserInfoController @Inject() (@Named("live") val service: UserInfoService, val appContext: AppContext, val cc:ControllerComponents)(implicit val executionContext: ExecutionContext) extends UserInfoController{
class LiveUserInfoController @Inject() (@Named("live") val service: UserInfoService, val appContext: AppContext, val cc: ControllerComponents)(implicit val executionContext: ExecutionContext) extends UserInfoController {
override val parser: BodyParser[AnyContent] = cc.parsers.defaultBodyParser

override protected def controllerComponents: ControllerComponents = cc
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

@Singleton
class FeatureSwitchController @Inject()()(implicit cc: ControllerComponents) extends BackendController(cc) {
class FeatureSwitchController @Inject() ()(implicit cc: ControllerComponents) extends BackendController(cc) {

implicit val featureSwitchReads = Json.reads[FeatureSwitch]
implicit val featureSwitchWrites = Json.writes[FeatureSwitch]
Expand All @@ -45,7 +45,7 @@ class FeatureSwitchController @Inject()()(implicit cc: ControllerComponents) ext
featureSwitches.foreach(fs =>
fs.isEnabled match {
case true => FeatureSwitch.enable(FeatureSwitch.forName(fs.name))
case _ => FeatureSwitch.disable(FeatureSwitch.forName(fs.name))
case _ => FeatureSwitch.disable(FeatureSwitch.forName(fs.name))
}
)
Future(Accepted(currentFeatureSwitchesAsJson))
Expand Down
22 changes: 11 additions & 11 deletions app/uk/gov/hmrc/openidconnect/userinfo/data/UserInfoGenerator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ class UserInfoGenerator {
def address = addressWithToggleableFeatures(UserInfoFeatureSwitches.addressLine5.isEnabled, UserInfoFeatureSwitches.countryCode.isEnabled)

val enrolments = Set(Enrolment("IR-SA", List(EnrolmentIdentifier("UTR", "174371121")), "Activated"))
val government_gateway_v1_0: GovernmentGatewayDetails = GovernmentGatewayDetails(Some("32131"), Some(Seq("User")), Some("Chambers"),Some("affinityGroup"),
Some("agent-code-12345"), Some("agent-id-12345"), Some("agent-friendly-name-12345"), Some("gateway-token-val"), Some(10), None, None)
val government_gateway_v1_1: GovernmentGatewayDetails = GovernmentGatewayDetails(Some("32131"), Some(Seq("User")), Some("Chambers"),Some("affinityGroup"),
Some("agent-code-12345"), Some("agent-id-12345"), Some("agent-friendly-name-12345"), Some("gateway-token-val"), Some(10), Some("some_url"), Some("some_other_url"))
val government_gateway_v1_0: GovernmentGatewayDetails = GovernmentGatewayDetails(Some("32131"), Some(Seq("User")), Some("Chambers"), Some("affinityGroup"),
Some("agent-code-12345"), Some("agent-id-12345"), Some("agent-friendly-name-12345"), Some("gateway-token-val"), Some(10), None, None)
val government_gateway_v1_1: GovernmentGatewayDetails = GovernmentGatewayDetails(Some("32131"), Some(Seq("User")), Some("Chambers"), Some("affinityGroup"),
Some("agent-code-12345"), Some("agent-id-12345"), Some("agent-friendly-name-12345"), Some("gateway-token-val"), Some(10), Some("some_url"), Some("some_other_url"))
val mdtp = Mdtp(deviceId, sessionId)

private lazy val ninoPrefixes = "ABCEGHJKLMNPRSTWXYZ"
Expand All @@ -76,11 +76,11 @@ class UserInfoGenerator {
private val suffixGen = Gen.oneOf(ninoSuffixes)
private val numbersGen = Gen.choose(100000, 999999)
private def email(name: Option[String], lastName: Option[String]): Option[String] = (name, lastName) match {
case (Some(n),None) Some(s"$n@abc.com")
case (None, Some(l)) Some(s"$l@abc.com")
case (Some(n), Some(l)) Some(s"$n.$l@abc.com")
case (None, None) None
}
case (Some(n), None) Some(s"$n@abc.com")
case (None, Some(l)) Some(s"$l@abc.com")
case (Some(n), Some(l)) Some(s"$n.$l@abc.com")
case (None, None) None
}

private def dateOfBirth = {
for {
Expand All @@ -106,7 +106,7 @@ class UserInfoGenerator {
dob <- dateOfBirth
nino <- formattedNino
} yield UserInfo(name, lastName, middleName, address, email(name, lastName), Some(dob), Some(nino), Some(enrolments),
Some(government_gateway_v1_0), Some(mdtp))
Some(government_gateway_v1_0), Some(mdtp))

val userInfoV1_1: Gen[UserInfo] = for {
name <- nameGen
Expand All @@ -115,5 +115,5 @@ class UserInfoGenerator {
dob <- dateOfBirth
nino <- formattedNino
} yield UserInfo(name, lastName, middleName, address, email(name, lastName), Some(dob), Some(nino), Some(enrolments),
Some(government_gateway_v1_1), Some(mdtp))
Some(government_gateway_v1_1), Some(mdtp))
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@
package uk.gov.hmrc.openidconnect.userinfo.domain

case class Authority(credId: String,
nino: Option[String] = None)
nino: Option[String] = None)
Loading

0 comments on commit 5b220a9

Please sign in to comment.