diff --git a/.gitignore b/.gitignore index e17913446..32cd33d61 100644 --- a/.gitignore +++ b/.gitignore @@ -28,4 +28,4 @@ package-lock.json .bloop .metals tmp.out - +.vscode diff --git a/.scalafmt.conf b/.scalafmt.conf index 51c86e61a..749635d17 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -1,3 +1,5 @@ +version=2.2.1 + style = default maxColumn = 100 diff --git a/modules/api/src/it/scala/vinyldns/api/domain/batch/BatchChangeRepositoryIntegrationSpec.scala b/modules/api/src/it/scala/vinyldns/api/domain/batch/BatchChangeRepositoryIntegrationSpec.scala index a1c7f8ff3..4c91645e5 100644 --- a/modules/api/src/it/scala/vinyldns/api/domain/batch/BatchChangeRepositoryIntegrationSpec.scala +++ b/modules/api/src/it/scala/vinyldns/api/domain/batch/BatchChangeRepositoryIntegrationSpec.scala @@ -57,14 +57,16 @@ class BatchChangeRepositoryIntegrationSpec None, None, None - )), + ) + ), approvalStatus = BatchChangeApprovalStatus.AutoApproved ) val f = for { saveBatchChangeResult <- batchChangeRepository.save(batchChange) getSingleChangesResult <- batchChangeRepository.getSingleChanges( - batchChange.changes.map(_.id)) + batchChange.changes.map(_.id) + ) } yield (saveBatchChangeResult, getSingleChangesResult) val (saveResponse, singleChanges) = f.unsafeRunSync() diff --git a/modules/api/src/it/scala/vinyldns/api/domain/dns/DnsConversionsIntegrationSpec.scala b/modules/api/src/it/scala/vinyldns/api/domain/dns/DnsConversionsIntegrationSpec.scala index 13ede96f4..20a7e5bd5 100644 --- a/modules/api/src/it/scala/vinyldns/api/domain/dns/DnsConversionsIntegrationSpec.scala +++ b/modules/api/src/it/scala/vinyldns/api/domain/dns/DnsConversionsIntegrationSpec.scala @@ -83,7 +83,8 @@ class DnsConversionsIntegrationSpec extends WordSpec with Matchers with ResultHe // deleting the record just added val deleteResult: DnsResponse = rightResultOf( - conn.deleteRecord(RecordSetChangeGenerator.forAdd(testRecord, testZone)).value) + conn.deleteRecord(RecordSetChangeGenerator.forAdd(testRecord, testZone)).value + ) deleteResult shouldBe a[NoError] diff --git a/modules/api/src/it/scala/vinyldns/api/domain/record/RecordSetServiceIntegrationSpec.scala b/modules/api/src/it/scala/vinyldns/api/domain/record/RecordSetServiceIntegrationSpec.scala index 9e8277050..0b5d8d6b6 100644 --- a/modules/api/src/it/scala/vinyldns/api/domain/record/RecordSetServiceIntegrationSpec.scala +++ b/modules/api/src/it/scala/vinyldns/api/domain/record/RecordSetServiceIntegrationSpec.scala @@ -75,7 +75,8 @@ class RecordSetServiceIntegrationSpec "test@test.com", status = ZoneStatus.Active, connection = testConnection, - adminGroupId = group.id) + adminGroupId = group.id + ) private val apexTestRecordA = RecordSet( zone.id, @@ -85,7 +86,8 @@ class RecordSetServiceIntegrationSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val apexTestRecordAAAA = RecordSet( zone.id, "live-zone-test", @@ -94,7 +96,8 @@ class RecordSetServiceIntegrationSpec RecordSetStatus.Active, DateTime.now, None, - List(AAAAData("fd69:27cc:fe91::60"))) + List(AAAAData("fd69:27cc:fe91::60")) + ) private val subTestRecordA = RecordSet( zone.id, "a-record", @@ -103,7 +106,8 @@ class RecordSetServiceIntegrationSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val subTestRecordAAAA = RecordSet( zone.id, "aaaa-record", @@ -112,7 +116,8 @@ class RecordSetServiceIntegrationSpec RecordSetStatus.Active, DateTime.now, None, - List(AAAAData("fd69:27cc:fe91::60"))) + List(AAAAData("fd69:27cc:fe91::60")) + ) private val subTestRecordNS = RecordSet( zone.id, "ns-record", @@ -121,14 +126,16 @@ class RecordSetServiceIntegrationSpec RecordSetStatus.Active, DateTime.now, None, - List(NSData("172.17.42.1."))) + List(NSData("172.17.42.1.")) + ) private val zoneTestNameConflicts = Zone( s"zone-test-name-conflicts.", "test@test.com", status = ZoneStatus.Active, connection = testConnection, - adminGroupId = group.id) + adminGroupId = group.id + ) private val apexTestRecordNameConflict = RecordSet( zoneTestNameConflicts.id, "zone-test-name-conflicts.", @@ -137,7 +144,8 @@ class RecordSetServiceIntegrationSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val subTestRecordNameConflict = RecordSet( zoneTestNameConflicts.id, "relative-name-conflict", @@ -146,14 +154,16 @@ class RecordSetServiceIntegrationSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val zoneTestAddRecords = Zone( s"zone-test-add-records.", "test@test.com", status = ZoneStatus.Active, connection = testConnection, - adminGroupId = group.id) + adminGroupId = group.id + ) private val highValueDomainRecord = RecordSet( zone.id, @@ -172,7 +182,8 @@ class RecordSetServiceIntegrationSpec status = ZoneStatus.Active, connection = testConnection, adminGroupId = group.id, - shared = true) + shared = true + ) private val sharedTestRecord = RecordSet( sharedZone.id, @@ -216,8 +227,9 @@ class RecordSetServiceIntegrationSpec zoneRepo = zoneRepository groupRepo = groupRepository List(group, group2, sharedGroup).map(g => waitForSuccess(groupRepo.save(g))) - List(zone, zoneTestNameConflicts, zoneTestAddRecords, sharedZone).map(z => - waitForSuccess(zoneRepo.save(z))) + List(zone, zoneTestNameConflicts, zoneTestAddRecords, sharedZone).map( + z => waitForSuccess(zoneRepo.save(z)) + ) // Seeding records in DB val records = List( @@ -242,7 +254,8 @@ class RecordSetServiceIntegrationSpec mock[RecordChangeRepository], mock[UserRepository], TestMessageQueue, - new AccessValidations()) + new AccessValidations() + ) } def tearDown(): Unit = () @@ -270,7 +283,8 @@ class RecordSetServiceIntegrationSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) val result = testRecordSetService .addRecordSet(newRecord, auth) @@ -387,7 +401,8 @@ class RecordSetServiceIntegrationSpec .unsafeRunSync() leftValue(result) shouldBe InvalidRequest( - HighValueDomainError("high-value-domain-new.live-zone-test.").message) + HighValueDomainError("high-value-domain-new.live-zone-test.").message + ) } "fail to update a record whose name is a high value domain" in { @@ -399,7 +414,8 @@ class RecordSetServiceIntegrationSpec .unsafeRunSync() leftValue(result) shouldBe InvalidRequest( - HighValueDomainError("high-value-domain-existing.live-zone-test.").message) + HighValueDomainError("high-value-domain-existing.live-zone-test.").message + ) } "fail to delete a record whose name is a high value domain" in { @@ -409,7 +425,8 @@ class RecordSetServiceIntegrationSpec .unsafeRunSync() leftValue(result) shouldBe InvalidRequest( - HighValueDomainError("high-value-domain-existing.live-zone-test.").message) + HighValueDomainError("high-value-domain-existing.live-zone-test.").message + ) } "get a shared record when user is in assigned ownerGroup" in { @@ -518,7 +535,8 @@ class RecordSetServiceIntegrationSpec .deleteRecordSet( testOwnerGroupRecordInNormalZone.id, testOwnerGroupRecordInNormalZone.zoneId, - auth2) + auth2 + ) .value ) diff --git a/modules/api/src/it/scala/vinyldns/api/domain/zone/ZoneServiceIntegrationSpec.scala b/modules/api/src/it/scala/vinyldns/api/domain/zone/ZoneServiceIntegrationSpec.scala index 5c781757c..6b3c7b9ae 100644 --- a/modules/api/src/it/scala/vinyldns/api/domain/zone/ZoneServiceIntegrationSpec.scala +++ b/modules/api/src/it/scala/vinyldns/api/domain/zone/ZoneServiceIntegrationSpec.scala @@ -83,7 +83,8 @@ class ZoneServiceIntegrationSpec ttl = 38400, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("10.1.1.1"))) + records = List(AData("10.1.1.1")) + ) private val changeSetSOA = ChangeSet(RecordSetChangeGenerator.forAdd(testRecordSOA, okZone)) private val changeSetNS = ChangeSet(RecordSetChangeGenerator.forAdd(testRecordNS, okZone)) @@ -159,7 +160,8 @@ class ZoneServiceIntegrationSpec "getBackendIds" should { "return backend ids in config" in { testZoneService.getBackendIds().value.unsafeRunSync() shouldBe Right( - List("func-test-backend")) + List("func-test-backend") + ) } } diff --git a/modules/api/src/it/scala/vinyldns/api/domain/zone/ZoneViewLoaderIntegrationSpec.scala b/modules/api/src/it/scala/vinyldns/api/domain/zone/ZoneViewLoaderIntegrationSpec.scala index 63ff8d1b1..3f3478e22 100644 --- a/modules/api/src/it/scala/vinyldns/api/domain/zone/ZoneViewLoaderIntegrationSpec.scala +++ b/modules/api/src/it/scala/vinyldns/api/domain/zone/ZoneViewLoaderIntegrationSpec.scala @@ -32,17 +32,21 @@ class ZoneViewLoaderIntegrationSpec extends WordSpec with Matchers { assertThrows[IllegalArgumentException]( DnsZoneViewLoader( Zone("vinyldns.", "bad@transfer.connection") - .copy(transferConnection = - Some(ZoneConnection("invalid-connection.", "bad-key", "invalid-key", "10.1.1.1")))) - .load() - .unsafeRunSync()) + .copy( + transferConnection = + Some(ZoneConnection("invalid-connection.", "bad-key", "invalid-key", "10.1.1.1")) + ) + ).load() + .unsafeRunSync() + ) } "return a failure if the zone doesn't exist in the DNS backend" in { assertThrows[ZoneTransferException]( DnsZoneViewLoader(Zone("non-existent-zone", "bad@zone.test")) .load() - .unsafeRunSync()) + .unsafeRunSync() + ) } "return a failure if the zone is larger than the max zone size" in { diff --git a/modules/api/src/it/scala/vinyldns/api/notifier/email/EmailNotifierIntegrationSpec.scala b/modules/api/src/it/scala/vinyldns/api/notifier/email/EmailNotifierIntegrationSpec.scala index 3ab3a2457..b36a472d7 100644 --- a/modules/api/src/it/scala/vinyldns/api/notifier/email/EmailNotifierIntegrationSpec.scala +++ b/modules/api/src/it/scala/vinyldns/api/notifier/email/EmailNotifierIntegrationSpec.scala @@ -72,7 +72,8 @@ class EmailNotifierIntegrationSpec None, None, None - )), + ) + ), approvalStatus = BatchChangeApprovalStatus.AutoApproved ) diff --git a/modules/api/src/it/scala/vinyldns/api/notifier/sns/SnsNotifierIntegrationSpec.scala b/modules/api/src/it/scala/vinyldns/api/notifier/sns/SnsNotifierIntegrationSpec.scala index 8281ed8f8..6c1aab887 100644 --- a/modules/api/src/it/scala/vinyldns/api/notifier/sns/SnsNotifierIntegrationSpec.scala +++ b/modules/api/src/it/scala/vinyldns/api/notifier/sns/SnsNotifierIntegrationSpec.scala @@ -68,7 +68,8 @@ class SnsNotifierIntegrationSpec None, None, None - )), + ) + ), approvalStatus = BatchChangeApprovalStatus.AutoApproved, id = "a615e2bb-8b35-4a39-8947-1edd0e653afa" ) @@ -76,12 +77,16 @@ class SnsNotifierIntegrationSpec val credentialsProvider = new AWSStaticCredentialsProvider( new BasicAWSCredentials( snsConfig.getString("access-key"), - snsConfig.getString("secret-key"))) + snsConfig.getString("secret-key") + ) + ) val sns = AmazonSNSClientBuilder.standard .withEndpointConfiguration( new EndpointConfiguration( snsConfig.getString("service-endpoint"), - snsConfig.getString("signing-region"))) + snsConfig.getString("signing-region") + ) + ) .withCredentials(credentialsProvider) .build() val sqs = AmazonSQSClientBuilder @@ -113,7 +118,8 @@ class SnsNotifierIntegrationSpec val notification = parse(messages.get(0).getBody) (notification \ "Message").extract[String] should be( """{"userId":"ok","userName":"ok","createdTimestamp":"2019-07-22T19:38:23Z",""" + - """"status":"Complete","approvalStatus":"AutoApproved","id":"a615e2bb-8b35-4a39-8947-1edd0e653afa"}""") + """"status":"Complete","approvalStatus":"AutoApproved","id":"a615e2bb-8b35-4a39-8947-1edd0e653afa"}""" + ) } } diff --git a/modules/api/src/main/scala/vinyldns/api/Boot.scala b/modules/api/src/main/scala/vinyldns/api/Boot.scala index f2e07992c..a5ec4fb3d 100644 --- a/modules/api/src/main/scala/vinyldns/api/Boot.scala +++ b/modules/api/src/main/scala/vinyldns/api/Boot.scala @@ -79,7 +79,8 @@ object Boot extends App { repositories.userRepository, repositories.groupRepository, repositories.zoneRepository, - repositories.membershipRepository) + repositories.membershipRepository + ) queueConfig <- VinylDNSConfig.messageQueueConfig messageQueue <- MessageQueueLoader.load(queueConfig) processingDisabled <- IO(VinylDNSConfig.vinyldnsConfig.getBoolean("processing-disabled")) @@ -128,16 +129,19 @@ object Boot extends App { connectionValidator, messageQueue, zoneValidations, - recordAccessValidations) + recordAccessValidations + ) val healthService = new HealthService( messageQueue.healthCheck :: connectionValidator.healthCheck(healthCheckTimeout) :: - loaderResponse.healthChecks) + loaderResponse.healthChecks + ) val batchChangeConverter = new BatchChangeConverter(repositories.batchChangeRepository, messageQueue) val authPrincipalProvider = new MembershipAuthPrincipalProvider( repositories.userRepository, - repositories.membershipRepository) + repositories.membershipRepository + ) val batchChangeService = BatchChangeService( repositories, batchChangeValidations, diff --git a/modules/api/src/main/scala/vinyldns/api/VinylDNSConfig.scala b/modules/api/src/main/scala/vinyldns/api/VinylDNSConfig.scala index ae16cf4d1..b50cb2c45 100644 --- a/modules/api/src/main/scala/vinyldns/api/VinylDNSConfig.scala +++ b/modules/api/src/main/scala/vinyldns/api/VinylDNSConfig.scala @@ -76,7 +76,8 @@ object VinylDNSConfig { lazy val highValueRegexList: List[Regex] = ZoneRecordValidations.toCaseIgnoredRegexList( - getOptionalStringList("high-value-domains.regex-list")) + getOptionalStringList("high-value-domains.regex-list") + ) lazy val highValueIpList: List[IpAddress] = getOptionalStringList("high-value-domains.ip-list").flatMap(ip => IpAddress(ip)) @@ -148,13 +149,15 @@ object VinylDNSConfig { lazy val domainListRequiringManualReview: List[Regex] = ZoneRecordValidations.toCaseIgnoredRegexList( - getOptionalStringList("manual-review-domains.domain-list")) + getOptionalStringList("manual-review-domains.domain-list") + ) lazy val ipListRequiringManualReview: List[IpAddress] = getOptionalStringList("manual-review-domains.ip-list").flatMap(ip => IpAddress(ip)) lazy val zoneNameListRequiringManualReview: Set[String] = { - Set() ++ getOptionalStringList("manual-review-domains.zone-name-list").map(zn => - DomainHelpers.ensureTrailingDot(zn.toLowerCase)) + Set() ++ getOptionalStringList("manual-review-domains.zone-name-list").map( + zn => DomainHelpers.ensureTrailingDot(zn.toLowerCase) + ) } } diff --git a/modules/api/src/main/scala/vinyldns/api/backend/CommandHandler.scala b/modules/api/src/main/scala/vinyldns/api/backend/CommandHandler.scala index e09902025..2a8e36dd2 100644 --- a/modules/api/src/main/scala/vinyldns/api/backend/CommandHandler.scala +++ b/modules/api/src/main/scala/vinyldns/api/backend/CommandHandler.scala @@ -59,7 +59,8 @@ object CommandHandler { pollingInterval: FiniteDuration, pauseSignal: SignallingRef[IO, Boolean], connections: ConfiguredDnsConnections, - maxOpen: Int = 4)(implicit timer: Timer[IO]): Stream[IO, Unit] = { + maxOpen: Int = 4 + )(implicit timer: Timer[IO]): Stream[IO, Unit] = { // Polls queue for message batches, connected to the signal which is toggled in the status endpoint val messageSource = startPolling(mq, count, pollingInterval).pauseWhen(pauseSignal) @@ -73,7 +74,8 @@ object CommandHandler { recordChangeHandler, zoneSyncHandler, batchChangeHandler, - connections) + connections + ) // Delete messages from message queue when complete val updateQueue = messageSink(mq) @@ -84,7 +86,8 @@ object CommandHandler { .map( _.observe(increaseTimeoutWhenSyncing) .through(changeRequestProcessor) - .through(updateQueue)) + .through(updateQueue) + ) .parJoin(maxOpen) .handleErrorWith { error => logger.error("Encountered unexpected error in main flow", error) @@ -98,7 +101,8 @@ object CommandHandler { /* Polls Message Queue for messages */ def startPolling(mq: MessageQueue, count: MessageCount, pollingInterval: FiniteDuration)( - implicit timer: Timer[IO]): Stream[IO, Stream[IO, CommandMessage]] = { + implicit timer: Timer[IO] + ): Stream[IO, Stream[IO, CommandMessage]] = { def pollingStream(): Stream[IO, Stream[IO, CommandMessage]] = // every delay duration, we poll @@ -145,7 +149,8 @@ object CommandHandler { recordChangeProcessor: (DnsConnection, RecordSetChange) => IO[RecordSetChange], zoneSyncProcessor: ZoneChange => IO[ZoneChange], batchChangeProcessor: BatchChangeCommand => IO[Option[BatchChange]], - connections: ConfiguredDnsConnections): Pipe[IO, CommandMessage, MessageOutcome] = + connections: ConfiguredDnsConnections + ): Pipe[IO, CommandMessage, MessageOutcome] = _.evalMap[IO, MessageOutcome] { message => message.command match { case sync: ZoneChange @@ -202,7 +207,8 @@ object CommandHandler { recordChangeRepo: RecordChangeRepository, batchChangeRepo: BatchChangeRepository, notifiers: AllNotifiers, - connections: ConfiguredDnsConnections)(implicit timer: Timer[IO]): IO[Unit] = { + connections: ConfiguredDnsConnections + )(implicit timer: Timer[IO]): IO[Unit] = { // Handlers for each type of change request val zoneChangeHandler = ZoneChangeHandler(zoneRepo, zoneChangeRepo, recordSetRepo) diff --git a/modules/api/src/main/scala/vinyldns/api/domain/DomainValidations.scala b/modules/api/src/main/scala/vinyldns/api/domain/DomainValidations.scala index 167a7b415..3295ede93 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/DomainValidations.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/DomainValidations.scala @@ -95,7 +95,8 @@ object DomainValidations { def validateStringLength( value: Option[String], minInclusive: Option[Int], - maxInclusive: Int): ValidatedNel[DomainValidationError, Option[String]] = + maxInclusive: Int + ): ValidatedNel[DomainValidationError, Option[String]] = validateIfDefined(value) { d => validateStringLength(d, minInclusive, maxInclusive) } @@ -103,7 +104,8 @@ object DomainValidations { def validateStringLength( value: String, minInclusive: Option[Int], - maxInclusive: Int): ValidatedNel[DomainValidationError, String] = + maxInclusive: Int + ): ValidatedNel[DomainValidationError, String] = if (minInclusive.forall(m => value.length >= m) && value.length <= maxInclusive) value.validNel else InvalidLength(value, minInclusive.getOrElse(0), maxInclusive).invalidNel diff --git a/modules/api/src/main/scala/vinyldns/api/domain/ReverseZoneHelpers.scala b/modules/api/src/main/scala/vinyldns/api/domain/ReverseZoneHelpers.scala index ffc6f6c2e..101bac316 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/ReverseZoneHelpers.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/ReverseZoneHelpers.scala @@ -57,7 +57,8 @@ object ReverseZoneHelpers { handleIpv6RecordValidation(zone: Zone, recordName) } else { InvalidRequest( - s"RecordSet $recordName does not specify a valid IP address in zone ${zone.name}").asLeft + s"RecordSet $recordName does not specify a valid IP address in zone ${zone.name}" + ).asLeft } def convertPTRtoIPv4(zone: Zone, recordName: String): String = { @@ -83,7 +84,8 @@ object ReverseZoneHelpers { private def recordsetIsWithinCidrMaskIpv4( mask: String, zone: Zone, - recordName: String): Boolean = { + recordName: String + ): Boolean = { val recordIpAddr = convertPTRtoIPv4(zone, recordName) Try { @@ -125,14 +127,16 @@ object ReverseZoneHelpers { private def handleIpv4RecordValidation( zone: Zone, - recordName: String): Either[Throwable, Unit] = { + recordName: String + ): Either[Throwable, Unit] = { val isValid = for { cidrMask <- getZoneAsCIDRString(zone) validated <- if (recordsetIsWithinCidrMask(cidrMask, zone, recordName)) { true.asRight } else { InvalidRequest( - s"RecordSet $recordName does not specify a valid IP address in zone ${zone.name}").asLeft + s"RecordSet $recordName does not specify a valid IP address in zone ${zone.name}" + ).asLeft } } yield validated @@ -141,14 +145,16 @@ object ReverseZoneHelpers { private def handleIpv6RecordValidation( zone: Zone, - recordName: String): Either[Throwable, Unit] = { + recordName: String + ): Either[Throwable, Unit] = { val v6Regex = "([0-9a-f][.]){32}ip6.arpa.".r s"$recordName.${zone.name}" match { case v6Regex(_*) => ().asRight case _ => InvalidRequest( - s"RecordSet $recordName does not specify a valid IP address in zone ${zone.name}").asLeft + s"RecordSet $recordName does not specify a valid IP address in zone ${zone.name}" + ).asLeft } } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/ValidationImprovements.scala b/modules/api/src/main/scala/vinyldns/api/domain/ValidationImprovements.scala index 1b6b78151..96c23d43b 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/ValidationImprovements.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/ValidationImprovements.scala @@ -26,8 +26,9 @@ object ValidationImprovements { * If the value is not present, will return None as success * */ - def validateIfDefined[E, A](value: => Option[A])( - validator: A => ValidatedNel[E, A]): ValidatedNel[E, Option[A]] = + def validateIfDefined[E, A]( + value: => Option[A] + )(validator: A => ValidatedNel[E, A]): ValidatedNel[E, Option[A]] = value match { case None => Option.empty[A].validNel[E] case Some(a) => validator(a).map(Some(_)) diff --git a/modules/api/src/main/scala/vinyldns/api/domain/access/AccessValidations.scala b/modules/api/src/main/scala/vinyldns/api/domain/access/AccessValidations.scala index 9846ad061..b8fa636a6 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/access/AccessValidations.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/access/AccessValidations.scala @@ -31,31 +31,39 @@ class AccessValidations(globalAcls: GlobalAcls = GlobalAcls(List.empty)) def canSeeZone(auth: AuthPrincipal, zone: Zone): Either[Throwable, Unit] = ensuring( - NotAuthorizedError(s"User ${auth.signedInUser.userName} cannot access zone '${zone.name}'"))( + NotAuthorizedError(s"User ${auth.signedInUser.userName} cannot access zone '${zone.name}'") + )( auth.isSystemAdmin || auth - .isGroupMember(zone.adminGroupId) || userHasAclRules(auth, zone)) + .isGroupMember(zone.adminGroupId) || userHasAclRules(auth, zone) + ) def canChangeZone( auth: AuthPrincipal, zoneName: String, - zoneAdminGroupId: String): Either[Throwable, Unit] = + zoneAdminGroupId: String + ): Either[Throwable, Unit] = ensuring( NotAuthorizedError( s"""User '${auth.signedInUser.userName}' cannot create or modify zone '$zoneName' because |they are not in the Zone Admin Group '$zoneAdminGroupId'""".stripMargin - .replace("\n", " ")))(auth.isSuper || auth.isGroupMember(zoneAdminGroupId)) + .replace("\n", " ") + ) + )(auth.isSuper || auth.isGroupMember(zoneAdminGroupId)) def canAddRecordSet( auth: AuthPrincipal, recordName: String, recordType: RecordType, zone: Zone, - recordData: List[RecordData] = List.empty): Either[Throwable, Unit] = { + recordData: List[RecordData] = List.empty + ): Either[Throwable, Unit] = { val accessLevel = getAccessLevel(auth, recordName, recordType, zone, None, recordData) ensuring( - NotAuthorizedError(s"User ${auth.signedInUser.userName} does not have access to create " + - s"$recordName.${zone.name}"))( - accessLevel == AccessLevel.Delete || accessLevel == AccessLevel.Write) + NotAuthorizedError( + s"User ${auth.signedInUser.userName} does not have access to create " + + s"$recordName.${zone.name}" + ) + )(accessLevel == AccessLevel.Delete || accessLevel == AccessLevel.Write) } def canUpdateRecordSet( @@ -64,13 +72,16 @@ class AccessValidations(globalAcls: GlobalAcls = GlobalAcls(List.empty)) recordType: RecordType, zone: Zone, recordOwnerGroupId: Option[String], - newRecordData: List[RecordData] = List.empty): Either[Throwable, Unit] = { + newRecordData: List[RecordData] = List.empty + ): Either[Throwable, Unit] = { val accessLevel = getAccessLevel(auth, recordName, recordType, zone, recordOwnerGroupId, newRecordData) ensuring( - NotAuthorizedError(s"User ${auth.signedInUser.userName} does not have access to update " + - s"$recordName.${zone.name}"))( - accessLevel == AccessLevel.Delete || accessLevel == AccessLevel.Write) + NotAuthorizedError( + s"User ${auth.signedInUser.userName} does not have access to update " + + s"$recordName.${zone.name}" + ) + )(accessLevel == AccessLevel.Delete || accessLevel == AccessLevel.Write) } def canDeleteRecordSet( @@ -79,16 +90,16 @@ class AccessValidations(globalAcls: GlobalAcls = GlobalAcls(List.empty)) recordType: RecordType, zone: Zone, recordOwnerGroupId: Option[String], - existingRecordData: List[RecordData] = List.empty): Either[Throwable, Unit] = + existingRecordData: List[RecordData] = List.empty + ): Either[Throwable, Unit] = ensuring( - NotAuthorizedError(s"User ${auth.signedInUser.userName} does not have access to delete " + - s"$recordName.${zone.name}"))(getAccessLevel( - auth, - recordName, - recordType, - zone, - recordOwnerGroupId, - existingRecordData) == AccessLevel.Delete) + NotAuthorizedError( + s"User ${auth.signedInUser.userName} does not have access to delete " + + s"$recordName.${zone.name}" + ) + )( + getAccessLevel(auth, recordName, recordType, zone, recordOwnerGroupId, existingRecordData) == AccessLevel.Delete + ) def canViewRecordSet( auth: AuthPrincipal, @@ -96,17 +107,22 @@ class AccessValidations(globalAcls: GlobalAcls = GlobalAcls(List.empty)) recordType: RecordType, zone: Zone, recordOwnerGroupId: Option[String], - recordData: List[RecordData] = List.empty): Either[Throwable, Unit] = + recordData: List[RecordData] = List.empty + ): Either[Throwable, Unit] = ensuring( - NotAuthorizedError(s"User ${auth.signedInUser.userName} does not have access to view " + - s"$recordName.${zone.name}"))( + NotAuthorizedError( + s"User ${auth.signedInUser.userName} does not have access to view " + + s"$recordName.${zone.name}" + ) + )( getAccessLevel(auth, recordName, recordType, zone, recordOwnerGroupId, recordData) != AccessLevel.NoAccess ) def getListAccessLevels( auth: AuthPrincipal, recordSets: List[RecordSetInfo], - zone: Zone): List[RecordSetListInfo] = + zone: Zone + ): List[RecordSetListInfo] = if (auth.isSuper || auth.isGroupMember(zone.adminGroupId)) recordSets.map(RecordSetListInfo(_, AccessLevel.Delete)) else { @@ -136,13 +152,15 @@ class AccessValidations(globalAcls: GlobalAcls = GlobalAcls(List.empty)) auth: AuthPrincipal, recordName: String, recordType: RecordType, - zone: Zone): AccessLevel = { + zone: Zone + ): AccessLevel = { val validRules = zone.acl.rules.filter { rule => ruleAppliesToUser(auth, rule) && ruleAppliesToRecordType(recordType, rule) && ruleAppliesToRecordName( recordName, recordType, zone, - rule) + rule + ) } getPrioritizedAccessLevel(recordType, validRules) } @@ -164,7 +182,8 @@ class AccessValidations(globalAcls: GlobalAcls = GlobalAcls(List.empty)) recordName: String, recordType: RecordType, zone: Zone, - rule: ACLRule): Boolean = + rule: ACLRule + ): Boolean = rule.recordMask match { case Some(mask) if recordType == RecordType.PTR => ReverseZoneHelpers.recordsetIsWithinCidrMask(mask, zone, recordName) @@ -192,7 +211,8 @@ class AccessValidations(globalAcls: GlobalAcls = GlobalAcls(List.empty)) recordType: RecordType, zone: Zone, recordOwnerGroupId: Option[String] = None, - recordData: List[RecordData] = List.empty): AccessLevel = auth match { + recordData: List[RecordData] = List.empty + ): AccessLevel = auth match { case testUser if testUser.isTestUser && !zone.isTest => AccessLevel.NoAccess case admin if admin.isGroupMember(zone.adminGroupId) => AccessLevel.Delete @@ -211,7 +231,8 @@ class AccessValidations(globalAcls: GlobalAcls = GlobalAcls(List.empty)) def sharedRecordAccess( auth: AuthPrincipal, recordType: RecordType, - recordOwnerGroupId: Option[String]): Boolean = + recordOwnerGroupId: Option[String] + ): Boolean = recordOwnerGroupId.exists(auth.isGroupMember) || (recordOwnerGroupId.isEmpty && VinylDNSConfig.sharedApprovedTypes.contains(recordType)) } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/access/AccessValidationsAlgebra.scala b/modules/api/src/main/scala/vinyldns/api/domain/access/AccessValidationsAlgebra.scala index 601dca019..59d6c300a 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/access/AccessValidationsAlgebra.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/access/AccessValidationsAlgebra.scala @@ -30,14 +30,16 @@ trait AccessValidationsAlgebra { def canChangeZone( auth: AuthPrincipal, zoneName: String, - zoneAdminGroupId: String): Either[Throwable, Unit] + zoneAdminGroupId: String + ): Either[Throwable, Unit] def canAddRecordSet( auth: AuthPrincipal, recordName: String, recordType: RecordType, zone: Zone, - recordData: List[RecordData] = List.empty): Either[Throwable, Unit] + recordData: List[RecordData] = List.empty + ): Either[Throwable, Unit] def canUpdateRecordSet( auth: AuthPrincipal, @@ -45,7 +47,8 @@ trait AccessValidationsAlgebra { recordType: RecordType, zone: Zone, recordOwnerGroupId: Option[String], - newRecordData: List[RecordData] = List.empty): Either[Throwable, Unit] + newRecordData: List[RecordData] = List.empty + ): Either[Throwable, Unit] def canDeleteRecordSet( auth: AuthPrincipal, @@ -53,7 +56,8 @@ trait AccessValidationsAlgebra { recordType: RecordType, zone: Zone, recordOwnerGroupId: Option[String], - existingRecordData: List[RecordData] = List.empty): Either[Throwable, Unit] + existingRecordData: List[RecordData] = List.empty + ): Either[Throwable, Unit] def canViewRecordSet( auth: AuthPrincipal, @@ -61,12 +65,14 @@ trait AccessValidationsAlgebra { recordType: RecordType, zone: Zone, recordOwnerGroupId: Option[String], - recordData: List[RecordData] = List.empty): Either[Throwable, Unit] + recordData: List[RecordData] = List.empty + ): Either[Throwable, Unit] def getListAccessLevels( auth: AuthPrincipal, recordSets: List[RecordSetInfo], - zone: Zone): List[RecordSetListInfo] + zone: Zone + ): List[RecordSetListInfo] def getZoneAccess(auth: AuthPrincipal, zone: Zone): AccessLevel } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/access/GlobalAcl.scala b/modules/api/src/main/scala/vinyldns/api/domain/access/GlobalAcl.scala index de8060d8f..474523c0b 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/access/GlobalAcl.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/access/GlobalAcl.scala @@ -47,7 +47,8 @@ final case class GlobalAcls(acls: List[GlobalAcl]) { recordName: String, recordType: RecordType, zone: Zone, - recordData: List[RecordData] = List.empty): Boolean = { + recordData: List[RecordData] = List.empty + ): Boolean = { def isAuthorized(authPrincipal: AuthPrincipal, fqdn: String): Boolean = { val regexList = authPrincipal.memberGroupIds.flatMap(aclMap.getOrElse(_, List.empty)).toList diff --git a/modules/api/src/main/scala/vinyldns/api/domain/auth/AuthPrincipalProvider.scala b/modules/api/src/main/scala/vinyldns/api/domain/auth/AuthPrincipalProvider.scala index 7aba70b72..1ff20eb81 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/auth/AuthPrincipalProvider.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/auth/AuthPrincipalProvider.scala @@ -28,8 +28,8 @@ trait AuthPrincipalProvider extends Monitored { class MembershipAuthPrincipalProvider( userRepo: UserRepository, - membershipRepo: MembershipRepository) - extends AuthPrincipalProvider { + membershipRepo: MembershipRepository +) extends AuthPrincipalProvider { def getAuthPrincipal(accessKey: String): IO[Option[AuthPrincipal]] = getUserByAccessKey(accessKey).flatMap { diff --git a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeConverter.scala b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeConverter.scala index 75223ef7e..74f3265d6 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeConverter.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeConverter.scala @@ -40,16 +40,19 @@ class BatchChangeConverter(batchChangeRepo: BatchChangeRepository, messageQueue: batchChange: BatchChange, existingZones: ExistingZones, groupedChanges: ChangeForValidationMap, - ownerGroupId: Option[String]): BatchResult[BatchConversionOutput] = { + ownerGroupId: Option[String] + ): BatchResult[BatchConversionOutput] = { logger.info( - s"Converting BatchChange [${batchChange.id}] with SingleChanges [${batchChange.changes.map(_.id)}]") + s"Converting BatchChange [${batchChange.id}] with SingleChanges [${batchChange.changes.map(_.id)}]" + ) for { recordSetChanges <- createRecordSetChangesForBatch( batchChange.changes, existingZones, groupedChanges, batchChange.userId, - ownerGroupId).toRightBatchResult + ownerGroupId + ).toRightBatchResult _ <- allChangesWereConverted(batchChange.changes, recordSetChanges) _ <- batchChangeRepo .save(batchChange) @@ -62,7 +65,8 @@ class BatchChangeConverter(batchChangeRepo: BatchChangeRepository, messageQueue: def allChangesWereConverted( singleChanges: List[SingleChange], - recordSetChanges: List[RecordSetChange]): BatchResult[Unit] = { + recordSetChanges: List[RecordSetChange] + ): BatchResult[Unit] = { val convertedIds = recordSetChanges.flatMap(_.singleBatchChangeIds).toSet singleChanges.find(ch => !convertedIds.contains(ch.id)) match { @@ -76,7 +80,8 @@ class BatchChangeConverter(batchChangeRepo: BatchChangeRepository, messageQueue: def putChangesOnQueue( recordSetChanges: List[RecordSetChange], - batchChangeId: String): BatchResult[List[RecordSetChange]] = + batchChangeId: String + ): BatchResult[List[RecordSetChange]] = recordSetChanges.toNel match { case None => recordSetChanges.toRightBatchResult // If list is empty, return normally without queueing @@ -94,7 +99,8 @@ class BatchChangeConverter(batchChangeRepo: BatchChangeRepository, messageQueue: def updateWithQueueingFailures( batchChange: BatchChange, - recordSetChanges: List[RecordSetChange]): BatchChange = { + recordSetChanges: List[RecordSetChange] + ): BatchChange = { // idsMap maps batchId to recordSetId val idsMap = recordSetChanges.flatMap { rsChange => rsChange.singleBatchChangeIds.map(batchId => (batchId, rsChange.id)) @@ -128,7 +134,8 @@ class BatchChangeConverter(batchChangeRepo: BatchChangeRepository, messageQueue: existingZones: ExistingZones, groupedChanges: ChangeForValidationMap, userId: String, - ownerGroupId: Option[String]): List[RecordSetChange] = { + ownerGroupId: Option[String] + ): List[RecordSetChange] = { // NOTE: this also assumes we are past approval and know the zone/record split at this point val supportedChangesByKey = changes .filter(sc => SupportedBatchChangeRecordTypes.get.contains(sc.typ)) @@ -155,7 +162,8 @@ class BatchChangeConverter(batchChangeRepo: BatchChangeRepository, messageQueue: proposedRecordData, userId, existingRecordSet, - ownerGroupId) + ownerGroupId + ) } yield recordSetChange } .toList @@ -170,7 +178,8 @@ class BatchChangeConverter(batchChangeRepo: BatchChangeRepository, messageQueue: proposedRecordData: Set[RecordData], userId: String, existingRecordSet: Option[RecordSet], - ownerGroupId: Option[String]): Option[RecordSetChange] = { + ownerGroupId: Option[String] + ): Option[RecordSetChange] = { val singleChangeIds = singleChangeNel.map(_.id).toList diff --git a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeConverterAlgebra.scala b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeConverterAlgebra.scala index cc6d704e4..cd8413581 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeConverterAlgebra.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeConverterAlgebra.scala @@ -30,5 +30,6 @@ trait BatchChangeConverterAlgebra { batchChange: BatchChange, existingZones: ExistingZones, groupedChanges: ChangeForValidationMap, - ownerGroupId: Option[String]): BatchResult[BatchConversionOutput] + ownerGroupId: Option[String] + ): BatchResult[BatchConversionOutput] } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeErrors.scala b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeErrors.scala index c79fba1cd..1d15c2025 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeErrors.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeErrors.scala @@ -30,8 +30,8 @@ final case class InvalidBatchChangeInput(errors: List[DomainValidationError]) // This separates error by change requested final case class InvalidBatchChangeResponses( changeRequests: List[ChangeInput], - changeRequestResponses: ValidatedBatch[ChangeForValidation]) - extends BatchChangeErrorResponse + changeRequestResponses: ValidatedBatch[ChangeForValidation] +) extends BatchChangeErrorResponse final case class BatchChangeFailedApproval(batchChange: BatchChange) extends BatchChangeErrorResponse diff --git a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeProtocol.scala b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeProtocol.scala index 3d90e6f50..0bd2e8b61 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeProtocol.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeProtocol.scala @@ -29,7 +29,8 @@ final case class BatchChangeInput( comments: Option[String], changes: List[ChangeInput], ownerGroupId: Option[String] = None, - scheduledTime: Option[DateTime] = None) + scheduledTime: Option[DateTime] = None +) object BatchChangeInput { def apply(batchChange: BatchChange): BatchChangeInput = { @@ -51,8 +52,8 @@ final case class AddChangeInput( inputName: String, typ: RecordType, ttl: Option[Long], - record: RecordData) - extends ChangeInput { + record: RecordData +) extends ChangeInput { def asNewStoredChange(errors: NonEmptyList[DomainValidationError]): SingleChange = { val knownTtl = ttl.getOrElse(VinylDNSConfig.defaultTtl) @@ -76,8 +77,8 @@ final case class AddChangeInput( final case class DeleteRRSetChangeInput( inputName: String, typ: RecordType, - record: Option[RecordData]) - extends ChangeInput { + record: Option[RecordData] +) extends ChangeInput { def asNewStoredChange(errors: NonEmptyList[DomainValidationError]): SingleChange = SingleDeleteRRSetChange( None, @@ -99,7 +100,8 @@ object AddChangeInput { inputName: String, typ: RecordType, ttl: Option[Long], - record: RecordData): AddChangeInput = { + record: RecordData + ): AddChangeInput = { val transformName = typ match { case PTR => inputName case _ => ensureTrailingDot(inputName) @@ -115,7 +117,8 @@ object DeleteRRSetChangeInput { def apply( inputName: String, typ: RecordType, - record: Option[RecordData] = None): DeleteRRSetChangeInput = { + record: Option[RecordData] = None + ): DeleteRRSetChangeInput = { val transformName = typ match { case PTR => inputName case _ => ensureTrailingDot(inputName) diff --git a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeReviewInfo.scala b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeReviewInfo.scala index c20c9f4e8..9291b95d7 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeReviewInfo.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeReviewInfo.scala @@ -21,4 +21,5 @@ import org.joda.time.DateTime final case class BatchChangeReviewInfo( reviewerId: String, reviewComment: Option[String], - reviewTimestamp: DateTime = DateTime.now()) + reviewTimestamp: DateTime = DateTime.now() +) diff --git a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeService.scala b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeService.scala index b2baae92a..dfb7ff43d 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeService.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeService.scala @@ -59,7 +59,8 @@ object BatchChangeService { authProvider: AuthPrincipalProvider, notifiers: AllNotifiers, scheduledChangesEnabled: Boolean, - v6DiscoveryNibbleBoundaries: V6DiscoveryNibbleBoundaries): BatchChangeService = + v6DiscoveryNibbleBoundaries: V6DiscoveryNibbleBoundaries + ): BatchChangeService = new BatchChangeService( dataAccessor.zoneRepository, dataAccessor.recordSetRepository, @@ -88,8 +89,8 @@ class BatchChangeService( authProvider: AuthPrincipalProvider, notifiers: AllNotifiers, scheduledChangesEnabled: Boolean, - v6zoneNibbleBoundaries: V6DiscoveryNibbleBoundaries) - extends BatchChangeServiceAlgebra { + v6zoneNibbleBoundaries: V6DiscoveryNibbleBoundaries +) extends BatchChangeServiceAlgebra { import batchChangeValidations._ @@ -97,7 +98,8 @@ class BatchChangeService( def applyBatchChange( batchChangeInput: BatchChangeInput, auth: AuthPrincipal, - allowManualReview: Boolean): BatchResult[BatchChange] = + allowManualReview: Boolean + ): BatchResult[BatchChange] = for { validationOutput <- applyBatchChangeValidationFlow(batchChangeInput, auth, isApproved = false) changeForConversion <- buildResponse( @@ -110,13 +112,15 @@ class BatchChangeService( changeForConversion, validationOutput.existingZones, validationOutput.groupedChanges, - batchChangeInput.ownerGroupId) + batchChangeInput.ownerGroupId + ) } yield serviceCompleteBatch def applyBatchChangeValidationFlow( batchChangeInput: BatchChangeInput, auth: AuthPrincipal, - isApproved: Boolean): BatchResult[BatchValidationFlowOutput] = + isApproved: Boolean + ): BatchResult[BatchValidationFlowOutput] = for { existingGroup <- getOwnerGroup(batchChangeInput.ownerGroupId) _ <- validateBatchChangeInput(batchChangeInput, existingGroup, auth) @@ -130,13 +134,15 @@ class BatchChangeService( groupedChanges, auth, isApproved, - batchChangeInput.ownerGroupId) + batchChangeInput.ownerGroupId + ) errorGroupIds <- getGroupIdsFromUnauthorizedErrors(validatedSingleChanges) validatedSingleChangesWithGroups = errorGroupMapping(errorGroupIds, validatedSingleChanges) } yield BatchValidationFlowOutput(validatedSingleChangesWithGroups, zoneMap, groupedChanges) def getGroupIdsFromUnauthorizedErrors( - changes: ValidatedBatch[ChangeForValidation]): BatchResult[Set[Group]] = { + changes: ValidatedBatch[ChangeForValidation] + ): BatchResult[Set[Group]] = { val list = changes.getInvalid.collect { case d: UserIsNotAuthorizedError => d.ownerGroupId }.toSet @@ -145,7 +151,8 @@ class BatchChangeService( def errorGroupMapping( groups: Set[Group], - validations: ValidatedBatch[ChangeForValidation]): ValidatedBatch[ChangeForValidation] = + validations: ValidatedBatch[ChangeForValidation] + ): ValidatedBatch[ChangeForValidation] = validations.map { case Invalid(err) => err.map { @@ -156,7 +163,8 @@ class BatchChangeService( e.ownerGroupId, e.ownerType, group.map(_.email), - group.map(_.name)) + group.map(_.name) + ) logger.error(updatedError.message) updatedError case e => @@ -169,7 +177,8 @@ class BatchChangeService( def rejectBatchChange( batchChangeId: String, authPrincipal: AuthPrincipal, - rejectBatchChangeInput: RejectBatchChangeInput): BatchResult[BatchChange] = + rejectBatchChangeInput: RejectBatchChangeInput + ): BatchResult[BatchChange] = for { batchChange <- getExistingBatchChange(batchChangeId) bypassTestCheck <- getBypassTestCheckForReject(authPrincipal, batchChange) @@ -177,14 +186,16 @@ class BatchChangeService( rejectedBatchChange <- rejectBatchChange( batchChange, rejectBatchChangeInput.reviewComment, - authPrincipal.signedInUser.id) + authPrincipal.signedInUser.id + ) _ <- notifiers.notify(Notification(rejectedBatchChange)).toBatchResult } yield rejectedBatchChange def approveBatchChange( batchChangeId: String, authPrincipal: AuthPrincipal, - approveBatchChangeInput: ApproveBatchChangeInput): BatchResult[BatchChange] = + approveBatchChangeInput: ApproveBatchChangeInput + ): BatchResult[BatchChange] = for { batchChange <- getExistingBatchChange(batchChangeId) requesterAuth <- EitherT.fromOptionF( @@ -195,23 +206,27 @@ class BatchChangeService( asInput = BatchChangeInput(batchChange) reviewInfo = BatchChangeReviewInfo( authPrincipal.userId, - approveBatchChangeInput.reviewComment) + approveBatchChangeInput.reviewComment + ) validationOutput <- applyBatchChangeValidationFlow(asInput, requesterAuth, isApproved = true) changeForConversion = rebuildBatchChangeForUpdate( batchChange, validationOutput.validatedChanges, - reviewInfo) + reviewInfo + ) serviceCompleteBatch <- convertOrSave( changeForConversion, validationOutput.existingZones, validationOutput.groupedChanges, - batchChange.ownerGroupId) + batchChange.ownerGroupId + ) response <- buildResponseForApprover(serviceCompleteBatch).toBatchResult } yield response def cancelBatchChange( batchChangeId: String, - authPrincipal: AuthPrincipal): BatchResult[BatchChange] = + authPrincipal: AuthPrincipal + ): BatchResult[BatchChange] = for { batchChange <- getExistingBatchChange(batchChangeId) _ <- validateBatchChangeCancellation(batchChange, authPrincipal).toBatchResult @@ -279,7 +294,8 @@ class BatchChangeService( def getExistingRecordSets( changes: ValidatedBatch[ChangeForValidation], - zoneMap: ExistingZones): IO[ExistingRecordSets] = { + zoneMap: ExistingZones + ): IO[ExistingRecordSets] = { val uniqueGets = changes.getValid.map { change => change.inputChange.typ match { case PTR => s"${change.recordName}.${change.zone.name}" @@ -295,7 +311,8 @@ class BatchChangeService( def doTtlMapping( changes: ValidatedBatch[ChangeForValidation], - existingRecordSets: ExistingRecordSets): ValidatedBatch[ChangeForValidation] = + existingRecordSets: ExistingRecordSets + ): ValidatedBatch[ChangeForValidation] = changes.mapValid { case add: AddChangeForValidation => existingRecordSets @@ -326,7 +343,8 @@ class BatchChangeService( def zoneDiscovery( changes: ValidatedBatch[ChangeInput], - zoneMap: ExistingZones): ValidatedBatch[ChangeForValidation] = + zoneMap: ExistingZones + ): ValidatedBatch[ChangeForValidation] = changes.mapValid { change => change.typ match { case A | AAAA | CNAME | MX | TXT => forwardZoneDiscovery(change, zoneMap) @@ -340,7 +358,8 @@ class BatchChangeService( def forwardZoneDiscovery( change: ChangeInput, - zoneMap: ExistingZones): SingleValidation[ChangeForValidation] = { + zoneMap: ExistingZones + ): SingleValidation[ChangeForValidation] = { // getAllPossibleZones is ordered most to least specific, so 1st match is right val zone = getAllPossibleZones(change.inputName).map(zoneMap.getByName).collectFirst { @@ -358,7 +377,8 @@ class BatchChangeService( def ptrIpv4ZoneDiscovery( change: ChangeInput, - zoneMap: ExistingZones): SingleValidation[ChangeForValidation] = { + zoneMap: ExistingZones + ): SingleValidation[ChangeForValidation] = { val recordName = change.inputName.split('.').takeRight(1).mkString val validZones = zoneMap.getipv4PTRMatches(change.inputName) @@ -374,7 +394,8 @@ class BatchChangeService( def ptrIpv6ZoneDiscovery( change: ChangeInput, - zoneMap: ExistingZones): SingleValidation[ChangeForValidation] = { + zoneMap: ExistingZones + ): SingleValidation[ChangeForValidation] = { val zones = zoneMap.getipv6PTRMatches(change.inputName) if (zones.isEmpty) @@ -403,7 +424,8 @@ class BatchChangeService( batchChangeInput: BatchChangeInput, transformed: ValidatedBatch[ChangeForValidation], auth: AuthPrincipal, - allowManualReview: Boolean): Either[BatchChangeErrorResponse, BatchChange] = { + allowManualReview: Boolean + ): Either[BatchChangeErrorResponse, BatchChange] = { // Respond with a fatal error that kicks the change out to the user def errorResponse = @@ -480,7 +502,8 @@ class BatchChangeService( def rebuildBatchChangeForUpdate( existingBatchChange: BatchChange, transformed: ValidatedBatch[ChangeForValidation], - reviewInfo: BatchChangeReviewInfo): BatchChange = { + reviewInfo: BatchChangeReviewInfo + ): BatchChange = { val changes = transformed.zip(existingBatchChange.changes).map { case (validated, existing) => validated match { @@ -508,7 +531,8 @@ class BatchChangeService( batchChange: BatchChange, existingZones: ExistingZones, groupedChanges: ChangeForValidationMap, - ownerGroupId: Option[String]): BatchResult[BatchChange] = batchChange.approvalStatus match { + ownerGroupId: Option[String] + ): BatchResult[BatchChange] = batchChange.approvalStatus match { case AutoApproved => // send on to the converter, it will be saved there batchChangeConverter @@ -527,12 +551,14 @@ class BatchChangeService( // this should not be called with a rejected change (or if manual review is off)! logger.error( s"convertOrSave called with a rejected batch change; " + - s"batchChangeId=${batchChange.id}; manualReviewEnabled=$manualReviewEnabled") + s"batchChangeId=${batchChange.id}; manualReviewEnabled=$manualReviewEnabled" + ) UnknownConversionError("Cannot convert a rejected batch change").toLeftBatchResult } def buildResponseForApprover( - batchChange: BatchChange): Either[BatchChangeErrorResponse, BatchChange] = + batchChange: BatchChange + ): Either[BatchChangeErrorResponse, BatchChange] = batchChange.approvalStatus match { case ManuallyApproved => batchChange.asRight case _ => BatchChangeFailedApproval(batchChange).asLeft @@ -540,7 +566,8 @@ class BatchChangeService( def addOwnerGroupNamesToSummaries( summaries: List[BatchChangeSummary], - groups: Set[Group]): List[BatchChangeSummary] = + groups: Set[Group] + ): List[BatchChangeSummary] = summaries.map { summary => val groupName = summary.ownerGroupId.flatMap(groupId => groups.find(_.id == groupId).map(_.name)) @@ -549,7 +576,8 @@ class BatchChangeService( def addReviewerUserNamesToSummaries( summaries: List[BatchChangeSummary], - reviewers: ListUsersResults): List[BatchChangeSummary] = + reviewers: ListUsersResults + ): List[BatchChangeSummary] = summaries.map { summary => val userName = summary.reviewerId.flatMap(userId => reviewers.users.find(_.id == userId).map(_.userName)) @@ -561,8 +589,8 @@ class BatchChangeService( startFrom: Option[Int] = None, maxItems: Int = 100, ignoreAccess: Boolean = false, - approvalStatus: Option[BatchChangeApprovalStatus] = None) - : BatchResult[BatchChangeSummaryList] = { + approvalStatus: Option[BatchChangeApprovalStatus] = None + ): BatchResult[BatchChangeSummaryList] = { val userId = if (ignoreAccess && auth.isSystemAdmin) None else Some(auth.userId) for { listResults <- batchChangeRepo @@ -572,23 +600,27 @@ class BatchChangeService( rsOwnerGroups <- groupRepository.getGroups(rsOwnerGroupIds).toBatchResult summariesWithGroupNames = addOwnerGroupNamesToSummaries( listResults.batchChanges, - rsOwnerGroups) + rsOwnerGroups + ) reviewerIds = listResults.batchChanges.flatMap(_.reviewerId).toSet reviewerUserNames <- userRepository.getUsers(reviewerIds, None, Some(maxItems)).toBatchResult summariesWithReviewerUserNames = addReviewerUserNamesToSummaries( summariesWithGroupNames, - reviewerUserNames) + reviewerUserNames + ) listWithGroupNames = listResults.copy( batchChanges = summariesWithReviewerUserNames, ignoreAccess = ignoreAccess, - approvalStatus = approvalStatus) + approvalStatus = approvalStatus + ) } yield listWithGroupNames } def rejectBatchChange( batchChange: BatchChange, reviewComment: Option[String], - reviewerId: String): BatchResult[BatchChange] = { + reviewerId: String + ): BatchResult[BatchChange] = { val rejectedSingleChanges = batchChange.changes.map(_.reject) // Update rejection attributes and single changes for batch change @@ -618,7 +650,8 @@ class BatchChangeService( def getBypassTestCheckForReject( rejecterAuth: AuthPrincipal, - batchChange: BatchChange): BatchResult[Boolean] = + batchChange: BatchChange + ): BatchResult[Boolean] = if (!rejecterAuth.isTestUser) { // if the rejecting user isnt a test user, we dont need to get the batch creator's info, can just pass along // true to bypass the test check diff --git a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeServiceAlgebra.scala b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeServiceAlgebra.scala index 4f8af90e9..aa66318a3 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeServiceAlgebra.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeServiceAlgebra.scala @@ -26,7 +26,8 @@ trait BatchChangeServiceAlgebra { def applyBatchChange( batchChangeInput: BatchChangeInput, auth: AuthPrincipal, - allowManualReview: Boolean): BatchResult[BatchChange] + allowManualReview: Boolean + ): BatchResult[BatchChange] def getBatchChange(id: String, auth: AuthPrincipal): BatchResult[BatchChangeInfo] @@ -35,17 +36,20 @@ trait BatchChangeServiceAlgebra { startFrom: Option[Int], maxItems: Int, ignoreAccess: Boolean, - approvalStatus: Option[BatchChangeApprovalStatus]): BatchResult[BatchChangeSummaryList] + approvalStatus: Option[BatchChangeApprovalStatus] + ): BatchResult[BatchChangeSummaryList] def rejectBatchChange( batchChangeId: String, authPrincipal: AuthPrincipal, - rejectBatchChangeInput: RejectBatchChangeInput): BatchResult[BatchChange] + rejectBatchChangeInput: RejectBatchChangeInput + ): BatchResult[BatchChange] def approveBatchChange( batchChangeId: String, authPrincipal: AuthPrincipal, - approveBatchChangeInput: ApproveBatchChangeInput): BatchResult[BatchChange] + approveBatchChangeInput: ApproveBatchChangeInput + ): BatchResult[BatchChange] def cancelBatchChange(id: String, auth: AuthPrincipal): BatchResult[BatchChange] } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeValidations.scala b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeValidations.scala index 5a4f640c9..fdf2c4c88 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeValidations.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchChangeValidations.scala @@ -35,42 +35,49 @@ trait BatchChangeValidationsAlgebra { def validateBatchChangeInput( input: BatchChangeInput, existingGroup: Option[Group], - authPrincipal: AuthPrincipal): BatchResult[Unit] + authPrincipal: AuthPrincipal + ): BatchResult[Unit] def validateInputChanges( input: List[ChangeInput], - isApproved: Boolean): ValidatedBatch[ChangeInput] + isApproved: Boolean + ): ValidatedBatch[ChangeInput] def validateChangesWithContext( groupedChanges: ChangeForValidationMap, auth: AuthPrincipal, isApproved: Boolean, - batchOwnerGroupId: Option[String]): ValidatedBatch[ChangeForValidation] + batchOwnerGroupId: Option[String] + ): ValidatedBatch[ChangeForValidation] def canGetBatchChange( batchChange: BatchChange, - auth: AuthPrincipal): Either[BatchChangeErrorResponse, Unit] + auth: AuthPrincipal + ): Either[BatchChangeErrorResponse, Unit] def validateBatchChangeRejection( batchChange: BatchChange, authPrincipal: AuthPrincipal, - bypassTestValidation: Boolean): Either[BatchChangeErrorResponse, Unit] + bypassTestValidation: Boolean + ): Either[BatchChangeErrorResponse, Unit] def validateBatchChangeApproval( batchChange: BatchChange, authPrincipal: AuthPrincipal, - isTestChange: Boolean): Either[BatchChangeErrorResponse, Unit] + isTestChange: Boolean + ): Either[BatchChangeErrorResponse, Unit] def validateBatchChangeCancellation( batchChange: BatchChange, - authPrincipal: AuthPrincipal): Either[BatchChangeErrorResponse, Unit] + authPrincipal: AuthPrincipal + ): Either[BatchChangeErrorResponse, Unit] } class BatchChangeValidations( changeLimit: Int, accessValidation: AccessValidationsAlgebra, - scheduledChangesEnabled: Boolean = false) - extends BatchChangeValidationsAlgebra { + scheduledChangesEnabled: Boolean = false +) extends BatchChangeValidationsAlgebra { import RecordType._ import accessValidation._ @@ -78,11 +85,13 @@ class BatchChangeValidations( def validateBatchChangeInput( input: BatchChangeInput, existingGroup: Option[Group], - authPrincipal: AuthPrincipal): BatchResult[Unit] = { + authPrincipal: AuthPrincipal + ): BatchResult[Unit] = { val validations = validateBatchChangeInputSize(input) |+| validateOwnerGroupId( input.ownerGroupId, existingGroup, - authPrincipal) + authPrincipal + ) for { _ <- validations @@ -105,7 +114,8 @@ class BatchChangeValidations( def validateOwnerGroupId( ownerGroupId: Option[String], existingGroup: Option[Group], - authPrincipal: AuthPrincipal): SingleValidation[Unit] = + authPrincipal: AuthPrincipal + ): SingleValidation[Unit] = (ownerGroupId, existingGroup) match { case (None, _) => ().validNel case (Some(groupId), None) => GroupDoesNotExist(groupId).invalidNel @@ -117,26 +127,33 @@ class BatchChangeValidations( def validateBatchChangeRejection( batchChange: BatchChange, authPrincipal: AuthPrincipal, - bypassTestValidation: Boolean): Either[BatchChangeErrorResponse, Unit] = + bypassTestValidation: Boolean + ): Either[BatchChangeErrorResponse, Unit] = validateAuthorizedReviewer(authPrincipal, batchChange, bypassTestValidation) |+| validateBatchChangePendingReview( - batchChange) + batchChange + ) def validateBatchChangeApproval( batchChange: BatchChange, authPrincipal: AuthPrincipal, - isTestChange: Boolean): Either[BatchChangeErrorResponse, Unit] = + isTestChange: Boolean + ): Either[BatchChangeErrorResponse, Unit] = validateAuthorizedReviewer(authPrincipal, batchChange, isTestChange) |+| validateBatchChangePendingReview( - batchChange) |+| validateScheduledApproval(batchChange) + batchChange + ) |+| validateScheduledApproval(batchChange) def validateBatchChangeCancellation( batchChange: BatchChange, - authPrincipal: AuthPrincipal): Either[BatchChangeErrorResponse, Unit] = + authPrincipal: AuthPrincipal + ): Either[BatchChangeErrorResponse, Unit] = validateBatchChangePendingReview(batchChange) |+| validateCreatorCancellation( batchChange, - authPrincipal) + authPrincipal + ) def validateBatchChangePendingReview( - batchChange: BatchChange): Either[BatchChangeErrorResponse, Unit] = + batchChange: BatchChange + ): Either[BatchChangeErrorResponse, Unit] = batchChange.approvalStatus match { case BatchChangeApprovalStatus.PendingReview => ().asRight case _ => BatchChangeNotPendingReview(batchChange.id).asLeft @@ -145,7 +162,8 @@ class BatchChangeValidations( def validateAuthorizedReviewer( auth: AuthPrincipal, batchChange: BatchChange, - bypassTestValidation: Boolean): Either[BatchChangeErrorResponse, Unit] = + bypassTestValidation: Boolean + ): Either[BatchChangeErrorResponse, Unit] = if (auth.isSystemAdmin && (bypassTestValidation || !auth.isTestUser)) { // bypassTestValidation = true for a test change ().asRight @@ -161,7 +179,8 @@ class BatchChangeValidations( def validateCreatorCancellation( batchChange: BatchChange, - auth: AuthPrincipal): Either[BatchChangeErrorResponse, Unit] = + auth: AuthPrincipal + ): Either[BatchChangeErrorResponse, Unit] = if (batchChange.userId == auth.userId) { ().asRight } else { @@ -171,7 +190,8 @@ class BatchChangeValidations( def validateInputChanges( input: List[ChangeInput], - isApproved: Boolean): ValidatedBatch[ChangeInput] = + isApproved: Boolean + ): ValidatedBatch[ChangeInput] = input.map { case a: AddChangeInput => validateAddChangeInput(a, isApproved).map(_ => a) case d: DeleteRRSetChangeInput => validateDeleteRRSetChangeInput(d, isApproved).map(_ => d) @@ -179,7 +199,8 @@ class BatchChangeValidations( def validateAddChangeInput( addChangeInput: AddChangeInput, - isApproved: Boolean): SingleValidation[Unit] = { + isApproved: Boolean + ): SingleValidation[Unit] = { val validTTL = addChangeInput.ttl.map(validateTTL(_).asUnit).getOrElse(().valid) val validRecord = validateRecordData(addChangeInput.record) val validInput = validateInputName(addChangeInput, isApproved) @@ -189,7 +210,8 @@ class BatchChangeValidations( def validateDeleteRRSetChangeInput( deleteRRSetChangeInput: DeleteRRSetChangeInput, - isApproved: Boolean): SingleValidation[Unit] = { + isApproved: Boolean + ): SingleValidation[Unit] = { val validRecord = deleteRRSetChangeInput.record match { case Some(recordData) => validateRecordData(recordData) case None => ().validNel @@ -244,7 +266,8 @@ class BatchChangeValidations( groupedChanges: ChangeForValidationMap, auth: AuthPrincipal, isApproved: Boolean, - batchOwnerGroupId: Option[String]): ValidatedBatch[ChangeForValidation] = + batchOwnerGroupId: Option[String] + ): ValidatedBatch[ChangeForValidation] = // Updates are a combination of an add and delete for a record with the same name and type in a zone. groupedChanges.changes.mapValid { case add: AddChangeForValidation @@ -274,13 +297,15 @@ class BatchChangeValidations( def ensureRecordExists( change: ChangeForValidation, - groupedChanges: ChangeForValidationMap): SingleValidation[Unit] = + groupedChanges: ChangeForValidationMap + ): SingleValidation[Unit] = change match { // For DeleteRecord inputs, need to verify that the record data actually exists case DeleteRRSetChangeForValidation( _, _, - DeleteRRSetChangeInput(inputName, _, Some(recordData))) + DeleteRRSetChangeInput(inputName, _, Some(recordData)) + ) if !groupedChanges .getExistingRecordSet(change.recordKey) .exists(_.records.contains(recordData)) => @@ -293,7 +318,8 @@ class BatchChangeValidations( change: ChangeForValidation, groupedChanges: ChangeForValidationMap, auth: AuthPrincipal, - isApproved: Boolean): SingleValidation[ChangeForValidation] = { + isApproved: Boolean + ): SingleValidation[ChangeForValidation] = { val validations = groupedChanges.getExistingRecordSet(change.recordKey) match { @@ -311,7 +337,8 @@ class BatchChangeValidations( groupedChanges: ChangeForValidationMap, auth: AuthPrincipal, isApproved: Boolean, - batchOwnerGroupId: Option[String]): SingleValidation[ChangeForValidation] = { + batchOwnerGroupId: Option[String] + ): SingleValidation[ChangeForValidation] = { // Updates require checking against other batch changes since multiple adds // could potentially be grouped with a single delete val typedValidations = change.inputChange.typ match { @@ -327,7 +354,8 @@ class BatchChangeValidations( change, groupedChanges.existingRecordSets .get(change.zone.id, change.recordName, change.inputChange.typ), - batchOwnerGroupId) |+| + batchOwnerGroupId + ) |+| zoneDoesNotRequireManualReview(change, isApproved) case None => RecordDoesNotExist(change.inputChange.inputName).invalidNel @@ -343,7 +371,8 @@ class BatchChangeValidations( change: ChangeForValidation, groupedChanges: ChangeForValidationMap, auth: AuthPrincipal, - isApproved: Boolean): SingleValidation[ChangeForValidation] = { + isApproved: Boolean + ): SingleValidation[ChangeForValidation] = { val validations = groupedChanges.getExistingRecordSet(change.recordKey) match { case Some(rs) => @@ -363,7 +392,8 @@ class BatchChangeValidations( groupedChanges: ChangeForValidationMap, auth: AuthPrincipal, isApproved: Boolean, - ownerGroupId: Option[String]): SingleValidation[ChangeForValidation] = { + ownerGroupId: Option[String] + ): SingleValidation[ChangeForValidation] = { val typedValidations = change.inputChange.typ match { case A | AAAA | MX => newRecordSetIsNotDotted(change) @@ -385,7 +415,8 @@ class BatchChangeValidations( change.recordName, change.inputChange.inputName, change.inputChange.typ, - groupedChanges) |+| + groupedChanges + ) |+| ownerGroupProvidedIfNeeded(change, None, ownerGroupId) |+| zoneDoesNotRequireManualReview(change, isApproved) @@ -394,7 +425,8 @@ class BatchChangeValidations( def cnameHasUniqueNameInBatch( cnameChange: AddChangeForValidation, - groupedChanges: ChangeForValidationMap): SingleValidation[Unit] = { + groupedChanges: ChangeForValidationMap + ): SingleValidation[Unit] = { val duplicateNameChangeInBatch = RecordType.values.toList.exists { recordType => val recordKey = RecordKey(cnameChange.zone.id, cnameChange.recordName, recordType) @@ -410,7 +442,8 @@ class BatchChangeValidations( def recordIsUniqueInBatch( change: AddChangeForValidation, - groupedChanges: ChangeForValidationMap): SingleValidation[Unit] = { + groupedChanges: ChangeForValidationMap + ): SingleValidation[Unit] = { // Ignore true duplicates, but identify multi-records val proposedAdds = groupedChanges.getProposedAdds(change.recordKey) @@ -424,7 +457,8 @@ class BatchChangeValidations( recordName: String, inputName: String, typ: RecordType, - groupedChanges: ChangeForValidationMap): SingleValidation[Unit] = + groupedChanges: ChangeForValidationMap + ): SingleValidation[Unit] = groupedChanges.getExistingRecordSet(RecordKey(zoneId, recordName, typ)) match { case Some(_) => RecordAlreadyExists(inputName).invalidNel case None => ().validNel @@ -432,7 +466,8 @@ class BatchChangeValidations( def noIncompatibleRecordExists( change: AddChangeForValidation, - groupedChanges: ChangeForValidationMap): SingleValidation[Unit] = { + groupedChanges: ChangeForValidationMap + ): SingleValidation[Unit] = { // find conflicting types in existing records val conflictingExistingTypes = change.inputChange.typ match { case CNAME => @@ -462,13 +497,15 @@ class BatchChangeValidations( def userCanAddRecordSet( input: AddChangeForValidation, - authPrincipal: AuthPrincipal): SingleValidation[Unit] = { + authPrincipal: AuthPrincipal + ): SingleValidation[Unit] = { val result = canAddRecordSet( authPrincipal, input.recordName, input.inputChange.typ, input.zone, - List(input.inputChange.record)) + List(input.inputChange.record) + ) result .leftMap( _ => @@ -476,7 +513,9 @@ class BatchChangeValidations( authPrincipal.signedInUser.userName, input.zone.adminGroupId, OwnerType.Zone, - Some(input.zone.email))) + Some(input.zone.email) + ) + ) .toValidatedNel } @@ -484,7 +523,8 @@ class BatchChangeValidations( input: ChangeForValidation, authPrincipal: AuthPrincipal, ownerGroupId: Option[String], - addRecords: List[RecordData]): SingleValidation[Unit] = { + addRecords: List[RecordData] + ): SingleValidation[Unit] = { val result = canUpdateRecordSet( authPrincipal, @@ -495,17 +535,20 @@ class BatchChangeValidations( addRecords ) result - .leftMap(_ => - ownerGroupId match { - case Some(id) if input.zone.shared => - UserIsNotAuthorizedError(authPrincipal.signedInUser.userName, id, OwnerType.Record) - case _ => - UserIsNotAuthorizedError( - authPrincipal.signedInUser.userName, - input.zone.adminGroupId, - OwnerType.Zone, - Some(input.zone.email)) - }) + .leftMap( + _ => + ownerGroupId match { + case Some(id) if input.zone.shared => + UserIsNotAuthorizedError(authPrincipal.signedInUser.userName, id, OwnerType.Record) + case _ => + UserIsNotAuthorizedError( + authPrincipal.signedInUser.userName, + input.zone.adminGroupId, + OwnerType.Zone, + Some(input.zone.email) + ) + } + ) .toValidatedNel } @@ -513,7 +556,8 @@ class BatchChangeValidations( input: ChangeForValidation, authPrincipal: AuthPrincipal, ownerGroupId: Option[String], - existingRecords: List[RecordData]): SingleValidation[Unit] = { + existingRecords: List[RecordData] + ): SingleValidation[Unit] = { val result = canDeleteRecordSet( authPrincipal, @@ -524,23 +568,27 @@ class BatchChangeValidations( existingRecords ) result - .leftMap(_ => - ownerGroupId match { - case Some(id) if input.zone.shared => - UserIsNotAuthorizedError(authPrincipal.signedInUser.userName, id, OwnerType.Record) - case _ => - UserIsNotAuthorizedError( - authPrincipal.signedInUser.userName, - input.zone.adminGroupId, - OwnerType.Zone, - Some(input.zone.email)) - }) + .leftMap( + _ => + ownerGroupId match { + case Some(id) if input.zone.shared => + UserIsNotAuthorizedError(authPrincipal.signedInUser.userName, id, OwnerType.Record) + case _ => + UserIsNotAuthorizedError( + authPrincipal.signedInUser.userName, + input.zone.adminGroupId, + OwnerType.Zone, + Some(input.zone.email) + ) + } + ) .toValidatedNel } def canGetBatchChange( batchChange: BatchChange, - auth: AuthPrincipal): Either[BatchChangeErrorResponse, Unit] = + auth: AuthPrincipal + ): Either[BatchChangeErrorResponse, Unit] = if (auth.isSystemAdmin || auth.userId == batchChange.userId) { ().asRight } else { @@ -554,7 +602,8 @@ class BatchChangeValidations( case _ => ZoneRecordValidations.isNotHighValueFqdn( VinylDNSConfig.highValueRegexList, - change.inputName) + change.inputName + ) } def doesNotRequireManualReview(change: ChangeInput, isApproved: Boolean): SingleValidation[Unit] = @@ -566,18 +615,21 @@ class BatchChangeValidations( case RecordType.PTR => ZoneRecordValidations.ipDoesNotRequireManualReview( VinylDNSConfig.ipListRequiringManualReview, - change.inputName) + change.inputName + ) case _ => ZoneRecordValidations.domainDoesNotRequireManualReview( VinylDNSConfig.domainListRequiringManualReview, - change.inputName) + change.inputName + ) } } def ownerGroupProvidedIfNeeded( change: AddChangeForValidation, existingRecord: Option[RecordSet], - ownerGroupId: Option[String]): SingleValidation[Unit] = + ownerGroupId: Option[String] + ): SingleValidation[Unit] = if (!change.zone.shared || ownerGroupId.isDefined) { ().validNel } else { @@ -591,7 +643,8 @@ class BatchChangeValidations( def validateScheduledChange( input: BatchChangeInput, - scheduledChangesEnabled: Boolean): Either[BatchChangeErrorResponse, Unit] = + scheduledChangesEnabled: Boolean + ): Either[BatchChangeErrorResponse, Unit] = (scheduledChangesEnabled, input.scheduledTime) match { case (_, None) => Right(()) case (true, Some(scheduledTime)) if scheduledTime.isAfterNow => Right(()) @@ -601,7 +654,8 @@ class BatchChangeValidations( def zoneDoesNotRequireManualReview( change: ChangeForValidation, - isApproved: Boolean): SingleValidation[Unit] = + isApproved: Boolean + ): SingleValidation[Unit] = if (isApproved) { ().validNel } else { diff --git a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchTransformations.scala b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchTransformations.scala index 20dbf3ff9..f531e6cdb 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchTransformations.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/batch/BatchTransformations.scala @@ -94,8 +94,8 @@ object BatchTransformations { zone: Zone, recordName: String, inputChange: AddChangeInput, - existingRecordTtl: Option[Long] = None) - extends ChangeForValidation { + existingRecordTtl: Option[Long] = None + ) extends ChangeForValidation { def asStoredChange(changeId: Option[String] = None): SingleChange = { val ttl = inputChange.ttl.orElse(existingRecordTtl).getOrElse(VinylDNSConfig.defaultTtl) @@ -123,8 +123,8 @@ object BatchTransformations { final case class DeleteRRSetChangeForValidation( zone: Zone, recordName: String, - inputChange: DeleteRRSetChangeInput) - extends ChangeForValidation { + inputChange: DeleteRRSetChangeInput + ) extends ChangeForValidation { def asStoredChange(changeId: Option[String] = None): SingleChange = SingleDeleteRRSetChange( Some(zone.id), @@ -146,11 +146,13 @@ object BatchTransformations { final case class BatchConversionOutput( batchChange: BatchChange, - recordSetChanges: List[RecordSetChange]) + recordSetChanges: List[RecordSetChange] + ) final case class ChangeForValidationMap( changes: ValidatedBatch[ChangeForValidation], - existingRecordSets: ExistingRecordSets) { + existingRecordSets: ExistingRecordSets + ) { import BatchChangeInterfaces._ val innerMap: Map[RecordKey, ValidationChanges] = { @@ -182,7 +184,8 @@ object BatchTransformations { object ValidationChanges { def apply( changes: List[ChangeForValidation], - existingRecordSet: Option[RecordSet]): ValidationChanges = { + existingRecordSet: Option[RecordSet] + ): ValidationChanges = { // Collect add DNS entries val addChangeRecordDataSet = changes.collect { case add: AddChangeForValidation => add.inputChange.record @@ -197,7 +200,8 @@ object BatchTransformations { case DeleteRRSetChangeForValidation( _, _, - DeleteRRSetChangeInput(_, _, Some(recordData))) => + DeleteRRSetChangeInput(_, _, Some(recordData)) + ) => Set(recordData) case _: DeleteRRSetChangeForValidation => existingRecords } @@ -228,7 +232,8 @@ object BatchTransformations { final case class ValidationChanges( proposedAdds: Set[RecordData], proposedRecordData: Set[RecordData], - logicalChangeType: LogicalChangeType) + logicalChangeType: LogicalChangeType + ) final case class BatchValidationFlowOutput( validatedChanges: ValidatedBatch[ChangeForValidation], diff --git a/modules/api/src/main/scala/vinyldns/api/domain/dns/DnsConnection.scala b/modules/api/src/main/scala/vinyldns/api/domain/dns/DnsConnection.scala index 73b04966f..3a25cf8f3 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/dns/DnsConnection.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/dns/DnsConnection.scala @@ -107,7 +107,8 @@ class DnsConnection(val resolver: DNS.SimpleResolver) extends DnsConversions { private[dns] def toQuery( name: String, zoneName: String, - typ: RecordType): Either[Throwable, DnsQuery] = { + typ: RecordType + ): Either[Throwable, DnsQuery] = { val dnsName = recordDnsName(name, zoneName) logger.info(s"Querying for dns dnsRecordName='${dnsName.toString}'; recordType='$typ'") val lookup = new DNS.Lookup(dnsName, toDnsRecordType(typ)) @@ -160,7 +161,8 @@ class DnsConnection(val resolver: DNS.SimpleResolver) extends DnsConversions { } yield resp logger.info( - s"DnsConnection.send - Sending DNS Message ${obscuredDnsMessage(msg).toString}\n...received response $result") + s"DnsConnection.send - Sending DNS Message ${obscuredDnsMessage(msg).toString}\n...received response $result" + ) result } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/dns/DnsConversions.scala b/modules/api/src/main/scala/vinyldns/api/domain/dns/DnsConversions.scala index 07d398412..cd64607a1 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/dns/DnsConversions.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/dns/DnsConversions.scala @@ -177,7 +177,8 @@ trait DnsConversions { def toFlattenedRecordSets( records: List[DNS.Record], zoneName: DNS.Name, - zoneId: String = "unknown"): List[RecordSet] = { + zoneId: String = "unknown" + ): List[RecordSet] = { /* Combines record sets into a list of one or Nil in case there are no record sets in the list provided */ def combineRecordSets(lst: List[RecordSet]): RecordSet = @@ -194,7 +195,8 @@ trait DnsConversions { // Do a "relativize" using the zoneName, this removes the zone name from the record itself // For example "test-01.vinyldns." becomes "test-01"...this is necessary as we want to run comparisons upstream def fromDnsRecord[A <: DNS.Record](r: A, zoneName: DNS.Name, zoneId: String)( - f: A => List[RecordData]): RecordSet = + f: A => List[RecordData] + ): RecordSet = record.RecordSet( zoneId = zoneId, name = relativize(r.getName, zoneName), @@ -240,7 +242,8 @@ trait DnsConversions { DnsSecAlgorithm(data.getAlgorithm), DigestType(data.getDigestID), ByteVector(data.getDigest) - )) + ) + ) } def fromMXRecord(r: DNS.MXRecord, zoneName: DNS.Name, zoneId: String): RecordSet = @@ -268,7 +271,9 @@ trait DnsConversions { data.getRefresh, data.getRetry, data.getExpire, - data.getMinimum)) + data.getMinimum + ) + ) } def fromSPFRecord(r: DNS.SPFRecord, zoneName: DNS.Name, zoneId: String): RecordSet = @@ -290,7 +295,9 @@ trait DnsConversions { data.getFlags, data.getService, data.getRegexp, - data.getReplacement.toString)) + data.getReplacement.toString + ) + ) } def fromSSHFPRecord(r: DNS.SSHFPRecord, zoneName: DNS.Name, zoneId: String): RecordSet = @@ -326,7 +333,8 @@ trait DnsConversions { keyTag, algorithm.value, digestType.value, - digest.toArray) + digest.toArray + ) case NSData(nsdname) => new DNS.NSRecord(recordName, DNS.DClass.IN, ttl, DNS.Name.fromString(nsdname)) @@ -337,7 +345,8 @@ trait DnsConversions { DNS.DClass.IN, ttl, preference, - DNS.Name.fromString(exchange)) + DNS.Name.fromString(exchange) + ) case PTRData(ptrdname) => new DNS.PTRRecord(recordName, DNS.DClass.IN, ttl, DNS.Name.fromString(ptrdname)) @@ -353,7 +362,8 @@ trait DnsConversions { refresh, retry, expire, - minimum) + minimum + ) case SRVData(priority, weight, port, target) => new DNS.SRVRecord( @@ -363,7 +373,8 @@ trait DnsConversions { priority, weight, port, - DNS.Name.fromString(target)) + DNS.Name.fromString(target) + ) case NAPTRData(order, preference, flags, service, regexp, replacement) => new DNS.NAPTRRecord( @@ -375,7 +386,8 @@ trait DnsConversions { flags, service, regexp, - DNS.Name.fromString(replacement)) + DNS.Name.fromString(replacement) + ) case SSHFPData(algorithm, typ, fingerprint) => new DNS.SSHFPRecord(recordName, DNS.DClass.IN, ttl, algorithm, typ, fingerprint.getBytes) @@ -422,7 +434,8 @@ trait DnsConversions { def toUpdateRecordMessage( r: DNS.RRset, old: DNS.RRset, - zoneName: String): Either[Throwable, DNS.Update] = { + zoneName: String + ): Either[Throwable, DNS.Update] = { val update = new DNS.Update(zoneDnsName(zoneName)) if (!r.getName.equals(old.getName) || r.getTTL != old.getTTL) { // Name or TTL has changed diff --git a/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipProtocol.scala b/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipProtocol.scala index 6e69dabec..daf54b8d1 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipProtocol.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipProtocol.scala @@ -119,13 +119,15 @@ final case class ListMembersResponse( members: Seq[MemberInfo], startFrom: Option[String] = None, nextId: Option[String] = None, - maxItems: Int) + maxItems: Int +) final case class ListUsersResponse( members: Seq[UserInfo], startFrom: Option[String] = None, nextId: Option[String] = None, - maxItems: Int) + maxItems: Int +) final case class ListAdminsResponse(admins: Seq[UserInfo]) @@ -133,7 +135,8 @@ final case class ListGroupChangesResponse( changes: Seq[GroupChangeInfo], startFrom: Option[String] = None, nextId: Option[String] = None, - maxItems: Int) + maxItems: Int +) final case class ListMyGroupsResponse( groups: Seq[GroupInfo], @@ -141,7 +144,8 @@ final case class ListMyGroupsResponse( startFrom: Option[String] = None, nextId: Option[String] = None, maxItems: Int, - ignoreAccess: Boolean) + ignoreAccess: Boolean +) final case class GroupNotFoundError(msg: String) extends Throwable(msg) diff --git a/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipService.scala b/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipService.scala index f9e3d619e..5c3bd2705 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipService.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipService.scala @@ -43,8 +43,8 @@ class MembershipService( membershipRepo: MembershipRepository, zoneRepo: ZoneRepository, groupChangeRepo: GroupChangeRepository, - recordSetRepo: RecordSetRepository) - extends MembershipServiceAlgebra { + recordSetRepo: RecordSetRepository +) extends MembershipServiceAlgebra { import MembershipValidations._ @@ -67,7 +67,8 @@ class MembershipService( description: Option[String], memberIds: Set[String], adminUserIds: Set[String], - authPrincipal: AuthPrincipal): Result[Group] = + authPrincipal: AuthPrincipal + ): Result[Group] = for { existingGroup <- getExistingGroup(groupId) newGroup = existingGroup.withUpdates(name, email, description, memberIds, adminUserIds) @@ -112,17 +113,18 @@ class MembershipService( groupId: String, startFrom: Option[String], maxItems: Int, - authPrincipal: AuthPrincipal): Result[ListMembersResponse] = + authPrincipal: AuthPrincipal + ): Result[ListMembersResponse] = for { group <- getExistingGroup(groupId) _ <- canSeeGroup(groupId, authPrincipal).toResult result <- getUsers(group.memberIds, startFrom, Some(maxItems)) - } yield - ListMembersResponse( - result.users.map(MemberInfo(_, group)), - startFrom, - result.lastEvaluatedId, - maxItems) + } yield ListMembersResponse( + result.users.map(MemberInfo(_, group)), + startFrom, + result.lastEvaluatedId, + maxItems + ) def listAdmins(groupId: String, authPrincipal: AuthPrincipal): Result[ListAdminsResponse] = for { @@ -136,7 +138,8 @@ class MembershipService( startFrom: Option[String], maxItems: Int, authPrincipal: AuthPrincipal, - ignoreAccess: Boolean): Result[ListMyGroupsResponse] = { + ignoreAccess: Boolean + ): Result[ListMyGroupsResponse] = { val groupsCall = if (authPrincipal.isSystemAdmin || ignoreAccess) { groupRepo.getAllGroups() @@ -154,7 +157,8 @@ class MembershipService( groupNameFilter: Option[String], startFrom: Option[String], maxItems: Int, - ignoreAccess: Boolean): ListMyGroupsResponse = { + ignoreAccess: Boolean + ): ListMyGroupsResponse = { val allMyGroups = allGroups .filter(_.status == GroupStatus.Active) .sortBy(_.id) @@ -174,23 +178,25 @@ class MembershipService( groupId: String, startFrom: Option[String], maxItems: Int, - authPrincipal: AuthPrincipal): Result[ListGroupChangesResponse] = + authPrincipal: AuthPrincipal + ): Result[ListGroupChangesResponse] = for { _ <- canSeeGroup(groupId, authPrincipal).toResult result <- groupChangeRepo .getGroupChanges(groupId, startFrom, maxItems) .toResult[ListGroupChangesResults] - } yield - ListGroupChangesResponse( - result.changes.map(GroupChangeInfo.apply), - startFrom, - result.lastEvaluatedTimeStamp, - maxItems) + } yield ListGroupChangesResponse( + result.changes.map(GroupChangeInfo.apply), + startFrom, + result.lastEvaluatedTimeStamp, + maxItems + ) def getUsers( userIds: Set[String], startFrom: Option[String] = None, - pageSize: Option[Int] = None): Result[ListUsersResults] = + pageSize: Option[Int] = None + ): Result[ListUsersResults] = userRepo .getUsers(userIds, startFrom, pageSize) .toResult[ListUsersResults] @@ -245,7 +251,8 @@ class MembershipService( .getZonesByAdminGroupId(group.id) .map { zones => ensuring(InvalidGroupRequestError(s"${group.name} is the admin of a zone. Cannot delete."))( - zones.isEmpty) + zones.isEmpty + ) } .toResult @@ -255,8 +262,9 @@ class MembershipService( .map { rsId => ensuring( InvalidGroupRequestError( - s"${group.name} is the owner for a record set including $rsId. Cannot delete."))( - rsId.isEmpty) + s"${group.name} is the owner for a record set including $rsId. Cannot delete." + ) + )(rsId.isEmpty) } .toResult @@ -264,15 +272,19 @@ class MembershipService( zoneRepo .getFirstOwnedZoneAclGroupId(group.id) .map { zId => - ensuring(InvalidGroupRequestError( - s"${group.name} has an ACL rule for a zone including $zId. Cannot delete."))(zId.isEmpty) + ensuring( + InvalidGroupRequestError( + s"${group.name} has an ACL rule for a zone including $zId. Cannot delete." + ) + )(zId.isEmpty) } .toResult def updateUserLockStatus( userId: String, lockStatus: LockStatus, - authPrincipal: AuthPrincipal): Result[User] = + authPrincipal: AuthPrincipal + ): Result[User] = for { _ <- isSuperAdmin(authPrincipal).toResult existingUser <- getExistingUser(userId) diff --git a/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipServiceAlgebra.scala b/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipServiceAlgebra.scala index b5c7245d7..4879c520b 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipServiceAlgebra.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/membership/MembershipServiceAlgebra.scala @@ -32,7 +32,8 @@ trait MembershipServiceAlgebra { description: Option[String], memberIds: Set[String], adminUserIds: Set[String], - authPrincipal: AuthPrincipal): Result[Group] + authPrincipal: AuthPrincipal + ): Result[Group] def deleteGroup(groupId: String, authPrincipal: AuthPrincipal): Result[Group] @@ -43,13 +44,15 @@ trait MembershipServiceAlgebra { startFrom: Option[String], maxItems: Int, authPrincipal: AuthPrincipal, - ignoreAccess: Boolean): Result[ListMyGroupsResponse] + ignoreAccess: Boolean + ): Result[ListMyGroupsResponse] def listMembers( groupId: String, startFrom: Option[String], maxItems: Int, - authPrincipal: AuthPrincipal): Result[ListMembersResponse] + authPrincipal: AuthPrincipal + ): Result[ListMembersResponse] def listAdmins(groupId: String, authPrincipal: AuthPrincipal): Result[ListAdminsResponse] @@ -57,10 +60,12 @@ trait MembershipServiceAlgebra { groupId: String, startFrom: Option[String], maxItems: Int, - authPrincipal: AuthPrincipal): Result[ListGroupChangesResponse] + authPrincipal: AuthPrincipal + ): Result[ListGroupChangesResponse] def updateUserLockStatus( userId: String, lockStatus: LockStatus, - authPrincipal: AuthPrincipal): Result[User] + authPrincipal: AuthPrincipal + ): Result[User] } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/record/ListRecordSetChangesResponse.scala b/modules/api/src/main/scala/vinyldns/api/domain/record/ListRecordSetChangesResponse.scala index 50fc10675..0dcda1985 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/record/ListRecordSetChangesResponse.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/record/ListRecordSetChangesResponse.scala @@ -24,17 +24,20 @@ case class ListRecordSetChangesResponse( recordSetChanges: List[RecordSetChangeInfo] = Nil, nextId: Option[String], startFrom: Option[String], - maxItems: Int) + maxItems: Int +) object ListRecordSetChangesResponse { def apply( zoneId: String, listResults: ListRecordSetChangesResults, - info: List[RecordSetChangeInfo]): ListRecordSetChangesResponse = + info: List[RecordSetChangeInfo] + ): ListRecordSetChangesResponse = ListRecordSetChangesResponse( zoneId, info, listResults.nextId, listResults.startFrom, - listResults.maxItems) + listResults.maxItems + ) } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetChangeGenerator.scala b/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetChangeGenerator.scala index 9ad1d76cf..65df2a81a 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetChangeGenerator.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetChangeGenerator.scala @@ -30,7 +30,8 @@ object RecordSetChangeGenerator extends DnsConversions { recordSet: RecordSet, zone: Zone, userId: String, - singleBatchChangeIds: List[String]): RecordSetChange = + singleBatchChangeIds: List[String] + ): RecordSetChange = RecordSetChange( zone = zone, recordSet = recordSet.copy( @@ -48,7 +49,8 @@ object RecordSetChangeGenerator extends DnsConversions { def forAdd( recordSet: RecordSet, zone: Zone, - auth: Option[AuthPrincipal] = None): RecordSetChange = + auth: Option[AuthPrincipal] = None + ): RecordSetChange = forAdd(recordSet, zone, auth.map(_.userId).getOrElse("system"), List()) def forAdd(recordSet: RecordSet, zone: Zone, auth: AuthPrincipal): RecordSetChange = @@ -59,14 +61,16 @@ object RecordSetChangeGenerator extends DnsConversions { newRecordSet: RecordSet, zone: Zone, userId: String, - singleBatchChangeIds: List[String]): RecordSetChange = + singleBatchChangeIds: List[String] + ): RecordSetChange = RecordSetChange( zone = zone, recordSet = newRecordSet.copy( id = replacing.id, name = relativize(newRecordSet.name, zone.name), status = RecordSetStatus.PendingUpdate, - updated = Some(DateTime.now)), + updated = Some(DateTime.now) + ), userId = userId, changeType = RecordSetChangeType.Update, status = RecordSetChangeStatus.Pending, @@ -78,21 +82,24 @@ object RecordSetChangeGenerator extends DnsConversions { replacing: RecordSet, newRecordSet: RecordSet, zone: Zone, - auth: Option[AuthPrincipal] = None): RecordSetChange = + auth: Option[AuthPrincipal] = None + ): RecordSetChange = forUpdate(replacing, newRecordSet, zone, auth.map(_.userId).getOrElse("system"), List()) def forUpdate( replacing: RecordSet, newRecordSet: RecordSet, zone: Zone, - auth: AuthPrincipal): RecordSetChange = + auth: AuthPrincipal + ): RecordSetChange = forUpdate(replacing, newRecordSet, zone, auth.userId, List()) def forDelete( recordSet: RecordSet, zone: Zone, userId: String, - singleBatchChangeIds: List[String]): RecordSetChange = + singleBatchChangeIds: List[String] + ): RecordSetChange = RecordSetChange( zone = zone, recordSet = recordSet.copy( @@ -109,7 +116,8 @@ object RecordSetChangeGenerator extends DnsConversions { def forDelete( recordSet: RecordSet, zone: Zone, - auth: Option[AuthPrincipal] = None): RecordSetChange = + auth: Option[AuthPrincipal] = None + ): RecordSetChange = forDelete(recordSet, zone, auth.map(_.userId).getOrElse("system"), List()) def forDelete(recordSet: RecordSet, zone: Zone, auth: AuthPrincipal): RecordSetChange = diff --git a/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetService.scala b/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetService.scala index 4216f3b0b..7515dac5c 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetService.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetService.scala @@ -33,7 +33,8 @@ object RecordSetService { def apply( dataAccessor: ApiDataAccessor, messageQueue: MessageQueue, - accessValidation: AccessValidationsAlgebra): RecordSetService = + accessValidation: AccessValidationsAlgebra + ): RecordSetService = new RecordSetService( dataAccessor.zoneRepository, dataAccessor.groupRepository, @@ -52,8 +53,8 @@ class RecordSetService( recordChangeRepository: RecordChangeRepository, userRepository: UserRepository, messageQueue: MessageQueue, - accessValidation: AccessValidationsAlgebra) - extends RecordSetServiceAlgebra { + accessValidation: AccessValidationsAlgebra +) extends RecordSetServiceAlgebra { import RecordSetValidations._ import accessValidation._ @@ -106,7 +107,8 @@ class RecordSetService( def deleteRecordSet( recordSetId: String, zoneId: String, - auth: AuthPrincipal): Result[ZoneCommandResult] = + auth: AuthPrincipal + ): Result[ZoneCommandResult] = for { zone <- getZone(zoneId) existing <- getRecordSet(recordSetId, zone) @@ -121,7 +123,8 @@ class RecordSetService( def getRecordSet( recordSetId: String, zoneId: String, - authPrincipal: AuthPrincipal): Result[RecordSetInfo] = + authPrincipal: AuthPrincipal + ): Result[RecordSetInfo] = for { zone <- getZone(zoneId) recordSet <- getRecordSet(recordSetId, zone) @@ -130,7 +133,8 @@ class RecordSetService( recordSet.name, recordSet.typ, zone, - recordSet.ownerGroupId).toResult + recordSet.ownerGroupId + ).toResult groupName <- getGroupName(recordSet.ownerGroupId) } yield RecordSetInfo(recordSet, groupName) @@ -139,7 +143,8 @@ class RecordSetService( startFrom: Option[String], maxItems: Option[Int], recordNameFilter: Option[String], - authPrincipal: AuthPrincipal): Result[ListRecordSetsResponse] = + authPrincipal: AuthPrincipal + ): Result[ListRecordSetsResponse] = for { zone <- getZone(zoneId) _ <- canSeeZone(authPrincipal, zone).toResult @@ -150,39 +155,44 @@ class RecordSetService( rsGroups <- groupRepository.getGroups(rsOwnerGroupIds).toResult[Set[Group]] setsWithGroupName = getListWithGroupNames(recordSetResults.recordSets, rsGroups) setsWithAccess <- getListAccessLevels(authPrincipal, setsWithGroupName, zone).toResult - } yield - ListRecordSetsResponse( - setsWithAccess, - recordSetResults.startFrom, - recordSetResults.nextId, - recordSetResults.maxItems, - recordSetResults.recordNameFilter) + } yield ListRecordSetsResponse( + setsWithAccess, + recordSetResults.startFrom, + recordSetResults.nextId, + recordSetResults.maxItems, + recordSetResults.recordNameFilter + ) def getRecordSetChange( zoneId: String, changeId: String, - authPrincipal: AuthPrincipal): Result[RecordSetChange] = + authPrincipal: AuthPrincipal + ): Result[RecordSetChange] = for { zone <- getZone(zoneId) change <- recordChangeRepository .getRecordSetChange(zone.id, changeId) .orFail( RecordSetChangeNotFoundError( - s"Unable to find record set change with id $changeId in zone ${zone.name}")) + s"Unable to find record set change with id $changeId in zone ${zone.name}" + ) + ) .toResult[RecordSetChange] _ <- canViewRecordSet( authPrincipal, change.recordSet.name, change.recordSet.typ, zone, - change.recordSet.ownerGroupId).toResult + change.recordSet.ownerGroupId + ).toResult } yield change def listRecordSetChanges( zoneId: String, startFrom: Option[String] = None, maxItems: Int = 100, - authPrincipal: AuthPrincipal): Result[ListRecordSetChangesResponse] = + authPrincipal: AuthPrincipal + ): Result[ListRecordSetChangesResponse] = for { zone <- getZone(zoneId) _ <- canSeeZone(authPrincipal, zone).toResult @@ -203,7 +213,9 @@ class RecordSetService( .getRecordSet(zone.id, recordsetId) .orFail( RecordSetNotFoundError( - s"RecordSet with id $recordsetId does not exist in zone ${zone.name}")) + s"RecordSet with id $recordsetId does not exist in zone ${zone.name}" + ) + ) .toResult[RecordSet] def recordSetDoesNotExist(recordSet: RecordSet, zone: Zone): Result[Unit] = @@ -215,18 +227,22 @@ class RecordSetService( Left( RecordSetAlreadyExists( s"RecordSet with name ${recordSet.name} and type ${recordSet.typ} already " + - s"exists in zone ${zone.name}")) + s"exists in zone ${zone.name}" + ) + ) } .toResult def buildRecordSetChangeInfo( - changes: List[RecordSetChange]): Result[List[RecordSetChangeInfo]] = { + changes: List[RecordSetChange] + ): Result[List[RecordSetChangeInfo]] = { val userIds = changes.map(_.userId).toSet for { users <- userRepository.getUsers(userIds, None, None).map(_.users).toResult[Seq[User]] userMap = users.map(u => (u.id, u.userName)).toMap - recordSetChangesInfo = changes.map(change => - RecordSetChangeInfo(change, userMap.get(change.userId))) + recordSetChangesInfo = changes.map( + change => RecordSetChangeInfo(change, userMap.get(change.userId)) + ) } yield recordSetChangesInfo } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetServiceAlgebra.scala b/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetServiceAlgebra.scala index 3256e72d0..ba02d84df 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetServiceAlgebra.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetServiceAlgebra.scala @@ -31,29 +31,34 @@ trait RecordSetServiceAlgebra { def deleteRecordSet( recordSetId: String, zoneId: String, - auth: AuthPrincipal): Result[ZoneCommandResult] + auth: AuthPrincipal + ): Result[ZoneCommandResult] def getRecordSet( recordSetId: String, zoneId: String, - authPrincipal: AuthPrincipal): Result[RecordSetInfo] + authPrincipal: AuthPrincipal + ): Result[RecordSetInfo] def listRecordSets( zoneId: String, startFrom: Option[String], maxItems: Option[Int], recordNameFilter: Option[String], - authPrincipal: AuthPrincipal): Result[ListRecordSetsResponse] + authPrincipal: AuthPrincipal + ): Result[ListRecordSetsResponse] def getRecordSetChange( zoneId: String, changeId: String, - authPrincipal: AuthPrincipal): Result[RecordSetChange] + authPrincipal: AuthPrincipal + ): Result[RecordSetChange] def listRecordSetChanges( zoneId: String, startFrom: Option[String], maxItems: Int, - authPrincipal: AuthPrincipal): Result[ListRecordSetChangesResponse] + authPrincipal: AuthPrincipal + ): Result[ListRecordSetChangesResponse] } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetValidations.scala b/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetValidations.scala index c2aab4ebc..8c8bd24ad 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetValidations.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/record/RecordSetValidations.scala @@ -38,7 +38,8 @@ object RecordSetValidations { ensuring(InvalidRequest("PTR is not valid in forward lookup zone"))(zone.isReverse) case _ => ensuring(InvalidRequest(s"${recordSet.typ} is not valid in reverse lookup zone."))( - !zone.isReverse) + !zone.isReverse + ) } def validRecordNameLength(recordSet: RecordSet, zone: Zone): Either[Throwable, Unit] = { @@ -52,38 +53,51 @@ object RecordSetValidations { ensuring( PendingUpdateError( s"RecordSet with id ${recordSet.id}, name ${recordSet.name} and type ${recordSet.typ} " + - s"currently has a pending change"))( + s"currently has a pending change" + ) + )( !recordSet.isPending ) def noCnameWithNewName( newRecordSet: RecordSet, existingRecordsWithName: List[RecordSet], - zone: Zone): Either[Throwable, Unit] = + zone: Zone + ): Either[Throwable, Unit] = ensuring( - RecordSetAlreadyExists(s"RecordSet with name ${newRecordSet.name} and type CNAME already " + - s"exists in zone ${zone.name}"))( + RecordSetAlreadyExists( + s"RecordSet with name ${newRecordSet.name} and type CNAME already " + + s"exists in zone ${zone.name}" + ) + )( !existingRecordsWithName.exists(rs => rs.id != newRecordSet.id && rs.typ == CNAME) ) def isUniqueUpdate( newRecordSet: RecordSet, existingRecordsWithName: List[RecordSet], - zone: Zone): Either[Throwable, Unit] = + zone: Zone + ): Either[Throwable, Unit] = ensuring( RecordSetAlreadyExists( s"RecordSet with name ${newRecordSet.name} and type ${newRecordSet.typ} already " + - s"exists in zone ${zone.name}"))( + s"exists in zone ${zone.name}" + ) + )( !existingRecordsWithName.exists(rs => rs.id != newRecordSet.id && rs.typ == newRecordSet.typ) ) def isNotDotted( newRecordSet: RecordSet, zone: Zone, - existingRecordSet: Option[RecordSet] = None): Either[Throwable, Unit] = - ensuring(InvalidRequest( - s"Record with name ${newRecordSet.name} and type ${newRecordSet.typ} is a dotted host which" + - s" is not allowed in zone ${zone.name}"))( + existingRecordSet: Option[RecordSet] = None + ): Either[Throwable, Unit] = + ensuring( + InvalidRequest( + s"Record with name ${newRecordSet.name} and type ${newRecordSet.typ} is a dotted host which" + + s" is not allowed in zone ${zone.name}" + ) + )( newRecordSet.name == zone.name || !newRecordSet.name.contains(".") || existingRecordSet.exists(_.name == newRecordSet.name) ) @@ -92,7 +106,8 @@ object RecordSetValidations { newRecordSet: RecordSet, existingRecordsWithName: List[RecordSet], zone: Zone, - existingRecordSet: Option[RecordSet] = None): Either[Throwable, Unit] = + existingRecordSet: Option[RecordSet] = None + ): Either[Throwable, Unit] = newRecordSet.typ match { case CNAME => cnameValidations(newRecordSet, existingRecordsWithName, zone, existingRecordSet) case NS => nsValidations(newRecordSet, zone, existingRecordSet) @@ -110,7 +125,8 @@ object RecordSetValidations { isNotOrigin( recordSet, zone, - s"Record with name ${recordSet.name} is an NS record at apex and cannot be edited") + s"Record with name ${recordSet.name} is an NS record at apex and cannot be edited" + ) case SOA => InvalidRequest("SOA records cannot be deleted").asLeft case _ => ().asRight } @@ -120,12 +136,16 @@ object RecordSetValidations { newRecordSet: RecordSet, existingRecordsWithName: List[RecordSet], zone: Zone, - existingRecordSet: Option[RecordSet] = None): Either[Throwable, Unit] = { + existingRecordSet: Option[RecordSet] = None + ): Either[Throwable, Unit] = { // cannot create a cname record if a record with the same exists val noRecordWithName = { ensuring( - RecordSetAlreadyExists(s"RecordSet with name ${newRecordSet.name} already " + - s"exists in zone ${zone.name}, CNAME record cannot use duplicate name"))( + RecordSetAlreadyExists( + s"RecordSet with name ${newRecordSet.name} already " + + s"exists in zone ${zone.name}, CNAME record cannot use duplicate name" + ) + )( existingRecordsWithName.forall(_.id == newRecordSet.id) ) } @@ -134,7 +154,8 @@ object RecordSetValidations { _ <- isNotOrigin( newRecordSet, zone, - "CNAME RecordSet cannot have name '@' because it points to zone origin") + "CNAME RecordSet cannot have name '@' because it points to zone origin" + ) _ <- noRecordWithName _ <- isNotDotted(newRecordSet, zone, existingRecordSet) } yield () @@ -144,17 +165,20 @@ object RecordSetValidations { def dsValidations( newRecordSet: RecordSet, existingRecordsWithName: List[RecordSet], - zone: Zone): Either[Throwable, Unit] = { + zone: Zone + ): Either[Throwable, Unit] = { // see https://tools.ietf.org/html/rfc4035#section-2.4 val nsChecks = existingRecordsWithName.find(_.typ == NS) match { case Some(ns) if ns.ttl == newRecordSet.ttl => ().asRight case Some(ns) => InvalidRequest( - s"DS record [${newRecordSet.name}] must have TTL matching its linked NS (${ns.ttl})").asLeft + s"DS record [${newRecordSet.name}] must have TTL matching its linked NS (${ns.ttl})" + ).asLeft case None => InvalidRequest( s"DS record [${newRecordSet.name}] is invalid because there is no NS record with that " + - s"name in the zone [${zone.name}]").asLeft + s"name in the zone [${zone.name}]" + ).asLeft } for { @@ -162,7 +186,8 @@ object RecordSetValidations { _ <- isNotOrigin( newRecordSet, zone, - s"Record with name [${newRecordSet.name}] is an DS record at apex and cannot be added") + s"Record with name [${newRecordSet.name}] is an DS record at apex and cannot be added" + ) _ <- nsChecks } yield () } @@ -170,7 +195,8 @@ object RecordSetValidations { def nsValidations( newRecordSet: RecordSet, zone: Zone, - oldRecordSet: Option[RecordSet] = None): Either[Throwable, Unit] = { + oldRecordSet: Option[RecordSet] = None + ): Either[Throwable, Unit] = { // TODO kept consistency with old validation. Not sure why NS could be dotted in reverse specifically val isNotDottedHost = if (!zone.isReverse) isNotDotted(newRecordSet, zone) else ().asRight @@ -179,14 +205,16 @@ object RecordSetValidations { _ <- isNotOrigin( newRecordSet, zone, - s"Record with name ${newRecordSet.name} is an NS record at apex and cannot be added") + s"Record with name ${newRecordSet.name} is an NS record at apex and cannot be added" + ) _ <- containsApprovedNameServers(newRecordSet) _ <- oldRecordSet .map { rs => isNotOrigin( rs, zone, - s"Record with name ${newRecordSet.name} is an NS record at apex and cannot be edited") + s"Record with name ${newRecordSet.name} is an NS record at apex and cannot be edited" + ) } .getOrElse(().asRight) } yield () @@ -233,7 +261,8 @@ object RecordSetValidations { def canUseOwnerGroup( ownerGroupId: Option[String], group: Option[Group], - authPrincipal: AuthPrincipal): Either[Throwable, Unit] = + authPrincipal: AuthPrincipal + ): Either[Throwable, Unit] = (ownerGroupId, group) match { case (None, _) => ().asRight case (Some(groupId), None) => diff --git a/modules/api/src/main/scala/vinyldns/api/domain/zone/AclRuleOrdering.scala b/modules/api/src/main/scala/vinyldns/api/domain/zone/AclRuleOrdering.scala index d82595aa9..972cede06 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/zone/AclRuleOrdering.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/zone/AclRuleOrdering.scala @@ -40,11 +40,13 @@ trait ACLRuleOrdering extends Ordering[ACLRule] { sortableUserValue(rule1), sortableRecordMaskValue(rule1), sortableRecordTypeValue(rule1), - rule1.accessLevel).compare( + rule1.accessLevel + ).compare( sortableUserValue(rule2), sortableRecordMaskValue(rule2), sortableRecordTypeValue(rule2), - rule2.accessLevel) + rule2.accessLevel + ) } object ACLRuleOrdering extends ACLRuleOrdering { diff --git a/modules/api/src/main/scala/vinyldns/api/domain/zone/ListZoneChangesResponse.scala b/modules/api/src/main/scala/vinyldns/api/domain/zone/ListZoneChangesResponse.scala index 5b4772d87..90997b927 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/zone/ListZoneChangesResponse.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/zone/ListZoneChangesResponse.scala @@ -24,7 +24,8 @@ case class ListZoneChangesResponse( zoneChanges: List[ZoneChange] = Nil, nextId: Option[String], startFrom: Option[String], - maxItems: Int) + maxItems: Int +) object ListZoneChangesResponse { def apply(zoneId: String, listResults: ListZoneChangesResults): ListZoneChangesResponse = @@ -33,5 +34,6 @@ object ListZoneChangesResponse { listResults.items, listResults.nextId, listResults.startFrom, - listResults.maxItems) + listResults.maxItems + ) } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneChangeGenerator.scala b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneChangeGenerator.scala index 4b1c44884..b84ac2a77 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneChangeGenerator.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneChangeGenerator.scala @@ -30,7 +30,8 @@ object ZoneChangeGenerator { def forAdd( zone: Zone, authPrincipal: AuthPrincipal, - status: ZoneChangeStatus = Pending): ZoneChange = + status: ZoneChangeStatus = Pending + ): ZoneChange = ZoneChange( zone .copy(id = UUID.randomUUID().toString, created = DateTime.now, status = ZoneStatus.Syncing), @@ -68,6 +69,7 @@ object ZoneChangeGenerator { val oldConn = oldZ.connection.getOrElse(newConn) newConn.copy( key = - if (oldConn.key == newConn.decrypted(Crypto.instance).key) oldConn.key else newConn.key) + if (oldConn.key == newConn.decrypted(Crypto.instance).key) oldConn.key else newConn.key + ) }) } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneConnectionValidator.scala b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneConnectionValidator.scala index 2d7761ea0..06528ed5c 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneConnectionValidator.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneConnectionValidator.scala @@ -43,27 +43,31 @@ object ZoneConnectionValidator { def getZoneConnection( zone: Zone, - configuredDnsConnections: ConfiguredDnsConnections): ZoneConnection = + configuredDnsConnections: ConfiguredDnsConnections + ): ZoneConnection = zone.connection .orElse(getDnsBackend(zone, configuredDnsConnections).map(_.zoneConnection)) .getOrElse(configuredDnsConnections.defaultZoneConnection) def getTransferConnection( zone: Zone, - configuredDnsConnections: ConfiguredDnsConnections): ZoneConnection = + configuredDnsConnections: ConfiguredDnsConnections + ): ZoneConnection = zone.transferConnection .orElse(getDnsBackend(zone, configuredDnsConnections).map(_.transferConnection)) .getOrElse(configuredDnsConnections.defaultTransferConnection) def getDnsBackend( zone: Zone, - configuredDnsConnections: ConfiguredDnsConnections): Option[DnsBackend] = + configuredDnsConnections: ConfiguredDnsConnections + ): Option[DnsBackend] = zone.backendId .flatMap { bid => val backend = configuredDnsConnections.dnsBackends.find(_.id == bid) if (backend.isEmpty) { logger.error( - s"BackendId [$bid] for zone [${zone.id}: ${zone.name}] is not defined in config") + s"BackendId [$bid] for zone [${zone.id}: ${zone.name}] is not defined in config" + ) } backend } @@ -96,7 +100,9 @@ class ZoneConnectionValidator(connections: ConfiguredDnsConnections) ZoneValidationFailed( zoneView.zone, nel.toList, - "Zone could not be loaded due to validation errors.")) + "Zone could not be loaded due to validation errors." + ) + ) .toEither .toResult } @@ -108,7 +114,8 @@ class ZoneConnectionValidator(connections: ConfiguredDnsConnections) withTimeout( loadDns(zone), opTimeout, - ConnectionFailed(zone, "Unable to connect to zone: Transfer connection invalid")) + ConnectionFailed(zone, "Unable to connect to zone: Transfer connection invalid") + ) def hasSOA(records: List[RecordSet], zone: Zone): Result[Unit] = { if (records.isEmpty) { @@ -138,8 +145,10 @@ class ZoneConnectionValidator(connections: ConfiguredDnsConnections) def healthCheck(timeout: Int): HealthCheck = Resource .fromAutoCloseable(IO(new Socket())) - .use(socket => - IO(socket.connect(new InetSocketAddress(healthCheckAddress, healthCheckPort), timeout))) + .use( + socket => + IO(socket.connect(new InetSocketAddress(healthCheckAddress, healthCheckPort), timeout)) + ) .attempt .asHealthCheck diff --git a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneProtocol.scala b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneProtocol.scala index 656d883da..c3fd3149f 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneProtocol.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneProtocol.scala @@ -44,14 +44,16 @@ case class ZoneInfo( adminGroupName: String, latestSync: Option[DateTime], backendId: Option[String], - accessLevel: AccessLevel) + accessLevel: AccessLevel +) object ZoneInfo { def apply( zone: Zone, aclInfo: ZoneACLInfo, groupName: String, - accessLevel: AccessLevel): ZoneInfo = + accessLevel: AccessLevel + ): ZoneInfo = ZoneInfo( name = zone.name, email = zone.email, @@ -88,7 +90,8 @@ case class ZoneSummaryInfo( adminGroupName: String, latestSync: Option[DateTime], backendId: Option[String], - accessLevel: AccessLevel) + accessLevel: AccessLevel +) object ZoneSummaryInfo { def apply(zone: Zone, groupName: String, accessLevel: AccessLevel): ZoneSummaryInfo = @@ -125,7 +128,8 @@ case class RecordSetListInfo( account: String, accessLevel: AccessLevel, ownerGroupId: Option[String], - ownerGroupName: Option[String]) + ownerGroupName: Option[String] +) object RecordSetListInfo { def apply(recordSet: RecordSetInfo, accessLevel: AccessLevel): RecordSetListInfo = @@ -158,7 +162,8 @@ case class RecordSetInfo( id: String, account: String, ownerGroupId: Option[String], - ownerGroupName: Option[String]) + ownerGroupName: Option[String] +) object RecordSetInfo { def apply(recordSet: RecordSet, groupName: Option[String]): RecordSetInfo = @@ -188,7 +193,8 @@ case class RecordSetChangeInfo( systemMessage: Option[String], updates: Option[RecordSet], id: String, - userName: String) + userName: String +) object RecordSetChangeInfo { def apply(recordSetChange: RecordSetChange, name: Option[String]): RecordSetChangeInfo = @@ -212,7 +218,8 @@ case class ListZonesResponse( startFrom: Option[String] = None, nextId: Option[String] = None, maxItems: Int = 100, - ignoreAccess: Boolean = false) + ignoreAccess: Boolean = false +) // Errors case class InvalidRequest(msg: String) extends Throwable(msg) diff --git a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneRecordValidations.scala b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneRecordValidations.scala index 07b347cd4..7ac5b0578 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneRecordValidations.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneRecordValidations.scala @@ -46,7 +46,8 @@ object ZoneRecordValidations { /* Checks to see if an individual ns data is part of the approved server list */ def isApprovedNameServer( approvedServerList: List[Regex], - nsData: NSData): ValidatedNel[String, NSData] = + nsData: NSData + ): ValidatedNel[String, NSData] = if (isStringInRegexList(approvedServerList, nsData.nsdname)) { nsData.validNel[String] } else { @@ -56,7 +57,8 @@ object ZoneRecordValidations { /* Inspects each record in the rdata, returning back the record set itself or all ns records that are not approved */ def containsApprovedNameServers( approvedServerList: List[Regex], - nsRecordSet: RecordSet): ValidatedNel[String, RecordSet] = { + nsRecordSet: RecordSet + ): ValidatedNel[String, RecordSet] = { val validations: List[ValidatedNel[String, NSData]] = nsRecordSet.records .collect { case ns: NSData => ns } .map(isApprovedNameServer(approvedServerList, _)) @@ -66,7 +68,8 @@ object ZoneRecordValidations { def isNotHighValueFqdn( highValueRegexList: List[Regex], - fqdn: String): ValidatedNel[DomainValidationError, Unit] = + fqdn: String + ): ValidatedNel[DomainValidationError, Unit] = if (!isStringInRegexList(highValueRegexList, fqdn)) { ().validNel } else { @@ -75,7 +78,8 @@ object ZoneRecordValidations { def isNotHighValueIp( highValueIpList: List[IpAddress], - ip: String): ValidatedNel[DomainValidationError, Unit] = + ip: String + ): ValidatedNel[DomainValidationError, Unit] = if (!isIpInIpList(highValueIpList, ip)) { ().validNel } else { @@ -84,7 +88,8 @@ object ZoneRecordValidations { def domainDoesNotRequireManualReview( regexList: List[Regex], - fqdn: String): ValidatedNel[DomainValidationError, Unit] = + fqdn: String + ): ValidatedNel[DomainValidationError, Unit] = if (!isStringInRegexList(regexList, fqdn)) { ().validNel } else { @@ -93,7 +98,8 @@ object ZoneRecordValidations { def ipDoesNotRequireManualReview( regexList: List[IpAddress], - ip: String): ValidatedNel[DomainValidationError, Unit] = + ip: String + ): ValidatedNel[DomainValidationError, Unit] = if (!isIpInIpList(regexList, ip)) { ().validNel } else { @@ -103,7 +109,8 @@ object ZoneRecordValidations { def zoneDoesNotRequireManualReview( zonesRequiringReview: Set[String], zoneName: String, - fqdn: String): ValidatedNel[DomainValidationError, Unit] = + fqdn: String + ): ValidatedNel[DomainValidationError, Unit] = if (!zonesRequiringReview.contains(DomainHelpers.ensureTrailingDot(zoneName.toLowerCase))) { ().validNel } else { diff --git a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneService.scala b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneService.scala index 5dea45088..1272fdb30 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneService.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneService.scala @@ -32,7 +32,8 @@ object ZoneService { connectionValidator: ZoneConnectionValidatorAlgebra, messageQueue: MessageQueue, zoneValidations: ZoneValidations, - accessValidation: AccessValidationsAlgebra): ZoneService = + accessValidation: AccessValidationsAlgebra + ): ZoneService = new ZoneService( dataAccessor.zoneRepository, dataAccessor.groupRepository, @@ -53,8 +54,8 @@ class ZoneService( connectionValidator: ZoneConnectionValidatorAlgebra, messageQueue: MessageQueue, zoneValidations: ZoneValidations, - accessValidation: AccessValidationsAlgebra) - extends ZoneServiceAlgebra { + accessValidation: AccessValidationsAlgebra +) extends ZoneServiceAlgebra { import accessValidation._ import zoneValidations._ @@ -62,7 +63,8 @@ class ZoneService( def connectToZone( createZoneInput: CreateZoneInput, - auth: AuthPrincipal): Result[ZoneCommandResult] = + auth: AuthPrincipal + ): Result[ZoneCommandResult] = for { _ <- isValidZoneAcl(createZoneInput.acl).toResult _ <- connectionValidator.isValidBackendId(createZoneInput.backendId).toResult @@ -84,7 +86,8 @@ class ZoneService( _ <- validateSharedZoneAuthorized( existingZone.shared, updateZoneInput.shared, - auth.signedInUser).toResult + auth.signedInUser + ).toResult _ <- canChangeZone(auth, existingZone.name, existingZone.adminGroupId).toResult _ <- adminGroupExists(updateZoneInput.adminGroupId) // if admin group changes, this confirms user has access to new group @@ -136,32 +139,35 @@ class ZoneService( nameFilter: Option[String] = None, startFrom: Option[String] = None, maxItems: Int = 100, - ignoreAccess: Boolean = false): Result[ListZonesResponse] = { + ignoreAccess: Boolean = false + ): Result[ListZonesResponse] = { for { listZonesResult <- zoneRepository.listZones( authPrincipal, nameFilter, startFrom, maxItems, - ignoreAccess) + ignoreAccess + ) zones = listZonesResult.zones groupIds = zones.map(_.adminGroupId).toSet groups <- groupRepository.getGroups(groupIds) zoneSummaryInfos = zoneSummaryInfoMapping(zones, authPrincipal, groups) - } yield - ListZonesResponse( - zoneSummaryInfos, - listZonesResult.zonesFilter, - listZonesResult.startFrom, - listZonesResult.nextId, - listZonesResult.maxItems, - listZonesResult.ignoreAccess) + } yield ListZonesResponse( + zoneSummaryInfos, + listZonesResult.zonesFilter, + listZonesResult.startFrom, + listZonesResult.nextId, + listZonesResult.maxItems, + listZonesResult.ignoreAccess + ) }.toResult def zoneSummaryInfoMapping( zones: List[Zone], auth: AuthPrincipal, - groups: Set[Group]): List[ZoneSummaryInfo] = + groups: Set[Group] + ): List[ZoneSummaryInfo] = zones.map { zn => val groupName = groups.find(_.id == zn.adminGroupId) match { case Some(group) => group.name @@ -175,7 +181,8 @@ class ZoneService( zoneId: String, authPrincipal: AuthPrincipal, startFrom: Option[String] = None, - maxItems: Int = 100): Result[ListZoneChangesResponse] = + maxItems: Int = 100 + ): Result[ListZoneChangesResponse] = for { zone <- getZoneOrFail(zoneId) _ <- canSeeZone(authPrincipal, zone).toResult @@ -187,7 +194,8 @@ class ZoneService( def addACLRule( zoneId: String, aclRuleInfo: ACLRuleInfo, - authPrincipal: AuthPrincipal): Result[ZoneCommandResult] = { + authPrincipal: AuthPrincipal + ): Result[ZoneCommandResult] = { val newRule = ACLRule(aclRuleInfo) for { zone <- getZoneOrFail(zoneId) @@ -207,7 +215,8 @@ class ZoneService( def deleteACLRule( zoneId: String, aclRuleInfo: ACLRuleInfo, - authPrincipal: AuthPrincipal): Result[ZoneCommandResult] = { + authPrincipal: AuthPrincipal + ): Result[ZoneCommandResult] = { val newRule = ACLRule(aclRuleInfo) for { zone <- getZoneOrFail(zoneId) @@ -233,7 +242,8 @@ class ZoneService( case Some(existingZone) if existingZone.status != ZoneStatus.Deleted => ZoneAlreadyExistsError( s"Zone with name $zoneName already exists. " + - s"Please contact ${existingZone.email} to request access to the zone.").asLeft + s"Please contact ${existingZone.email} to request access to the zone." + ).asLeft case _ => ().asRight } .toResult diff --git a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneServiceAlgebra.scala b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneServiceAlgebra.scala index ebfaec3cf..01457a64b 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneServiceAlgebra.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneServiceAlgebra.scala @@ -24,7 +24,8 @@ trait ZoneServiceAlgebra { def connectToZone( createZoneInput: CreateZoneInput, - auth: AuthPrincipal): Result[ZoneCommandResult] + auth: AuthPrincipal + ): Result[ZoneCommandResult] def updateZone(updateZoneInput: UpdateZoneInput, auth: AuthPrincipal): Result[ZoneCommandResult] @@ -41,23 +42,27 @@ trait ZoneServiceAlgebra { nameFilter: Option[String], startFrom: Option[String], maxItems: Int, - ignoreAccess: Boolean): Result[ListZonesResponse] + ignoreAccess: Boolean + ): Result[ListZonesResponse] def listZoneChanges( zoneId: String, authPrincipal: AuthPrincipal, startFrom: Option[String], - maxItems: Int): Result[ListZoneChangesResponse] + maxItems: Int + ): Result[ListZoneChangesResponse] def addACLRule( zoneId: String, aclRuleInfo: ACLRuleInfo, - authPrincipal: AuthPrincipal): Result[ZoneCommandResult] + authPrincipal: AuthPrincipal + ): Result[ZoneCommandResult] def deleteACLRule( zoneId: String, aclRuleInfo: ACLRuleInfo, - authPrincipal: AuthPrincipal): Result[ZoneCommandResult] + authPrincipal: AuthPrincipal + ): Result[ZoneCommandResult] def getBackendIds(): Result[List[String]] diff --git a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneValidations.scala b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneValidations.scala index 3d24f89c0..fd660d465 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneValidations.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneValidations.scala @@ -74,15 +74,18 @@ class ZoneValidations(syncDelayMillis: Int) { // Validates that the zone is either not shared or shared and the user is a super or support user def validateSharedZoneAuthorized(zoneShared: Boolean, user: User): Either[Throwable, Unit] = ensuring(NotAuthorizedError("Not authorized to create shared zones."))( - !zoneShared || user.isSuper || user.isSupport) + !zoneShared || user.isSuper || user.isSupport + ) // Validates that the zone shared status has not been changed, or changed and the user is a super user def validateSharedZoneAuthorized( currentShared: Boolean, updateShared: Boolean, - user: User): Either[Throwable, Unit] = + user: User + ): Either[Throwable, Unit] = ensuring( NotAuthorizedError( - s"Not authorized to update zone shared status from $currentShared to $updateShared."))( - currentShared == updateShared || user.isSuper || user.isSupport) + s"Not authorized to update zone shared status from $currentShared to $updateShared." + ) + )(currentShared == updateShared || user.isSuper || user.isSupport) } diff --git a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneViewLoader.scala b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneViewLoader.scala index 33fc285b3..736e05d58 100644 --- a/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneViewLoader.scala +++ b/modules/api/src/main/scala/vinyldns/api/domain/zone/ZoneViewLoader.scala @@ -62,8 +62,8 @@ object DnsZoneViewLoader extends DnsConversions { case class DnsZoneViewLoader( zone: Zone, zoneTransfer: Zone => ZoneTransferIn, - maxZoneSize: Int = VinylDNSConfig.maxZoneSize) - extends ZoneViewLoader + maxZoneSize: Int = VinylDNSConfig.maxZoneSize +) extends ZoneViewLoader with DnsConversions with Monitored { @@ -76,17 +76,21 @@ case class DnsZoneViewLoader( xfr.run() xfr.getAXFR.asScala.map(_.asInstanceOf[DNS.Record]).toList.distinct } - rawDnsRecords = zoneXfr.filter(record => - fromDnsRecordType(record.getType) != RecordType.UNKNOWN) + rawDnsRecords = zoneXfr.filter( + record => fromDnsRecordType(record.getType) != RecordType.UNKNOWN + ) _ <- if (rawDnsRecords.length > maxZoneSize) IO.raiseError(ZoneTooLargeError(zone, rawDnsRecords.length, maxZoneSize)) else IO.pure(Unit) dnsZoneName <- IO(zoneDnsName(zone.name)) recordSets <- IO(rawDnsRecords.map(toRecordSet(_, dnsZoneName, zone.id))) - _ <- IO(DnsZoneViewLoader.logger.info( - s"dns.loadDnsView zoneName=${zone.name}; rawRsCount=${zoneXfr.size}; rsCount=${recordSets.size}")) + _ <- IO( + DnsZoneViewLoader.logger.info( + s"dns.loadDnsView zoneName=${zone.name}; rawRsCount=${zoneXfr.size}; rsCount=${recordSets.size}" + ) + ) } yield ZoneView(zone, recordSets) - } + } } object VinylDNSZoneViewLoader { @@ -103,11 +107,13 @@ case class VinylDNSZoneViewLoader(zone: Zone, recordSetRepository: RecordSetRepo zoneId = zone.id, startFrom = None, maxItems = None, - recordNameFilter = None) + recordNameFilter = None + ) .map { result => VinylDNSZoneViewLoader.logger.info( - s"vinyldns.loadZoneView zoneName=${zone.name}; rsCount=${result.recordSets.size}") + s"vinyldns.loadZoneView zoneName=${zone.name}; rsCount=${result.recordSets.size}" + ) ZoneView(zone, result.recordSets) } - } + } } diff --git a/modules/api/src/main/scala/vinyldns/api/engine/BatchChangeHandler.scala b/modules/api/src/main/scala/vinyldns/api/engine/BatchChangeHandler.scala index 388c84c2c..0c99c7084 100644 --- a/modules/api/src/main/scala/vinyldns/api/engine/BatchChangeHandler.scala +++ b/modules/api/src/main/scala/vinyldns/api/engine/BatchChangeHandler.scala @@ -31,7 +31,8 @@ object BatchChangeHandler { def apply( batchChangeRepository: BatchChangeRepository, - notifiers: AllNotifiers): BatchChangeCommand => IO[Option[BatchChange]] = + notifiers: AllNotifiers + ): BatchChangeCommand => IO[Option[BatchChange]] = batchChangeId => { process( batchChangeRepository: BatchChangeRepository, @@ -43,7 +44,8 @@ object BatchChangeHandler { def process( batchChangeRepository: BatchChangeRepository, notifiers: AllNotifiers, - batchChangeCommand: BatchChangeCommand): IO[Option[BatchChange]] = + batchChangeCommand: BatchChangeCommand + ): IO[Option[BatchChange]] = for { batchChange <- batchChangeRepository.getBatchChange(batchChangeCommand.id) _ <- notify(notifiers, batchChange, batchChangeCommand) @@ -55,15 +57,16 @@ object BatchChangeHandler { private final case class Pending( change: Option[BatchChange], - batchChangeCommand: BatchChangeCommand) - extends BatchChangeProcessorState + batchChangeCommand: BatchChangeCommand + ) extends BatchChangeProcessorState private final case class PendingBatchNotificationError(change: BatchChange) extends Throwable private def notify( notifiers: AllNotifiers, change: Option[BatchChange], - batchChangeCommand: BatchChangeCommand): IO[Unit] = + batchChangeCommand: BatchChangeCommand + ): IO[Unit] = change match { case Some(pendingBatch) if pendingBatch.status == BatchChangeStatus.PendingProcessing || @@ -75,7 +78,8 @@ object BatchChangeHandler { notifiers.notify(Notification(completedBatch)) case None => logger.error( - s"Notification not sent since batch change with ID ${batchChangeCommand.id} not found.") + s"Notification not sent since batch change with ID ${batchChangeCommand.id} not found." + ) IO.unit } diff --git a/modules/api/src/main/scala/vinyldns/api/engine/RecordSetChangeHandler.scala b/modules/api/src/main/scala/vinyldns/api/engine/RecordSetChangeHandler.scala index ec4f4da8f..0c8bec642 100644 --- a/modules/api/src/main/scala/vinyldns/api/engine/RecordSetChangeHandler.scala +++ b/modules/api/src/main/scala/vinyldns/api/engine/RecordSetChangeHandler.scala @@ -38,15 +38,16 @@ object RecordSetChangeHandler { def apply( recordSetRepository: RecordSetRepository, recordChangeRepository: RecordChangeRepository, - batchChangeRepository: BatchChangeRepository)( - implicit timer: Timer[IO]): (DnsConnection, RecordSetChange) => IO[RecordSetChange] = + batchChangeRepository: BatchChangeRepository + )(implicit timer: Timer[IO]): (DnsConnection, RecordSetChange) => IO[RecordSetChange] = (conn, recordSetChange) => { process( recordSetRepository, recordChangeRepository, batchChangeRepository, conn, - recordSetChange) + recordSetChange + ) } def process( @@ -54,7 +55,8 @@ object RecordSetChangeHandler { recordChangeRepository: RecordChangeRepository, batchChangeRepository: BatchChangeRepository, conn: DnsConnection, - recordSetChange: RecordSetChange)(implicit timer: Timer[IO]): IO[RecordSetChange] = + recordSetChange: RecordSetChange + )(implicit timer: Timer[IO]): IO[RecordSetChange] = for { wildCardExists <- wildCardExistsForRecord(recordSetChange.recordSet, recordSetRepository) completedState <- fsm(Pending(recordSetChange), conn, wildCardExists) @@ -62,14 +64,16 @@ object RecordSetChangeHandler { _ <- recordSetRepository.apply(changeSet) _ <- recordChangeRepository.save(changeSet) singleBatchChanges <- batchChangeRepository.getSingleChanges( - recordSetChange.singleBatchChangeIds) + recordSetChange.singleBatchChangeIds + ) singleChangeStatusUpdates = updateBatchStatuses(singleBatchChanges, completedState.change) _ <- batchChangeRepository.updateSingleChanges(singleChangeStatusUpdates) } yield completedState.change def updateBatchStatuses( singleChanges: List[SingleChange], - recordSetChange: RecordSetChange): List[SingleChange] = + recordSetChange: RecordSetChange + ): List[SingleChange] = recordSetChange.status match { case RecordSetChangeStatus.Complete => singleChanges.map(_.complete(recordSetChange.id, recordSetChange.recordSet.id)) @@ -146,7 +150,8 @@ object RecordSetChangeHandler { } private def fsm(state: ProcessorState, conn: DnsConnection, wildcardExists: Boolean)( - implicit timer: Timer[IO]): IO[ProcessorState] = { + implicit timer: Timer[IO] + ): IO[ProcessorState] = { /** * If there is a wildcard record with the same type, then we skip validation and verification steps. @@ -161,8 +166,9 @@ object RecordSetChangeHandler { * We also skip verification for NS records. We cannot create delegations for zones hosted on the * same ANS if we attempt to validate NS records */ - def bypassValidation(skip: => ProcessorState)( - orElse: => IO[ProcessorState]): IO[ProcessorState] = { + def bypassValidation( + skip: => ProcessorState + )(orElse: => IO[ProcessorState]): IO[ProcessorState] = { val toRun = if (wildcardExists || state.change.recordSet.typ == RecordType.NS) IO.pure(skip) else orElse @@ -199,8 +205,11 @@ object RecordSetChangeHandler { case AlreadyApplied(_) => Completed(change.successful) case ReadyToApply(_) => Validated(change) case Failure(_, message) => - Completed(change.failed( - s"Failed validating update to DNS for change ${change.id}:${change.recordSet.name}: " + message)) + Completed( + change.failed( + s"Failed validating update to DNS for change ${change.id}:${change.recordSet.name}: " + message + ) + ) } /* Step 2: Apply the change to the dns backend */ @@ -209,8 +218,11 @@ object RecordSetChangeHandler { case Right(_: NoError) => Applied(change) case Left(error) => - Completed(change.failed( - s"Failed applying update to DNS for change ${change.id}:${change.recordSet.name}: ${error.getMessage}")) + Completed( + change.failed( + s"Failed applying update to DNS for change ${change.id}:${change.recordSet.name}: ${error.getMessage}" + ) + ) } /* Step 3: Verify the record was created. We attempt 12 times over 6 seconds */ @@ -219,13 +231,22 @@ object RecordSetChangeHandler { getProcessingStatus(change, dnsConn).flatMap { case AlreadyApplied(_) => IO.pure(Completed(change.successful)) case ReadyToApply(_) if retries <= 0 => - IO.pure(Completed(change.failed(s"""Failed verifying update to DNS for - |change ${change.id}:${change.recordSet.name}: Verify out of retries.""".stripMargin))) + IO.pure( + Completed( + change.failed(s"""Failed verifying update to DNS for + |change ${change.id}:${change.recordSet.name}: Verify out of retries.""".stripMargin) + ) + ) case ReadyToApply(_) => IO.sleep(500.milliseconds) *> loop(retries - 1) case Failure(_, message) => - IO.pure(Completed(change.failed( - s"Failed verifying update to DNS for change ${change.id}:${change.recordSet.name}: $message"))) + IO.pure( + Completed( + change.failed( + s"Failed verifying update to DNS for change ${change.id}:${change.recordSet.name}: $message" + ) + ) + ) } loop() @@ -245,10 +266,11 @@ object RecordSetChangeHandler { private def wildCardExistsForRecord( recordSet: RecordSet, - recordSetRepository: RecordSetRepository): IO[Boolean] = + recordSetRepository: RecordSetRepository + ): IO[Boolean] = ( recordSetRepository.getRecordSets(recordSet.zoneId, "*", recordSet.typ), - recordSetRepository.getRecordSets(recordSet.zoneId, "*", RecordType.CNAME)) - .parMapN(_ ++ _) + recordSetRepository.getRecordSets(recordSet.zoneId, "*", RecordType.CNAME) + ).parMapN(_ ++ _) .map(_.nonEmpty) } diff --git a/modules/api/src/main/scala/vinyldns/api/engine/ZoneChangeHandler.scala b/modules/api/src/main/scala/vinyldns/api/engine/ZoneChangeHandler.scala index 699e571af..11f33de82 100644 --- a/modules/api/src/main/scala/vinyldns/api/engine/ZoneChangeHandler.scala +++ b/modules/api/src/main/scala/vinyldns/api/engine/ZoneChangeHandler.scala @@ -24,14 +24,16 @@ object ZoneChangeHandler { def apply( zoneRepository: ZoneRepository, zoneChangeRepository: ZoneChangeRepository, - recordSetRepository: RecordSetRepository): ZoneChange => IO[ZoneChange] = + recordSetRepository: RecordSetRepository + ): ZoneChange => IO[ZoneChange] = zoneChange => zoneRepository.save(zoneChange.zone).flatMap { case Left(duplicateZoneError) => zoneChangeRepository.save( zoneChange.copy( status = ZoneChangeStatus.Failed, - systemMessage = Some(duplicateZoneError.message)) + systemMessage = Some(duplicateZoneError.message) + ) ) case Right(_) if zoneChange.changeType == ZoneChangeType.Delete => recordSetRepository @@ -42,5 +44,5 @@ object ZoneChangeHandler { } case Right(_) => zoneChangeRepository.save(zoneChange.copy(status = ZoneChangeStatus.Synced)) - } + } } diff --git a/modules/api/src/main/scala/vinyldns/api/engine/ZoneSyncHandler.scala b/modules/api/src/main/scala/vinyldns/api/engine/ZoneSyncHandler.scala index 6c8b185df..fcd032b2e 100644 --- a/modules/api/src/main/scala/vinyldns/api/engine/ZoneSyncHandler.scala +++ b/modules/api/src/main/scala/vinyldns/api/engine/ZoneSyncHandler.scala @@ -45,7 +45,8 @@ object ZoneSyncHandler extends DnsConversions with Monitored { zoneRepository: ZoneRepository, dnsLoader: Zone => DnsZoneViewLoader = DnsZoneViewLoader.apply, vinyldnsLoader: (Zone, RecordSetRepository) => VinylDNSZoneViewLoader = - VinylDNSZoneViewLoader.apply): ZoneChange => IO[ZoneChange] = + VinylDNSZoneViewLoader.apply + ): ZoneChange => IO[ZoneChange] = zoneChange => for { _ <- saveZoneAndChange(zoneRepository, zoneChangeRepository, zoneChange) // initial save to store zone status @@ -55,7 +56,8 @@ object ZoneSyncHandler extends DnsConversions with Monitored { recordChangeRepository, zoneChange, dnsLoader, - vinyldnsLoader) + vinyldnsLoader + ) _ <- saveZoneAndChange(zoneRepository, zoneChangeRepository, syncChange) // final save to store zone status // as Active } yield syncChange @@ -63,13 +65,15 @@ object ZoneSyncHandler extends DnsConversions with Monitored { def saveZoneAndChange( zoneRepository: ZoneRepository, zoneChangeRepository: ZoneChangeRepository, - zoneChange: ZoneChange): IO[ZoneChange] = + zoneChange: ZoneChange + ): IO[ZoneChange] = zoneRepository.save(zoneChange.zone).flatMap { case Left(duplicateZoneError) => zoneChangeRepository.save( zoneChange.copy( status = ZoneChangeStatus.Failed, - systemMessage = Some(duplicateZoneError.message)) + systemMessage = Some(duplicateZoneError.message) + ) ) case Right(_) => zoneChangeRepository.save(zoneChange) @@ -81,7 +85,8 @@ object ZoneSyncHandler extends DnsConversions with Monitored { zoneChange: ZoneChange, dnsLoader: Zone => DnsZoneViewLoader = DnsZoneViewLoader.apply, vinyldnsLoader: (Zone, RecordSetRepository) => VinylDNSZoneViewLoader = - VinylDNSZoneViewLoader.apply): IO[ZoneChange] = + VinylDNSZoneViewLoader.apply + ): IO[ZoneChange] = monitor("zone.sync") { time(s"zone.sync; zoneName='${zoneChange.zone.name}'") { val zone = zoneChange.zone @@ -91,7 +96,8 @@ object ZoneSyncHandler extends DnsConversions with Monitored { s"zone.sync.loadDnsView; zoneName='${zone.name}'; zoneChange='${zoneChange.id}'" )(dnsLoader(zone).load()) val vinyldnsView = time(s"zone.sync.loadVinylDNSView; zoneName='${zone.name}'")( - vinyldnsLoader(zone, recordSetRepository).load()) + vinyldnsLoader(zone, recordSetRepository).load() + ) val recordSetChanges = (dnsView, vinyldnsView).parTupled.map { case (dnsZoneView, vinylDnsZoneView) => vinylDnsZoneView.diff(dnsZoneView) } @@ -101,11 +107,14 @@ object ZoneSyncHandler extends DnsConversions with Monitored { if (changesWithUserIds.isEmpty) { logger.info( - s"zone.sync.changes; zoneName='${zone.name}'; changeCount=0; zoneChange='${zoneChange.id}'") + s"zone.sync.changes; zoneName='${zone.name}'; changeCount=0; zoneChange='${zoneChange.id}'" + ) IO.pure( zoneChange.copy( zone.copy(status = ZoneStatus.Active, latestSync = Some(DateTime.now)), - status = ZoneChangeStatus.Synced)) + status = ZoneChangeStatus.Synced + ) + ) } else { changesWithUserIds .filter { chg => @@ -120,29 +129,33 @@ object ZoneSyncHandler extends DnsConversions with Monitored { logger.info( s"Zone sync for zoneName='${zone.name}'; zoneId='${zone.id}'; " + s"zoneChange='${zoneChange.id}' includes the following ${dottedGroup.length} " + - s"dotted host records: [$dottedGroupString]") + s"dotted host records: [$dottedGroupString]" + ) } logger.info( s"zone.sync.changes; zoneName='${zone.name}'; " + - s"changeCount=${changesWithUserIds.size}; zoneChange='${zoneChange.id}'") + s"changeCount=${changesWithUserIds.size}; zoneChange='${zoneChange.id}'" + ) val changeSet = ChangeSet(changesWithUserIds).copy(status = ChangeSetStatus.Applied) // we want to make sure we write to both the change repo and record set repo // at the same time as this can take a while val saveRecordChanges = time(s"zone.sync.saveChanges; zoneName='${zone.name}'")( - recordChangeRepository.save(changeSet)) + recordChangeRepository.save(changeSet) + ) val saveRecordSets = time(s"zone.sync.saveRecordSets; zoneName='${zone.name}'")( - recordSetRepository.apply(changeSet)) + recordSetRepository.apply(changeSet) + ) // join together the results of saving both the record changes as well as the record sets for { _ <- saveRecordChanges _ <- saveRecordSets - } yield - zoneChange.copy( - zone.copy(status = ZoneStatus.Active, latestSync = Some(DateTime.now)), - status = ZoneChangeStatus.Synced) + } yield zoneChange.copy( + zone.copy(status = ZoneStatus.Active, latestSync = Some(DateTime.now)), + status = ZoneChangeStatus.Synced + ) } } } @@ -151,11 +164,13 @@ object ZoneSyncHandler extends DnsConversions with Monitored { case Left(e: Throwable) => logger.error( s"Encountered error syncing ; zoneName='${zoneChange.zone.name}'; zoneChange='${zoneChange.id}'", - e) + e + ) // We want to just move back to an active status, do not update latest sync zoneChange.copy( zone = zoneChange.zone.copy(status = ZoneStatus.Active), - status = ZoneChangeStatus.Failed) + status = ZoneChangeStatus.Failed + ) case Right(ok) => ok } } diff --git a/modules/api/src/main/scala/vinyldns/api/metrics/APIMetrics.scala b/modules/api/src/main/scala/vinyldns/api/metrics/APIMetrics.scala index 3dd351cd5..f48e93e03 100644 --- a/modules/api/src/main/scala/vinyldns/api/metrics/APIMetrics.scala +++ b/modules/api/src/main/scala/vinyldns/api/metrics/APIMetrics.scala @@ -45,7 +45,8 @@ object APIMetrics { def initialize( settings: APIMetricsSettings, - reporter: ScheduledReporter = logReporter): IO[Unit] = IO { + reporter: ScheduledReporter = logReporter + ): IO[Unit] = IO { if (settings.memory.logEnabled) { reporter.start(settings.memory.logSeconds, TimeUnit.SECONDS) } diff --git a/modules/api/src/main/scala/vinyldns/api/notifier/email/EmailNotifier.scala b/modules/api/src/main/scala/vinyldns/api/notifier/email/EmailNotifier.scala index a71f121d1..23811b671 100644 --- a/modules/api/src/main/scala/vinyldns/api/notifier/email/EmailNotifier.scala +++ b/modules/api/src/main/scala/vinyldns/api/notifier/email/EmailNotifier.scala @@ -77,7 +77,8 @@ class EmailNotifier(config: EmailNotifierConfig, session: Session, userRepositor case Some(user: User) if user.email.isDefined => IO { logger.warn( - s"Unable to properly parse email for ${user.id}: ${user.email.getOrElse("")}") + s"Unable to properly parse email for ${user.id}: ${user.email.getOrElse("")}" + ) } case None => IO { logger.warn(s"Unable to find user: ${bc.userId}") } case _ => IO.unit @@ -95,16 +96,23 @@ class EmailNotifier(config: EmailNotifierConfig, session: Session, userRepositor // For manually reviewed e-mails, add additional info; e-mails are not sent for pending batch changes if (bc.approvalStatus != AutoApproved) { - bc.reviewComment.foreach(reviewComment => - sb.append(s"Review comment: $reviewComment
")) - bc.reviewTimestamp.foreach(reviewTimestamp => - sb.append( - s"Time reviewed: ${reviewTimestamp.toString(DateTimeFormat.fullDateTime)}
")) + bc.reviewComment.foreach( + reviewComment => sb.append(s"Review comment: $reviewComment
") + ) + bc.reviewTimestamp.foreach( + reviewTimestamp => + sb.append( + s"Time reviewed: ${reviewTimestamp.toString(DateTimeFormat.fullDateTime)}
" + ) + ) } - bc.cancelledTimestamp.foreach(cancelledTimestamp => - sb.append( - s"Time cancelled: ${cancelledTimestamp.toString(DateTimeFormat.fullDateTime)}
")) + bc.cancelledTimestamp.foreach( + cancelledTimestamp => + sb.append( + s"Time cancelled: ${cancelledTimestamp.toString(DateTimeFormat.fullDateTime)}
" + ) + ) // Single change data table sb.append(s"""
@@ -138,7 +146,8 @@ class EmailNotifier(config: EmailNotifierConfig, session: Session, userRepositor _, _, _, - _) => + _ + ) => s""" | | """ @@ -154,7 +163,8 @@ class EmailNotifier(config: EmailNotifierConfig, session: Session, userRepositor _, _, _, - _) => + _ + ) => val recordDataValue = recordData.map(_.toString).getOrElse("") s""" |
${index + 1}Add$typ$inputName$ttl${formatRecordData(recordData)}$status${systemMessage.getOrElse("")}
${index + 1}Delete$typ$inputName$recordDataValue$status${systemMessage diff --git a/modules/api/src/main/scala/vinyldns/api/notifier/sns/SnsNotifier.scala b/modules/api/src/main/scala/vinyldns/api/notifier/sns/SnsNotifier.scala index 71d9894c9..6eb7bf5e8 100644 --- a/modules/api/src/main/scala/vinyldns/api/notifier/sns/SnsNotifier.scala +++ b/modules/api/src/main/scala/vinyldns/api/notifier/sns/SnsNotifier.scala @@ -48,7 +48,8 @@ class SnsNotifier(config: SnsNotifierConfig, sns: AmazonSNS) val request = new PublishRequest(config.topicArn, message) request.addMessageAttributesEntry( "userName", - new MessageAttributeValue().withDataType("String").withStringValue(bc.userName)) + new MessageAttributeValue().withDataType("String").withStringValue(bc.userName) + ) sns.publish(request) logger.info(s"Sending batch change success; batchChange='${bc.id}'") }.handleErrorWith { e => diff --git a/modules/api/src/main/scala/vinyldns/api/notifier/sns/SnsNotifierProvider.scala b/modules/api/src/main/scala/vinyldns/api/notifier/sns/SnsNotifierProvider.scala index 7f60b2152..c4acbe064 100644 --- a/modules/api/src/main/scala/vinyldns/api/notifier/sns/SnsNotifierProvider.scala +++ b/modules/api/src/main/scala/vinyldns/api/notifier/sns/SnsNotifierProvider.scala @@ -42,12 +42,17 @@ class SnsNotifierProvider extends NotifierProvider { "Setting up sns notifier client with settings: " + s"service endpoint: ${config.serviceEndpoint}; " + s"signing region: ${config.signingRegion}; " + - s"topic name: ${config.topicArn}") + s"topic name: ${config.topicArn}" + ) AmazonSNSClientBuilder.standard .withEndpointConfiguration( - new EndpointConfiguration(config.serviceEndpoint, config.signingRegion)) - .withCredentials(new AWSStaticCredentialsProvider( - new BasicAWSCredentials(config.accessKey, config.secretKey))) + new EndpointConfiguration(config.serviceEndpoint, config.signingRegion) + ) + .withCredentials( + new AWSStaticCredentialsProvider( + new BasicAWSCredentials(config.accessKey, config.secretKey) + ) + ) .build() } diff --git a/modules/api/src/main/scala/vinyldns/api/repository/ApiDataAccessor.scala b/modules/api/src/main/scala/vinyldns/api/repository/ApiDataAccessor.scala index 1fd1368c7..ffc12c06d 100644 --- a/modules/api/src/main/scala/vinyldns/api/repository/ApiDataAccessor.scala +++ b/modules/api/src/main/scala/vinyldns/api/repository/ApiDataAccessor.scala @@ -36,5 +36,5 @@ final case class ApiDataAccessor( recordChangeRepository: RecordChangeRepository, zoneChangeRepository: ZoneChangeRepository, zoneRepository: ZoneRepository, - batchChangeRepository: BatchChangeRepository) - extends DataAccessor + batchChangeRepository: BatchChangeRepository +) extends DataAccessor diff --git a/modules/api/src/main/scala/vinyldns/api/repository/ApiDataAccessorProvider.scala b/modules/api/src/main/scala/vinyldns/api/repository/ApiDataAccessorProvider.scala index 7342d82d7..b9ae7a2a1 100644 --- a/modules/api/src/main/scala/vinyldns/api/repository/ApiDataAccessorProvider.scala +++ b/modules/api/src/main/scala/vinyldns/api/repository/ApiDataAccessorProvider.scala @@ -37,10 +37,12 @@ object ApiDataAccessorProvider extends DataAccessorProvider[ApiDataAccessor] { recordChange, zoneChange, zone, - batchChange) + batchChange + ) def create( - dataStores: List[(DataStoreConfig, DataStore)]): ValidatedNel[String, ApiDataAccessor] = + dataStores: List[(DataStoreConfig, DataStore)] + ): ValidatedNel[String, ApiDataAccessor] = ( getRepoOf[UserRepository](dataStores, user), getRepoOf[GroupRepository](dataStores, group), diff --git a/modules/api/src/main/scala/vinyldns/api/repository/TestDataLoader.scala b/modules/api/src/main/scala/vinyldns/api/repository/TestDataLoader.scala index f6707dab2..1d83f4b0f 100644 --- a/modules/api/src/main/scala/vinyldns/api/repository/TestDataLoader.scala +++ b/modules/api/src/main/scala/vinyldns/api/repository/TestDataLoader.scala @@ -192,7 +192,8 @@ object TestDataLoader { id = "shared-zone-group", email = "email", memberIds = Set(sharedZoneUser.id), - adminUserIds = Set(sharedZoneUser.id)) + adminUserIds = Set(sharedZoneUser.id) + ) final val sharedZone = Zone( name = "shared.", @@ -207,14 +208,16 @@ object TestDataLoader { id = "global-acl-group-id", email = "email", memberIds = Set(okUser.id, dummyUser.id), - adminUserIds = Set(okUser.id, dummyUser.id)) + adminUserIds = Set(okUser.id, dummyUser.id) + ) final val anotherGlobalACLGroup = Group( name = "globalACLGroup", id = "another-global-acl-group", email = "email", memberIds = Set(testUser.id), - adminUserIds = Set(testUser.id)) + adminUserIds = Set(testUser.id) + ) final val duGroup = Group( name = "duGroup", @@ -237,7 +240,8 @@ object TestDataLoader { userRepo: UserRepository, groupRepo: GroupRepository, zoneRepo: ZoneRepository, - membershipRepo: MembershipRepository): IO[Unit] = + membershipRepo: MembershipRepository + ): IO[Unit] = for { _ <- (testUser :: okUser :: dummyUser :: sharedZoneUser :: lockedUser :: listGroupUser :: listZonesUser :: listBatchChangeSummariesUser :: listZeroBatchChangeSummariesUser :: zoneHistoryUser :: supportUser :: @@ -258,7 +262,8 @@ object TestDataLoader { IO.raiseError(new RuntimeException(msg)) } else { logger.info( - s"Deleting existing shared zones on startup: ${toDelete.map(z => (z.name, z.id))}") + s"Deleting existing shared zones on startup: ${toDelete.map(z => (z.name, z.id))}" + ) IO.unit } _ <- toDelete.map(zoneRepo.save).parSequence @@ -269,17 +274,21 @@ object TestDataLoader { _ <- groupRepo.save(listBatchChangeSummariesGroup) _ <- membershipRepo.addMembers( groupId = "shared-zone-group", - memberUserIds = Set(sharedZoneUser.id)) + memberUserIds = Set(sharedZoneUser.id) + ) _ <- membershipRepo.addMembers( groupId = "global-acl-group-id", - memberUserIds = Set(okUser.id, dummyUser.id)) + memberUserIds = Set(okUser.id, dummyUser.id) + ) _ <- membershipRepo.addMembers( groupId = "another-global-acl-group", - memberUserIds = Set(testUser.id)) + memberUserIds = Set(testUser.id) + ) _ <- membershipRepo.addMembers(groupId = duGroup.id, memberUserIds = duGroup.memberIds) _ <- membershipRepo.addMembers( groupId = listBatchChangeSummariesGroup.id, - memberUserIds = listBatchChangeSummariesGroup.memberIds) + memberUserIds = listBatchChangeSummariesGroup.memberIds + ) _ <- zoneRepo.save(sharedZone) _ <- zoneRepo.save(nonTestSharedZone) } yield () diff --git a/modules/api/src/main/scala/vinyldns/api/route/Aws4Authenticator.scala b/modules/api/src/main/scala/vinyldns/api/route/Aws4Authenticator.scala index 73b74cedb..77b38de1c 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/Aws4Authenticator.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/Aws4Authenticator.scala @@ -47,7 +47,8 @@ object Aws4Authenticator { "akid", "creds", "shs", - "sig") + "sig" + ) def parseAuthHeader(auth: String): Option[Regex.Match] = aws4AuthRegex.findPrefixMatchOf(auth) } @@ -99,12 +100,14 @@ class Aws4Authenticator { req: HttpRequest, authorization: List[String], secret: String, - content: String): Boolean = { + content: String + ): Boolean = { val List( _, signatureScope, // signature scope signatureHeaders, // signed headers - signatureReceived) = authorization + signatureReceived + ) = authorization val signedHeaders = Set() ++ signatureHeaders.split(';') // convert Date header to canonical form required by AWS val dateTime = iso8601Format.print(getDate(req).get) @@ -133,7 +136,8 @@ class Aws4Authenticator { // XXX - need to canonicalize non-trimmed white space def canonicalHeaders( req: HttpRequest, - signedHeaderNames: Set[String]): TreeMap[String, Seq[String]] = { + signedHeaderNames: Set[String] + ): TreeMap[String, Seq[String]] = { def getHeaderValue(name: String): Option[String] = name match { case "content-type" => Some(req.entity.contentType.value) case "content-length" => req.entity.contentLengthOption.map(_.toString) @@ -160,7 +164,8 @@ class Aws4Authenticator { val stringToSign = joinStrings('\n', aws4AuthScheme, dateTime, scope, hashString(creq)) hexString( - runHmac(Mac.getInstance(hmacAlgorithm))(signingKey(secret, scope).getEncoded, stringToSign)) + runHmac(Mac.getInstance(hmacAlgorithm))(signingKey(secret, scope).getEncoded, stringToSign) + ) } /** @@ -208,7 +213,8 @@ class Aws4Authenticator { req: HttpRequest, hdrs: CanonicalHeaders, signedHeaders: String, - content: String): String = { + content: String + ): String = { val lines = MutableList[String](req.method.value) ++ canonicalURI(req) // add canonical headers diff --git a/modules/api/src/main/scala/vinyldns/api/route/BatchChangeJsonProtocol.scala b/modules/api/src/main/scala/vinyldns/api/route/BatchChangeJsonProtocol.scala index d88399538..93d8b76b4 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/BatchChangeJsonProtocol.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/BatchChangeJsonProtocol.scala @@ -88,7 +88,8 @@ trait BatchChangeJsonProtocol extends JsonValidation { (js \ "inputName").required[String]("Missing BatchChangeInput.changes.inputName"), recordType, (js \ "ttl").optional[Long], - recordType.andThen(extractRecord(_, js \ "record"))).mapN(AddChangeInput.apply) + recordType.andThen(extractRecord(_, js \ "record")) + ).mapN(AddChangeInput.apply) } override def toJson(aci: AddChangeInput): JValue = @@ -112,7 +113,8 @@ trait BatchChangeJsonProtocol extends JsonValidation { ( (js \ "inputName").required[String]("Missing BatchChangeInput.changes.inputName"), recordType, - recordData).mapN(DeleteRRSetChangeInput.apply) + recordData + ).mapN(DeleteRRSetChangeInput.apply) } override def toJson(drsci: DeleteRRSetChangeInput): JValue = @@ -218,7 +220,8 @@ trait BatchChangeJsonProtocol extends JsonValidation { (js \ "reviewComment") .optional[String] .check( - s"Comment length must not exceed $MAX_COMMENT_LENGTH characters." -> checkCommentLength) + s"Comment length must not exceed $MAX_COMMENT_LENGTH characters." -> checkCommentLength + ) .map(RejectBatchChangeInput) } @@ -228,7 +231,8 @@ trait BatchChangeJsonProtocol extends JsonValidation { (js \ "reviewComment") .optional[String] .check( - s"Comment length must not exceed $MAX_COMMENT_LENGTH characters." -> checkCommentLength) + s"Comment length must not exceed $MAX_COMMENT_LENGTH characters." -> checkCommentLength + ) .map(ApproveBatchChangeInput) } @@ -242,7 +246,8 @@ trait BatchChangeJsonProtocol extends JsonValidation { case TXT => js.required[TXTData]("Missing BatchChangeInput.changes.record.text") case MX => js.required[MXData]( - "Missing BatchChangeInput.changes.record.preference and BatchChangeInput.changes.record.exchange") + "Missing BatchChangeInput.changes.record.preference and BatchChangeInput.changes.record.exchange" + ) case _ => s"Unsupported type $typ, valid types include: A, AAAA, CNAME, PTR, TXT, and MX".invalidNel } diff --git a/modules/api/src/main/scala/vinyldns/api/route/BatchChangeRouting.scala b/modules/api/src/main/scala/vinyldns/api/route/BatchChangeRouting.scala index 07edb3ad0..33403c21c 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/BatchChangeRouting.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/BatchChangeRouting.scala @@ -24,8 +24,8 @@ import vinyldns.api.domain.batch._ class BatchChangeRoute( batchChangeService: BatchChangeServiceAlgebra, - val vinylDNSAuthenticator: VinylDNSAuthenticator) - extends VinylDNSJsonProtocol + val vinylDNSAuthenticator: VinylDNSAuthenticator +) extends VinylDNSJsonProtocol with VinylDNSDirectives[BatchChangeErrorResponse] { def getRoutes: Route = batchChangeRoute @@ -59,7 +59,8 @@ class BatchChangeRoute( authenticateAndExecuteWithEntity[BatchChange, BatchChangeInput]( (authPrincipal, batchChangeInput) => batchChangeService - .applyBatchChange(batchChangeInput, authPrincipal, allowManualReview)) { chg => + .applyBatchChange(batchChangeInput, authPrincipal, allowManualReview) + ) { chg => complete(StatusCodes.Accepted, chg) } } @@ -69,26 +70,31 @@ class BatchChangeRoute( "startFrom".as[Int].?, "maxItems".as[Int].?(MAX_ITEMS_LIMIT), "ignoreAccess".as[Boolean].?(false), - "approvalStatus".as[String].?) { + "approvalStatus".as[String].? + ) { ( startFrom: Option[Int], maxItems: Int, ignoreAccess: Boolean, - approvalStatus: Option[String]) => + approvalStatus: Option[String] + ) => { val convertApprovalStatus = approvalStatus.flatMap(BatchChangeApprovalStatus.find) handleRejections(invalidQueryHandler) { validate( 0 < maxItems && maxItems <= MAX_ITEMS_LIMIT, - s"maxItems was $maxItems, maxItems must be between 1 and $MAX_ITEMS_LIMIT, inclusive.") { + s"maxItems was $maxItems, maxItems must be between 1 and $MAX_ITEMS_LIMIT, inclusive." + ) { authenticateAndExecute( batchChangeService.listBatchChangeSummaries( _, startFrom, maxItems, ignoreAccess, - convertApprovalStatus)) { summaries => + convertApprovalStatus + ) + ) { summaries => complete(StatusCodes.OK, summaries) } } @@ -111,9 +117,9 @@ class BatchChangeRoute( authenticateAndExecuteWithEntity[BatchChange, Option[RejectBatchChangeInput]]( (authPrincipal, input) => batchChangeService - .rejectBatchChange(id, authPrincipal, input.getOrElse(RejectBatchChangeInput()))) { - chg => - complete(StatusCodes.OK, chg) + .rejectBatchChange(id, authPrincipal, input.getOrElse(RejectBatchChangeInput())) + ) { chg => + complete(StatusCodes.OK, chg) } // TODO: Update response entity to return modified batch change } @@ -123,10 +129,8 @@ class BatchChangeRoute( authenticateAndExecuteWithEntity[BatchChange, Option[ApproveBatchChangeInput]]( (authPrincipal, input) => batchChangeService - .approveBatchChange( - id, - authPrincipal, - input.getOrElse(ApproveBatchChangeInput()))) { chg => + .approveBatchChange(id, authPrincipal, input.getOrElse(ApproveBatchChangeInput())) + ) { chg => complete(StatusCodes.Accepted, chg) // TODO: Update response entity to return modified batch change } diff --git a/modules/api/src/main/scala/vinyldns/api/route/DnsJsonProtocol.scala b/modules/api/src/main/scala/vinyldns/api/route/DnsJsonProtocol.scala index f4675f95b..15ff98622 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/DnsJsonProtocol.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/DnsJsonProtocol.scala @@ -208,8 +208,8 @@ trait DnsJsonProtocol extends JsonValidation { override def fromJson(js: JValue): ValidatedNel[String, RecordSetListInfo] = ( RecordSetInfoSerializer.fromJson(js), - (js \ "accessLevel").required[AccessLevel.AccessLevel]("Missing RecordSet.zoneId")) - .mapN(RecordSetListInfo.apply) + (js \ "accessLevel").required[AccessLevel.AccessLevel]("Missing RecordSet.zoneId") + ).mapN(RecordSetListInfo.apply) override def toJson(rs: RecordSetListInfo): JValue = ("type" -> Extraction.decompose(rs.typ)) ~ diff --git a/modules/api/src/main/scala/vinyldns/api/route/JsonValidation.scala b/modules/api/src/main/scala/vinyldns/api/route/JsonValidation.scala index 5a89660e7..150518fc3 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/JsonValidation.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/JsonValidation.scala @@ -41,8 +41,11 @@ object VinylDateParser { format.dateFormat .parse(s) .map(_.getTime) - .getOrElse(throw new MappingException( - s"Invalid date format $s; provide the date format as YYYY-MM-DDTHH:MM:SSZ")) + .getOrElse( + throw new MappingException( + s"Invalid date format $s; provide the date format as YYYY-MM-DDTHH:MM:SSZ" + ) + ) } case object VinylDateTimeSerializer extends CustomSerializer[DateTime]( @@ -54,7 +57,8 @@ case object VinylDateTimeSerializer }, { case d: DateTime => JString(format.dateFormat.format(d.toDate)) } - )) + ) + ) trait JsonValidationSupport extends Json4sSupport { @@ -72,7 +76,8 @@ trait JsonValidationSupport extends Json4sSupport { IntervalSerializer(), LocalDateSerializer(), LocalTimeSerializer(), - PeriodSerializer) + PeriodSerializer + ) /** * Returns an adjusted set of serializers excluding the serializer passed in. This is needed otherwise @@ -101,7 +106,8 @@ trait JsonValidation extends JsonValidationSupport { def JsonV[A: Manifest]( validator: JValue => ValidatedNel[String, A], - serializer: A => JValue): ValidationSerializer[A] = + serializer: A => JValue + ): ValidationSerializer[A] = new ValidationSerializer[A] { override def fromJson(jv: JValue) = validator(jv) override def toJson(a: A) = serializer(a) @@ -215,8 +221,9 @@ trait JsonValidation extends JsonValidationSupport { } } - def extractEnum[E <: Enumeration](enum: E)( - default: => ValidatedNel[String, E#Value]): ValidatedNel[String, E#Value] = { + def extractEnum[E <: Enumeration]( + enum: E + )(default: => ValidatedNel[String, E#Value]): ValidatedNel[String, E#Value] = { lazy val invalidMsg = s"Invalid ${enum.getClass.getSimpleName.replace("$", "")}".invalidNel[E#Value] diff --git a/modules/api/src/main/scala/vinyldns/api/route/MembershipJsonProtocol.scala b/modules/api/src/main/scala/vinyldns/api/route/MembershipJsonProtocol.scala index b13617d38..2ea5783d6 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/MembershipJsonProtocol.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/MembershipJsonProtocol.scala @@ -31,14 +31,16 @@ object MembershipJsonProtocol { email: String, description: Option[String], members: Set[UserInfo], - admins: Set[UserInfo]) + admins: Set[UserInfo] + ) final case class UpdateGroupInput( id: String, name: String, email: String, description: Option[String], members: Set[UserInfo], - admins: Set[UserInfo]) + admins: Set[UserInfo] + ) } /* Defines the JSON serialization to support the Membership Routes */ diff --git a/modules/api/src/main/scala/vinyldns/api/route/MembershipRouting.scala b/modules/api/src/main/scala/vinyldns/api/route/MembershipRouting.scala index 29e857fef..f05ac4d45 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/MembershipRouting.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/MembershipRouting.scala @@ -25,8 +25,8 @@ import vinyldns.core.domain.membership.{Group, LockStatus} class MembershipRoute( membershipService: MembershipServiceAlgebra, - val vinylDNSAuthenticator: VinylDNSAuthenticator) - extends VinylDNSJsonProtocol + val vinylDNSAuthenticator: VinylDNSAuthenticator +) extends VinylDNSJsonProtocol with VinylDNSDirectives[Throwable] { final private val DEFAULT_MAX_ITEMS: Int = 100 final private val MAX_ITEMS_LIMIT: Int = 1000 @@ -62,7 +62,8 @@ class MembershipRoute( input.email, input.description, memberIds = (input.members ++ input.admins).map(_.id), - adminUserIds = input.admins.map(_.id)) + adminUserIds = input.admins.map(_.id) + ) membershipService.createGroup(group, authPrincipal) } { group => complete(StatusCodes.OK, GroupInfo(group)) @@ -73,12 +74,14 @@ class MembershipRoute( "startFrom".?, "maxItems".as[Int].?(DEFAULT_MAX_ITEMS), "groupNameFilter".?, - "ignoreAccess".as[Boolean].?(false)) { + "ignoreAccess".as[Boolean].?(false) + ) { ( startFrom: Option[String], maxItems: Int, groupNameFilter: Option[String], - ignoreAccess: Boolean) => + ignoreAccess: Boolean + ) => { handleRejections(invalidQueryHandler) { validate( @@ -88,10 +91,11 @@ class MembershipRoute( | and $MAX_ITEMS_LIMIT inclusive" """.stripMargin ) { - authenticateAndExecute(membershipService - .listMyGroups(groupNameFilter, startFrom, maxItems, _, ignoreAccess)) { - groups => - complete(StatusCodes.OK, groups) + authenticateAndExecute( + membershipService + .listMyGroups(groupNameFilter, startFrom, maxItems, _, ignoreAccess) + ) { groups => + complete(StatusCodes.OK, groups) } } } @@ -110,7 +114,9 @@ class MembershipRoute( input.description, (input.members ++ input.admins).map(_.id), input.admins.map(_.id), - authPrincipal)) { group => + authPrincipal + ) + ) { group => complete(StatusCodes.OK, GroupInfo(group)) } } @@ -122,9 +128,12 @@ class MembershipRoute( handleRejections(invalidQueryHandler) { validate( 0 < maxItems && maxItems <= MAX_ITEMS_LIMIT, - s"maxItems was $maxItems, maxItems must be between 0 exclusive and $MAX_ITEMS_LIMIT inclusive") { - authenticateAndExecute(membershipService - .listMembers(groupId, startFrom, maxItems, _)) { members => + s"maxItems was $maxItems, maxItems must be between 0 exclusive and $MAX_ITEMS_LIMIT inclusive" + ) { + authenticateAndExecute( + membershipService + .listMembers(groupId, startFrom, maxItems, _) + ) { members => complete(StatusCodes.OK, members) } } @@ -146,9 +155,12 @@ class MembershipRoute( handleRejections(invalidQueryHandler) { validate( 0 < maxItems && maxItems <= MAX_ITEMS_LIMIT, - s"maxItems was $maxItems, maxItems must be between 0 and $MAX_ITEMS_LIMIT") { - authenticateAndExecute(membershipService - .getGroupActivity(groupId, startFrom, maxItems, _)) { activity => + s"maxItems was $maxItems, maxItems must be between 0 and $MAX_ITEMS_LIMIT" + ) { + authenticateAndExecute( + membershipService + .getGroupActivity(groupId, startFrom, maxItems, _) + ) { activity => complete(StatusCodes.OK, activity) } } diff --git a/modules/api/src/main/scala/vinyldns/api/route/RecordSetRouting.scala b/modules/api/src/main/scala/vinyldns/api/route/RecordSetRouting.scala index 3502bf064..c5853bae0 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/RecordSetRouting.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/RecordSetRouting.scala @@ -33,12 +33,13 @@ case class ListRecordSetsResponse( startFrom: Option[String] = None, nextId: Option[String] = None, maxItems: Option[Int] = None, - recordNameFilter: Option[String] = None) + recordNameFilter: Option[String] = None +) class RecordSetRoute( recordSetService: RecordSetServiceAlgebra, - val vinylDNSAuthenticator: VinylDNSAuthenticator) - extends VinylDNSJsonProtocol + val vinylDNSAuthenticator: VinylDNSAuthenticator +) extends VinylDNSJsonProtocol with VinylDNSDirectives[Throwable] { def getRoutes: Route = recordSetRoute @@ -63,8 +64,9 @@ class RecordSetRoute( val recordSetRoute: Route = path("zones" / Segment / "recordsets") { zoneId => (post & monitor("Endpoint.addRecordSet")) { - authenticateAndExecuteWithEntity[ZoneCommandResult, RecordSet]((authPrincipal, recordSet) => - recordSetService.addRecordSet(recordSet, authPrincipal)) { rc => + authenticateAndExecuteWithEntity[ZoneCommandResult, RecordSet]( + (authPrincipal, recordSet) => recordSetService.addRecordSet(recordSet, authPrincipal) + ) { rc => complete(StatusCodes.Accepted, rc) } } ~ @@ -74,11 +76,13 @@ class RecordSetRoute( handleRejections(invalidQueryHandler) { validate( 0 < maxItems && maxItems <= DEFAULT_MAX_ITEMS, - s"maxItems was $maxItems, maxItems must be between 0 and $DEFAULT_MAX_ITEMS") { - authenticateAndExecute(recordSetService - .listRecordSets(zoneId, startFrom, Some(maxItems), recordNameFilter, _)) { - rsResponse => - complete(StatusCodes.OK, rsResponse) + s"maxItems was $maxItems, maxItems must be between 0 and $DEFAULT_MAX_ITEMS" + ) { + authenticateAndExecute( + recordSetService + .listRecordSets(zoneId, startFrom, Some(maxItems), recordNameFilter, _) + ) { rsResponse => + complete(StatusCodes.OK, rsResponse) } } } @@ -129,8 +133,10 @@ class RecordSetRoute( errorMsg = s"maxItems was $maxItems, maxItems must be between 0 exclusive " + s"and $DEFAULT_MAX_ITEMS inclusive" ) { - authenticateAndExecute(recordSetService - .listRecordSetChanges(zoneId, startFrom, maxItems, _)) { changes => + authenticateAndExecute( + recordSetService + .listRecordSetChanges(zoneId, startFrom, maxItems, _) + ) { changes => complete(StatusCodes.OK, changes) } } diff --git a/modules/api/src/main/scala/vinyldns/api/route/StatusRouting.scala b/modules/api/src/main/scala/vinyldns/api/route/StatusRouting.scala index 90d90b7e7..65d488453 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/StatusRouting.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/StatusRouting.scala @@ -29,7 +29,8 @@ case class CurrentStatus( processingDisabled: Boolean, color: String, keyName: String, - version: String) + version: String +) object CurrentStatus { val color = VinylDNSConfig.vinyldnsConfig.getString("color") @@ -50,7 +51,8 @@ trait StatusRoute extends Directives { onSuccess(processingDisabled.get.unsafeToFuture()) { isProcessingDisabled => complete( StatusCodes.OK, - CurrentStatus(isProcessingDisabled, color, vinyldnsKeyName, version)) + CurrentStatus(isProcessingDisabled, color, vinyldnsKeyName, version) + ) } } ~ (post & path("status")) { @@ -58,7 +60,8 @@ trait StatusRoute extends Directives { onSuccess(processingDisabled.set(isProcessingDisabled).unsafeToFuture()) { complete( StatusCodes.OK, - CurrentStatus(isProcessingDisabled, color, vinyldnsKeyName, version)) + CurrentStatus(isProcessingDisabled, color, vinyldnsKeyName, version) + ) } } } diff --git a/modules/api/src/main/scala/vinyldns/api/route/VinylDNSAuthentication.scala b/modules/api/src/main/scala/vinyldns/api/route/VinylDNSAuthentication.scala index d6409bd06..d23ee483c 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/VinylDNSAuthentication.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/VinylDNSAuthentication.scala @@ -36,18 +36,20 @@ final case class AccountLocked(reason: String) extends VinylDNSAuthenticationErr trait VinylDNSAuthenticator { def authenticate( ctx: RequestContext, - content: String): IO[Either[VinylDNSAuthenticationError, AuthPrincipal]] + content: String + ): IO[Either[VinylDNSAuthenticationError, AuthPrincipal]] } class ProductionVinylDNSAuthenticator( val authenticator: Aws4Authenticator, - val authPrincipalProvider: AuthPrincipalProvider) - extends VinylDNSAuthenticator + val authPrincipalProvider: AuthPrincipalProvider +) extends VinylDNSAuthenticator with Monitored { def authenticate( ctx: RequestContext, - content: String): IO[Either[VinylDNSAuthenticationError, AuthPrincipal]] = + content: String + ): IO[Either[VinylDNSAuthenticationError, AuthPrincipal]] = // Need to refactor getAuthPrincipal to be an IO[Either[E, A]] instead of how it is implemented. getAuthPrincipal(ctx, content).attempt.flatMap { case Left(e: VinylDNSAuthenticationError) => IO.pure(Left(e)) @@ -104,7 +106,8 @@ class ProductionVinylDNSAuthenticator( req: HttpRequest, secretKey: String, authHeaderRegex: Regex.Match, - content: String): IO[Unit] = + content: String + ): IO[Unit] = authHeaderRegex match { case auth if authenticator.authenticateReq(req, auth.subgroups, secretKey, content) => IO.unit @@ -138,7 +141,8 @@ class ProductionVinylDNSAuthenticator( ctx.request, decryptSecret(authPrincipal.secretKey), regexMatch, - content) + content + ) } yield authPrincipal def decryptSecret(str: String, crypto: CryptoAlgebra = Crypto.instance): String = @@ -149,7 +153,8 @@ class ProductionVinylDNSAuthenticator( case Some(ok) => if (ok.signedInUser.lockStatus == LockStatus.Locked) { IO.raiseError( - AccountLocked(s"Account with username ${ok.signedInUser.userName} is locked")) + AccountLocked(s"Account with username ${ok.signedInUser.userName} is locked") + ) } else IO.pure(ok) case None => IO.raiseError(AuthRejected(s"Account with accessKey $accessKey specified was not found")) diff --git a/modules/api/src/main/scala/vinyldns/api/route/VinylDNSDirectives.scala b/modules/api/src/main/scala/vinyldns/api/route/VinylDNSDirectives.scala index e67db285d..78939122c 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/VinylDNSDirectives.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/VinylDNSDirectives.scala @@ -42,8 +42,8 @@ trait VinylDNSDirectives[E] extends Directives { def authenticate: Directive1[AuthPrincipal] = extractRequestContext.flatMap { ctx => extractStrictEntity(10.seconds).flatMap { strictEntity => onSuccess( - vinylDNSAuthenticator.authenticate(ctx, strictEntity.data.utf8String).unsafeToFuture()) - .flatMap { + vinylDNSAuthenticator.authenticate(ctx, strictEntity.data.utf8String).unsafeToFuture() + ).flatMap { case Right(authPrincipal) ⇒ provide(authPrincipal) case Left(e) ⇒ @@ -159,8 +159,9 @@ trait VinylDNSDirectives[E] extends Directives { * return error to user. * - Invoke service call, f, and return the response to the user. */ - def authenticateAndExecuteWithEntity[A, B](f: (AuthPrincipal, B) => EitherT[IO, E, A])( - g: A => Route)(implicit um: FromRequestUnmarshaller[B]): Route = + def authenticateAndExecuteWithEntity[A, B]( + f: (AuthPrincipal, B) => EitherT[IO, E, A] + )(g: A => Route)(implicit um: FromRequestUnmarshaller[B]): Route = authenticate { authPrincipal => entity(as[B]) { deserializedEntity => onSuccess(f(authPrincipal, deserializedEntity).value.unsafeToFuture()) { diff --git a/modules/api/src/main/scala/vinyldns/api/route/VinylDNSService.scala b/modules/api/src/main/scala/vinyldns/api/route/VinylDNSService.scala index 93fc8cee9..243866a8c 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/VinylDNSService.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/VinylDNSService.scala @@ -84,32 +84,34 @@ object VinylDNSService { req: HttpRequest => { val startTime = System.currentTimeMillis() - r: Any => - { - val endTime = System.currentTimeMillis() - val duration = endTime - startTime - doNotLog.contains(req.uri.path) match { - case false => { - r match { - case res: HttpResponse => - Some(LogEntry(VinylDNSService.logMessage(req, Some(res), duration), InfoLevel)) - case res: Complete => - Some( - LogEntry( - VinylDNSService.logMessage(req, Some(res.response), duration), - InfoLevel)) - case _: Rejected => - Some(LogEntry(VinylDNSService.logMessage(req, None, duration), ErrorLevel)) - case x => // this can happen if sealRoute below cannot convert into a response. - val res = HttpResponse( - status = StatusCodes.InternalServerError, - entity = HttpEntity(x.toString)) - Some(LogEntry(VinylDNSService.logMessage(req, Some(res), duration), ErrorLevel)) - } + r: Any => { + val endTime = System.currentTimeMillis() + val duration = endTime - startTime + doNotLog.contains(req.uri.path) match { + case false => { + r match { + case res: HttpResponse => + Some(LogEntry(VinylDNSService.logMessage(req, Some(res), duration), InfoLevel)) + case res: Complete => + Some( + LogEntry( + VinylDNSService.logMessage(req, Some(res.response), duration), + InfoLevel + ) + ) + case _: Rejected => + Some(LogEntry(VinylDNSService.logMessage(req, None, duration), ErrorLevel)) + case x => // this can happen if sealRoute below cannot convert into a response. + val res = HttpResponse( + status = StatusCodes.InternalServerError, + entity = HttpEntity(x.toString) + ) + Some(LogEntry(VinylDNSService.logMessage(req, Some(res), duration), ErrorLevel)) } - case true => None } + case true => None } + } } } @@ -122,7 +124,8 @@ object VinylDNSService { HttpResponse( status = StatusCodes.BadRequest, entity = HttpEntity(ContentTypes.`application/json`, msg) - )) + ) + ) } .handleNotFound { extractUnmatchedPath { p => @@ -141,8 +144,8 @@ class VinylDNSService( val recordSetService: RecordSetServiceAlgebra, val batchChangeService: BatchChangeServiceAlgebra, val collectorRegistry: CollectorRegistry, - authPrincipalProvider: AuthPrincipalProvider) - extends PingRoute + authPrincipalProvider: AuthPrincipalProvider +) extends PingRoute with HealthCheckRoute with BlueGreenRoute with StatusRoute @@ -167,9 +170,10 @@ class VinylDNSService( Uri.Path("/color"), Uri.Path("/ping"), Uri.Path("/status"), - Uri.Path("/metrics/prometheus")) + Uri.Path("/metrics/prometheus") + ) val unloggedRoutes - : Route = healthCheckRoute ~ pingRoute ~ colorRoute ~ statusRoute ~ prometheusRoute + : Route = healthCheckRoute ~ pingRoute ~ colorRoute ~ statusRoute ~ prometheusRoute val allRoutes: Route = unloggedRoutes ~ batchChangeRoute ~ diff --git a/modules/api/src/main/scala/vinyldns/api/route/ZoneRouting.scala b/modules/api/src/main/scala/vinyldns/api/route/ZoneRouting.scala index d4254516d..aa214156e 100644 --- a/modules/api/src/main/scala/vinyldns/api/route/ZoneRouting.scala +++ b/modules/api/src/main/scala/vinyldns/api/route/ZoneRouting.scala @@ -60,7 +60,8 @@ class ZoneRoute(zoneService: ZoneServiceAlgebra, val vinylDNSAuthenticator: Viny (post & monitor("Endpoint.createZone")) { authenticateAndExecuteWithEntity[ZoneCommandResult, CreateZoneInput]( (authPrincipal, createZoneInput) => - zoneService.connectToZone(encrypt(createZoneInput), authPrincipal)) { chg => + zoneService.connectToZone(encrypt(createZoneInput), authPrincipal) + ) { chg => complete(StatusCodes.Accepted, chg) } } ~ @@ -69,19 +70,24 @@ class ZoneRoute(zoneService: ZoneServiceAlgebra, val vinylDNSAuthenticator: Viny "nameFilter".?, "startFrom".as[String].?, "maxItems".as[Int].?(DEFAULT_MAX_ITEMS), - "ignoreAccess".as[Boolean].?(false)) { + "ignoreAccess".as[Boolean].?(false) + ) { ( nameFilter: Option[String], startFrom: Option[String], maxItems: Int, - ignoreAccess: Boolean) => + ignoreAccess: Boolean + ) => { handleRejections(invalidQueryHandler) { validate( 0 < maxItems && maxItems <= MAX_ITEMS_LIMIT, - s"maxItems was $maxItems, maxItems must be between 0 and $MAX_ITEMS_LIMIT") { - authenticateAndExecute(zoneService - .listZones(_, nameFilter, startFrom, maxItems, ignoreAccess)) { result => + s"maxItems was $maxItems, maxItems must be between 0 and $MAX_ITEMS_LIMIT" + ) { + authenticateAndExecute( + zoneService + .listZones(_, nameFilter, startFrom, maxItems, ignoreAccess) + ) { result => complete(StatusCodes.OK, result) } } @@ -111,7 +117,8 @@ class ZoneRoute(zoneService: ZoneServiceAlgebra, val vinylDNSAuthenticator: Viny (put & monitor("Endpoint.updateZone")) { authenticateAndExecuteWithEntity[ZoneCommandResult, UpdateZoneInput]( (authPrincipal, updateZoneInput) => - zoneService.updateZone(encrypt(updateZoneInput), authPrincipal)) { chg => + zoneService.updateZone(encrypt(updateZoneInput), authPrincipal) + ) { chg => complete(StatusCodes.Accepted, chg) } } ~ @@ -135,7 +142,8 @@ class ZoneRoute(zoneService: ZoneServiceAlgebra, val vinylDNSAuthenticator: Viny handleRejections(invalidQueryHandler) { validate( 0 < maxItems && maxItems <= DEFAULT_MAX_ITEMS, - s"maxItems was $maxItems, maxItems must be between 0 exclusive and $DEFAULT_MAX_ITEMS inclusive") { + s"maxItems was $maxItems, maxItems must be between 0 exclusive and $DEFAULT_MAX_ITEMS inclusive" + ) { authenticateAndExecute(zoneService.listZoneChanges(id, _, startFrom, maxItems)) { changes => complete(StatusCodes.OK, changes) @@ -147,14 +155,16 @@ class ZoneRoute(zoneService: ZoneServiceAlgebra, val vinylDNSAuthenticator: Viny } ~ path("zones" / Segment / "acl" / "rules") { id => (put & monitor("Endpoint.addZoneACLRule")) { - authenticateAndExecuteWithEntity[ZoneCommandResult, ACLRuleInfo]((authPrincipal, rule) => - zoneService.addACLRule(id, rule, authPrincipal)) { chg => + authenticateAndExecuteWithEntity[ZoneCommandResult, ACLRuleInfo]( + (authPrincipal, rule) => zoneService.addACLRule(id, rule, authPrincipal) + ) { chg => complete(StatusCodes.Accepted, chg) } } ~ (delete & monitor("Endpoint.deleteZoneACLRule")) { - authenticateAndExecuteWithEntity[ZoneCommandResult, ACLRuleInfo]((authPrincipal, rule) => - zoneService.deleteACLRule(id, rule, authPrincipal)) { chg => + authenticateAndExecuteWithEntity[ZoneCommandResult, ACLRuleInfo]( + (authPrincipal, rule) => zoneService.deleteACLRule(id, rule, authPrincipal) + ) { chg => complete(StatusCodes.Accepted, chg) } } diff --git a/modules/api/src/test/scala/vinyldns/api/CatsHelpers.scala b/modules/api/src/test/scala/vinyldns/api/CatsHelpers.scala index 8f307f19a..ee82bd253 100644 --- a/modules/api/src/test/scala/vinyldns/api/CatsHelpers.scala +++ b/modules/api/src/test/scala/vinyldns/api/CatsHelpers.scala @@ -43,7 +43,8 @@ trait CatsHelpers { // Waits for the future to complete, then returns the value as an Either[Throwable, T] def awaitResultOf[E, T]( f: => IO[Either[E, T]], - duration: FiniteDuration = 1.second): Either[E, T] = { + duration: FiniteDuration = 1.second + ): Either[E, T] = { val timeOut = IO.sleep(duration) *> IO(new RuntimeException("Timed out waiting for result")) IO.race(timeOut, f).unsafeRunSync().toOption.get } @@ -76,10 +77,12 @@ trait ValidatedBatchMatcherImprovements { MatchResult( left.contains(expectedChange.validNel), s"ValidatedBatch $left does not contain $expectedChange", - s"ValidatedBatch $left contains $expectedChange") + s"ValidatedBatch $left contains $expectedChange" + ) } def containChangeForValidation( - expectedChange: ChangeForValidation): ValidatedBatchContainsChangeForValidation = + expectedChange: ChangeForValidation + ): ValidatedBatchContainsChangeForValidation = new ValidatedBatchContainsChangeForValidation(expectedChange) } diff --git a/modules/api/src/test/scala/vinyldns/api/ResultHelpers.scala b/modules/api/src/test/scala/vinyldns/api/ResultHelpers.scala index 69bd1a179..6a18b6ff1 100644 --- a/modules/api/src/test/scala/vinyldns/api/ResultHelpers.scala +++ b/modules/api/src/test/scala/vinyldns/api/ResultHelpers.scala @@ -40,10 +40,12 @@ trait ResultHelpers { // Waits for the future to complete, then returns the value as an Either[Throwable, T] def awaitResultOf[T]( f: => IO[Either[Throwable, T]], - duration: FiniteDuration = 1.second): Either[Throwable, T] = { + duration: FiniteDuration = 1.second + ): Either[Throwable, T] = { val timeOut = IO.sleep(duration) *> IO( - TimeoutException("Timed out waiting for result").asInstanceOf[Throwable]) + TimeoutException("Timed out waiting for result").asInstanceOf[Throwable] + ) IO.race(timeOut, f.handleError(e => Left(e))).unsafeRunSync() match { case Left(e) => Left(e) @@ -61,7 +63,8 @@ trait ResultHelpers { // Assumes that the result of the future operation will fail, this will error on a right disjunction def leftResultOf[T]( f: => IO[Either[Throwable, T]], - duration: FiniteDuration = 1.second): Throwable = awaitResultOf(f, duration).swap.toOption.get + duration: FiniteDuration = 1.second + ): Throwable = awaitResultOf(f, duration).swap.toOption.get def leftValue[T](t: Either[Throwable, T]): Throwable = t.swap.toOption.get @@ -71,7 +74,8 @@ trait ResultHelpers { object ValidationTestImprovements extends PropSpec with Matchers with ValidatedMatchers { implicit class ValidatedNelTestImprovements[DomainValidationError, A]( - value: ValidatedNel[DomainValidationError, A]) { + value: ValidatedNel[DomainValidationError, A] + ) { def failures: List[DomainValidationError] = value match { case Invalid(e) => e.toList diff --git a/modules/api/src/test/scala/vinyldns/api/VinylDNSConfigSpec.scala b/modules/api/src/test/scala/vinyldns/api/VinylDNSConfigSpec.scala index cec260438..4c29ad0c2 100644 --- a/modules/api/src/test/scala/vinyldns/api/VinylDNSConfigSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/VinylDNSConfigSpec.scala @@ -42,7 +42,8 @@ class VinylDNSConfigSpec extends WordSpec with Matchers { zone, batchChange, user, - recordSet) + recordSet + ) } "assign the correct dynamodb repositories" in { val dynamodbConfig = diff --git a/modules/api/src/test/scala/vinyldns/api/backend/CommandHandlerSpec.scala b/modules/api/src/test/scala/vinyldns/api/backend/CommandHandlerSpec.scala index 068778873..f3485a6b5 100644 --- a/modules/api/src/test/scala/vinyldns/api/backend/CommandHandlerSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/backend/CommandHandlerSpec.scala @@ -56,8 +56,10 @@ class CommandHandlerSpec private implicit val timer: Timer[IO] = IO.timer(ExecutionContext.global) private implicit val cs: ContextShift[IO] = IO.contextShift(scala.concurrent.ExecutionContext.global) - private val messages = for { i <- 0 to 10 } yield - TestCommandMessage(pendingCreateAAAA, i.toString) + private val messages = for { i <- 0 to 10 } yield TestCommandMessage( + pendingCreateAAAA, + i.toString + ) private val count = MessageCount(10).right.value private val mockZoneChangeProcessor = mock[ZoneChange => IO[ZoneChange]] @@ -224,7 +226,8 @@ class CommandHandlerSpec "use the default zone connection when the change zone connection is not defined" in { val noConnChange = pendingCreateAAAA.copy( - zone = pendingCreateAAAA.zone.copy(connection = None, transferConnection = None)) + zone = pendingCreateAAAA.zone.copy(connection = None, transferConnection = None) + ) val default = defaultConn.copy(primaryServer = "default.conn.test.com") val defaultConnProcessor = CommandHandler.processChangeRequests( diff --git a/modules/api/src/test/scala/vinyldns/api/domain/ReverseZoneHelpersSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/ReverseZoneHelpersSpec.scala index 6498df631..4bf319625 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/ReverseZoneHelpersSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/ReverseZoneHelpersSpec.scala @@ -79,7 +79,8 @@ class ReverseZoneHelpersSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) ReverseZoneHelpers.convertPTRtoIPv6(zn1, rs1.name) shouldBe "2001:0db8:0000:0000:0000:0000:0567:89ab" } @@ -92,7 +93,8 @@ class ReverseZoneHelpersSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) ReverseZoneHelpers.convertPTRtoIPv6(zn1, rs1.name) shouldBe "2001:0db8:0000:0000:0000:0000:0567:89ab" } @@ -105,7 +107,8 @@ class ReverseZoneHelpersSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) ReverseZoneHelpers.convertPTRtoIPv6(zn1, rs1.name) shouldBe "2001:0db8:0000:0000:0000:0000:0567:89ab" } @@ -179,7 +182,8 @@ class ReverseZoneHelpersSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val znFalse = Zone("5.b.e.f.9.d.2.f.9.5.c.c.7.4.a.a.8.ip6.arpa.", "email") val rsFalse = RecordSet( "id", @@ -187,7 +191,8 @@ class ReverseZoneHelpersSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) ReverseZoneHelpers.recordsetIsWithinCidrMask(mask, znTrue, rsTrue.name) shouldBe true ReverseZoneHelpers.recordsetIsWithinCidrMask(mask, znFalse, rsFalse.name) shouldBe false @@ -202,7 +207,8 @@ class ReverseZoneHelpersSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val znFalse = Zone("5.b.e.f.9.d.2.f.9.5.c.c.7.4.a.a.8.ip6.arpa.", "email") val rsFalse = RecordSet( "id", @@ -210,7 +216,8 @@ class ReverseZoneHelpersSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) ReverseZoneHelpers.recordsetIsWithinCidrMask(mask, znTrue, rsTrue.name) shouldBe true ReverseZoneHelpers.recordsetIsWithinCidrMask(mask, znFalse, rsFalse.name) shouldBe false @@ -225,7 +232,8 @@ class ReverseZoneHelpersSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val znFalse = Zone("5.b.e.f.9.d.2.f.9.5.c.c.7.4.a.a.8.ip6.arpa.", "email") val rsFalse = RecordSet( "id", @@ -233,7 +241,8 @@ class ReverseZoneHelpersSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) ReverseZoneHelpers.recordsetIsWithinCidrMask(mask, znTrue, rsTrue.name) shouldBe true ReverseZoneHelpers.recordsetIsWithinCidrMask(mask, znFalse, rsFalse.name) shouldBe false diff --git a/modules/api/src/test/scala/vinyldns/api/domain/access/AccessValidationsSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/access/AccessValidationsSpec.scala index dc3e47614..7cd48321b 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/access/AccessValidationsSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/access/AccessValidationsSpec.scala @@ -91,7 +91,8 @@ class AccessValidationsSpec "return true if the user is an admin or super user" in { val auth = okAuth.copy( signedInUser = okAuth.signedInUser.copy(isSuper = true), - memberGroupIds = Seq.empty) + memberGroupIds = Seq.empty + ) accessValidationTest.canSeeZone(auth, okZone) should be(right) } @@ -105,7 +106,8 @@ class AccessValidationsSpec "return true if the user is a support admin" in { val supportAuth = okAuth.copy( signedInUser = okAuth.signedInUser.copy(isSupport = true), - memberGroupIds = Seq.empty) + memberGroupIds = Seq.empty + ) accessValidationTest.canSeeZone(supportAuth, okZone) should be(right) } @@ -119,7 +121,8 @@ class AccessValidationsSpec "return a NotAuthorizedError if the user is not admin or super user" in { val error = leftValue( accessValidationTest - .canChangeZone(okAuth, zoneNotAuthorized.name, zoneNotAuthorized.adminGroupId)) + .canChangeZone(okAuth, zoneNotAuthorized.name, zoneNotAuthorized.adminGroupId) + ) error shouldBe a[NotAuthorizedError] } @@ -130,17 +133,20 @@ class AccessValidationsSpec "return true if the user is an admin and a support user" in { val auth = okAuth.copy( signedInUser = okAuth.signedInUser.copy(isSupport = true), - memberGroupIds = Seq(okGroup.id)) + memberGroupIds = Seq(okGroup.id) + ) accessValidationTest.canChangeZone(auth, okZone.name, okZone.adminGroupId) should be(right) } "return a NotAuthorizedError if the user is a support user only" in { val auth = okAuth.copy( signedInUser = okAuth.signedInUser.copy(isSupport = true), - memberGroupIds = Seq.empty) + memberGroupIds = Seq.empty + ) val error = leftValue( accessValidationTest - .canChangeZone(auth, okZone.name, okZone.adminGroupId)) + .canChangeZone(auth, okZone.name, okZone.adminGroupId) + ) error shouldBe a[NotAuthorizedError] } } @@ -149,25 +155,29 @@ class AccessValidationsSpec "return a NotAuthorizedError if the user has AccessLevel.NoAccess" in { val error = leftValue( accessValidationTest - .canAddRecordSet(userAuthNone, "test", RecordType.A, zoneInNone)) + .canAddRecordSet(userAuthNone, "test", RecordType.A, zoneInNone) + ) error shouldBe a[NotAuthorizedError] } "return a NotAuthorizedError if the user has AccessLevel.Read" in { val error = leftValue( accessValidationTest - .canAddRecordSet(userAuthRead, "test", RecordType.A, zoneInRead)) + .canAddRecordSet(userAuthRead, "test", RecordType.A, zoneInRead) + ) error shouldBe a[NotAuthorizedError] } "return true if the user has AccessLevel.Write" in { accessValidationTest.canAddRecordSet(userAuthWrite, "test", RecordType.A, zoneInWrite) should be( - right) + right + ) } "return true if the user has AccessLevel.Delete" in { accessValidationTest.canAddRecordSet(userAuthDelete, "test", RecordType.A, zoneInDelete) should be( - right) + right + ) } "return a NotAuthorizedError if the user is a test user in a non-test zone" in { @@ -175,7 +185,8 @@ class AccessValidationsSpec val error = leftValue( accessValidationTest - .canAddRecordSet(auth, "test", RecordType.A, okZone)) + .canAddRecordSet(auth, "test", RecordType.A, okZone) + ) error shouldBe a[NotAuthorizedError] } @@ -197,7 +208,8 @@ class AccessValidationsSpec userAuthWrite, "someRecordName", RecordType.NS, - zoneInWrite) should be(right) + zoneInWrite + ) should be(right) } "return true if recordset matches the global ACL" in { @@ -205,7 +217,8 @@ class AccessValidationsSpec userAuthGlobalAcl, "someRecordName", RecordType.A, - okZone.copy(name = "foo.comcast.com")) should be(right) + okZone.copy(name = "foo.comcast.com") + ) should be(right) } "return false if the record set does not match the global ACL" in { @@ -213,7 +226,8 @@ class AccessValidationsSpec val error = leftValue( globalAclTest - .canAddRecordSet(auth, "test-foo", RecordType.A, okZone)) + .canAddRecordSet(auth, "test-foo", RecordType.A, okZone) + ) error shouldBe a[NotAuthorizedError] } @@ -231,14 +245,16 @@ class AccessValidationsSpec "return a NotAuthorizedError if the user has AccessLevel.NoAccess" in { val error = leftValue( accessValidationTest - .canUpdateRecordSet(userAuthNone, "test", RecordType.A, zoneInNone, None)) + .canUpdateRecordSet(userAuthNone, "test", RecordType.A, zoneInNone, None) + ) error shouldBe a[NotAuthorizedError] } "return a NotAuthorizedError if the user has AccessLevel.Read" in { val error = leftValue( accessValidationTest - .canUpdateRecordSet(userAuthRead, "test", RecordType.A, zoneInRead, None)) + .canUpdateRecordSet(userAuthRead, "test", RecordType.A, zoneInRead, None) + ) error shouldBe a[NotAuthorizedError] } @@ -248,7 +264,8 @@ class AccessValidationsSpec "test", RecordType.A, zoneInWrite, - None) should be(right) + None + ) should be(right) } "return true if the user has AccessLevel.Delete" in { @@ -257,7 +274,8 @@ class AccessValidationsSpec val userAcl = ACLRule(AccessLevel.Delete, userId = Some(userAuth.userId), groupId = None) val zoneIn = zoneNotAuthorized.copy(acl = ZoneACL(Set(userAcl))) accessValidationTest.canUpdateRecordSet(userAuth, "test", RecordType.A, zoneIn, None) should be( - right) + right + ) } "return true if the user is in the owner group and the zone is shared" in { @@ -293,7 +311,8 @@ class AccessValidationsSpec val error = leftValue( accessValidationTest - .canUpdateRecordSet(auth, "test", RecordType.A, okZone, None)) + .canUpdateRecordSet(auth, "test", RecordType.A, okZone, None) + ) error shouldBe a[NotAuthorizedError] } @@ -311,7 +330,8 @@ class AccessValidationsSpec "someRecordName", RecordType.A, okZone.copy(name = "foo.comcast.com"), - None) should be(right) + None + ) should be(right) } "return false if the record set does not match the global ACL" in { @@ -319,7 +339,8 @@ class AccessValidationsSpec val error = leftValue( globalAclTest - .canUpdateRecordSet(auth, "test-foo", RecordType.A, okZone, None)) + .canUpdateRecordSet(auth, "test-foo", RecordType.A, okZone, None) + ) error shouldBe a[NotAuthorizedError] } @@ -339,21 +360,24 @@ class AccessValidationsSpec "return a NotAuthorizedError if the user has AccessLevel.NoAccess" in { val error = leftValue( accessValidationTest - .canDeleteRecordSet(userAuthNone, "test", RecordType.A, zoneInNone, None)) + .canDeleteRecordSet(userAuthNone, "test", RecordType.A, zoneInNone, None) + ) error shouldBe a[NotAuthorizedError] } "return a NotAuthorizedError if the user has AccessLevel.Read" in { val error = leftValue( accessValidationTest - .canDeleteRecordSet(userAuthRead, "test", RecordType.A, zoneInRead, None)) + .canDeleteRecordSet(userAuthRead, "test", RecordType.A, zoneInRead, None) + ) error shouldBe a[NotAuthorizedError] } "return a NotAuthorizedError if the user has AccessLevel.Write" in { val error = leftValue( accessValidationTest - .canDeleteRecordSet(userAuthWrite, "test", RecordType.A, zoneInWrite, None)) + .canDeleteRecordSet(userAuthWrite, "test", RecordType.A, zoneInWrite, None) + ) error shouldBe a[NotAuthorizedError] } @@ -363,7 +387,8 @@ class AccessValidationsSpec "test", RecordType.A, zoneInDelete, - None) should be(right) + None + ) should be(right) } "return a NotAuthorizedError if the user is a test user in a non-test zone" in { @@ -371,7 +396,8 @@ class AccessValidationsSpec val error = leftValue( accessValidationTest - .canDeleteRecordSet(auth, "test", RecordType.A, okZone, None)) + .canDeleteRecordSet(auth, "test", RecordType.A, okZone, None) + ) error shouldBe a[NotAuthorizedError] } @@ -389,7 +415,8 @@ class AccessValidationsSpec "someRecordName", RecordType.A, okZone.copy(name = "foo.comcast.com"), - None) should be(right) + None + ) should be(right) } "return false if the record set does not match the global ACL" in { @@ -397,7 +424,8 @@ class AccessValidationsSpec val error = leftValue( globalAclTest - .canDeleteRecordSet(auth, "test-foo", RecordType.A, okZone, None)) + .canDeleteRecordSet(auth, "test-foo", RecordType.A, okZone, None) + ) error shouldBe a[NotAuthorizedError] } @@ -417,18 +445,21 @@ class AccessValidationsSpec "return a NotAuthorizedError if the user has AccessLevel.NoAccess" in { val error = leftValue( accessValidationTest - .canViewRecordSet(userAuthNone, "test", RecordType.A, zoneInNone, None)) + .canViewRecordSet(userAuthNone, "test", RecordType.A, zoneInNone, None) + ) error shouldBe a[NotAuthorizedError] } "return true if the user has AccessLevel.Read" in { accessValidationTest.canViewRecordSet(userAuthRead, "test", RecordType.A, zoneInRead, None) should be( - right) + right + ) } "return true if the user has AccessLevel.Write" in { accessValidationTest.canViewRecordSet(userAuthWrite, "test", RecordType.A, zoneInWrite, None) should be( - right) + right + ) } "return true if the user has AccessLevel.Delete" in { @@ -437,7 +468,8 @@ class AccessValidationsSpec "test", RecordType.A, zoneInDelete, - None) should be(right) + None + ) should be(right) } "return true if the user is in the recordSet owner group and the recordSet is in a shared zone" in { @@ -447,7 +479,8 @@ class AccessValidationsSpec recordSet.name, recordSet.typ, sharedZone, - recordSet.ownerGroupId) should be(right) + recordSet.ownerGroupId + ) should be(right) } "return a NotAuthorizedError if the user is in the recordSet owner group but it is not in a shared zone" in { @@ -458,7 +491,9 @@ class AccessValidationsSpec recordSet.name, recordSet.typ, zoneNotAuthorized, - recordSet.ownerGroupId)) + recordSet.ownerGroupId + ) + ) error shouldBe a[NotAuthorizedError] } @@ -467,7 +502,8 @@ class AccessValidationsSpec val error = leftValue( accessValidationTest - .canViewRecordSet(auth, "test", RecordType.A, okZone, None)) + .canViewRecordSet(auth, "test", RecordType.A, okZone, None) + ) error shouldBe a[NotAuthorizedError] } @@ -485,7 +521,8 @@ class AccessValidationsSpec "someRecordName", RecordType.A, okZone.copy(name = "foo.comcast.com"), - None) should be(right) + None + ) should be(right) } "return false if the record set does not match the global ACL" in { @@ -493,7 +530,8 @@ class AccessValidationsSpec val error = leftValue( globalAclTest - .canViewRecordSet(auth, "test-foo", RecordType.A, okZone, None)) + .canViewRecordSet(auth, "test-foo", RecordType.A, okZone, None) + ) error shouldBe a[NotAuthorizedError] } @@ -518,7 +556,8 @@ class AccessValidationsSpec mockRecordSet.name, mockRecordSet.typ, okZone, - None) + None + ) result shouldBe AccessLevel.Delete } @@ -530,7 +569,8 @@ class AccessValidationsSpec sharedZoneRecord.name, sharedZoneRecord.typ, sharedZone, - sharedZoneRecord.ownerGroupId) + sharedZoneRecord.ownerGroupId + ) result shouldBe AccessLevel.Delete } @@ -541,7 +581,8 @@ class AccessValidationsSpec sharedZoneRecordNoOwnerGroup.name, RecordType.AAAA, sharedZone, - None) + None + ) result shouldBe AccessLevel.Delete } @@ -552,7 +593,8 @@ class AccessValidationsSpec sharedZoneRecordNotApprovedRecordType.name, RecordType.MX, sharedZone, - None) + None + ) result shouldBe AccessLevel.NoAccess } @@ -563,7 +605,8 @@ class AccessValidationsSpec notSharedZoneRecordWithOwnerGroup.name, notSharedZoneRecordWithOwnerGroup.typ, zoneNotAuthorized, - notSharedZoneRecordWithOwnerGroup.ownerGroupId) + notSharedZoneRecordWithOwnerGroup.ownerGroupId + ) result shouldBe AccessLevel.NoAccess } @@ -573,7 +616,8 @@ class AccessValidationsSpec "test", RecordType.A, okZone.copy(adminGroupId = "not-a-real-group"), - None) + None + ) result shouldBe AccessLevel.Read } @@ -583,7 +627,8 @@ class AccessValidationsSpec "test", RecordType.A, okZone.copy(adminGroupId = "not-a-real-group"), - None) + None + ) result shouldBe AccessLevel.Read } @@ -608,7 +653,8 @@ class AccessValidationsSpec mockRecordSet.name, mockRecordSet.typ, zoneIn, - None) + None + ) result shouldBe AccessLevel.Write } @@ -713,7 +759,8 @@ class AccessValidationsSpec RecordType.A, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val aclRuleA = ACLRule(AccessLevel.Read, userId = Some(okAuth.userId), recordTypes = Set(RecordType.A)) @@ -731,7 +778,8 @@ class AccessValidationsSpec RecordType.A, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val aclRuleA = ACLRule(AccessLevel.Read, userId = Some(okAuth.userId), recordTypes = Set(RecordType.AAAA)) @@ -749,13 +797,15 @@ class AccessValidationsSpec RecordType.A, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val aclRuleA = ACLRule(AccessLevel.Write, userId = Some(okAuth.userId), recordTypes = Set(RecordType.A)) val aclRuleMany = ACLRule( AccessLevel.Read, userId = Some(okAuth.userId), - recordTypes = Set(RecordType.A, RecordType.AAAA)) + recordTypes = Set(RecordType.A, RecordType.AAAA) + ) val zoneAcl = ZoneACL(Set(aclRuleA, aclRuleMany)) val zone = Zone("name", "email", acl = zoneAcl) @@ -771,7 +821,8 @@ class AccessValidationsSpec RecordType.A, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val aclRuleA = ACLRule(AccessLevel.Write, userId = Some(okAuth.userId), recordTypes = Set(RecordType.A)) val aclRuleAll = @@ -791,7 +842,8 @@ class AccessValidationsSpec RecordType.A, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val aclRule = userReadAcl.copy(recordMask = Some("rs.*")) val zoneAcl = ZoneACL(Set(aclRule)) @@ -808,7 +860,8 @@ class AccessValidationsSpec RecordType.A, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val aclRule = userReadAcl.copy(recordMask = Some("bad.*")) val zoneAcl = ZoneACL(Set(aclRule)) @@ -825,7 +878,8 @@ class AccessValidationsSpec RecordType.A, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val aclRuleRM = userReadAcl.copy(recordMask = Some("rs.*")) val aclRuleAll = userWriteAcl.copy(recordMask = None) @@ -891,7 +945,8 @@ class AccessValidationsSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val aclRule = userReadAcl.copy(recordMask = Some(".*0.*")) val zoneAcl = ZoneACL(Set(aclRule)) @@ -913,7 +968,8 @@ class AccessValidationsSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val znFalse = Zone("5.b.e.f.9.d.2.f.9.5.c.c.7.4.a.a.8.ip6.arpa.", "email") val rsFalse = RecordSet( "id", @@ -921,7 +977,8 @@ class AccessValidationsSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) accessValidationTest.ruleAppliesToRecordName(rsTrue.name, rsTrue.typ, znTrue, aclRule) shouldBe true accessValidationTest.ruleAppliesToRecordName(rsFalse.name, rsFalse.typ, znFalse, aclRule) shouldBe false @@ -937,7 +994,8 @@ class AccessValidationsSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val znFalse = Zone("5.b.e.f.9.d.2.f.9.5.c.c.7.4.a.a.8.ip6.arpa.", "email") val rsFalse = RecordSet( "id", @@ -945,7 +1003,8 @@ class AccessValidationsSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) accessValidationTest.ruleAppliesToRecordName(rsTrue.name, rsTrue.typ, znTrue, aclRule) shouldBe true accessValidationTest.ruleAppliesToRecordName(rsFalse.name, rsFalse.typ, znFalse, aclRule) shouldBe false @@ -961,7 +1020,8 @@ class AccessValidationsSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) val znFalse = Zone("5.b.e.f.9.d.2.f.9.5.c.c.7.4.a.a.8.ip6.arpa.", "email") val rsFalse = RecordSet( "id", @@ -969,7 +1029,8 @@ class AccessValidationsSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) accessValidationTest.ruleAppliesToRecordName(rsTrue.name, rsTrue.typ, znTrue, aclRule) shouldBe true accessValidationTest.ruleAppliesToRecordName(rsFalse.name, rsFalse.typ, znFalse, aclRule) shouldBe false @@ -984,7 +1045,8 @@ class AccessValidationsSpec RecordType.PTR, 200, RecordSetStatus.Active, - DateTime.now) + DateTime.now + ) accessValidationTest.ruleAppliesToRecordName(rs.name, rs.typ, zn, aclRule) shouldBe true } @@ -994,7 +1056,8 @@ class AccessValidationsSpec val multiRecordList = List("rs1", "rs2", "rs3").map { name => RecordSetInfo( RecordSet("zoneId", name, RecordType.A, 100, RecordSetStatus.Active, DateTime.now()), - None) + None + ) } "return access level DELETE if the user is admin/super of the zone" in { @@ -1020,7 +1083,8 @@ class AccessValidationsSpec "return access level Read if there is no ACL rule for the user and user is a support admin" in { val supportAuth = okAuth.copy( signedInUser = okAuth.signedInUser.copy(isSupport = true), - memberGroupIds = Seq.empty) + memberGroupIds = Seq.empty + ) val zone = Zone("test", "test") @@ -1034,7 +1098,8 @@ class AccessValidationsSpec val rs1 = RecordSetInfo( RecordSet("zoneId", "rs1", RecordType.A, 100, RecordSetStatus.Active, DateTime.now()), - None) + None + ) val rs2 = rs1.copy(name = "rs2") val rs3 = rs1.copy(name = "rs3") val recordList = List(rs1, rs2, rs3) @@ -1051,7 +1116,8 @@ class AccessValidationsSpec val expected = List( RecordSetListInfo(rs1, AccessLevel.Write), RecordSetListInfo(rs2, AccessLevel.NoAccess), - RecordSetListInfo(rs3, AccessLevel.Read)) + RecordSetListInfo(rs3, AccessLevel.Read) + ) result shouldBe expected } diff --git a/modules/api/src/test/scala/vinyldns/api/domain/access/GlobalAclSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/access/GlobalAclSpec.scala index 105af0e8d..5e7a5b1c9 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/access/GlobalAclSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/access/GlobalAclSpec.scala @@ -33,7 +33,8 @@ class GlobalAclSpec import vinyldns.core.TestZoneData._ private val globalAcls = GlobalAcls( - List(GlobalAcl(List(okGroup.id, dummyGroup.id), List(".*foo.*", ".*bar.com.")))) + List(GlobalAcl(List(okGroup.id, dummyGroup.id), List(".*foo.*", ".*bar.com."))) + ) "isAuthorized" should { "return false if the acl list is empty" in { @@ -54,7 +55,8 @@ class GlobalAclSpec "foo", RecordType.PTR, zoneIp4, - List(PTRData("foo.com"), PTRData("bar.com"))) shouldBe true + List(PTRData("foo.com"), PTRData("bar.com")) + ) shouldBe true } "return false for a PTR record if one of the PTR records does not match an acl" in { globalAcls.isAuthorized( @@ -62,7 +64,8 @@ class GlobalAclSpec "foo", RecordType.PTR, zoneIp4, - List(PTRData("foo.com"), PTRData("blah.net"))) shouldBe false + List(PTRData("foo.com"), PTRData("blah.net")) + ) shouldBe false } "return false for a PTR record if the record data is empty" in { globalAcls.isAuthorized(okAuth, "foo", RecordType.PTR, zoneIp4, Nil) shouldBe false diff --git a/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeConverterSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeConverterSpec.scala index d7e81f900..df7eec535 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeConverterSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeConverterSpec.scala @@ -40,7 +40,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { name: String, recordData: RecordData, typ: RecordType = A, - zone: Zone = okZone) = { + zone: Zone = okZone + ) = { val fqdn = s"$name.${zone.name}" SingleAddChange( Some(zone.id), @@ -53,7 +54,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { SingleChangeStatus.Pending, None, None, - None) + None + ) } private def makeSingleDeleteRRSetChange(name: String, typ: RecordType, zone: Zone = okZone) = { @@ -68,25 +70,30 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { SingleChangeStatus.Pending, None, None, - None) + None + ) } private def makeAddChangeForValidation( recordName: String, recordData: RecordData, - typ: RecordType = RecordType.A): AddChangeForValidation = + typ: RecordType = RecordType.A + ): AddChangeForValidation = AddChangeForValidation( okZone, s"$recordName", - AddChangeInput(s"$recordName.ok.", typ, Some(123), recordData)) + AddChangeInput(s"$recordName.ok.", typ, Some(123), recordData) + ) private def makeDeleteRRSetChangeForValidation( recordName: String, - typ: RecordType = RecordType.A): DeleteRRSetChangeForValidation = + typ: RecordType = RecordType.A + ): DeleteRRSetChangeForValidation = DeleteRRSetChangeForValidation( okZone, s"$recordName", - DeleteRRSetChangeInput(s"$recordName.ok.", typ)) + DeleteRRSetChangeInput(s"$recordName.ok.", typ) + ) private val addSingleChangesGood = List( makeSingleAddChange("one", AData("1.1.1.1")), @@ -184,7 +191,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { RecordSetStatus.Active, DateTime.now, None, - List(AData("1.1.1.1"))) + List(AData("1.1.1.1")) + ) private val cnameToDelete = RecordSet( okZone.id, "cnameToDelete", @@ -193,7 +201,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { RecordSetStatus.Active, DateTime.now, None, - List(CNAMEData("old.com."))) + List(CNAMEData("old.com.")) + ) private val aToUpdate = RecordSet( okZone.id, "aToUpdate", @@ -202,7 +211,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { RecordSetStatus.Active, DateTime.now, None, - List(AData("1.1.1.1"))) + List(AData("1.1.1.1")) + ) private val cnameToUpdate = RecordSet( okZone.id, "cnameToUpdate", @@ -211,7 +221,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { RecordSetStatus.Active, DateTime.now, None, - List(CNAMEData("old.com."))) + List(CNAMEData("old.com.")) + ) private val txtToUpdate = RecordSet( okZone.id, "txtToUpdate", @@ -220,7 +231,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { RecordSetStatus.Active, DateTime.now, None, - List(TXTData("old"))) + List(TXTData("old")) + ) private val txtToDelete = RecordSet( okZone.id, "txtToDelete", @@ -229,7 +241,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { RecordSetStatus.Active, DateTime.now, None, - List(TXTData("test"))) + List(TXTData("test")) + ) private val mxToUpdate = RecordSet( okZone.id, "mxToUpdate", @@ -238,7 +251,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { RecordSetStatus.Active, DateTime.now, None, - List(MXData(1, "old.com."))) + List(MXData(1, "old.com.")) + ) private val mxToDelete = RecordSet( okZone.id, "mxToDelete", @@ -247,7 +261,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { RecordSetStatus.Active, DateTime.now, None, - List(MXData(1, "delete.com."))) + List(MXData(1, "delete.com.")) + ) private def existingRecordSets = ExistingRecordSets( List( @@ -258,7 +273,9 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { txtToUpdate, txtToDelete, mxToUpdate, - mxToDelete)) + mxToDelete + ) + ) private val batchChangeRepo = new InMemoryBatchChangeRepository private val underTest = new BatchChangeConverter(batchChangeRepo, TestMessageQueue) @@ -272,15 +289,18 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { None, DateTime.now, addSingleChangesGood, - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) val result = rightResultOf( underTest .sendBatchForProcessing( batchChange, existingZones, ChangeForValidationMap(addChangeForValidationGood.map(_.validNel), existingRecordSets), - None) - .value) + None + ) + .value + ) val rsChanges = result.recordSetChanges // validate recordset changes generated from batch @@ -303,7 +323,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { None, DateTime.now, deleteSingleChangesGood, - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) val result = rightResultOf( underTest .sendBatchForProcessing( @@ -311,9 +332,12 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { existingZones, ChangeForValidationMap( deleteRRSetChangeForValidationGood.map(_.validNel), - existingRecordSets), - None) - .value) + existingRecordSets + ), + None + ) + .value + ) val rsChanges = result.recordSetChanges // validate recordset change basics generated from batch @@ -323,7 +347,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { cnameToDelete.name, rsChanges, batchChange, - RecordSetChangeType.Delete) + RecordSetChangeType.Delete + ) validateRecordSetChange(txtToDelete.name, rsChanges, batchChange, RecordSetChangeType.Delete) validateRecordSetChange(mxToDelete.name, rsChanges, batchChange, RecordSetChangeType.Delete) @@ -332,7 +357,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { aToDelete.id, cnameToDelete.id, txtToDelete.id, - mxToDelete.id) + mxToDelete.id + ) // validate statuses unchanged as returned result.batchChange shouldBe batchChange @@ -346,7 +372,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { None, DateTime.now, updateSingleChangesGood, - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) val result = rightResultOf( underTest .sendBatchForProcessing( @@ -354,9 +381,12 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { existingZones, ChangeForValidationMap( updateChangeForValidationGood.map(_.validNel), - existingRecordSets), - None) - .value) + existingRecordSets + ), + None + ) + .value + ) val rsChanges = result.recordSetChanges // validate recordset changes generated from batch @@ -371,7 +401,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { aToUpdate.id, cnameToUpdate.id, txtToUpdate.id, - mxToUpdate.id) + mxToUpdate.id + ) // validate statuses unchanged as returned result.batchChange shouldBe batchChange @@ -388,15 +419,18 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { None, DateTime.now, changes, - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) val result = rightResultOf( underTest .sendBatchForProcessing( batchChange, existingZones, ChangeForValidationMap(changeForValidation.map(_.validNel), existingRecordSets), - None) - .value) + None + ) + .value + ) val rsChanges = result.recordSetChanges // validate recordset changes generated from batch @@ -436,15 +470,18 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) val result = rightResultOf( underTest .sendBatchForProcessing( batchChange, existingZones, ChangeForValidationMap(List(), existingRecordSets), - None) - .value) + None + ) + .value + ) result.batchChange shouldBe batchChange } @@ -457,15 +494,18 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { None, DateTime.now, singleChangesOneBad, - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) val result = rightResultOf( underTest .sendBatchForProcessing( batchWithBadChange, existingZones, ChangeForValidationMap(changeForValidationOneBad.map(_.validNel), existingRecordSets), - None) - .value) + None + ) + .value + ) val rsChanges = result.recordSetChanges rsChanges.length shouldBe 3 @@ -500,7 +540,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { None, DateTime.now, singleChangesOneUnsupported, - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) val result = leftResultOf( underTest .sendBatchForProcessing( @@ -508,9 +549,12 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { existingZones, ChangeForValidationMap( changeForValidationOneUnsupported.map(_.validNel), - existingRecordSets), - None) - .value) + existingRecordSets + ), + None + ) + .value + ) result shouldBe an[BatchConversionError] val notSaved: Option[BatchChange] = @@ -533,7 +577,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { Set(singleAddChange.recordData), okUser.id, None, - None) + None + ) result shouldBe defined result.foreach(_.recordSet.ownerGroupId shouldBe None) } @@ -548,7 +593,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { Set(singleAddChange.recordData), okUser.id, None, - ownerGroupId) + ownerGroupId + ) result shouldBe defined result.foreach(_.recordSet.ownerGroupId shouldBe ownerGroupId) } @@ -563,7 +609,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { Set(singleAddChange.recordData), okUser.id, None, - ownerGroupId) + ownerGroupId + ) result shouldBe defined result.foreach(_.recordSet.ownerGroupId shouldBe None) } @@ -630,7 +677,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { name: String, recordSetChanges: List[RecordSetChange], batchChange: BatchChange, - typ: RecordSetChangeType) = { + typ: RecordSetChangeType + ) = { val singleChangesOut = batchChange.changes.filter { change => change.recordName match { case Some(rn) if rn == name => true @@ -659,7 +707,8 @@ class BatchChangeConverterSpec extends WordSpec with Matchers with CatsHelpers { private def validateRecordDataCombination( name: String, recordSetChanges: List[RecordSetChange], - batchChange: BatchChange) = { + batchChange: BatchChange + ) = { val singleChangesOut = batchChange.changes.filter { change => change.recordName match { case Some(rn) if rn == name => true diff --git a/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeInputSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeInputSpec.scala index d141c5df6..66b90d4d5 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeInputSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeInputSpec.scala @@ -42,7 +42,8 @@ class BatchChangeInputSpec extends WordSpec with Matchers { val input = BatchChangeInput( None, List(changeA, changeAAAA, changeCname, changeADotted, changeAAAADotted, changeCnameDotted), - None) + None + ) input.changes(0).inputName shouldBe "apex.test.com." input.changes(1).inputName shouldBe "aaaa.test.com." @@ -141,7 +142,8 @@ class BatchChangeInputSpec extends WordSpec with Matchers { BatchChangeInput( Some("comments"), List(expectedAddChange, expectedDelChange), - Some("owner")) + Some("owner") + ) BatchChangeInput(change) shouldBe expectedInput } diff --git a/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeServiceSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeServiceSpec.scala index 773a6a1f2..7c514dac9 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeServiceSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeServiceSpec.scala @@ -87,7 +87,8 @@ class BatchChangeServiceSpec "cname.55.144.10.in-addr.arpa", RecordType.CNAME, ttl, - CNAMEData("testing.cname.com.")) + CNAMEData("testing.cname.com.") + ) private val ptrAdd = AddChangeInput("10.144.55.11", RecordType.PTR, ttl, PTRData("ptr")) private val ptrAdd2 = AddChangeInput("10.144.55.255", RecordType.PTR, ttl, PTRData("ptr")) private val ptrDelegatedAdd = AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("ptr")) @@ -121,7 +122,8 @@ class BatchChangeServiceSpec private val ptrV6AddForVal = AddChangeForValidation( ipv6PTRZone, "9.2.3.8.2.4.0.0.0.0.f.f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0", - ptrV6Add) + ptrV6Add + ) private val defaultv6Discovery = new V6DiscoveryNibbleBoundaries(5, 16) @@ -136,7 +138,8 @@ class BatchChangeServiceSpec SingleChangeStatus.Pending, None, None, - None) + None + ) private val singleChangeGood = SingleAddChange( Some(baseZone.id), @@ -184,14 +187,16 @@ class BatchChangeServiceSpec batchChange: BatchChange, existingZones: ExistingZones, groupedChanges: ChangeForValidationMap, - ownerGroupId: Option[String]): BatchResult[BatchConversionOutput] = + ownerGroupId: Option[String] + ): BatchResult[BatchConversionOutput] = batchChange.comments match { case Some("conversionError") => BatchConversionError(pendingChange).toLeftBatchResult case Some("checkConverter") => // hacking reviewComment to determine if things were sent to the converter BatchConversionOutput( batchChange.copy(reviewComment = Some("batchSentToConverter")), - List()).toRightBatchResult + List() + ).toRightBatchResult case _ => BatchConversionOutput(batchChange, List()).toRightBatchResult } } @@ -202,7 +207,8 @@ class BatchChangeServiceSpec zoneId: String, name: String, typ: RecordType, - recordData: Option[List[RecordData]] = None): RecordSet = { + recordData: Option[List[RecordData]] = None + ): RecordSet = { val records = recordData.getOrElse(List()) RecordSet(zoneId, name, typ, 100, RecordSetStatus.Active, DateTime.now(), records = records) } @@ -214,7 +220,8 @@ class BatchChangeServiceSpec nonApexAddForVal.zone.id, nonApexAddForVal.recordName, TXT, - recordData = Some(List(TXTData("some data")))) + recordData = Some(List(TXTData("some data"))) + ) private val existingPtr: RecordSet = makeRS(ptrAddForVal.zone.id, ptrAddForVal.recordName, PTR) private val existingPtrDelegated: RecordSet = @@ -233,7 +240,8 @@ class BatchChangeServiceSpec (existingPtrDelegated, "193.64/25.55.144.10.in-addr.arpa."), ( existingPtrV6, - "9.2.3.8.2.4.0.0.0.0.f.f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.0.0.2.ip6.arpa."), + "9.2.3.8.2.4.0.0.0.0.f.f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.0.0.2.ip6.arpa." + ), (deletedZoneApex, "apex.test.com.") ) @@ -304,7 +312,8 @@ class BatchChangeServiceSpec otherPTRZone, ipv6PTR16Zone, ipv6PTR17Zone, - ipv6PTR18Zone) + ipv6PTR18Zone + ) override def getZonesByNames(zoneNames: Set[String]): IO[Set[Zone]] = IO.pure(dbZones.filter(zn => zoneNames.contains(zn.name))) @@ -338,7 +347,8 @@ class BatchChangeServiceSpec override def getUsers( userIds: Set[String], startFrom: Option[String], - maxItems: Option[Int]): IO[ListUsersResults] = + maxItems: Option[Int] + ): IO[ListUsersResults] = IO.pure(ListUsersResults(Seq(superUser), None)) } @@ -415,7 +425,8 @@ class BatchChangeServiceSpec "2001:0000:0000:0001:0000:ff00:0042:8329", RecordType.PTR, ttl, - PTRData("ptr")) + PTRData("ptr") + ) val input = BatchChangeInput(None, List(ptr), Some(authGrp.id)) @@ -444,7 +455,8 @@ class BatchChangeServiceSpec "2001:0000:0000:0001:0000:ff00:0042:8329", RecordType.PTR, ttl, - PTRData("ptr")) + PTRData("ptr") + ) val input = BatchChangeInput(None, List(ptr), Some(authGrp.id)) @@ -476,7 +488,8 @@ class BatchChangeServiceSpec result shouldBe InvalidBatchChangeInput( - List(NotAMemberOfOwnerGroup(ownerGroupId, notAuth.signedInUser.userName))) + List(NotAMemberOfOwnerGroup(ownerGroupId, notAuth.signedInUser.userName)) + ) } "succeed if owner group ID is provided and user is a member of the group" in { @@ -493,7 +506,8 @@ class BatchChangeServiceSpec rightResultOf( underTest .applyBatchChange(input, AuthPrincipal(superUser, Seq(baseZone.adminGroupId)), true) - .value) + .value + ) result.changes.length shouldBe 1 } @@ -525,7 +539,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(pendingChange), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) batchChangeRepo.save(batchChange) doReturn(IO.unit).when(mockNotifier).notify(any[Notification[_]]) @@ -536,8 +551,10 @@ class BatchChangeServiceSpec .rejectBatchChange( batchChange.id, supportUserAuth, - RejectBatchChangeInput(Some("review comment"))) - .value) + RejectBatchChangeInput(Some("review comment")) + ) + .value + ) result.status shouldBe BatchChangeStatus.Rejected result.approvalStatus shouldBe BatchChangeApprovalStatus.ManuallyRejected @@ -557,7 +574,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(pendingChange), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) batchChangeRepo.save(batchChange) val rejectAuth = AuthPrincipal(supportUser.copy(isTest = true), List()) @@ -565,7 +583,8 @@ class BatchChangeServiceSpec rightResultOf( underTestManualEnabled .rejectBatchChange(batchChange.id, rejectAuth, RejectBatchChangeInput(Some("bad"))) - .value) + .value + ) result.status shouldBe BatchChangeStatus.Rejected } @@ -577,7 +596,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(pendingChange), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) batchChangeRepo.save(batchChange) val rejectAuth = AuthPrincipal(supportUser.copy(isTest = true), List()) @@ -585,7 +605,8 @@ class BatchChangeServiceSpec leftResultOf( underTestManualEnabled .rejectBatchChange(batchChange.id, rejectAuth, RejectBatchChangeInput(Some("bad"))) - .value) + .value + ) result shouldBe UserNotAuthorizedError(batchChange.id) } @@ -597,14 +618,16 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val result = leftResultOf( underTest .rejectBatchChange(batchChange.id, supportUserAuth, RejectBatchChangeInput()) - .value) + .value + ) result shouldBe BatchChangeNotPendingReview(batchChange.id) } @@ -617,12 +640,14 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) batchChangeRepo.save(batchChange) val result = leftResultOf( - underTest.rejectBatchChange(batchChange.id, auth, RejectBatchChangeInput()).value) + underTest.rejectBatchChange(batchChange.id, auth, RejectBatchChangeInput()).value + ) result shouldBe UserNotAuthorizedError(batchChange.id) } @@ -635,12 +660,14 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val result = leftResultOf( - underTest.rejectBatchChange(batchChange.id, auth, RejectBatchChangeInput()).value) + underTest.rejectBatchChange(batchChange.id, auth, RejectBatchChangeInput()).value + ) result shouldBe UserNotAuthorizedError(batchChange.id) } @@ -665,8 +692,10 @@ class BatchChangeServiceSpec .approveBatchChange( batchChangeNeedsApproval.id, supportUserAuth, - ApproveBatchChangeInput(Some("reviewed!"))) - .value) + ApproveBatchChangeInput(Some("reviewed!")) + ) + .value + ) result.userId shouldBe batchChangeNeedsApproval.userId result.userName shouldBe batchChangeNeedsApproval.userName @@ -691,8 +720,10 @@ class BatchChangeServiceSpec .approveBatchChange( batchChangeNeedsApproval.id, auth, - ApproveBatchChangeInput(Some("reviewed!"))) - .value) + ApproveBatchChangeInput(Some("reviewed!")) + ) + .value + ) result shouldBe UserNotAuthorizedError(batchChangeNeedsApproval.id) } @@ -705,7 +736,8 @@ class BatchChangeServiceSpec leftResultOf( underTest .approveBatchChange(batchChange.id, supportUserAuth, ApproveBatchChangeInput()) - .value) + .value + ) result shouldBe BatchChangeNotPendingReview(batchChange.id) } @@ -717,7 +749,8 @@ class BatchChangeServiceSpec leftResultOf( underTest .approveBatchChange(batchChangeNeedsApproval.id, auth, ApproveBatchChangeInput()) - .value) + .value + ) result shouldBe UserNotAuthorizedError(batchChangeNeedsApproval.id) } @@ -729,7 +762,8 @@ class BatchChangeServiceSpec val result = leftResultOf( - underTest.approveBatchChange(batchChange.id, auth, ApproveBatchChangeInput()).value) + underTest.approveBatchChange(batchChange.id, auth, ApproveBatchChangeInput()).value + ) result shouldBe UserNotAuthorizedError(batchChange.id) } @@ -742,14 +776,16 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) batchChangeRepo.save(batchChange) val result = leftResultOf( underTest .approveBatchChange(batchChange.id, superUserAuth, ApproveBatchChangeInput()) - .value) + .value + ) result shouldBe BatchRequesterNotFound("someOtherUserId", "someUn") } @@ -764,14 +800,16 @@ class BatchChangeServiceSpec None, DateTime.now, List(pendingChange), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) batchChangeRepo.save(batchChange) val result = rightResultOf( underTest .cancelBatchChange(batchChange.id, auth) - .value) + .value + ) result.status shouldBe BatchChangeStatus.Cancelled result.approvalStatus shouldBe BatchChangeApprovalStatus.Cancelled @@ -787,7 +825,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(pendingChange), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) batchChangeRepo.save(batchChange) val result = @@ -804,14 +843,16 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val result = leftResultOf( underTest .cancelBatchChange(batchChange.id, auth) - .value) + .value + ) result shouldBe BatchChangeNotPendingReview(batchChange.id) } @@ -824,14 +865,16 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val result = leftResultOf( underTest .cancelBatchChange(batchChange.id, supportUserAuth) - .value) + .value + ) result shouldBe BatchChangeNotPendingReview(batchChange.id) } @@ -846,7 +889,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val result = rightResultOf(underTest.getBatchChange(batchChange.id, auth).value) @@ -867,7 +911,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val result = leftResultOf(underTest.getBatchChange(batchChange.id, notAuth).value) @@ -882,7 +927,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val authSuper = notAuth.copy(signedInUser = notAuth.signedInUser.copy(isSuper = true)) @@ -899,7 +945,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val authSuper = notAuth.copy(signedInUser = notAuth.signedInUser.copy(isSupport = true)) @@ -918,7 +965,8 @@ class BatchChangeServiceSpec DateTime.now, List(), ownerGroupId = Some(okGroup.id), - BatchChangeApprovalStatus.AutoApproved) + BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val result = rightResultOf(underTest.getBatchChange(batchChange.id, auth).value) @@ -934,7 +982,8 @@ class BatchChangeServiceSpec DateTime.now, List(), ownerGroupId = Some("no-existo"), - BatchChangeApprovalStatus.AutoApproved) + BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val result = rightResultOf(underTest.getBatchChange(batchChange.id, auth).value) @@ -973,7 +1022,8 @@ class BatchChangeServiceSpec ptrAddForVal.validNel, ptrDelegatedAddForVal.validNel, ptrV6AddForVal.validNel, - error) + error + ) val zoneMap = ExistingZones(Set(apexZone, baseZone, ptrZone, delegatedPTRZone, ipv6PTRZone)) val result = await(underTest.getExistingRecordSets(in, zoneMap)) @@ -989,7 +1039,8 @@ class BatchChangeServiceSpec ptrAddForVal.validNel, ptrDelegatedAddForVal.validNel, ptrV6AddForVal.validNel, - error) + error + ) val zoneMap = ExistingZones(Set(apexZone, baseZone, ptrZone, ipv6PTRZone)) val result = await(underTest.getExistingRecordSets(in, zoneMap)) @@ -1184,7 +1235,8 @@ class BatchChangeServiceSpec underTest.zoneDiscovery(List(onlyApexAddA.validNel), ExistingZones(Set(onlyApexZone))) result should containChangeForValidation( - AddChangeForValidation(onlyApexZone, "only.apex.exists.", onlyApexAddA)) + AddChangeForValidation(onlyApexZone, "only.apex.exists.", onlyApexAddA) + ) } "map the batch change input to the base zone if only the base zone exists for A records" in { @@ -1192,7 +1244,8 @@ class BatchChangeServiceSpec underTest.zoneDiscovery(List(onlyBaseAddAAAA.validNel), ExistingZones(Set(onlyBaseZone))) result should containChangeForValidation( - AddChangeForValidation(onlyBaseZone, "have", onlyBaseAddAAAA)) + AddChangeForValidation(onlyBaseZone, "have", onlyBaseAddAAAA) + ) } "map the batch change input to the base zone only for CNAME records" in { @@ -1218,7 +1271,8 @@ class BatchChangeServiceSpec val discovered = underTest.zoneDiscovery( List(aApex.validNel, aNormal.validNel, aDotted.validNel), - ExistingZones(Set(apexZone, baseZone))) + ExistingZones(Set(apexZone, baseZone)) + ) discovered.getValid shouldBe expected } @@ -1239,7 +1293,8 @@ class BatchChangeServiceSpec val discovered = underTest.zoneDiscovery( List(txtApex.validNel, txtNormal.validNel, txtDotted.validNel), - ExistingZones(Set(apexZone, baseZone))) + ExistingZones(Set(apexZone, baseZone)) + ) discovered.getValid shouldBe expected } @@ -1266,29 +1321,35 @@ class BatchChangeServiceSpec "handle mapping a combination of zone discovery successes and failures" in { val result = underTest.zoneDiscovery( List(apexAddA.validNel, onlyApexAddA.validNel, onlyBaseAddAAAA.validNel, cnameAdd.validNel), - ExistingZones(Set(apexZone, baseZone, onlyBaseZone))) + ExistingZones(Set(apexZone, baseZone, onlyBaseZone)) + ) result.head should beValid[ChangeForValidation](apexAddForVal) result(1) should haveInvalid[DomainValidationError](ZoneDiscoveryError("only.apex.exists.")) result(2) should beValid[ChangeForValidation]( - AddChangeForValidation(onlyBaseZone, "have", onlyBaseAddAAAA)) + AddChangeForValidation(onlyBaseZone, "have", onlyBaseAddAAAA) + ) result(3) should beValid[ChangeForValidation]( - AddChangeForValidation(baseZone, "cname", cnameAdd)) + AddChangeForValidation(baseZone, "cname", cnameAdd) + ) } "map the batch change input to the delegated PTR zone for PTR records (ipv4)" in { val result = underTest.zoneDiscovery( List(ptrAdd.validNel), - ExistingZones(Set(delegatedPTRZone, ptrZone))) + ExistingZones(Set(delegatedPTRZone, ptrZone)) + ) result should containChangeForValidation( - AddChangeForValidation(delegatedPTRZone, "11", ptrAdd)) + AddChangeForValidation(delegatedPTRZone, "11", ptrAdd) + ) } "map the batch change input to the non delegated PTR zone for PTR records (ipv4)" in { val result = underTest.zoneDiscovery( List(ptrAdd2.validNel), - ExistingZones(Set(delegatedPTRZone, ptrZone))) + ExistingZones(Set(delegatedPTRZone, ptrZone)) + ) result should containChangeForValidation(AddChangeForValidation(ptrZone, "255", ptrAdd2)) } @@ -1302,7 +1363,8 @@ class BatchChangeServiceSpec "return an error for PTR if there are zone matches for the IP but no match on the record name" in { val result = underTest.zoneDiscovery( List(ptrAdd.validNel), - ExistingZones(Set(delegatedPTRZone.copy(name = "192/30.55.144.10.in-addr.arpa.")))) + ExistingZones(Set(delegatedPTRZone.copy(name = "192/30.55.144.10.in-addr.arpa."))) + ) result.head should haveInvalid[DomainValidationError](ZoneDiscoveryError(ptrAdd.inputName)) } @@ -1318,41 +1380,52 @@ class BatchChangeServiceSpec "2001:0db8:0111:0000:0000:ff00:0042:8329", RecordType.PTR, ttl, - PTRData("ptr")) + PTRData("ptr") + ) val bigZoneAdd = AddChangeInput( "2001:0000:0000:0000:0000:ff00:0042:8329", RecordType.PTR, ttl, - PTRData("ptr")) + PTRData("ptr") + ) val notFoundZoneAdd = AddChangeInput("::1", RecordType.PTR, ttl, PTRData("ptr")) val ptripv6Adds = List( smallZoneAdd.validNel, medZoneAdd.validNel, bigZoneAdd.validNel, - notFoundZoneAdd.validNel) + notFoundZoneAdd.validNel + ) val result = underTest.zoneDiscovery( ptripv6Adds, - ExistingZones(Set(ptrv6ZoneSmall, ptrv6ZoneMed, ptrv6ZoneBig))) + ExistingZones(Set(ptrv6ZoneSmall, ptrv6ZoneMed, ptrv6ZoneBig)) + ) result should containChangeForValidation( AddChangeForValidation( ptrv6ZoneSmall, "9.2.3.8.2.4.0.0.0.0.f.f.0.0.0.0.0.0.0.0", - smallZoneAdd)) + smallZoneAdd + ) + ) result should containChangeForValidation( AddChangeForValidation( ptrv6ZoneMed, "9.2.3.8.2.4.0.0.0.0.f.f.0.0.0.0.0.0.0.0.1.1.1", - medZoneAdd)) + medZoneAdd + ) + ) result should containChangeForValidation( AddChangeForValidation( ptrv6ZoneBig, "9.2.3.8.2.4.0.0.0.0.f.f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0", - bigZoneAdd)) + bigZoneAdd + ) + ) result(3) should haveInvalid[DomainValidationError]( - ZoneDiscoveryError(notFoundZoneAdd.inputName)) + ZoneDiscoveryError(notFoundZoneAdd.inputName) + ) } } @@ -1490,7 +1563,8 @@ class BatchChangeServiceSpec None, List(apexAddA), Some("owner-group-id"), - scheduledTime = Some(DateTime.now.plusMinutes(1))), + scheduledTime = Some(DateTime.now.plusMinutes(1)) + ), List( AddChangeForValidation(apexZone, "apex.test.com.", apexAddA).validNel ), @@ -1526,7 +1600,8 @@ class BatchChangeServiceSpec None, List(apexAddA), None, - scheduledTime = Some(DateTime.now.plusMinutes(1))), + scheduledTime = Some(DateTime.now.plusMinutes(1)) + ), List( AddChangeForValidation(apexZone, "apex.test.com.", apexAddA).validNel ), @@ -1625,7 +1700,8 @@ class BatchChangeServiceSpec None, List(apexAddA), Some("owner-group-id"), - Some(DateTime.now.plusMinutes(1))), + Some(DateTime.now.plusMinutes(1)) + ), List( AddChangeForValidation(apexZone, "apex.test.com.", apexAddA).validNel, nonFatalError.invalidNel, @@ -1662,7 +1738,8 @@ class BatchChangeServiceSpec List( ZoneDiscoveryError("no.zone.match.").invalidNel, AddChangeForValidation(baseZone, "non-apex", nonApexAddA).validNel, - nonFatalError.invalidNel), + nonFatalError.invalidNel + ), okAuth, true ) @@ -1672,9 +1749,11 @@ class BatchChangeServiceSpec result shouldBe an[InvalidBatchChangeResponses] val ibcr = result.asInstanceOf[InvalidBatchChangeResponses] ibcr.changeRequestResponses.head should haveInvalid[DomainValidationError]( - ZoneDiscoveryError("no.zone.match.")) + ZoneDiscoveryError("no.zone.match.") + ) ibcr.changeRequestResponses(1) shouldBe Valid( - AddChangeForValidation(baseZone, "non-apex", nonApexAddA)) + AddChangeForValidation(baseZone, "non-apex", nonApexAddA) + ) ibcr.changeRequestResponses(2) should haveInvalid[DomainValidationError](nonFatalError) } @@ -1706,7 +1785,8 @@ class BatchChangeServiceSpec None, List(apexAddA, onlyBaseAddAAAA, delete), None, - Some(DateTime.now.plusMinutes(1))), + Some(DateTime.now.plusMinutes(1)) + ), List( AddChangeForValidation(apexZone, "apex.test.com.", apexAddA).validNel, nonFatalError.invalidNel, @@ -1728,7 +1808,8 @@ class BatchChangeServiceSpec None, List(noZoneAddA, nonApexAddA), None, - Some(DateTime.now.plusMinutes(1))), + Some(DateTime.now.plusMinutes(1)) + ), List( ZoneDiscoveryError("no.zone.match.", fatal = true).invalidNel, AddChangeForValidation(baseZone, "non-apex", nonApexAddA).validNel @@ -1770,7 +1851,8 @@ class BatchChangeServiceSpec None, List(apexAddA), Some("owner-group-id"), - Some(DateTime.now.plusMinutes(1))), + Some(DateTime.now.plusMinutes(1)) + ), List( AddChangeForValidation(apexZone, "apex.test.com.", apexAddA).validNel, nonFatalError.invalidNel, @@ -1825,7 +1907,8 @@ class BatchChangeServiceSpec AddChangeForValidation( baseZone, singleChangeGood.inputName.split('.').head, - asAdds.head).validNel, + asAdds.head + ).validNel, AddChangeForValidation(baseZone, singleChangeNR.inputName.split('.').head, asAdds(1)).validNel ), reviewInfo @@ -1844,7 +1927,8 @@ class BatchChangeServiceSpec AddChangeForValidation( baseZone, singleChangeGood.inputName.split('.').head, - asAdds.head).validNel, + asAdds.head + ).validNel, fatalError.invalidNel ), reviewInfo @@ -1894,7 +1978,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeOne) val batchChangeTwo = BatchChange( @@ -1903,7 +1988,8 @@ class BatchChangeServiceSpec None, new DateTime(DateTime.now.getMillis + 1000), List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeTwo) val result = rightResultOf(underTest.listBatchChangeSummaries(auth, maxItems = 100).value) @@ -1926,7 +2012,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeOne) val batchChangeTwo = BatchChange( @@ -1935,7 +2022,8 @@ class BatchChangeServiceSpec None, new DateTime(DateTime.now.getMillis + 1000), List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeTwo) val result = rightResultOf(underTest.listBatchChangeSummaries(auth, maxItems = 1).value) @@ -1957,7 +2045,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) batchChangeRepo.save(batchChangeOne) val batchChangeTwo = BatchChange( @@ -1966,15 +2055,18 @@ class BatchChangeServiceSpec None, new DateTime(DateTime.now.getMillis + 1000), List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeTwo) val result = rightResultOf( underTest .listBatchChangeSummaries( auth, - approvalStatus = Some(BatchChangeApprovalStatus.PendingReview)) - .value) + approvalStatus = Some(BatchChangeApprovalStatus.PendingReview) + ) + .value + ) result.maxItems shouldBe 100 result.nextId shouldBe None @@ -1994,7 +2086,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeOne) val batchChangeTwo = BatchChange( @@ -2003,7 +2096,8 @@ class BatchChangeServiceSpec None, new DateTime(DateTime.now.getMillis + 1000), List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeTwo) val result = @@ -2026,7 +2120,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeUserOne) val batchChangeUserTwo = BatchChange( @@ -2035,7 +2130,8 @@ class BatchChangeServiceSpec None, new DateTime(DateTime.now.getMillis + 1000), List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeUserTwo) val result = @@ -2053,7 +2149,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeUserOne) val batchChangeUserTwo = BatchChange( @@ -2062,7 +2159,8 @@ class BatchChangeServiceSpec None, new DateTime(DateTime.now.getMillis + 1000), List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeUserTwo) val result = @@ -2080,7 +2178,8 @@ class BatchChangeServiceSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeUserOne) val batchChangeUserTwo = BatchChange( @@ -2089,7 +2188,8 @@ class BatchChangeServiceSpec None, new DateTime(DateTime.now.getMillis + 1000), List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChangeUserTwo) val result = @@ -2121,7 +2221,8 @@ class BatchChangeServiceSpec DateTime.now, List(), ownerGroupId = Some(okGroup.id), - BatchChangeApprovalStatus.AutoApproved) + BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val result = rightResultOf(underTest.listBatchChangeSummaries(auth, maxItems = 100).value) @@ -2145,7 +2246,8 @@ class BatchChangeServiceSpec DateTime.now, List(), ownerGroupId = Some("no-existo"), - BatchChangeApprovalStatus.AutoApproved) + BatchChangeApprovalStatus.AutoApproved + ) batchChangeRepo.save(batchChange) val result = rightResultOf(underTest.listBatchChangeSummaries(auth, maxItems = 100).value) @@ -2198,7 +2300,8 @@ class BatchChangeServiceSpec Some("checkConverter"), DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) val result = rightResultOf( underTestManualEnabled @@ -2206,8 +2309,10 @@ class BatchChangeServiceSpec batchChange, ExistingZones(Set()), ChangeForValidationMap(List(), ExistingRecordSets(List())), - None) - .value) + None + ) + .value + ) result.reviewComment shouldBe Some("batchSentToConverter") } "not send to the converter, save the change if PendingReview and MA enabled" in { @@ -2218,7 +2323,8 @@ class BatchChangeServiceSpec Some("checkConverter"), DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) val result = rightResultOf( underTestManualEnabled @@ -2226,8 +2332,10 @@ class BatchChangeServiceSpec batchChange, ExistingZones(Set()), ChangeForValidationMap(List(), ExistingRecordSets(List())), - None) - .value) + None + ) + .value + ) // not sent to converter result.reviewComment shouldBe None @@ -2242,7 +2350,8 @@ class BatchChangeServiceSpec Some("checkConverter"), DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) val result = leftResultOf( underTest @@ -2250,8 +2359,10 @@ class BatchChangeServiceSpec batchChange, ExistingZones(Set()), ChangeForValidationMap(List(), ExistingRecordSets(List())), - None) - .value) + None + ) + .value + ) result shouldBe an[UnknownConversionError] } @@ -2263,7 +2374,8 @@ class BatchChangeServiceSpec Some("checkConverter"), DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.ManuallyApproved) + approvalStatus = BatchChangeApprovalStatus.ManuallyApproved + ) val result = leftResultOf( underTest @@ -2271,8 +2383,10 @@ class BatchChangeServiceSpec batchChange, ExistingZones(Set()), ChangeForValidationMap(List(), ExistingRecordSets(List())), - None) - .value) + None + ) + .value + ) result shouldBe an[UnknownConversionError] } } @@ -2357,10 +2471,13 @@ class BatchChangeServiceSpec okGroup.id, OwnerType.Zone, Some(okGroup.email), - Some(okGroup.name))) + Some(okGroup.name) + ) + ) result(1) should beValid[ChangeForValidation]( - AddChangeForValidation(apexZone, "apex.test.com.", apexAddA)) + AddChangeForValidation(apexZone, "apex.test.com.", apexAddA) + ) } } } diff --git a/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeValidationsSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeValidationsSpec.scala index 6765863d8..b8ccd5f7e 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeValidationsSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchChangeValidationsSpec.scala @@ -60,14 +60,16 @@ class BatchChangeValidationsSpec "test@test.com", status = ZoneStatus.Active, connection = testConnection, - adminGroupId = okGroup.id) + adminGroupId = okGroup.id + ) private val validIp4ReverseZone = Zone( "2.0.192.in-addr.arpa", "test@test.com", status = ZoneStatus.Active, connection = testConnection, - adminGroupId = okGroup.id) + adminGroupId = okGroup.id + ) private val ttl = Some(100L) @@ -103,32 +105,38 @@ class BatchChangeValidationsSpec private val createPrivateAddChange = AddChangeForValidation( okZone, "private-create", - AddChangeInput("private-create", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("private-create", RecordType.A, ttl, AData("1.1.1.1")) + ) private val createSharedAddChange = AddChangeForValidation( sharedZone, "shared-create", - AddChangeInput("shared-create", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("shared-create", RecordType.A, ttl, AData("1.1.1.1")) + ) private val updatePrivateAddChange = AddChangeForValidation( okZone, "private-update", - AddChangeInput("private-update", RecordType.A, ttl, AAAAData("1.2.3.4"))) + AddChangeInput("private-update", RecordType.A, ttl, AAAAData("1.2.3.4")) + ) private val updatePrivateDeleteChange = DeleteRRSetChangeForValidation( okZone, "private-update", - DeleteRRSetChangeInput("private-update", RecordType.A)) + DeleteRRSetChangeInput("private-update", RecordType.A) + ) private val updateSharedAddChange = AddChangeForValidation( sharedZone, "shared-update", - AddChangeInput("shared-update", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8"))) + AddChangeInput("shared-update", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8")) + ) private val updateSharedDeleteChange = DeleteRRSetChangeForValidation( sharedZone, "shared-update", - DeleteRRSetChangeInput("shared-update", RecordType.AAAA)) + DeleteRRSetChangeInput("shared-update", RecordType.AAAA) + ) private val deletePrivateChange = DeleteRRSetChangeForValidation( okZone, @@ -148,7 +156,8 @@ class BatchChangeValidationsSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) private val invalidPendingBatchChange = BatchChange( okUser.id, @@ -156,23 +165,28 @@ class BatchChangeValidationsSpec None, DateTime.now, List(), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) private def makeAddUpdateRecord( recordName: String, - aData: AData = AData("1.2.3.4")): AddChangeForValidation = + aData: AData = AData("1.2.3.4") + ): AddChangeForValidation = AddChangeForValidation( okZone, s"$recordName", - AddChangeInput(s"$recordName.ok.", RecordType.A, ttl, aData)) + AddChangeInput(s"$recordName.ok.", RecordType.A, ttl, aData) + ) private def makeDeleteUpdateDeleteRRSet( recordName: String, - recordData: Option[RecordData] = None): DeleteRRSetChangeForValidation = + recordData: Option[RecordData] = None + ): DeleteRRSetChangeForValidation = DeleteRRSetChangeForValidation( okZone, s"$recordName", - DeleteRRSetChangeInput(s"$recordName.ok.", RecordType.A, recordData)) + DeleteRRSetChangeInput(s"$recordName.ok.", RecordType.A, recordData) + ) property("validateBatchChangeInputSize: should fail if batch has no changes") { validateBatchChangeInputSize(BatchChangeInput(None, List())) should @@ -180,32 +194,37 @@ class BatchChangeValidationsSpec } property( - "validateBatchChangeInputSize: should succeed with at least one but fewer than max inputs") { + "validateBatchChangeInputSize: should succeed with at least one but fewer than max inputs" + ) { forAll(validBatchChangeInput(1, maxChanges)) { input: BatchChangeInput => validateBatchChangeInputSize(input).isValid shouldBe true } forAll(validBatchChangeInput(maxChanges + 1, 100)) { input: BatchChangeInput => validateBatchChangeInputSize(input) should haveInvalid[DomainValidationError]( - ChangeLimitExceeded(maxChanges)) + ChangeLimitExceeded(maxChanges) + ) } } property( - "validateScheduledChange: should fail if batch is scheduled and scheduled change disabled") { + "validateScheduledChange: should fail if batch is scheduled and scheduled change disabled" + ) { val input = BatchChangeInput(None, List(), scheduledTime = Some(DateTime.now)) validateScheduledChange(input, scheduledChangesEnabled = false) should beLeft[BatchChangeErrorResponse](ScheduledChangesDisabled) } property( - "validateScheduledChange: should succeed if batch is scheduled and scheduled change enabled") { + "validateScheduledChange: should succeed if batch is scheduled and scheduled change enabled" + ) { val input = BatchChangeInput(None, List(), scheduledTime = Some(DateTime.now.plusHours(1))) validateScheduledChange(input, scheduledChangesEnabled = true) should beRight(()) } property( - "validateScheduledChange: should succeed if batch is not scheduled and scheduled change disabled") { + "validateScheduledChange: should succeed if batch is not scheduled and scheduled change disabled" + ) { val input = BatchChangeInput(None, List(), scheduledTime = None) validateScheduledChange(input, scheduledChangesEnabled = false) should beRight(()) } @@ -235,22 +254,27 @@ class BatchChangeValidationsSpec } property( - "validateOwnerGroupId: should fail if user is not an admin and does not belong to owner group") { + "validateOwnerGroupId: should fail if user is not an admin and does not belong to owner group" + ) { validateOwnerGroupId(Some(okGroup.id), Some(okGroup), dummyAuth) should haveInvalid[DomainValidationError]( - NotAMemberOfOwnerGroup(okGroup.id, dummyAuth.signedInUser.userName)) + NotAMemberOfOwnerGroup(okGroup.id, dummyAuth.signedInUser.userName) + ) } property( - "validateBatchChangeInput: should succeed if input size and owner group ID are both valid") { + "validateBatchChangeInput: should succeed if input size and owner group ID are both valid" + ) { forAll(validBatchChangeInput(1, 10)) { batchChangeInput => validateBatchChangeInput(batchChangeInput, None, okAuth).value.unsafeRunSync() should be( - right) + right + ) } } property( - "validateBatchChangeInput: should fail if input size is invalid and owner group ID is valid") { + "validateBatchChangeInput: should fail if input size is invalid and owner group ID is valid" + ) { forAll(validBatchChangeInput(11, 20)) { batchChangeInput => validateBatchChangeInput(batchChangeInput, None, okAuth).value .unsafeRunSync() shouldBe @@ -259,54 +283,68 @@ class BatchChangeValidationsSpec } property( - "validateBatchChangeInput: should fail if input size is valid and owner group ID is invalid") { + "validateBatchChangeInput: should fail if input size is valid and owner group ID is invalid" + ) { forAll(validBatchChangeInput(1, 10)) { batchChangeInput => validateBatchChangeInput( batchChangeInput.copy(ownerGroupId = Some(okGroup.id)), Some(okGroup), - dummyAuth).value.unsafeRunSync() shouldBe + dummyAuth + ).value.unsafeRunSync() shouldBe Left( InvalidBatchChangeInput( - List(NotAMemberOfOwnerGroup(okGroup.id, dummyAuth.signedInUser.userName)))) + List(NotAMemberOfOwnerGroup(okGroup.id, dummyAuth.signedInUser.userName)) + ) + ) } } property( - "validateBatchChangeInput: should fail if both input size is valid and owner group ID are invalid") { + "validateBatchChangeInput: should fail if both input size is valid and owner group ID are invalid" + ) { forAll(validBatchChangeInput(0, 0)) { batchChangeInput => val result = validateBatchChangeInput( batchChangeInput.copy(ownerGroupId = Some(dummyGroup.id)), None, - okAuth).value.unsafeRunSync() + okAuth + ).value.unsafeRunSync() result shouldBe Left( InvalidBatchChangeInput( - List(BatchChangeIsEmpty(maxChanges), GroupDoesNotExist(dummyGroup.id)))) + List(BatchChangeIsEmpty(maxChanges), GroupDoesNotExist(dummyGroup.id)) + ) + ) } } property( - "validateBatchChangeInput: should fail if scheduled is set but scheduled changes disabled") { + "validateBatchChangeInput: should fail if scheduled is set but scheduled changes disabled" + ) { val input = BatchChangeInput( None, List(AddChangeInput("private-create", RecordType.A, ttl, AData("1.1.1.1"))), - scheduledTime = Some(DateTime.now)) + scheduledTime = Some(DateTime.now) + ) val bcv = new BatchChangeValidations(maxChanges, accessValidations, scheduledChangesEnabled = false) bcv.validateBatchChangeInput(input, None, okAuth).value.unsafeRunSync() shouldBe Left( - ScheduledChangesDisabled) + ScheduledChangesDisabled + ) } property( - "validateBatchChangeInput: should fail if scheduled changes is enabled but scheduled time is in the past") { + "validateBatchChangeInput: should fail if scheduled changes is enabled but scheduled time is in the past" + ) { val input = BatchChangeInput( None, List(AddChangeInput("private-create", RecordType.A, ttl, AData("1.1.1.1"))), - scheduledTime = Some(DateTime.now.minusHours(1))) + scheduledTime = Some(DateTime.now.minusHours(1)) + ) val bcv = new BatchChangeValidations(maxChanges, accessValidations, scheduledChangesEnabled = true) bcv.validateBatchChangeInput(input, None, okAuth).value.unsafeRunSync() shouldBe Left( - ScheduledTimeMustBeInFuture) + ScheduledTimeMustBeInFuture + ) } property("validateBatchChangePendingReview: should succeed if batch change is PendingReview") { @@ -344,17 +382,20 @@ class BatchChangeValidationsSpec } property( - "validateAuthorizedReviewer: should fail if a test reviewer tries to approve a non-test change") { + "validateAuthorizedReviewer: should fail if a test reviewer tries to approve a non-test change" + ) { val testSupport = supportUser.copy(isTest = true) validateAuthorizedReviewer(AuthPrincipal(testSupport, List()), validPendingBatchChange, false) shouldBe Left(UserNotAuthorizedError(validPendingBatchChange.id)) } property( - "validateAuthorizedReviewer: should succeed if a test reviewer tries to approve a test change") { + "validateAuthorizedReviewer: should succeed if a test reviewer tries to approve a test change" + ) { val testSupport = supportUser.copy(isTest = true) validateAuthorizedReviewer(AuthPrincipal(testSupport, List()), validPendingBatchChange, true) should be( - right) + right + ) } property("validateAuthorizedReviewer: should fail if the reviewer is not a super or support user") { @@ -364,22 +405,26 @@ class BatchChangeValidationsSpec property( "validateBatchChangeRejection: should succeed if batch change is pending review and reviewer" + - "is authorized") { + "is authorized" + ) { validateBatchChangeRejection(validPendingBatchChange, supportUserAuth, false) should be(right) } property( - "validateBatchChangeRejection: should fail if a test reviewer tries to reject a non-test change") { + "validateBatchChangeRejection: should fail if a test reviewer tries to reject a non-test change" + ) { val testSupport = supportUser.copy(isTest = true) validateBatchChangeRejection(validPendingBatchChange, AuthPrincipal(testSupport, List()), false) shouldBe Left(UserNotAuthorizedError(validPendingBatchChange.id)) } property( - "validateBatchChangeRejection: should succeed if a test reviewer tries to reject a test change") { + "validateBatchChangeRejection: should succeed if a test reviewer tries to reject a test change" + ) { val testSupport = supportUser.copy(isTest = true) validateBatchChangeRejection(validPendingBatchChange, AuthPrincipal(testSupport, List()), true) should be( - right) + right + ) } property("validateBatchChangeRejection: should fail if batch change is not pending review") { @@ -394,27 +439,31 @@ class BatchChangeValidationsSpec property( "validateBatchChangeRejection: should fail if batch change is not pending review and reviewer is not" + - "authorized") { + "authorized" + ) { validateBatchChangeRejection(invalidPendingBatchChange, okAuth, false) shouldBe Left(UserNotAuthorizedError(invalidPendingBatchChange.id)) } property( "validateBatchChangeCancellation: should succeed if batch change is pending review" + - " and user was the creator") { + " and user was the creator" + ) { validateBatchChangeCancellation(validPendingBatchChange, okAuth) should be(right) } property( "validateBatchChangeCancellation: should fail if user was the creator" + - " but batch change is not pending review") { + " but batch change is not pending review" + ) { validateBatchChangeCancellation(invalidPendingBatchChange, okAuth) shouldBe Left(BatchChangeNotPendingReview(invalidPendingBatchChange.id)) } property( "validateBatchChangeCancellation: should fail if batch change is pending review" + - " but user was not the creator") { + " but user was not the creator" + ) { validateBatchChangeCancellation(validPendingBatchChange, supportUserAuth) shouldBe Left(UserNotAuthorizedError(validPendingBatchChange.id)) } @@ -430,7 +479,8 @@ class BatchChangeValidationsSpec val result = validateInputChanges( List(goodInput, goodAAAAInput, invalidDomainNameInput, invalidIpv6Input), - false) + false + ) result(0) shouldBe valid result(1) shouldBe valid result(2) should haveInvalid[DomainValidationError](InvalidDomainName("invalidDomainName$.")) @@ -449,10 +499,12 @@ class BatchChangeValidationsSpec val resultIpV6 = validateInputName(changeIpV6, false) resultA should haveInvalid[DomainValidationError]( - HighValueDomainError("high-value-domain.foo.")) + HighValueDomainError("high-value-domain.foo.") + ) resultIpV4 should haveInvalid[DomainValidationError](HighValueDomainError("192.0.2.252")) resultIpV6 should haveInvalid[DomainValidationError]( - HighValueDomainError("fd69:27cc:fe91:0:0:0:0:ffff")) + HighValueDomainError("fd69:27cc:fe91:0:0:0:0:ffff") + ) } property("""validateInputName: should fail with a RecordRequiresManualReview @@ -467,10 +519,12 @@ class BatchChangeValidationsSpec val resultIpV6 = validateInputName(changeIpV6, false) resultA should haveInvalid[DomainValidationError]( - RecordRequiresManualReview("needs-review.foo.")) + RecordRequiresManualReview("needs-review.foo.") + ) resultIpV4 should haveInvalid[DomainValidationError](RecordRequiresManualReview("192.0.2.254")) resultIpV6 should haveInvalid[DomainValidationError]( - RecordRequiresManualReview("fd69:27cc:fe91:0:0:0:ffff:1")) + RecordRequiresManualReview("fd69:27cc:fe91:0:0:0:ffff:1") + ) } property("doesNotRequireManualReview: should succeed if user is reviewing") { @@ -485,10 +539,12 @@ class BatchChangeValidationsSpec val addChangeForValidation = AddChangeForValidation( Zone("Zone.needs.review", "some@email.com"), "not-allowed", - addChangeInput) + addChangeInput + ) zoneDoesNotRequireManualReview(addChangeForValidation, false) should haveInvalid[DomainValidationError]( - RecordRequiresManualReview("not-allowed.zone.NEEDS.review.")) + RecordRequiresManualReview("not-allowed.zone.NEEDS.review.") + ) } property("""zoneDoesNotRequireManualReview: should succeed if user is reviewing""") { @@ -497,7 +553,8 @@ class BatchChangeValidationsSpec val addChangeForValidation = AddChangeForValidation( Zone("Zone.needs.review", "some@email.com"), "not-allowed", - addChangeInput) + addChangeInput + ) zoneDoesNotRequireManualReview(addChangeForValidation, true) shouldBe valid } @@ -533,7 +590,8 @@ class BatchChangeValidationsSpec } property( - "validateAddChangeInput: should succeed if single addChangeInput is good for AAAA Record") { + "validateAddChangeInput: should succeed if single addChangeInput is good for AAAA Record" + ) { forAll(validAAAAChangeGen) { input: AddChangeInput => val result = validateAddChangeInput(input, false) result shouldBe valid @@ -557,13 +615,15 @@ class BatchChangeValidationsSpec } property( - "validateAddChangeInput: should fail with InvalidRange if validateRange fails for an addChangeInput") { + "validateAddChangeInput: should fail with InvalidRange if validateRange fails for an addChangeInput" + ) { forAll(choose[Long](0, 29)) { invalidTTL: Long => val change = AddChangeInput("test.comcast.com.", RecordType.A, Some(invalidTTL), AData("1.1.1.1")) val result = validateAddChangeInput(change, false) result should haveInvalid[DomainValidationError]( - InvalidTTL(invalidTTL, DomainValidations.TTL_MIN_LENGTH, DomainValidations.TTL_MAX_LENGTH)) + InvalidTTL(invalidTTL, DomainValidations.TTL_MIN_LENGTH, DomainValidations.TTL_MAX_LENGTH) + ) } } @@ -588,7 +648,8 @@ class BatchChangeValidationsSpec val badAChange = AddChangeInput(invalidInputName, RecordType.A, ttl, AData("1.1.1.1")) val result = validateAddChangeInput(badAChange, false) result should haveInvalid[DomainValidationError]( - RecordInReverseZoneError(invalidInputName, RecordType.A.toString)) + RecordInReverseZoneError(invalidInputName, RecordType.A.toString) + ) } property("validateAddChangeInput: should fail if AAAA inputName includes a reverse zone address") { @@ -597,7 +658,8 @@ class BatchChangeValidationsSpec AddChangeInput(invalidInputName, RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8")) val result = validateAddChangeInput(badAAAAChange, false) result should haveInvalid[DomainValidationError]( - RecordInReverseZoneError(invalidInputName, RecordType.AAAA.toString)) + RecordInReverseZoneError(invalidInputName, RecordType.AAAA.toString) + ) } property("""validateAddChangeInput: should fail with InvalidDomainName @@ -618,7 +680,8 @@ class BatchChangeValidationsSpec val result = validateAddChangeInput(change, false) result should haveInvalid[DomainValidationError]( - InvalidLength(s"$invalidCNAMERecordData.", 2, 255)) + InvalidLength(s"$invalidCNAMERecordData.", 2, 255) + ) } property("""validateAddChangeInput: PTR should fail with InvalidIPAddress @@ -639,25 +702,30 @@ class BatchChangeValidationsSpec } property( - "validateChangesWithContext: should properly validate with mix of success and failure inputs") { + "validateChangesWithContext: should properly validate with mix of success and failure inputs" + ) { val authZone = okZone val reverseZone = okZone.copy(name = "2.0.192.in-addr.arpa.") val addA1 = AddChangeForValidation( authZone, "valid", - AddChangeInput("valid.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("valid.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val existingA = AddChangeForValidation( authZone, "existingA", - AddChangeInput("existingA.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("existingA.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val existingCname = AddChangeForValidation( authZone, "existingCname", - AddChangeInput("existingCname.ok.", RecordType.CNAME, ttl, CNAMEData("cname"))) + AddChangeInput("existingCname.ok.", RecordType.CNAME, ttl, CNAMEData("cname")) + ) val addA2 = AddChangeForValidation( okZone, "valid2", - AddChangeInput("valid2.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("valid2.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val duplicateNameCname = AddChangeForValidation( reverseZone, "199", @@ -665,18 +733,22 @@ class BatchChangeValidationsSpec "199.2.0.192.in-addr.arpa.", RecordType.CNAME, ttl, - CNAMEData("199.192/30.2.0.192.in-addr.arpa"))) + CNAMEData("199.192/30.2.0.192.in-addr.arpa") + ) + ) val duplicateNamePTR = AddChangeForValidation( reverseZone, "199", - AddChangeInput("192.0.2.199", RecordType.PTR, ttl, PTRData("ptr.ok."))) + AddChangeInput("192.0.2.199", RecordType.PTR, ttl, PTRData("ptr.ok.")) + ) val existingRsList: List[RecordSet] = List( rsOk.copy(zoneId = existingA.zone.id, name = existingA.recordName), rsOk.copy( zoneId = existingCname.zone.id, name = existingCname.recordName, - typ = RecordType.CNAME) + typ = RecordType.CNAME + ) ) val result = validateChangesWithContext( @@ -687,7 +759,8 @@ class BatchChangeValidationsSpec existingCname.validNel, addA2.validNel, duplicateNameCname.validNel, - duplicateNamePTR.validNel), + duplicateNamePTR.validNel + ), ExistingRecordSets(existingRsList) ), okAuth, @@ -697,14 +770,19 @@ class BatchChangeValidationsSpec result(0) shouldBe valid result(1) should haveInvalid[DomainValidationError]( - RecordAlreadyExists(existingA.inputChange.inputName)) + RecordAlreadyExists(existingA.inputChange.inputName) + ) result(2) should haveInvalid[DomainValidationError]( - RecordAlreadyExists(existingCname.inputChange.inputName)).and( + RecordAlreadyExists(existingCname.inputChange.inputName) + ).and( haveInvalid[DomainValidationError]( - CnameIsNotUniqueError(existingCname.inputChange.inputName, existingCname.inputChange.typ))) + CnameIsNotUniqueError(existingCname.inputChange.inputName, existingCname.inputChange.typ) + ) + ) result(3) shouldBe valid result(4) should haveInvalid[DomainValidationError]( - RecordNameNotUniqueInBatch("199.2.0.192.in-addr.arpa.", RecordType.CNAME)) + RecordNameNotUniqueInBatch("199.2.0.192.in-addr.arpa.", RecordType.CNAME) + ) result(5) shouldBe valid } @@ -746,7 +824,8 @@ class BatchChangeValidationsSpec deleteSingleEntryAndRRSet, deleteAllEntries, deleteAllEntriesAndRRSet, - deleteSingleEntryMultipleAdd) + deleteSingleEntryMultipleAdd + ) ) ), okAuth, @@ -786,7 +865,8 @@ class BatchChangeValidationsSpec deleteSingleEntryAndRRSet, deleteAllEntries, deleteAllEntriesAndRRSet - )) + ) + ) ), okAuth, false, @@ -802,57 +882,70 @@ class BatchChangeValidationsSpec val addUpdateA = AddChangeForValidation( okZone.addACLRule(writeAcl), "update", - AddChangeInput("update.ok.", RecordType.A, ttl, AData("1.2.3.4"))) + AddChangeInput("update.ok.", RecordType.A, ttl, AData("1.2.3.4")) + ) val deleteUpdateA = DeleteRRSetChangeForValidation( okZone.addACLRule(writeAcl), "update", - DeleteRRSetChangeInput("update.ok.", RecordType.A)) + DeleteRRSetChangeInput("update.ok.", RecordType.A) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(addUpdateA.validNel, deleteUpdateA.validNel), - ExistingRecordSets(List(existingRecord))), + ExistingRecordSets(List(existingRecord)) + ), notAuth, false, - None) + None + ) result(0) shouldBe valid result(1) shouldBe valid } property( - "validateChangesWithContext: should fail for update if user does not have sufficient access") { + "validateChangesWithContext: should fail for update if user does not have sufficient access" + ) { val readAcl = ACLRule(accessLevel = AccessLevel.Read, userId = Some(notAuth.signedInUser.userName)) val existingRecord = rsOk.copy(name = "update", ttl = 300) val addUpdateA = AddChangeForValidation( okZone.addACLRule(readAcl), "update", - AddChangeInput("update.ok.", RecordType.A, ttl, AData("1.2.3.4"))) + AddChangeInput("update.ok.", RecordType.A, ttl, AData("1.2.3.4")) + ) val deleteUpdateA = DeleteRRSetChangeForValidation( okZone.addACLRule(readAcl), "update", - DeleteRRSetChangeInput("update.ok.", RecordType.A)) + DeleteRRSetChangeInput("update.ok.", RecordType.A) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(addUpdateA.validNel, deleteUpdateA.validNel), - ExistingRecordSets(List(existingRecord))), + ExistingRecordSets(List(existingRecord)) + ), notAuth, false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( UserIsNotAuthorizedError( notAuth.signedInUser.userName, addUpdateA.zone.adminGroupId, OwnerType.Zone, - Some(addUpdateA.zone.email))) + Some(addUpdateA.zone.email) + ) + ) result(1) should haveInvalid[DomainValidationError]( UserIsNotAuthorizedError( notAuth.signedInUser.userName, deleteUpdateA.zone.adminGroupId, OwnerType.Zone, - Some(deleteUpdateA.zone.email))) + Some(deleteUpdateA.zone.email) + ) + ) } property("validateChangesWithContext: should fail for update if record does not exist") { @@ -878,7 +971,8 @@ class BatchChangeValidationsSpec result(0) shouldBe valid result(1) should haveInvalid[DomainValidationError]( - RecordDoesNotExist(deleteRRSet.inputChange.inputName)) + RecordDoesNotExist(deleteRRSet.inputChange.inputName) + ) result(3) should haveInvalid[DomainValidationError]( RecordDoesNotExist(deleteRecord.inputChange.inputName) ) @@ -895,25 +989,30 @@ class BatchChangeValidationsSpec property( """validateChangesWithContext: should succeed for update in shared zone if user belongs to record - | owner group""".stripMargin) { + | owner group""".stripMargin + ) { val existingRecord = sharedZoneRecord.copy(name = "mx", typ = RecordType.MX, records = List(MXData(200, "mx"))) val addUpdateA = AddChangeForValidation( sharedZone, "mx", - AddChangeInput("mx.shared.", RecordType.MX, ttl, MXData(200, "mx"))) + AddChangeInput("mx.shared.", RecordType.MX, ttl, MXData(200, "mx")) + ) val deleteUpdateA = DeleteRRSetChangeForValidation( sharedZone, "mx", - DeleteRRSetChangeInput("mx.shared.", RecordType.MX)) + DeleteRRSetChangeInput("mx.shared.", RecordType.MX) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(addUpdateA.validNel, deleteUpdateA.validNel), - ExistingRecordSets(List(existingRecord))), + ExistingRecordSets(List(existingRecord)) + ), okAuth, false, - None) + None + ) result(0) shouldBe valid result(1) shouldBe valid @@ -927,7 +1026,8 @@ class BatchChangeValidationsSpec val deleteCnameRRSet = DeleteRRSetChangeForValidation( okZone, "deleteRRSet", - DeleteRRSetChangeInput("deleteRRSet.ok.", RecordType.CNAME)) + DeleteRRSetChangeInput("deleteRRSet.ok.", RecordType.CNAME) + ) val deleteCnameEntry = DeleteRRSetChangeForValidation( okZone, "deleteRecord", @@ -939,7 +1039,8 @@ class BatchChangeValidationsSpec makeAddUpdateRecord("deleteRRSet"), // DeleteRRSet deleteCnameRRSet, makeAddUpdateRecord("deleteRecord"), // Delete record - deleteCnameEntry).map(_.validNel), + deleteCnameEntry + ).map(_.validNel), ExistingRecordSets(List(existingCname, existingCname2)) ), okAuth, @@ -950,24 +1051,29 @@ class BatchChangeValidationsSpec result.foreach(_ shouldBe valid) } - property("""validateChangesWithContext: should fail AddChangeForValidation with - |CnameWithRecordNameAlreadyExists if record already exists as CNAME record type""".stripMargin) { + property( + """validateChangesWithContext: should fail AddChangeForValidation with + |CnameWithRecordNameAlreadyExists if record already exists as CNAME record type""".stripMargin + ) { List(rsOk, aaaa, ptrIp4, ptrIp6).foreach { recordSet => forAll(generateValidAddChangeForValidation(recordSet)) { input: AddChangeForValidation => val existingCNAMERecord = recordSet.copy( zoneId = input.zone.id, name = input.recordName, typ = RecordType.CNAME, - records = List(CNAMEData("cname"))) + records = List(CNAMEData("cname")) + ) val newRecordSetList = existingCNAMERecord :: recordSetList val result = validateChangesWithContext( ChangeForValidationMap(List(input.validNel), ExistingRecordSets(newRecordSetList)), okAuth, false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( - CnameIsNotUniqueError(input.inputChange.inputName, RecordType.CNAME)) + CnameIsNotUniqueError(input.inputChange.inputName, RecordType.CNAME) + ) } } } @@ -979,62 +1085,74 @@ class BatchChangeValidationsSpec ChangeForValidationMap(List(input.validNel), ExistingRecordSets(recordSetList)), okAuth, false, - None) + None + ) result(0) shouldBe valid } } property( - "validateChangesWithContext: should succeed if all inputs of different record types are good") { + "validateChangesWithContext: should succeed if all inputs of different record types are good" + ) { List(rsOk, aaaa, ptrIp4, ptrIp6).foreach { recordSet => forAll(generateValidAddChangeForValidation(recordSet)) { input: AddChangeForValidation => val result = validateChangesWithContext( ChangeForValidationMap(List(input.validNel), ExistingRecordSets(recordSetList)), okAuth, false, - None) + None + ) result(0) shouldBe valid } } } property( - "validateChangesWithContext: should fail with RecordAlreadyExists if record already exists") { + "validateChangesWithContext: should fail with RecordAlreadyExists if record already exists" + ) { forAll(validAddChangeForValidationGen) { input: AddChangeForValidation => val existingRecordSetList = rsOk.copy( zoneId = input.zone.id, - name = input.recordName.toUpperCase) :: recordSetList + name = input.recordName.toUpperCase + ) :: recordSetList val result = validateChangesWithContext( ChangeForValidationMap(List(input.validNel), ExistingRecordSets(existingRecordSetList)), okAuth, false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( - RecordAlreadyExists(input.inputChange.inputName)) + RecordAlreadyExists(input.inputChange.inputName) + ) } } property( - "validateChangesWithContext: should succeed if CNAME record name already exists but is being deleted") { + "validateChangesWithContext: should succeed if CNAME record name already exists but is being deleted" + ) { val addCname = AddChangeForValidation( validZone, "existingCname", - AddChangeInput("existingCname.ok.", RecordType.CNAME, ttl, CNAMEData("cname"))) + AddChangeInput("existingCname.ok.", RecordType.CNAME, ttl, CNAMEData("cname")) + ) val deleteA = DeleteRRSetChangeForValidation( validZone, "existingCname", - DeleteRRSetChangeInput("existingCname.ok.", RecordType.A)) + DeleteRRSetChangeInput("existingCname.ok.", RecordType.A) + ) val existingA = rsOk.copy(zoneId = addCname.zone.id, name = addCname.recordName) val newRecordSetList = existingA :: recordSetList val result = validateChangesWithContext( ChangeForValidationMap( List(addCname.validNel, deleteA.validNel), - ExistingRecordSets(newRecordSetList)), + ExistingRecordSets(newRecordSetList) + ), okAuth, false, - None) + None + ) result(0) shouldBe valid result(1) shouldBe valid @@ -1045,17 +1163,20 @@ class BatchChangeValidationsSpec val addCname = AddChangeForValidation( validZone, "existingCname", - AddChangeInput("existingCname.ok.", RecordType.CNAME, ttl, CNAMEData("cname"))) + AddChangeInput("existingCname.ok.", RecordType.CNAME, ttl, CNAMEData("cname")) + ) val existingA = rsOk.copy(zoneId = addCname.zone.id, name = addCname.recordName) val newRecordSetList = existingA :: recordSetList val result = validateChangesWithContext( ChangeForValidationMap(List(addCname.validNel), ExistingRecordSets(newRecordSetList)), okAuth, false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( - CnameIsNotUniqueError(addCname.inputChange.inputName, existingA.typ)) + CnameIsNotUniqueError(addCname.inputChange.inputName, existingA.typ) + ) } property("""validateChangesWithContext: should succeed for CNAME record @@ -1068,15 +1189,18 @@ class BatchChangeValidationsSpec val deletePtr = DeleteRRSetChangeForValidation( validIp4ReverseZone, "30", - DeleteRRSetChangeInput("192.0.2.30", RecordType.PTR)) + DeleteRRSetChangeInput("192.0.2.30", RecordType.PTR) + ) val ptr4 = ptrIp4.copy(zoneId = validIp4ReverseZone.id) val result = validateChangesWithContext( ChangeForValidationMap( List(addCname.validNel, deletePtr.validNel), - ExistingRecordSets(List(ptr4))), + ExistingRecordSets(List(ptr4)) + ), okAuth, false, - None) + None + ) result(0) shouldBe valid result(1) shouldBe valid @@ -1091,17 +1215,20 @@ class BatchChangeValidationsSpec "0.6.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.9.e.f.c.c.7.2.9.6.d.f.ip6.arpa.", RecordType.CNAME, ttl, - CNAMEData("cname")) + CNAMEData("cname") + ) ) val existingRecordPTR = ptrIp6.copy(zoneId = addCname.zone.id, name = addCname.recordName) val result = validateChangesWithContext( ChangeForValidationMap(List(addCname.validNel), ExistingRecordSets(List(existingRecordPTR))), okAuth, false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( - CnameIsNotUniqueError(addCname.inputChange.inputName, existingRecordPTR.typ)) + CnameIsNotUniqueError(addCname.inputChange.inputName, existingRecordPTR.typ) + ) } property("""validateChangesWithContext: CNAME record should pass @@ -1109,22 +1236,27 @@ class BatchChangeValidationsSpec val addA = AddChangeForValidation( okZone, "test", - AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val addAAAA = AddChangeForValidation( okZone, "testAAAA", - AddChangeInput("testAAAA.ok.", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8"))) + AddChangeInput("testAAAA.ok.", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8")) + ) val addCname = AddChangeForValidation( okZone, "new", - AddChangeInput("new.ok.", RecordType.CNAME, ttl, CNAMEData("hey.ok.com."))) + AddChangeInput("new.ok.", RecordType.CNAME, ttl, CNAMEData("hey.ok.com.")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(addA.validNel, addAAAA.validNel, addCname.validNel), - ExistingRecordSets(List())), + ExistingRecordSets(List()) + ), okAuth, false, - None) + None + ) result(0) shouldBe valid result(1) shouldBe valid @@ -1136,29 +1268,36 @@ class BatchChangeValidationsSpec val addA = AddChangeForValidation( okZone, "test", - AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val addDuplicateCname = AddChangeForValidation( okZone, "testAAAA", - AddChangeInput("testAAAA.ok.", RecordType.CNAME, ttl, CNAMEData("hey.ok.com."))) + AddChangeInput("testAAAA.ok.", RecordType.CNAME, ttl, CNAMEData("hey.ok.com.")) + ) val addAAAA = AddChangeForValidation( okZone, "testAAAA", - AddChangeInput("testAAAA.ok.", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8"))) + AddChangeInput("testAAAA.ok.", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(addA.validNel, addAAAA.validNel, addDuplicateCname.validNel), - ExistingRecordSets(List())), + ExistingRecordSets(List()) + ), okAuth, false, - None) + None + ) result(0) shouldBe valid result(1) shouldBe valid result(2) should haveInvalid[DomainValidationError]( RecordNameNotUniqueInBatch( addDuplicateCname.inputChange.inputName, - addDuplicateCname.inputChange.typ)) + addDuplicateCname.inputChange.typ + ) + ) } property("""validateChangesWithContext: both CNAME records should fail @@ -1166,30 +1305,38 @@ class BatchChangeValidationsSpec val addA = AddChangeForValidation( okZone, "test", - AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val addCname = AddChangeForValidation( okZone, "testAAAA", - AddChangeInput("testAAAA.ok.", RecordType.CNAME, ttl, CNAMEData("hey.ok.com."))) + AddChangeInput("testAAAA.ok.", RecordType.CNAME, ttl, CNAMEData("hey.ok.com.")) + ) val addDuplicateCname = AddChangeForValidation( okZone, "testAAAA", - AddChangeInput("testAAAA.ok.", RecordType.CNAME, ttl, CNAMEData("hey2.ok.com."))) + AddChangeInput("testAAAA.ok.", RecordType.CNAME, ttl, CNAMEData("hey2.ok.com.")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(addA.validNel, addCname.validNel, addDuplicateCname.validNel), - ExistingRecordSets(List())), + ExistingRecordSets(List()) + ), okAuth, false, - None) + None + ) result(0) shouldBe valid result(1) should haveInvalid[DomainValidationError]( - RecordNameNotUniqueInBatch(addCname.inputChange.inputName, addCname.inputChange.typ)) + RecordNameNotUniqueInBatch(addCname.inputChange.inputName, addCname.inputChange.typ) + ) result(2) should haveInvalid[DomainValidationError]( RecordNameNotUniqueInBatch( addDuplicateCname.inputChange.inputName, - addDuplicateCname.inputChange.typ)) + addDuplicateCname.inputChange.typ + ) + ) } property("""validateChangesWithContext: both PTR records should succeed @@ -1197,22 +1344,27 @@ class BatchChangeValidationsSpec val addA = AddChangeForValidation( okZone, "test", - AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val addPtr = AddChangeForValidation( okZone, "193", - AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("test.ok."))) + AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("test.ok.")) + ) val addDuplicatePtr = AddChangeForValidation( okZone, "193", - AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("hey.ok.com."))) + AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("hey.ok.com.")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(addA.validNel, addPtr.validNel, addDuplicatePtr.validNel), - ExistingRecordSets(List())), + ExistingRecordSets(List()) + ), okAuth, false, - None) + None + ) result.map(_ shouldBe valid) } @@ -1222,39 +1374,47 @@ class BatchChangeValidationsSpec val addA = AddChangeForValidation( validZone, "valid", - AddChangeInput("valid.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("valid.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val result = validateChangesWithContext( ChangeForValidationMap(List(addA.validNel), ExistingRecordSets(recordSetList)), okAuth, false, - None) + None + ) result(0) shouldBe valid } property( - "validateChangesWithContext: should fail for AddChangeForValidation if user is a superUser with no other access") { + "validateChangesWithContext: should fail for AddChangeForValidation if user is a superUser with no other access" + ) { val addA = AddChangeForValidation( validZone, "valid", - AddChangeInput("valid.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("valid.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val result = validateChangesWithContext( ChangeForValidationMap(List(addA.validNel), ExistingRecordSets(recordSetList)), AuthPrincipal(superUser, Seq.empty), false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( UserIsNotAuthorizedError( superUser.userName, addA.zone.adminGroupId, OwnerType.Zone, - Some(addA.zone.email))) + Some(addA.zone.email) + ) + ) } property( - "validateChangesWithContext: should succeed for AddChangeForValidation if user has necessary ACL rule") { + "validateChangesWithContext: should succeed for AddChangeForValidation if user has necessary ACL rule" + ) { val addA = AddChangeForValidation( validZone.addACLRule(ACLRule(accessLevel = AccessLevel.Write, userId = Some(notAuth.userId))), "valid", @@ -1265,28 +1425,33 @@ class BatchChangeValidationsSpec ChangeForValidationMap(List(addA.validNel), ExistingRecordSets(recordSetList)), notAuth, false, - None) + None + ) result(0) shouldBe valid } property( """validateChangesWithContext: should fail AddChangeForValidation with UserIsNotAuthorized if user - |is not a superuser, doesn't have group admin access, or doesn't have necessary ACL rule""".stripMargin) { + |is not a superuser, doesn't have group admin access, or doesn't have necessary ACL rule""".stripMargin + ) { forAll(validAddChangeForValidationGen) { input: AddChangeForValidation => val result = validateChangesWithContext( ChangeForValidationMap(List(input.validNel), ExistingRecordSets(recordSetList)), notAuth, false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( UserIsNotAuthorizedError( notAuth.signedInUser.userName, input.zone.adminGroupId, OwnerType.Zone, - Some(input.zone.email))) + Some(input.zone.email) + ) + ) } } @@ -1295,43 +1460,52 @@ class BatchChangeValidationsSpec val addCname = AddChangeForValidation( validZone, "existing", - AddChangeInput("existing.ok.", RecordType.CNAME, ttl, PTRData("orders.vinyldns."))) + AddChangeInput("existing.ok.", RecordType.CNAME, ttl, PTRData("orders.vinyldns.")) + ) val addPtr = AddChangeForValidation( validZone, "existing", - AddChangeInput("existing.ok.", RecordType.PTR, ttl, CNAMEData("ptrdname."))) + AddChangeInput("existing.ok.", RecordType.PTR, ttl, CNAMEData("ptrdname.")) + ) val result = validateChangesWithContext( ChangeForValidationMap(List(addCname.validNel, addPtr.validNel), ExistingRecordSets(List())), okAuth, false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( - RecordNameNotUniqueInBatch("existing.ok.", RecordType.CNAME)) + RecordNameNotUniqueInBatch("existing.ok.", RecordType.CNAME) + ) } property( - "validateChangesWithContext: should succeed for DeleteChangeForValidation if record exists") { + "validateChangesWithContext: should succeed for DeleteChangeForValidation if record exists" + ) { val deleteA = DeleteRRSetChangeForValidation( validZone, "Record-exists", - DeleteRRSetChangeInput("record-exists.ok.", RecordType.A)) + DeleteRRSetChangeInput("record-exists.ok.", RecordType.A) + ) val existingDeleteRecord = rsOk.copy(zoneId = deleteA.zone.id, name = deleteA.recordName.toLowerCase) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteA.validNel), - ExistingRecordSets(List(existingDeleteRecord))), + ExistingRecordSets(List(existingDeleteRecord)) + ), okAuth, false, - None) + None + ) result(0) shouldBe valid } property( """validateChangesWithContext: should fail DeleteChangeForValidation with RecordDoesNotExist - |if record does not exist""".stripMargin) { + |if record does not exist""".stripMargin + ) { val deleteRRSet = makeDeleteUpdateDeleteRRSet("record-does-not-exist") val deleteRecord = makeDeleteUpdateDeleteRRSet("record-also-does-not-exist", Some(AData("1.1.1.1"))) @@ -1339,15 +1513,19 @@ class BatchChangeValidationsSpec validateChangesWithContext( ChangeForValidationMap( List(deleteRRSet.validNel, deleteRecord.validNel), - ExistingRecordSets(recordSetList)), + ExistingRecordSets(recordSetList) + ), okAuth, false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( - RecordDoesNotExist(deleteRRSet.inputChange.inputName)) + RecordDoesNotExist(deleteRRSet.inputChange.inputName) + ) result(1) should haveInvalid[DomainValidationError]( - RecordDoesNotExist(deleteRecord.inputChange.inputName)) + RecordDoesNotExist(deleteRecord.inputChange.inputName) + ) } property("""validateChangesWithContext: should succeed for DeleteChangeForValidation @@ -1355,18 +1533,22 @@ class BatchChangeValidationsSpec val deleteA = DeleteRRSetChangeForValidation( validZone, "Active-record-status", - DeleteRRSetChangeInput("active-record-status", RecordType.A)) + DeleteRRSetChangeInput("active-record-status", RecordType.A) + ) val existingDeleteRecord = rsOk.copy( zoneId = deleteA.zone.id, name = deleteA.recordName.toLowerCase, - status = RecordSetStatus.Active) + status = RecordSetStatus.Active + ) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteA.validNel), - ExistingRecordSets(List(existingDeleteRecord))), + ExistingRecordSets(List(existingDeleteRecord)) + ), okAuth, false, - None) + None + ) result(0) shouldBe valid } @@ -1377,15 +1559,18 @@ class BatchChangeValidationsSpec DeleteRRSetChangeForValidation( validZone, "valid", - DeleteRRSetChangeInput("valid.ok.", RecordType.A)) + DeleteRRSetChangeInput("valid.ok.", RecordType.A) + ) val existingDeleteRecord = rsOk.copy(zoneId = deleteA.zone.id, name = deleteA.recordName) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteA.validNel), - ExistingRecordSets(List(existingDeleteRecord))), + ExistingRecordSets(List(existingDeleteRecord)) + ), okAuth, false, - None) + None + ) result(0) shouldBe valid } @@ -1396,65 +1581,81 @@ class BatchChangeValidationsSpec DeleteRRSetChangeForValidation( validZone, "valid", - DeleteRRSetChangeInput("valid.ok.", RecordType.A)) + DeleteRRSetChangeInput("valid.ok.", RecordType.A) + ) val existingDeleteRecord = rsOk.copy(zoneId = deleteA.zone.id, name = deleteA.recordName) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteA.validNel), - ExistingRecordSets(List(existingDeleteRecord))), + ExistingRecordSets(List(existingDeleteRecord)) + ), AuthPrincipal(superUser, Seq.empty), false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( UserIsNotAuthorizedError( superUser.userName, deleteA.zone.adminGroupId, OwnerType.Zone, - Some(deleteA.zone.email))) + Some(deleteA.zone.email) + ) + ) } property( - "validateChangesWithContext: should succeed for DeleteChangeForValidation if user has necessary ACL rule") { + "validateChangesWithContext: should succeed for DeleteChangeForValidation if user has necessary ACL rule" + ) { val deleteA = DeleteRRSetChangeForValidation( validZone.addACLRule( - ACLRule(accessLevel = AccessLevel.Delete, userId = Some(notAuth.userId))), + ACLRule(accessLevel = AccessLevel.Delete, userId = Some(notAuth.userId)) + ), "valid", - DeleteRRSetChangeInput("valid.ok.", RecordType.A)) + DeleteRRSetChangeInput("valid.ok.", RecordType.A) + ) val existingDeleteRecord = rsOk.copy(zoneId = deleteA.zone.id, name = deleteA.recordName) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteA.validNel), - ExistingRecordSets(List(existingDeleteRecord))), + ExistingRecordSets(List(existingDeleteRecord)) + ), notAuth, false, - None) + None + ) result(0) shouldBe valid } property( """validateChangesWithContext: should fail DeleteChangeForValidation with UserIsNotAuthorized if user - |is not a superuser, doesn't have group admin access, or doesn't have necessary ACL rule""".stripMargin) { + |is not a superuser, doesn't have group admin access, or doesn't have necessary ACL rule""".stripMargin + ) { val deleteA = DeleteRRSetChangeForValidation( validZone.addACLRule(ACLRule(accessLevel = AccessLevel.Write, userId = Some(notAuth.userId))), "valid", - DeleteRRSetChangeInput("valid.ok.", RecordType.A)) + DeleteRRSetChangeInput("valid.ok.", RecordType.A) + ) val existingDeleteRecord = rsOk.copy(zoneId = deleteA.zone.id, name = deleteA.recordName) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteA.validNel), - ExistingRecordSets(List(existingDeleteRecord))), + ExistingRecordSets(List(existingDeleteRecord)) + ), notAuth, false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( UserIsNotAuthorizedError( notAuth.signedInUser.userName, deleteA.zone.adminGroupId, OwnerType.Zone, - Some(deleteA.zone.email))) + Some(deleteA.zone.email) + ) + ) } property("""validateChangesWithContext: should properly process batch that contains @@ -1462,29 +1663,35 @@ class BatchChangeValidationsSpec val addDuplicateA = AddChangeForValidation( okZone, "test", - AddChangeInput("test.com.", RecordType.A, ttl, AData("10.1.1.1"))) + AddChangeInput("test.com.", RecordType.A, ttl, AData("10.1.1.1")) + ) val addDuplicateCname = AddChangeForValidation( okZone, "test", - AddChangeInput("test.com.", RecordType.CNAME, ttl, CNAMEData("thing.com."))) + AddChangeInput("test.com.", RecordType.CNAME, ttl, CNAMEData("thing.com.")) + ) val deleteA = DeleteRRSetChangeForValidation( okZone, "delete", - DeleteRRSetChangeInput("delete.ok.", RecordType.A)) + DeleteRRSetChangeInput("delete.ok.", RecordType.A) + ) val addCname = AddChangeForValidation( okZone, "delete", - AddChangeInput("delete.ok.", RecordType.CNAME, ttl, CNAMEData("thing.com."))) + AddChangeInput("delete.ok.", RecordType.CNAME, ttl, CNAMEData("thing.com.")) + ) val addA = AddChangeForValidation( okZone, "delete-this", - AddChangeInput("delete-this.ok.", RecordType.A, ttl, AData("10.1.1.1"))) + AddChangeInput("delete-this.ok.", RecordType.A, ttl, AData("10.1.1.1")) + ) val deleteCname = DeleteRRSetChangeForValidation( okZone, "delete", - DeleteRRSetChangeInput("delete-this.ok.", RecordType.CNAME)) + DeleteRRSetChangeInput("delete-this.ok.", RecordType.CNAME) + ) val existingA = rsOk.copy(zoneId = deleteA.zone.id, name = deleteA.recordName) val existingCname = rsOk.copy(zoneId = deleteCname.zone.id, name = deleteCname.recordName, typ = RecordType.CNAME) @@ -1496,7 +1703,8 @@ class BatchChangeValidationsSpec deleteA.validNel, addCname.validNel, addA.validNel, - deleteCname.validNel), + deleteCname.validNel + ), ExistingRecordSets(List(existingA, existingCname)) ), okAuth, @@ -1506,7 +1714,8 @@ class BatchChangeValidationsSpec result(0) shouldBe valid result(1) should haveInvalid[DomainValidationError]( - RecordNameNotUniqueInBatch(addDuplicateCname.inputChange.inputName, RecordType.CNAME)) + RecordNameNotUniqueInBatch(addDuplicateCname.inputChange.inputName, RecordType.CNAME) + ) result(2) shouldBe valid result(3) shouldBe valid result(4) shouldBe valid @@ -1521,23 +1730,28 @@ class BatchChangeValidationsSpec val addA = AddChangeForValidation( okZone, "test", - AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val addAAAA = AddChangeForValidation( okZone, "testAAAA", - AddChangeInput("testAAAA.ok.", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8"))) + AddChangeInput("testAAAA.ok.", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8")) + ) val addCname = AddChangeForValidation( okZone, "new", - AddChangeInput("new.ok.", RecordType.CNAME, ttl, CNAMEData("hey.ok."))) + AddChangeInput("new.ok.", RecordType.CNAME, ttl, CNAMEData("hey.ok.")) + ) val addPtr = AddChangeForValidation( okZone, "193", - AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("test.ok."))) + AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("test.ok.")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteA.validNel, addA.validNel, addAAAA.validNel, addCname.validNel, addPtr.validNel), - ExistingRecordSets(List(existingA))), + ExistingRecordSets(List(existingA)) + ), okAuth, false, None @@ -1546,7 +1760,8 @@ class BatchChangeValidationsSpec } property( - "validateChangesWithContext: should succeed with add AAAA, delete CNAME of the same name") { + "validateChangesWithContext: should succeed with add AAAA, delete CNAME of the same name" + ) { val existingCname = rsOk.copy(name = "new", typ = RecordType.CNAME, records = List(CNAMEData("hey.ok."))) @@ -1554,24 +1769,29 @@ class BatchChangeValidationsSpec DeleteRRSetChangeForValidation( okZone, "new", - DeleteRRSetChangeInput("new.ok.", RecordType.CNAME)) + DeleteRRSetChangeInput("new.ok.", RecordType.CNAME) + ) val addA = AddChangeForValidation( okZone, "test", - AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("test.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val addAAAA = AddChangeForValidation( okZone, "new", - AddChangeInput("new.ok.", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8"))) + AddChangeInput("new.ok.", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8")) + ) val addPtr = AddChangeForValidation( okZone, "193", - AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("test.ok."))) + AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("test.ok.")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteCname.validNel, addA.validNel, addAAAA.validNel, addPtr.validNel), - ExistingRecordSets(List(existingCname))), + ExistingRecordSets(List(existingCname)) + ), okAuth, false, None @@ -1580,7 +1800,8 @@ class BatchChangeValidationsSpec } property( - "validateChangesWithContext: should succeed with delete and add (update) of same CNAME input name") { + "validateChangesWithContext: should succeed with delete and add (update) of same CNAME input name" + ) { val existingCname = rsOk.copy(name = "new", typ = RecordType.CNAME, records = List(CNAMEData("hey.ok."))) @@ -1588,18 +1809,22 @@ class BatchChangeValidationsSpec DeleteRRSetChangeForValidation( okZone, "new", - DeleteRRSetChangeInput("new.ok.", RecordType.CNAME)) + DeleteRRSetChangeInput("new.ok.", RecordType.CNAME) + ) val addCname = AddChangeForValidation( okZone, "new", - AddChangeInput("new.ok.", RecordType.CNAME, ttl, CNAMEData("updateData.com"))) + AddChangeInput("new.ok.", RecordType.CNAME, ttl, CNAMEData("updateData.com")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteCname.validNel, addCname.validNel), - ExistingRecordSets(List(existingCname))), + ExistingRecordSets(List(existingCname)) + ), okAuth, false, - None) + None + ) result.map(_ shouldBe valid) } @@ -1608,25 +1833,30 @@ class BatchChangeValidationsSpec zoneId = okZone.id, name = "name-conflict", typ = RecordType.CNAME, - records = List(CNAMEData("existing.cname."))) + records = List(CNAMEData("existing.cname.")) + ) val deleteUpdateCname = DeleteRRSetChangeForValidation( okZone, "name-conflict", - DeleteRRSetChangeInput("existing.ok.", RecordType.CNAME)) + DeleteRRSetChangeInput("existing.ok.", RecordType.CNAME) + ) val addUpdateCname = AddChangeForValidation( okZone, "name-conflict", - AddChangeInput("add.ok.", RecordType.CNAME, ttl, CNAMEData("updated.cname."))) + AddChangeInput("add.ok.", RecordType.CNAME, ttl, CNAMEData("updated.cname.")) + ) val addCname = AddChangeForValidation( okZone, "name-conflict", - AddChangeInput("add.ok.", RecordType.CNAME, ttl, CNAMEData("new.add.cname."))) + AddChangeInput("add.ok.", RecordType.CNAME, ttl, CNAMEData("new.add.cname.")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteUpdateCname.validNel, addUpdateCname.validNel, addCname.validNel), - ExistingRecordSets(List(existingCname))), + ExistingRecordSets(List(existingCname)) + ), okAuth, false, None @@ -1634,9 +1864,11 @@ class BatchChangeValidationsSpec result(0) shouldBe valid result(1) should haveInvalid[DomainValidationError]( - RecordNameNotUniqueInBatch("add.ok.", RecordType.CNAME)) + RecordNameNotUniqueInBatch("add.ok.", RecordType.CNAME) + ) result(2) should haveInvalid[DomainValidationError]( - RecordNameNotUniqueInBatch("add.ok.", RecordType.CNAME)) + RecordNameNotUniqueInBatch("add.ok.", RecordType.CNAME) + ) } property("validateChangesWithContext: should succeed with add CNAME, delete PTR of the same name") { @@ -1644,50 +1876,61 @@ class BatchChangeValidationsSpec zoneId = validIp4ReverseZone.id, name = "193", typ = RecordType.PTR, - records = List(PTRData("hey.there."))) + records = List(PTRData("hey.there.")) + ) val deletePtr = DeleteRRSetChangeForValidation( validIp4ReverseZone, "193", - DeleteRRSetChangeInput("192.0.2.193", RecordType.PTR)) + DeleteRRSetChangeInput("192.0.2.193", RecordType.PTR) + ) val addCname = AddChangeForValidation( validIp4ReverseZone, "193", - AddChangeInput("test.ok.", RecordType.CNAME, ttl, CNAMEData("hey2.there."))) + AddChangeInput("test.ok.", RecordType.CNAME, ttl, CNAMEData("hey2.there.")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(deletePtr.validNel, addCname.validNel), - ExistingRecordSets(List(existingPtr))), + ExistingRecordSets(List(existingPtr)) + ), okAuth, false, - None) + None + ) result.map(_ shouldBe valid) } property( - "validateChangesWithContext: should succeed with delete and add (update) of same PTR input name") { + "validateChangesWithContext: should succeed with delete and add (update) of same PTR input name" + ) { val existingPtr = rsOk.copy( zoneId = validIp4ReverseZone.id, name = "193", typ = RecordType.PTR, - records = List(PTRData("hey.ok."))) + records = List(PTRData("hey.ok.")) + ) val deletePtr = DeleteRRSetChangeForValidation( validIp4ReverseZone, "193", - DeleteRRSetChangeInput("192.0.2.193", RecordType.PTR)) + DeleteRRSetChangeInput("192.0.2.193", RecordType.PTR) + ) val addPtr = AddChangeForValidation( validIp4ReverseZone, "193", - AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("updateData.com"))) + AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("updateData.com")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(deletePtr.validNel, addPtr.validNel), - ExistingRecordSets(List(existingPtr))), + ExistingRecordSets(List(existingPtr)) + ), okAuth, false, - None) + None + ) result.map(_ shouldBe valid) } @@ -1696,28 +1939,34 @@ class BatchChangeValidationsSpec zoneId = validIp4ReverseZone.id, name = "193", typ = RecordType.PTR, - records = List(PTRData("existing.ptr."))) + records = List(PTRData("existing.ptr.")) + ) val deleteUpdatePtr = DeleteRRSetChangeForValidation( validIp4ReverseZone, "193", - DeleteRRSetChangeInput("192.0.2.193", RecordType.PTR)) + DeleteRRSetChangeInput("192.0.2.193", RecordType.PTR) + ) val addUpdatePtr = AddChangeForValidation( validIp4ReverseZone, "193", - AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("updated.ptr."))) + AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("updated.ptr.")) + ) val addPtr = AddChangeForValidation( validIp4ReverseZone, "193", - AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("new.add.ptr."))) + AddChangeInput("192.0.2.193", RecordType.PTR, ttl, PTRData("new.add.ptr.")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteUpdatePtr.validNel, addUpdatePtr.validNel, addPtr.validNel), - ExistingRecordSets(List(existingPtr))), + ExistingRecordSets(List(existingPtr)) + ), okAuth, false, - None) + None + ) result.map(_ shouldBe valid) } @@ -1735,7 +1984,8 @@ class BatchChangeValidationsSpec } property( - "validateAddChangeInput: should fail for a TXT addChangeInput with TXTData that is too many characters") { + "validateAddChangeInput: should fail for a TXT addChangeInput with TXTData that is too many characters" + ) { val txtData = "x" * 64765 val input = AddChangeInput("txt.ok.", RecordType.TXT, ttl, TXTData(txtData)) val result = validateAddChangeInput(input, false) @@ -1758,12 +2008,16 @@ class BatchChangeValidationsSpec InvalidMxPreference( -1, DomainValidations.MX_PREFERENCE_MIN_VALUE, - DomainValidations.MX_PREFERENCE_MAX_VALUE)) + DomainValidations.MX_PREFERENCE_MAX_VALUE + ) + ) resultLarge should haveInvalid[DomainValidationError]( InvalidMxPreference( 1000000, DomainValidations.MX_PREFERENCE_MIN_VALUE, - DomainValidations.MX_PREFERENCE_MAX_VALUE)) + DomainValidations.MX_PREFERENCE_MAX_VALUE + ) + ) } property("validateAddChangeInput: should fail for a MX addChangeInput with invalid exchange") { @@ -1773,19 +2027,23 @@ class BatchChangeValidationsSpec } property( - "validateAddChangeInput: should fail for a MX addChangeInput with invalid preference and exchange") { + "validateAddChangeInput: should fail for a MX addChangeInput with invalid preference and exchange" + ) { val input = AddChangeInput("mx.ok.", RecordType.MX, ttl, MXData(-1, "foo$.bar.")) val result = validateAddChangeInput(input, false) result should haveInvalid[DomainValidationError]( InvalidMxPreference( -1, DomainValidations.MX_PREFERENCE_MIN_VALUE, - DomainValidations.MX_PREFERENCE_MAX_VALUE)) + DomainValidations.MX_PREFERENCE_MAX_VALUE + ) + ) result should haveInvalid[DomainValidationError](InvalidDomainName("foo$.bar.")) } property( - "validateDeleteChangeInput: should succeed for valid data when no record data is passed in") { + "validateDeleteChangeInput: should succeed for valid data when no record data is passed in" + ) { val input = DeleteRRSetChangeInput("a.ok.", RecordType.A, None) validateDeleteRRSetChangeInput(input, false) shouldBe valid } @@ -1807,18 +2065,21 @@ class BatchChangeValidationsSpec zoneId = okZone.id, name = "name-conflict", typ = RecordType.MX, - records = List(MXData(1, "foo.bar."))) + records = List(MXData(1, "foo.bar.")) + ) val addMX = AddChangeForValidation( okZone, "name-conflict", - AddChangeInput("name-conflict", RecordType.MX, ttl, MXData(1, "foo.bar."))) + AddChangeInput("name-conflict", RecordType.MX, ttl, MXData(1, "foo.bar.")) + ) val result = validateChangesWithContext( ChangeForValidationMap(List(addMX.validNel), ExistingRecordSets(List(existingMX))), okAuth, false, - None) + None + ) result(0) should haveInvalid[DomainValidationError](RecordAlreadyExists("name-conflict.")) } @@ -1826,17 +2087,20 @@ class BatchChangeValidationsSpec val addMx = AddChangeForValidation( okZone, "name-conflict", - AddChangeInput("name-conflict", RecordType.MX, ttl, MXData(1, "foo.bar."))) + AddChangeInput("name-conflict", RecordType.MX, ttl, MXData(1, "foo.bar.")) + ) val addMx2 = AddChangeForValidation( okZone, "name-conflict", - AddChangeInput("name-conflict", RecordType.MX, ttl, MXData(2, "foo.bar."))) + AddChangeInput("name-conflict", RecordType.MX, ttl, MXData(2, "foo.bar.")) + ) val result = validateChangesWithContext( ChangeForValidationMap(List(addMx.validNel, addMx2.validNel), ExistingRecordSets(List())), okAuth, false, - None) + None + ) result(0) shouldBe valid } @@ -1845,23 +2109,28 @@ class BatchChangeValidationsSpec zoneId = okZone.id, name = "name-conflict", typ = RecordType.MX, - records = List(MXData(1, "foo.bar."))) + records = List(MXData(1, "foo.bar.")) + ) val deleteMx = DeleteRRSetChangeForValidation( okZone, "name-conflict", - DeleteRRSetChangeInput("name-conflict", RecordType.MX)) + DeleteRRSetChangeInput("name-conflict", RecordType.MX) + ) val addMx = AddChangeForValidation( okZone, "name-conflict", - AddChangeInput("name-conflict", RecordType.MX, ttl, MXData(1, "foo.bar."))) + AddChangeInput("name-conflict", RecordType.MX, ttl, MXData(1, "foo.bar.")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(deleteMx.validNel, addMx.validNel), - ExistingRecordSets(List(existingMx))), + ExistingRecordSets(List(existingMx)) + ), okAuth, false, - None) + None + ) result(0) shouldBe valid } @@ -1884,7 +2153,8 @@ class BatchChangeValidationsSpec sharedZoneRecord.copy(name = "shared-update"), rsOk.copy(name = "private-delete"), sharedZoneRecord.copy(name = "shared-delete") - )) + ) + ) ), AuthPrincipal(okUser, Seq(abcGroup.id, okGroup.id)), false, @@ -1913,7 +2183,8 @@ class BatchChangeValidationsSpec sharedZoneRecordNoOwnerGroup.copy(name = "shared-update"), rsOk.copy(name = "private-delete"), sharedZoneRecord.copy(name = "shared-delete") - )) + ) + ) ), AuthPrincipal(okUser, Seq(abcGroup.id, okGroup.id)), false, @@ -1923,26 +2194,31 @@ class BatchChangeValidationsSpec result(0) shouldBe valid result(1) should haveInvalid[DomainValidationError]( - MissingOwnerGroupId(createSharedAddChange.recordName, createSharedAddChange.zone.name)) + MissingOwnerGroupId(createSharedAddChange.recordName, createSharedAddChange.zone.name) + ) result(2) shouldBe valid result(3) shouldBe valid result(4) should haveInvalid[DomainValidationError]( - MissingOwnerGroupId(updateSharedAddChange.recordName, updateSharedAddChange.zone.name)) + MissingOwnerGroupId(updateSharedAddChange.recordName, updateSharedAddChange.zone.name) + ) result(5) shouldBe valid result(6) shouldBe valid result(7) shouldBe valid } property( - "validateChangesWithContext: should fail deleting record for normal user not in owner group in shared zone") { + "validateChangesWithContext: should fail deleting record for normal user not in owner group in shared zone" + ) { val result = validateChangesWithContext( ChangeForValidationMap( List(deleteSharedChange.validNel), - ExistingRecordSets(List(sharedZoneRecord.copy(name = "shared-delete")))), + ExistingRecordSets(List(sharedZoneRecord.copy(name = "shared-delete"))) + ), dummyAuth, false, - None) + None + ) result(0) should haveInvalid[DomainValidationError]( @@ -1950,18 +2226,23 @@ class BatchChangeValidationsSpec dummyAuth.signedInUser.userName, sharedZoneRecord.ownerGroupId.get, OwnerType.Record, - None)) + None + ) + ) } property( - "validateChangesWithContext: should delete record without owner group for normal user in shared zone") { + "validateChangesWithContext: should delete record without owner group for normal user in shared zone" + ) { val result = validateChangesWithContext( ChangeForValidationMap( List(deleteSharedChange.validNel), - ExistingRecordSets(List(sharedZoneRecord.copy(name = "shared-delete")))), + ExistingRecordSets(List(sharedZoneRecord.copy(name = "shared-delete"))) + ), okAuth, false, - None) + None + ) result(0) shouldBe valid } @@ -1970,10 +2251,12 @@ class BatchChangeValidationsSpec val result = validateChangesWithContext( ChangeForValidationMap( List(deleteSharedChange.validNel), - ExistingRecordSets(List(sharedZoneRecord.copy(name = "shared-delete")))), + ExistingRecordSets(List(sharedZoneRecord.copy(name = "shared-delete"))) + ), sharedAuth, false, - None) + None + ) result(0) shouldBe valid } @@ -1982,10 +2265,12 @@ class BatchChangeValidationsSpec val existing = List( sharedZoneRecord.copy( name = updateSharedAddChange.recordName, - records = List(AAAAData("1::1"), AAAAData("2::2"))), + records = List(AAAAData("1::1"), AAAAData("2::2")) + ), sharedZoneRecord.copy( name = deleteSharedChange.recordName, - records = List(AAAAData("1::1"), AAAAData("2::2"))), + records = List(AAAAData("1::1"), AAAAData("2::2")) + ), rsOk.copy(name = updatePrivateAddChange.recordName), rsOk.copy(name = deletePrivateChange.recordName) ) @@ -2061,38 +2346,46 @@ class BatchChangeValidationsSpec result(5) shouldBe valid } - property("""validateChangesWithContext: should fail validateAddWithContext with - |ZoneDiscoveryError if new record is dotted host but not a TXT record type""".stripMargin) { + property( + """validateChangesWithContext: should fail validateAddWithContext with + |ZoneDiscoveryError if new record is dotted host but not a TXT record type""".stripMargin + ) { val addA = AddChangeForValidation( okZone, "dotted.a", - AddChangeInput("dotted.a.ok.", RecordType.A, ttl, AData("1.1.1.1"))) + AddChangeInput("dotted.a.ok.", RecordType.A, ttl, AData("1.1.1.1")) + ) val addAAAA = AddChangeForValidation( okZone, "dotted.aaaa", - AddChangeInput("dotted.aaaa.ok.", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8"))) + AddChangeInput("dotted.aaaa.ok.", RecordType.AAAA, ttl, AAAAData("1:2:3:4:5:6:7:8")) + ) val addCNAME = AddChangeForValidation( okZone, "dotted.cname", - AddChangeInput("dotted.cname.ok.", RecordType.CNAME, ttl, CNAMEData("foo.com"))) + AddChangeInput("dotted.cname.ok.", RecordType.CNAME, ttl, CNAMEData("foo.com")) + ) val addMX = AddChangeForValidation( okZone, "dotted.mx", - AddChangeInput("dotted.mx.ok.", RecordType.MX, ttl, MXData(1, "foo.bar."))) + AddChangeInput("dotted.mx.ok.", RecordType.MX, ttl, MXData(1, "foo.bar.")) + ) val addTXT = AddChangeForValidation( okZone, "dotted.txt", - AddChangeInput("dotted.txt.ok.", RecordType.TXT, ttl, TXTData("test"))) + AddChangeInput("dotted.txt.ok.", RecordType.TXT, ttl, TXTData("test")) + ) val result = validateChangesWithContext( ChangeForValidationMap( List(addA.validNel, addAAAA.validNel, addCNAME.validNel, addMX.validNel, addTXT.validNel), - ExistingRecordSets(List())), + ExistingRecordSets(List()) + ), okAuth, false, None @@ -2114,23 +2407,28 @@ class BatchChangeValidationsSpec val deleteA = DeleteRRSetChangeForValidation( okZone, "existing.dotted.a", - DeleteRRSetChangeInput("existing.dotted.a.ok.", RecordType.A)) + DeleteRRSetChangeInput("existing.dotted.a.ok.", RecordType.A) + ) val deleteAAAA = DeleteRRSetChangeForValidation( okZone, "existing.dotted.aaaa", - DeleteRRSetChangeInput("existing.dotted.aaaa.ok.", RecordType.AAAA)) + DeleteRRSetChangeInput("existing.dotted.aaaa.ok.", RecordType.AAAA) + ) val deleteCname = DeleteRRSetChangeForValidation( okZone, "existing.dotted.cname", - DeleteRRSetChangeInput("existing.dotted.cname.ok.", RecordType.CNAME)) + DeleteRRSetChangeInput("existing.dotted.cname.ok.", RecordType.CNAME) + ) val deleteMX = DeleteRRSetChangeForValidation( okZone, "existing.dotted.mx", - DeleteRRSetChangeInput("existing.dotted.mx.ok.", RecordType.MX)) + DeleteRRSetChangeInput("existing.dotted.mx.ok.", RecordType.MX) + ) val deleteTXT = DeleteRRSetChangeForValidation( okZone, "existing.dotted.txt", - DeleteRRSetChangeInput("existing.dotted.txt.ok.", RecordType.TXT)) + DeleteRRSetChangeInput("existing.dotted.txt.ok.", RecordType.TXT) + ) val result = validateChangesWithContext( ChangeForValidationMap( List( @@ -2138,7 +2436,8 @@ class BatchChangeValidationsSpec deleteAAAA.validNel, deleteCname.validNel, deleteMX.validNel, - deleteTXT.validNel), + deleteTXT.validNel + ), ExistingRecordSets(List(existingA, existingAAAA, existingCname, existingMX, existingTXT)) ), okAuth, @@ -2163,28 +2462,34 @@ class BatchChangeValidationsSpec val deleteA = DeleteRRSetChangeForValidation( okZone, "existing.dotted.a", - DeleteRRSetChangeInput("existing.dotted.a.ok.", RecordType.A)) + DeleteRRSetChangeInput("existing.dotted.a.ok.", RecordType.A) + ) val deleteAAAA = DeleteRRSetChangeForValidation( okZone, "existing.dotted.aaaa", - DeleteRRSetChangeInput("existing.dotted.aaaa.ok.", RecordType.AAAA)) + DeleteRRSetChangeInput("existing.dotted.aaaa.ok.", RecordType.AAAA) + ) val deleteCname = DeleteRRSetChangeForValidation( okZone, "existing.dotted.cname", - DeleteRRSetChangeInput("existing.dotted.cname.ok.", RecordType.CNAME)) + DeleteRRSetChangeInput("existing.dotted.cname.ok.", RecordType.CNAME) + ) val deleteMX = DeleteRRSetChangeForValidation( okZone, "existing.dotted.mx", - DeleteRRSetChangeInput("existing.dotted.mx.ok.", RecordType.MX)) + DeleteRRSetChangeInput("existing.dotted.mx.ok.", RecordType.MX) + ) val deleteTXT = DeleteRRSetChangeForValidation( okZone, "existing.dotted.txt", - DeleteRRSetChangeInput("existing.dotted.txt.ok.", RecordType.TXT)) + DeleteRRSetChangeInput("existing.dotted.txt.ok.", RecordType.TXT) + ) val addUpdateA = AddChangeForValidation( okZone, "existing.dotted.a", - AddChangeInput("existing.dotted.a.ok.", RecordType.A, ttl, AData("1.2.3.4"))) + AddChangeInput("existing.dotted.a.ok.", RecordType.A, ttl, AData("1.2.3.4")) + ) val addUpdateAAAA = AddChangeForValidation( okZone, "existing.dotted.aaaa", @@ -2192,19 +2497,24 @@ class BatchChangeValidationsSpec "existing.dotted.aaaa.ok.", RecordType.AAAA, Some(700), - AAAAData("1:2:3:4:5:6:7:8"))) + AAAAData("1:2:3:4:5:6:7:8") + ) + ) val addUpdateCNAME = AddChangeForValidation( okZone, "existing.dotted.cname", - AddChangeInput("existing.dotted.cname.ok.", RecordType.CNAME, Some(700), CNAMEData("test"))) + AddChangeInput("existing.dotted.cname.ok.", RecordType.CNAME, Some(700), CNAMEData("test")) + ) val addUpdateMX = AddChangeForValidation( okZone, "existing.dotted.mx", - AddChangeInput("existing.dotted.mx.ok.", RecordType.MX, Some(700), MXData(3, "mx"))) + AddChangeInput("existing.dotted.mx.ok.", RecordType.MX, Some(700), MXData(3, "mx")) + ) val addUpdateTXT = AddChangeForValidation( okZone, "existing.dotted.txt", - AddChangeInput("existing.dotted.txt.ok.", RecordType.TXT, Some(700), TXTData("testing"))) + AddChangeInput("existing.dotted.txt.ok.", RecordType.TXT, Some(700), TXTData("testing")) + ) val result = validateChangesWithContext( ChangeForValidationMap( diff --git a/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchTransformationsSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchTransformationsSpec.scala index 0177f948f..828127d58 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchTransformationsSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/batch/BatchTransformationsSpec.scala @@ -49,13 +49,16 @@ class BatchTransformationsSpec extends WordSpec with Matchers { ipv6nonMatch1, ipv6nonMatch2, ipv6nonMatch3, - forwardMatch1)) + forwardMatch1 + ) + ) "getipv4PTRMatches" should { "return all possible matches including proper delegations" in { existingZones.getipv4PTRMatches("3.2.1.2") should contain theSameElementsAs List( ip4base1, - ip4del1) + ip4del1 + ) } "return all possible matches excluding similar delegations" in { existingZones.getipv4PTRMatches("3.2.1.55") should contain theSameElementsAs List(ip4base1) @@ -75,7 +78,8 @@ class BatchTransformationsSpec extends WordSpec with Matchers { // only matches 1st option existingZones.getipv6PTRMatches("2001:0db0:0000:0000:0000:0000:0000:0000") shouldBe List( - ipv6match1) + ipv6match1 + ) existingZones.getipv6PTRMatches("2001:db0::ff00:42:8329") shouldBe List(ipv6match1) } "return empty if there are no matches" in { diff --git a/modules/api/src/test/scala/vinyldns/api/domain/dns/DnsConnectionSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/dns/DnsConnectionSpec.scala index f6da50e76..307c80a32 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/dns/DnsConnectionSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/dns/DnsConnectionSpec.scala @@ -55,7 +55,8 @@ class DnsConnectionSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val testAMultiple = RecordSet( testZone.id, @@ -65,13 +66,15 @@ class DnsConnectionSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("1.1.1.1"), AData("2.2.2.2"))) + List(AData("1.1.1.1"), AData("2.2.2.2")) + ) private val testDnsA = new DNS.ARecord( DNS.Name.fromString("a-record."), DNS.DClass.IN, 200L, - InetAddress.getByName("10.1.1.1")) + InetAddress.getByName("10.1.1.1") + ) private val mockResolver = mock[DNS.SimpleResolver] private val mockMessage = mock[DNS.Message] @@ -81,7 +84,8 @@ class DnsConnectionSpec override def toQuery( name: String, zoneName: String, - typ: RecordType): Either[Throwable, DnsQuery] = + typ: RecordType + ): Either[Throwable, DnsQuery] = name match { case "try-again" => Right(new DnsQuery(new Lookup("try-again.vinyldns.", 0, 0), new Name(testZone.name))) @@ -165,12 +169,14 @@ class DnsConnectionSpec DNS.Name.fromString("a-record."), DNS.DClass.IN, 200L, - InetAddress.getByName("1.1.1.1")) + InetAddress.getByName("1.1.1.1") + ) val a2 = new DNS.ARecord( DNS.Name.fromString("a-record."), DNS.DClass.IN, 200L, - InetAddress.getByName("2.2.2.2")) + InetAddress.getByName("2.2.2.2") + ) doReturn(List(a1, a2)).when(mockDnsQuery).run() val records: List[RecordSet] = @@ -342,7 +348,8 @@ class DnsConnectionSpec } "send an appropriate replace message to the resolver for multiple records" in { val change = updateRsChange(testZone, testAMultiple).copy( - updates = Some(testAMultiple.copy(name = "updated-a-record"))) + updates = Some(testAMultiple.copy(name = "updated-a-record")) + ) val result: DnsResponse = rightResultOf(underTest.updateRecord(change).value) @@ -439,7 +446,8 @@ class DnsConnectionSpec } "send an appropriate replace message to the resolver for multiple records" in { val change = updateRsChange(testZone, testAMultiple).copy( - updates = Some(testAMultiple.copy(records = List(AData("4.4.4.4"), AData("3.3.3.3"))))) + updates = Some(testAMultiple.copy(records = List(AData("4.4.4.4"), AData("3.3.3.3")))) + ) val result: DnsResponse = rightResultOf(underTest.updateRecord(change).value) @@ -535,17 +543,20 @@ class DnsConnectionSpec "applyChange" should { "yield a successful DNS response for a create if there are no errors" in { underTest.applyChange(addRsChange()).value.unsafeRunSync() shouldBe Right( - NoError(mockMessage)) + NoError(mockMessage) + ) } "yield a successful DNS response for an update if there are no errors" in { underTest.applyChange(updateRsChange()).value.unsafeRunSync() shouldBe Right( - NoError(mockMessage)) + NoError(mockMessage) + ) } "yield a successful DNS response for a delete if there are no errors" in { underTest.applyChange(deleteRsChange()).value.unsafeRunSync() shouldBe Right( - NoError(mockMessage)) + NoError(mockMessage) + ) } } diff --git a/modules/api/src/test/scala/vinyldns/api/domain/dns/DnsConversionsSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/dns/DnsConversionsSpec.scala index c0999eeb3..eb01852b9 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/dns/DnsConversionsSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/dns/DnsConversionsSpec.scala @@ -50,7 +50,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val testAMultiple = RecordSet( testZone.id, "a-record", @@ -59,7 +60,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("1.1.1.1"), AData("2.2.2.2"))) + List(AData("1.1.1.1"), AData("2.2.2.2")) + ) private val testAAAA = RecordSet( testZone.id, "aaaa-record", @@ -68,7 +70,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(AAAAData("2001:db8:0:0:0:0:0:3"))) + List(AAAAData("2001:db8:0:0:0:0:0:3")) + ) private val testCNAME = RecordSet( testZone.id, "cname-record", @@ -77,7 +80,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(CNAMEData("cname.foo.vinyldns."))) + List(CNAMEData("cname.foo.vinyldns.")) + ) private val testMX = RecordSet( testZone.id, "mx-record", @@ -86,7 +90,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(MXData(100, "exchange.vinyldns."))) + List(MXData(100, "exchange.vinyldns.")) + ) private val testNS = RecordSet( testZone.id, "ns-record", @@ -95,7 +100,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(NSData("nsdname.vinyldns."))) + List(NSData("nsdname.vinyldns.")) + ) private val testPTR = RecordSet( testZone.id, "ptr-record", @@ -104,7 +110,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(PTRData("ptr.vinyldns."))) + List(PTRData("ptr.vinyldns.")) + ) private val testSOA = RecordSet( testZone.id, "soa-record", @@ -123,7 +130,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(SPFData("spf"))) + List(SPFData("spf")) + ) private val testLongSPF = RecordSet( testZone.id, "long-spf-record", @@ -132,7 +140,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(SPFData("s" * 256))) + List(SPFData("s" * 256)) + ) private val testSRV = RecordSet( testZone.id, "srv-record", @@ -141,7 +150,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(SRVData(1, 2, 3, "target.vinyldns."))) + List(SRVData(1, 2, 3, "target.vinyldns.")) + ) private val testNAPTR = RecordSet( testZone.id, "naptr-record", @@ -160,7 +170,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(SSHFPData(1, 2, "fingerprint"))) + List(SSHFPData(1, 2, "fingerprint")) + ) private val testTXT = RecordSet( testZone.id, "txt-record", @@ -169,7 +180,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(TXTData("text"))) + List(TXTData("text")) + ) private val testLongTXT = RecordSet( testZone.id, "long-txt-record", @@ -178,7 +190,8 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(TXTData("a" * 64763))) + List(TXTData("a" * 64763)) + ) private val testAt = RecordSet( testZone.id, "vinyldns.", @@ -187,45 +200,53 @@ class DnsConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val testDS = ds.copy(zoneId = testZone.id) private val testDnsUnknown = DNS.Record.newRecord( DNS.Name.fromString("unknown-record."), DNS.Type.AFSDB, DNS.DClass.IN, - 200L) + 200L + ) private val testDnsA = new DNS.ARecord( DNS.Name.fromString("a-record."), DNS.DClass.IN, 200L, - InetAddress.getByName("10.1.1.1")) + InetAddress.getByName("10.1.1.1") + ) private val testDnsA1 = new DNS.ARecord( DNS.Name.fromString("a-record."), DNS.DClass.IN, 200L, - InetAddress.getByName("1.1.1.1")) + InetAddress.getByName("1.1.1.1") + ) private val testDnsA2 = new DNS.ARecord( DNS.Name.fromString("a-record."), DNS.DClass.IN, 200L, - InetAddress.getByName("2.2.2.2")) + InetAddress.getByName("2.2.2.2") + ) private val testDnsAReplace = new DNS.ARecord( DNS.Name.fromString("a-record-2."), DNS.DClass.IN, 200L, - InetAddress.getByName("2.2.2.2")) + InetAddress.getByName("2.2.2.2") + ) private val testDnsAAAA = new DNS.AAAARecord( DNS.Name.fromString("aaaa-record."), DNS.DClass.IN, 200L, - InetAddress.getByName("2001:db8::3")) + InetAddress.getByName("2001:db8::3") + ) private val testDnsAt = new DNS.ARecord( DNS.Name.fromString("@", DNS.Name.fromString("vinyldns.")), DNS.DClass.IN, 200L, - InetAddress.getByName("10.1.1.1")) + InetAddress.getByName("10.1.1.1") + ) private val testDnsARRset = new DNS.RRset() testDnsARRset.addRR(testDnsA1) diff --git a/modules/api/src/test/scala/vinyldns/api/domain/membership/MembershipServiceSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/membership/MembershipServiceSpec.scala index 1c2327520..fa7823a2e 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/membership/MembershipServiceSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/membership/MembershipServiceSpec.scala @@ -54,7 +54,8 @@ class MembershipServiceSpec mockMembershipRepo, mockZoneRepo, mockGroupChangeRepo, - mockRecordSetRepo) + mockRecordSetRepo + ) private val underTest = spy(backingService) private val okUserInfo: UserInfo = UserInfo(okUser) @@ -74,7 +75,8 @@ class MembershipServiceSpec private val existingGroup = okGroup.copy( id = "id", memberIds = Set("user1", "user2", "user3", "user4"), - adminUserIds = Set("user1", "user2", "ok")) + adminUserIds = Set("user1", "user2", "ok") + ) // the update will remove users 3 and 4, add users 5 and 6, as well as a new admin user 7 and remove user2 as admin private val updatedInfo = Group( @@ -101,7 +103,8 @@ class MembershipServiceSpec mockMembershipRepo, mockGroupChangeRepo, mockRecordSetRepo, - underTest) + underTest + ) "MembershipService" should { "create a new group" should { @@ -157,7 +160,8 @@ class MembershipServiceSpec doReturn(IO.pure(Some(okUser))).when(mockUserRepo).getUser("ok") val info = groupInfo.copy( memberIds = Set(okUserInfo.id, dummyUserInfo.id), - adminUserIds = Set(okUserInfo.id, dummyUserInfo.id)) + adminUserIds = Set(okUserInfo.id, dummyUserInfo.id) + ) val expectedMembersAdded = Set(okUserInfo.id, dummyUserInfo.id) doReturn(().toResult).when(underTest).groupWithSameNameDoesNotExist(info.name) @@ -275,8 +279,10 @@ class MembershipServiceSpec updatedInfo.description, updatedInfo.memberIds, updatedInfo.adminUserIds, - okAuth) - .value) + okAuth + ) + .value + ) val groupCaptor = ArgumentCaptor.forClass(classOf[Group]) val addedMemberCaptor = ArgumentCaptor.forClass(classOf[Set[String]]) @@ -326,8 +332,10 @@ class MembershipServiceSpec updatedInfo.description, updatedInfo.memberIds, updatedInfo.adminUserIds, - dummyAuth) - .value) + dummyAuth + ) + .value + ) error shouldBe a[NotAuthorizedError] } @@ -350,8 +358,10 @@ class MembershipServiceSpec updatedInfo.description, updatedInfo.memberIds, updatedInfo.adminUserIds, - okAuth) - .value) + okAuth + ) + .value + ) error shouldBe a[GroupAlreadyExistsError] } @@ -367,8 +377,10 @@ class MembershipServiceSpec updatedInfo.description, updatedInfo.memberIds, updatedInfo.adminUserIds, - okAuth) - .value) + okAuth + ) + .value + ) error shouldBe a[GroupNotFoundError] } @@ -392,8 +404,10 @@ class MembershipServiceSpec updatedInfo.description, updatedInfo.memberIds, updatedInfo.adminUserIds, - okAuth) - .value) + okAuth + ) + .value + ) error shouldBe a[UserNotFoundError] } @@ -411,8 +425,10 @@ class MembershipServiceSpec updatedInfo.description, Set(), Set(), - okAuth) - .value) + okAuth + ) + .value + ) error shouldBe an[InvalidGroupError] } } @@ -537,7 +553,8 @@ class MembershipServiceSpec None, nextId = Some(listOfDummyGroups(99).id), maxItems = 100, - ignoreAccess = false) + ignoreAccess = false + ) } "return only return groups whose name matches the filter" in { doReturn(IO.pure(listOfDummyGroups.toSet)) @@ -550,15 +567,18 @@ class MembershipServiceSpec startFrom = None, maxItems = 100, listOfDummyGroupsAuth, - false) - .value) + false + ) + .value + ) result shouldBe ListMyGroupsResponse( groups = listOfDummyGroupInfo.slice(10, 20), groupNameFilter = Some("name-dummy01"), startFrom = None, nextId = None, maxItems = 100, - ignoreAccess = false) + ignoreAccess = false + ) } "return only return groups after startFrom" in { doReturn(IO.pure(listOfDummyGroups.toSet)) @@ -571,15 +591,18 @@ class MembershipServiceSpec startFrom = Some(listOfDummyGroups(99).id), maxItems = 100, listOfDummyGroupsAuth, - ignoreAccess = false) - .value) + ignoreAccess = false + ) + .value + ) result shouldBe ListMyGroupsResponse( groups = listOfDummyGroupInfo.slice(100, 200), groupNameFilter = None, startFrom = Some(listOfDummyGroups(99).id), nextId = None, maxItems = 100, - ignoreAccess = false) + ignoreAccess = false + ) } "return only return maxItems groups" in { doReturn(IO.pure(listOfDummyGroups.toSet)) @@ -592,15 +615,18 @@ class MembershipServiceSpec startFrom = None, maxItems = 10, listOfDummyGroupsAuth, - ignoreAccess = false) - .value) + ignoreAccess = false + ) + .value + ) result shouldBe ListMyGroupsResponse( groups = listOfDummyGroupInfo.slice(0, 10), groupNameFilter = None, startFrom = None, nextId = Some(listOfDummyGroups(9).id), maxItems = 10, - ignoreAccess = false) + ignoreAccess = false + ) } "return an empty set if the user is not a member of any groups" in { doReturn(IO.pure(Set())).when(mockGroupRepo).getGroups(any[Set[String]]) @@ -615,7 +641,8 @@ class MembershipServiceSpec verify(mockGroupRepo).getAllGroups() result.groups should contain theSameElementsAs Seq( GroupInfo(dummyGroup), - GroupInfo(okGroup)) + GroupInfo(okGroup) + ) } "return all groups from the database for super users even if ignoreAccess is false" in { doReturn(IO.pure(Set(okGroup, dummyGroup))).when(mockGroupRepo).getAllGroups() @@ -624,7 +651,8 @@ class MembershipServiceSpec verify(mockGroupRepo).getAllGroups() result.groups should contain theSameElementsAs Seq( GroupInfo(dummyGroup), - GroupInfo(okGroup)) + GroupInfo(okGroup) + ) } "return all groups from the database for super users if ignoreAccess is true" in { doReturn(IO.pure(Set(okGroup, dummyGroup))).when(mockGroupRepo).getAllGroups() @@ -633,7 +661,8 @@ class MembershipServiceSpec verify(mockGroupRepo).getAllGroups() result.groups should contain theSameElementsAs Seq( GroupInfo(dummyGroup), - GroupInfo(okGroup)) + GroupInfo(okGroup) + ) } "return all groups from the database for support users even if ignoreAccess is false" in { val supportAuth = AuthPrincipal(okUser.copy(isSupport = true), Seq()) @@ -643,7 +672,8 @@ class MembershipServiceSpec verify(mockGroupRepo).getAllGroups() result.groups should contain theSameElementsAs Seq( GroupInfo(dummyGroup), - GroupInfo(okGroup)) + GroupInfo(okGroup) + ) } "return all groups from the database for support users if ignoreAccess is true" in { val supportAuth = AuthPrincipal(okUser.copy(isSupport = true), Seq()) @@ -653,7 +683,8 @@ class MembershipServiceSpec verify(mockGroupRepo).getAllGroups() result.groups should contain theSameElementsAs Seq( GroupInfo(dummyGroup), - GroupInfo(okGroup)) + GroupInfo(okGroup) + ) } "do not return deleted groups" in { val deletedGroupAuth: AuthPrincipal = AuthPrincipal(okUser, Seq(deletedGroup.id)) @@ -670,7 +701,8 @@ class MembershipServiceSpec "return the group activity" in { val groupChangeRepoResponse = ListGroupChangesResults( listOfDummyGroupChanges.take(100), - Some(listOfDummyGroupChanges(100).id)) + Some(listOfDummyGroupChanges(100).id) + ) doReturn(IO.pure(groupChangeRepoResponse)) .when(mockGroupChangeRepo) .getGroupChanges(anyString, any[Option[String]], anyInt) @@ -748,7 +780,8 @@ class MembershipServiceSpec val expectedMembers = List(MemberInfo(okUser, okGroup), MemberInfo(dummyUser, dummyGroup)) val supportAuth = okAuth.copy( signedInUser = dummyAuth.signedInUser.copy(isSupport = true), - memberGroupIds = Seq.empty) + memberGroupIds = Seq.empty + ) doReturn(IO.pure(Some(testGroup))).when(mockGroupRepo).getGroup(testGroup.id) doReturn(IO.pure(testListUsersResult)) @@ -830,7 +863,8 @@ class MembershipServiceSpec doReturn(IO.pure(Some(okGroup))).when(mockGroupRepo).getGroupByName(okGroup.name) val result = awaitResultOf( - underTest.differentGroupWithSameNameDoesNotExist(okGroup.name, okGroup.id).value) + underTest.differentGroupWithSameNameDoesNotExist(okGroup.name, okGroup.id).value + ) result should be(right) } @@ -842,7 +876,8 @@ class MembershipServiceSpec .getGroupByName(okGroup.name) val result = awaitResultOf( - underTest.differentGroupWithSameNameDoesNotExist(okGroup.name, okGroup.id).value) + underTest.differentGroupWithSameNameDoesNotExist(okGroup.name, okGroup.id).value + ) result should be(right) } } @@ -942,7 +977,8 @@ class MembershipServiceSpec val error = leftResultOf( underTest .updateUserLockStatus(okUser.id, LockStatus.Locked, dummyAuth) - .value) + .value + ) error shouldBe a[NotAuthorizedError] } @@ -950,11 +986,13 @@ class MembershipServiceSpec "return an error if the signed in user is only a support admin" in { val supportAuth = okAuth.copy( signedInUser = dummyAuth.signedInUser.copy(isSupport = true), - memberGroupIds = Seq.empty) + memberGroupIds = Seq.empty + ) val error = leftResultOf( underTest .updateUserLockStatus(okUser.id, LockStatus.Locked, supportAuth) - .value) + .value + ) error shouldBe a[NotAuthorizedError] } @@ -965,7 +1003,8 @@ class MembershipServiceSpec val error = leftResultOf( underTest .updateUserLockStatus(okUser.id, LockStatus.Locked, superUserAuth) - .value) + .value + ) error shouldBe a[UserNotFoundError] } diff --git a/modules/api/src/test/scala/vinyldns/api/domain/record/RecordSetServiceSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/record/RecordSetServiceSpec.scala index bb46ac55c..40f60343a 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/record/RecordSetServiceSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/record/RecordSetServiceSpec.scala @@ -68,7 +68,8 @@ class RecordSetServiceSpec mockRecordChangeRepo, mockUserRepo, mockMessageQueue, - new AccessValidations()) + new AccessValidations() + ) "addRecordSet" should { "return the recordSet change as the result" in { @@ -83,7 +84,8 @@ class RecordSetServiceSpec val result: RecordSetChange = rightResultOf( - underTest.addRecordSet(record, okAuth).map(_.asInstanceOf[RecordSetChange]).value) + underTest.addRecordSet(record, okAuth).map(_.asInstanceOf[RecordSetChange]).value + ) matches(result.recordSet, record, okZone.name) shouldBe true result.changeType shouldBe RecordSetChangeType.Create @@ -148,7 +150,8 @@ class RecordSetServiceSpec val result = leftResultOf(underTest.addRecordSet(record, okAuth).value) result shouldBe InvalidRequest( - HighValueDomainError(s"high-value-domain.${okZone.name}").message) + HighValueDomainError(s"high-value-domain.${okZone.name}").message + ) } "succeed if record is apex with dot" in { val name = okZone.name @@ -163,7 +166,8 @@ class RecordSetServiceSpec .getRecordSetsByName(okZone.id, record.name) val result: RecordSetChange = rightResultOf( - underTest.addRecordSet(record, okAuth).map(_.asInstanceOf[RecordSetChange]).value) + underTest.addRecordSet(record, okAuth).map(_.asInstanceOf[RecordSetChange]).value + ) result.recordSet.name shouldBe okZone.name } @@ -180,7 +184,8 @@ class RecordSetServiceSpec .getRecordSetsByName(okZone.id, record.name) val result: RecordSetChange = rightResultOf( - underTest.addRecordSet(record, okAuth).map(_.asInstanceOf[RecordSetChange]).value) + underTest.addRecordSet(record, okAuth).map(_.asInstanceOf[RecordSetChange]).value + ) result.recordSet.name shouldBe okZone.name } @@ -197,7 +202,8 @@ class RecordSetServiceSpec .getRecordSetsByName(okZone.id, record.name) val result: RecordSetChange = rightResultOf( - underTest.addRecordSet(record, okAuth).map(_.asInstanceOf[RecordSetChange]).value) + underTest.addRecordSet(record, okAuth).map(_.asInstanceOf[RecordSetChange]).value + ) result.recordSet.name shouldBe okZone.name } @@ -215,7 +221,8 @@ class RecordSetServiceSpec .getGroup(okGroup.id) val result: RecordSetChange = rightResultOf( - underTest.addRecordSet(record, okAuth).map(_.asInstanceOf[RecordSetChange]).value) + underTest.addRecordSet(record, okAuth).map(_.asInstanceOf[RecordSetChange]).value + ) result.recordSet.ownerGroupId shouldBe Some(okGroup.id) } @@ -268,7 +275,8 @@ class RecordSetServiceSpec .getRecordSetsByName(okZone.id, newRecord.name) val result: RecordSetChange = rightResultOf( - underTest.updateRecordSet(newRecord, okAuth).map(_.asInstanceOf[RecordSetChange]).value) + underTest.updateRecordSet(newRecord, okAuth).map(_.asInstanceOf[RecordSetChange]).value + ) matches(result.recordSet, newRecord, okZone.name) shouldBe true matches(result.updates.get, oldRecord, okZone.name) shouldBe true @@ -280,7 +288,8 @@ class RecordSetServiceSpec .when(mockRecordRepo) .getRecordSet(zoneNotAuthorized.id, aaaa.id) val result = leftResultOf( - underTest.updateRecordSet(aaaa.copy(zoneId = zoneNotAuthorized.id), okAuth).value) + underTest.updateRecordSet(aaaa.copy(zoneId = zoneNotAuthorized.id), okAuth).value + ) result shouldBe a[NotAuthorizedError] } "fail if the new record name is dotted" in { @@ -324,7 +333,8 @@ class RecordSetServiceSpec .getRecordSetsByName(okZone.id, newRecord.name) val result: RecordSetChange = rightResultOf( - underTest.updateRecordSet(newRecord, okAuth).map(_.asInstanceOf[RecordSetChange]).value) + underTest.updateRecordSet(newRecord, okAuth).map(_.asInstanceOf[RecordSetChange]).value + ) result.recordSet.name shouldBe okZone.name } @@ -341,7 +351,8 @@ class RecordSetServiceSpec .getRecordSetsByName(okZone.id, newRecord.name) val result: RecordSetChange = rightResultOf( - underTest.updateRecordSet(newRecord, okAuth).map(_.asInstanceOf[RecordSetChange]).value) + underTest.updateRecordSet(newRecord, okAuth).map(_.asInstanceOf[RecordSetChange]).value + ) result.recordSet.name shouldBe okZone.name } @@ -358,7 +369,8 @@ class RecordSetServiceSpec .getRecordSetsByName(okZone.id, newRecord.name) val result: RecordSetChange = rightResultOf( - underTest.updateRecordSet(newRecord, okAuth).map(_.asInstanceOf[RecordSetChange]).value) + underTest.updateRecordSet(newRecord, okAuth).map(_.asInstanceOf[RecordSetChange]).value + ) result.recordSet.name shouldBe okZone.name } @@ -370,7 +382,8 @@ class RecordSetServiceSpec val result = leftResultOf(underTest.updateRecordSet(newRecord, okAuth).value) result shouldBe InvalidRequest( - HighValueDomainError(s"high-value-domain.${okZone.name}").message) + HighValueDomainError(s"high-value-domain.${okZone.name}").message + ) } "fail if user is in owner group but zone is not shared" in { val auth = AuthPrincipal(listOfDummyUsers.head, Seq(oneUserDummyGroup.id)) @@ -378,7 +391,8 @@ class RecordSetServiceSpec name = "test-owner-group-failure", zoneId = okZone.id, status = RecordSetStatus.Active, - ownerGroupId = Some(oneUserDummyGroup.id)) + ownerGroupId = Some(oneUserDummyGroup.id) + ) val newRecord = oldRecord.copy(ttl = oldRecord.ttl + 1000) @@ -393,7 +407,8 @@ class RecordSetServiceSpec name = "test-owner-group-failure", zoneId = zone.id, status = RecordSetStatus.Active, - ownerGroupId = Some(oneUserDummyGroup.id)) + ownerGroupId = Some(oneUserDummyGroup.id) + ) val newRecord = oldRecord.copy(ownerGroupId = Some("doesnt-exist")) @@ -421,7 +436,8 @@ class RecordSetServiceSpec name = "test-owner-group-failure", zoneId = zone.id, status = RecordSetStatus.Active, - ownerGroupId = Some(oneUserDummyGroup.id)) + ownerGroupId = Some(oneUserDummyGroup.id) + ) val newRecord = oldRecord.copy(ownerGroupId = Some(okGroup.id)) @@ -448,7 +464,8 @@ class RecordSetServiceSpec name = "test-owner-group-success", zoneId = zone.id, status = RecordSetStatus.Active, - ownerGroupId = Some(oneUserDummyGroup.id)) + ownerGroupId = Some(oneUserDummyGroup.id) + ) val newRecord = oldRecord.copy(ttl = oldRecord.ttl + 1000) @@ -466,7 +483,8 @@ class RecordSetServiceSpec .getGroup(oneUserDummyGroup.id) val result = rightResultOf( - underTest.updateRecordSet(newRecord, auth).map(_.asInstanceOf[RecordSetChange]).value) + underTest.updateRecordSet(newRecord, auth).map(_.asInstanceOf[RecordSetChange]).value + ) result.recordSet.ttl shouldBe newRecord.ttl result.recordSet.ownerGroupId shouldBe Some(oneUserDummyGroup.id) @@ -478,7 +496,8 @@ class RecordSetServiceSpec name = "test-owner-group-success", zoneId = zone.id, status = RecordSetStatus.Active, - ownerGroupId = Some(oneUserDummyGroup.id)) + ownerGroupId = Some(oneUserDummyGroup.id) + ) val newRecord = oldRecord.copy(ownerGroupId = None) @@ -493,7 +512,8 @@ class RecordSetServiceSpec .getRecordSetsByName(zone.id, newRecord.name) val result = rightResultOf( - underTest.updateRecordSet(newRecord, auth).map(_.asInstanceOf[RecordSetChange]).value) + underTest.updateRecordSet(newRecord, auth).map(_.asInstanceOf[RecordSetChange]).value + ) result.recordSet.ttl shouldBe newRecord.ttl result.recordSet.ownerGroupId shouldBe None @@ -527,7 +547,8 @@ class RecordSetServiceSpec underTest .deleteRecordSet(record.id, okZone.id, okAuth) .map(_.asInstanceOf[RecordSetChange]) - .value) + .value + ) matches(result.recordSet, record, okZone.name) shouldBe true result.changeType shouldBe RecordSetChangeType.Delete @@ -552,12 +573,14 @@ class RecordSetServiceSpec val result = leftResultOf(underTest.deleteRecordSet(record.id, okZone.id, okAuth).value) result shouldBe InvalidRequest( - HighValueDomainError(s"high-value-domain.${okZone.name}").message) + HighValueDomainError(s"high-value-domain.${okZone.name}").message + ) } "fail for user who is not in record owner group in shared zone" in { val result = leftResultOf( - underTest.deleteRecordSet(sharedZoneRecord.id, sharedZoneRecord.zoneId, dummyAuth).value) + underTest.deleteRecordSet(sharedZoneRecord.id, sharedZoneRecord.zoneId, dummyAuth).value + ) result shouldBe a[NotAuthorizedError] } @@ -568,7 +591,8 @@ class RecordSetServiceSpec val result = leftResultOf( - underTest.deleteRecordSet(sharedZoneRecord.id, sharedZoneRecord.zoneId, okAuth).value) + underTest.deleteRecordSet(sharedZoneRecord.id, sharedZoneRecord.zoneId, okAuth).value + ) result shouldBe a[NotAuthorizedError] } @@ -682,7 +706,8 @@ class RecordSetServiceSpec val result: RecordSetInfo = rightResultOf( - underTest.getRecordSet(sharedZoneRecordNoOwnerGroup.id, sharedZone.id, sharedAuth).value) + underTest.getRecordSet(sharedZoneRecordNoOwnerGroup.id, sharedZone.id, sharedAuth).value + ) result shouldBe expectedRecordSetInfo } @@ -697,7 +722,8 @@ class RecordSetServiceSpec leftResultOf( underTest .getRecordSet(sharedZoneRecordNotApprovedRecordType.id, sharedZone.id, okAuth) - .value) + .value + ) result shouldBe a[NotAuthorizedError] } @@ -726,7 +752,8 @@ class RecordSetServiceSpec val result = leftResultOf( underTest .getRecordSet(notSharedZoneRecordWithOwnerGroup.id, zoneNotAuthorized.id, okAuth) - .value) + .value + ) result shouldBe a[NotAuthorizedError] } } @@ -752,13 +779,14 @@ class RecordSetServiceSpec .getGroups(Set(okGroup.id, "not-in-backend")) doReturn( - IO.pure(ListRecordSetResults(List(sharedZoneRecord, sharedZoneRecordNotFoundOwnerGroup)))) - .when(mockRecordRepo) + IO.pure(ListRecordSetResults(List(sharedZoneRecord, sharedZoneRecordNotFoundOwnerGroup))) + ).when(mockRecordRepo) .listRecordSets( zoneId = sharedZone.id, startFrom = None, maxItems = None, - recordNameFilter = None) + recordNameFilter = None + ) val result: ListRecordSetsResponse = rightResultOf( underTest @@ -767,16 +795,20 @@ class RecordSetServiceSpec startFrom = None, maxItems = None, recordNameFilter = None, - authPrincipal = sharedAuth) - .value) + authPrincipal = sharedAuth + ) + .value + ) result.recordSets shouldBe List( RecordSetListInfo( RecordSetInfo(sharedZoneRecord, Some(okGroup.name)), - AccessLevel.Delete), + AccessLevel.Delete + ), RecordSetListInfo( RecordSetInfo(sharedZoneRecordNotFoundOwnerGroup, None), - AccessLevel.Delete) + AccessLevel.Delete + ) ) } "return the recordSet for support admin" in { @@ -790,7 +822,8 @@ class RecordSetServiceSpec zoneId = okZone.id, startFrom = None, maxItems = None, - recordNameFilter = None) + recordNameFilter = None + ) val result: ListRecordSetsResponse = rightResultOf( underTest @@ -801,9 +834,11 @@ class RecordSetServiceSpec recordNameFilter = None, authPrincipal = AuthPrincipal(okAuth.signedInUser.copy(isSupport = true), Seq.empty) ) - .value) + .value + ) result.recordSets shouldBe List( - RecordSetListInfo(RecordSetInfo(aaaa, None), AccessLevel.Read)) + RecordSetListInfo(RecordSetInfo(aaaa, None), AccessLevel.Read) + ) } "fails when the account is not authorized" in { val result = leftResultOf( @@ -813,8 +848,10 @@ class RecordSetServiceSpec startFrom = None, maxItems = None, recordNameFilter = None, - authPrincipal = okAuth) - .value) + authPrincipal = okAuth + ) + .value + ) result shouldBe a[NotAuthorizedError] } } @@ -840,7 +877,8 @@ class RecordSetServiceSpec recordSetChanges = changesWithName, nextId = None, startFrom = None, - maxItems = 100) + maxItems = 100 + ) result shouldBe expectedResults } @@ -856,13 +894,15 @@ class RecordSetServiceSpec recordSetChanges = List(), nextId = None, startFrom = None, - maxItems = 100) + maxItems = 100 + ) result shouldBe expectedResults } "return a NotAuthorizedError" in { val error = leftResultOf( - underTest.listRecordSetChanges(zoneNotAuthorized.id, authPrincipal = okAuth).value) + underTest.listRecordSetChanges(zoneNotAuthorized.id, authPrincipal = okAuth).value + ) error shouldBe a[NotAuthorizedError] } @@ -883,7 +923,8 @@ class RecordSetServiceSpec recordSetChanges = changesWithName, nextId = None, startFrom = None, - maxItems = 100) + maxItems = 100 + ) result shouldBe expectedResults } } @@ -906,7 +947,8 @@ class RecordSetServiceSpec val actual: RecordSetChange = rightResultOf( - underTest.getRecordSetChange(sharedZone.id, pendingCreateSharedRecord.id, okAuth).value) + underTest.getRecordSetChange(sharedZone.id, pendingCreateSharedRecord.id, okAuth).value + ) actual shouldBe pendingCreateSharedRecord } @@ -926,7 +968,8 @@ class RecordSetServiceSpec .getRecordSetChange(zoneActive.id, pendingCreateAAAA.id) val error = leftResultOf( - underTest.getRecordSetChange(zoneActive.id, pendingCreateAAAA.id, dummyAuth).value) + underTest.getRecordSetChange(zoneActive.id, pendingCreateAAAA.id, dummyAuth).value + ) error shouldBe a[NotAuthorizedError] } @@ -937,9 +980,15 @@ class RecordSetServiceSpec .when(mockRecordChangeRepo) .getRecordSetChange(zoneNotAuthorized.id, pendingCreateSharedRecordNotSharedZone.id) - val error = leftResultOf(underTest - .getRecordSetChange(zoneNotAuthorized.id, pendingCreateSharedRecordNotSharedZone.id, okAuth) - .value) + val error = leftResultOf( + underTest + .getRecordSetChange( + zoneNotAuthorized.id, + pendingCreateSharedRecordNotSharedZone.id, + okAuth + ) + .value + ) error shouldBe a[NotAuthorizedError] } diff --git a/modules/api/src/test/scala/vinyldns/api/domain/record/RecordSetValidationsSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/record/RecordSetValidationsSpec.scala index efd7b9456..4037eff77 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/record/RecordSetValidationsSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/record/RecordSetValidationsSpec.scala @@ -209,7 +209,8 @@ class RecordSetValidationsSpec dottedARecord, List(), okZone, - Some(dottedARecord.copy(ttl = 300))) should be(right) + Some(dottedARecord.copy(ttl = 300)) + ) should be(right) } "return a success for any existing record with dotted hosts in forward zones (CNAME)" in { @@ -218,7 +219,8 @@ class RecordSetValidationsSpec dottedCNAMERecord, List(), okZone, - Some(dottedCNAMERecord.copy(ttl = 300))) should be(right) + Some(dottedCNAMERecord.copy(ttl = 300)) + ) should be(right) } "return a failure for any existing record with dotted hosts in forward zones (NS)" in { @@ -228,7 +230,8 @@ class RecordSetValidationsSpec dottedNSRecord, List(), okZone, - Some(dottedNSRecord.copy(ttl = 300))) + Some(dottedNSRecord.copy(ttl = 300)) + ) ) shouldBe an[InvalidRequest] } } @@ -311,7 +314,8 @@ class RecordSetValidationsSpec RecordSetStatus.Active, DateTime.now, None, - List(SOAData("something", "other", 1, 2, 3, 5, 6))) + List(SOAData("something", "other", 1, 2, 3, 5, 6)) + ) typeSpecificValidations(test, List(), zoneIp4) should be(right) } @@ -323,7 +327,8 @@ class RecordSetValidationsSpec "return ok if the record is an NS record but not origin" in { val valid = invalidNsApexRs.copy( name = "this-is-not-origin-mate", - records = List(NSData("some.test.ns."))) + records = List(NSData("some.test.ns.")) + ) nsValidations(valid, okZone) should be(right) } @@ -406,12 +411,14 @@ class RecordSetValidationsSpec } "return ok if new recordset name does not contain dot" in { cnameValidations(cname, List(), okZone, Some(cname.copy(name = "not-dotted"))) should be( - right) + right + ) } "return ok if dotted host name doesn't change" in { val newRecord = cname.copy(name = "dot.ted", ttl = 500) cnameValidations(newRecord, List(), okZone, Some(newRecord.copy(ttl = 300))) should be( - right) + right + ) } "return an InvalidRequest if a cname record set name is updated to '@'" in { val error = leftValue(cnameValidations(cname.copy(name = "@"), List(), okZone, Some(cname))) @@ -485,7 +492,8 @@ class RecordSetValidationsSpec val ownerGroupIdBad = "bar" val auth = okAuth.copy( memberGroupIds = Seq("foo"), - signedInUser = okAuth.signedInUser.copy(isSuper = true)) + signedInUser = okAuth.signedInUser.copy(isSuper = true) + ) val ownerGroup = Group(id = ownerGroupIdGood, name = "test", email = "test@test.com") canUseOwnerGroup(Some(ownerGroupIdGood), Some(ownerGroup), auth) should be(right) diff --git a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneConnectionValidatorSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneConnectionValidatorSpec.scala index b425cbee0..8b17d36e3 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneConnectionValidatorSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneConnectionValidatorSpec.scala @@ -103,7 +103,8 @@ class ZoneConnectionValidatorSpec RecordSetStatus.Active, DateTime.now, None, - List(SOAData("something", "other", 1, 2, 3, 5, 6))) + List(SOAData("something", "other", 1, 2, 3, 5, 6)) + ) private val successNS = RecordSet( testZone.id, @@ -113,7 +114,8 @@ class ZoneConnectionValidatorSpec RecordSetStatus.Active, DateTime.now, None, - List(NSData("some.test.ns."))) + List(NSData("some.test.ns.")) + ) private val failureNs = RecordSet( testZone.id, @@ -123,7 +125,8 @@ class ZoneConnectionValidatorSpec RecordSetStatus.Active, DateTime.now, None, - List(NSData("some.test.ns."), NSData("not.approved."))) + List(NSData("some.test.ns."), NSData("not.approved.")) + ) private val delegatedNS = RecordSet( testZone.id, @@ -133,7 +136,8 @@ class ZoneConnectionValidatorSpec RecordSetStatus.Active, DateTime.now, None, - List(NSData("sub.some.test.ns."))) + List(NSData("sub.some.test.ns.")) + ) private val mockRecordSet = mock[RecordSet] @@ -142,7 +146,8 @@ class ZoneConnectionValidatorSpec val backend = DnsBackend( "some-backend-id", zc.copy(name = "backend-conn"), - transfer.copy(name = "backend-transfer")) + transfer.copy(name = "backend-transfer") + ) val connections = ConfiguredDnsConnections(zc, transfer, List(backend)) "ConnectionValidator" should { @@ -172,7 +177,8 @@ class ZoneConnectionValidatorSpec result shouldBe ZoneValidationFailed( testZone, List(s"Name Server not.approved. is not an approved name server."), - "Zone could not be loaded due to validation errors.") + "Zone could not be loaded due to validation errors." + ) } "respond with a failure if no records are returned from the backend" in { @@ -187,7 +193,8 @@ class ZoneConnectionValidatorSpec result shouldBe ZoneValidationFailed( testZone, List("Missing apex NS record"), - "Zone could not be loaded due to validation errors.") + "Zone could not be loaded due to validation errors." + ) } "respond with a failure if any failure is returned from the backend" in { @@ -256,7 +263,8 @@ class ZoneConnectionValidatorSpec val backend = DnsBackend("some-test-backend", testDefaultConnection, testDefaultConnection) val underTest = new ZoneConnectionValidator( - ConfiguredDnsConnections(testDefaultConnection, testDefaultConnection, List(backend))) + ConfiguredDnsConnections(testDefaultConnection, testDefaultConnection, List(backend)) + ) "return success if the backendId exists" in { underTest.isValidBackendId(Some("some-test-backend")) shouldBe right diff --git a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneRecordValidationsSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneRecordValidationsSpec.scala index fa2a6a13e..d1ca2719e 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneRecordValidationsSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneRecordValidationsSpec.scala @@ -77,7 +77,8 @@ class ZoneRecordValidationsSpec extends WordSpec with Matchers with ValidatedMat "return an error if fqdn is in high value list" in { val result = isNotHighValueFqdn(highValueRegexList, "high-value-domain.foo.") result should haveInvalid[DomainValidationError]( - HighValueDomainError("high-value-domain.foo.")) + HighValueDomainError("high-value-domain.foo.") + ) } } @@ -134,14 +135,15 @@ class ZoneRecordValidationsSpec extends WordSpec with Matchers with ValidatedMat "return failure if none of the name servers are in the list of approved name servers" in { val test = ns.copy(records = List(NSData("blah1."), NSData("blah2."))) containsApprovedNameServers(approvedNameServers, test) should haveInvalid( - "Name Server blah1. is not an approved name server.").and( - haveInvalid("Name Server blah2. is not an approved name server.")) + "Name Server blah1. is not an approved name server." + ).and(haveInvalid("Name Server blah2. is not an approved name server.")) } "return a failure if any of the name servers are not in the list of approved name servers" in { val test = ns.copy(records = List(NSData("blah1."), NSData("ns1.test.com"))) containsApprovedNameServers(approvedNameServers, test) should haveInvalid( - "Name Server blah1. is not an approved name server.") + "Name Server blah1. is not an approved name server." + ) } "return success if the name server matches a regular expression" in { @@ -160,7 +162,8 @@ class ZoneRecordValidationsSpec extends WordSpec with Matchers with ValidatedMat val test = ns.copy(records = List(NSData("test-foo-ns."))) val approved = List(".*bar.*".r, "www.*".r) containsApprovedNameServers(approved, test) should haveInvalid( - "Name Server test-foo-ns. is not an approved name server.") + "Name Server test-foo-ns. is not an approved name server." + ) } } diff --git a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneServiceSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneServiceSpec.scala index 2d26fe430..703a5f33c 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneServiceSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneServiceSpec.scala @@ -74,20 +74,23 @@ class ZoneServiceSpec TestConnectionValidator, mockMessageQueue, new ZoneValidations(1000), - new AccessValidations()) + new AccessValidations() + ) private val createZoneAuthorized = CreateZoneInput( "ok.zone.recordsets.", "test@test.com", connection = testConnection, - adminGroupId = okGroup.id) + adminGroupId = okGroup.id + ) private val updateZoneAuthorized = UpdateZoneInput( okZone.id, "ok.zone.recordsets.", "updated-test@test.com", connection = testConnection, - adminGroupId = okGroup.id) + adminGroupId = okGroup.id + ) override protected def beforeEach(): Unit = { reset(mockGroupRepo, mockZoneRepo, mockUserRepo) @@ -100,7 +103,8 @@ class ZoneServiceSpec doReturn(IO.pure(None)).when(mockZoneRepo).getZoneByName(anyString) val resultChange: ZoneChange = rightResultOf( - underTest.connectToZone(createZoneAuthorized, okAuth).map(_.asInstanceOf[ZoneChange]).value) + underTest.connectToZone(createZoneAuthorized, okAuth).map(_.asInstanceOf[ZoneChange]).value + ) resultChange.changeType shouldBe ZoneChangeType.Create Option(resultChange.created) shouldBe defined @@ -124,7 +128,8 @@ class ZoneServiceSpec underTest .connectToZone(createZoneAuthorized, nonTestUser) .map(_.asInstanceOf[ZoneChange]) - .value) + .value + ) resultChange.zone.isTest shouldBe false } @@ -138,7 +143,8 @@ class ZoneServiceSpec underTest .connectToZone(createZoneAuthorized, testUser) .map(_.asInstanceOf[ZoneChange]) - .value) + .value + ) resultChange.zone.isTest shouldBe true } @@ -164,7 +170,8 @@ class ZoneServiceSpec doReturn(IO.pure(Some(zoneDeleted))).when(mockZoneRepo).getZoneByName(anyString) val resultChange: ZoneChange = rightResultOf( - underTest.connectToZone(createZoneAuthorized, okAuth).map(_.asInstanceOf[ZoneChange]).value) + underTest.connectToZone(createZoneAuthorized, okAuth).map(_.asInstanceOf[ZoneChange]).value + ) resultChange.changeType shouldBe ZoneChangeType.Create } @@ -181,7 +188,8 @@ class ZoneServiceSpec doReturn(IO.pure(None)).when(mockZoneRepo).getZoneByName(anyString) val resultZone = rightResultOf( - underTest.connectToZone(newZone, superUserAuth).map(_.asInstanceOf[ZoneChange]).value).zone + underTest.connectToZone(newZone, superUserAuth).map(_.asInstanceOf[ZoneChange]).value + ).zone Option(resultZone.id) should not be None resultZone.email shouldBe okZone.email @@ -199,7 +207,8 @@ class ZoneServiceSpec underTest .connectToZone(newZone, supportUserAuth) .map(_.asInstanceOf[ZoneChange]) - .value).zone + .value + ).zone Option(resultZone.id) should not be None resultZone.email shouldBe okZone.email @@ -237,7 +246,8 @@ class ZoneServiceSpec .updateZone(updateZoneInput, doubleAuth) .map(_.asInstanceOf[ZoneChange]) .value, - duration = 2.seconds) + duration = 2.seconds + ) resultChange.zone.id shouldBe okZone.id resultChange.changeType shouldBe ZoneChangeType.Update @@ -259,7 +269,8 @@ class ZoneServiceSpec underTest .updateZone(newZone, doubleAuth) .map(_.asInstanceOf[ZoneChange]) - .value) + .value + ) resultChange.zone.id shouldBe oldZone.id resultChange.zone.connection shouldBe oldZone.connection } @@ -302,7 +313,8 @@ class ZoneServiceSpec val result = rightResultOf( underTest .updateZone(newZone, AuthPrincipal(superUser, List.empty)) - .value) + .value + ) result shouldBe a[ZoneChange] } @@ -315,7 +327,8 @@ class ZoneServiceSpec val result = rightResultOf( underTest .updateZone(newZone, supportUserAuth) - .value) + .value + ) result shouldBe a[ZoneChange] } @@ -449,7 +462,8 @@ class ZoneServiceSpec zoneWithRules, ZoneACLInfo(Set(goodUserRuleInfo, goodGroupRuleInfo, goodAllRuleInfo)), goodGroup.name, - AccessLevel.Delete) + AccessLevel.Delete + ) val result: ZoneInfo = rightResultOf(underTest.getZone(zoneWithRules.id, abcAuth).value) result shouldBe expectedZoneInfo } @@ -564,8 +578,10 @@ class ZoneServiceSpec List(abcZone, xyzZone), maxItems = 2, nextId = Some("zone2."), - ignoreAccess = false))) - .when(mockZoneRepo) + ignoreAccess = false + ) + ) + ).when(mockZoneRepo) .listZones(abcAuth, None, None, 2, false) doReturn(IO.pure(Set(abcGroup, xyzGroup))) .when(mockGroupRepo) @@ -588,8 +604,10 @@ class ZoneServiceSpec zonesFilter = Some("foo"), maxItems = 2, nextId = Some("zone2."), - ignoreAccess = false))) - .when(mockZoneRepo) + ignoreAccess = false + ) + ) + ).when(mockZoneRepo) .listZones(abcAuth, Some("foo"), None, 2, false) doReturn(IO.pure(Set(abcGroup, xyzGroup))) .when(mockGroupRepo) @@ -610,8 +628,10 @@ class ZoneServiceSpec List(abcZone, xyzZone), startFrom = Some("zone4."), maxItems = 2, - ignoreAccess = false))) - .when(mockZoneRepo) + ignoreAccess = false + ) + ) + ).when(mockZoneRepo) .listZones(abcAuth, None, Some("zone4."), 2, false) doReturn(IO.pure(Set(abcGroup, xyzGroup))) .when(mockGroupRepo) @@ -631,8 +651,10 @@ class ZoneServiceSpec startFrom = Some("zone4."), maxItems = 2, nextId = Some("zone6."), - ignoreAccess = false))) - .when(mockZoneRepo) + ignoreAccess = false + ) + ) + ).when(mockZoneRepo) .listZones(abcAuth, None, Some("zone4."), 2, false) doReturn(IO.pure(Set(abcGroup, xyzGroup))) .when(mockGroupRepo) @@ -719,7 +741,8 @@ class ZoneServiceSpec underTest .addACLRule(okZone.id, userAclRuleInfo, okAuth) .map(_.asInstanceOf[ZoneChange]) - .value) + .value + ) result.changeType shouldBe ZoneChangeType.Update result.zone.acl.rules.size shouldBe 1 @@ -754,7 +777,8 @@ class ZoneServiceSpec underTest .deleteACLRule(zone.id, userAclRuleInfo, okAuth) .map(_.asInstanceOf[ZoneChange]) - .value) + .value + ) result.changeType shouldBe ZoneChangeType.Update result.zone.acl.rules.size shouldBe 0 diff --git a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneValidationsSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneValidationsSpec.scala index bdc3425f2..a670bd73f 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneValidationsSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneValidationsSpec.scala @@ -62,7 +62,8 @@ class ZoneValidationsSpec "fail if given an invalid CIDR rule" in { val invalidPtrAclRuleInfo = baseAclRuleInfo.copy( recordMask = Some("not a cidr rule"), - recordTypes = Set(RecordType.PTR)) + recordTypes = Set(RecordType.PTR) + ) val error = leftValue(isValidAclRule(ACLRule(invalidPtrAclRuleInfo))) error shouldBe a[InvalidRequest] error.getMessage shouldBe "PTR types must have no mask or a valid CIDR mask: Invalid CIDR block" @@ -71,7 +72,8 @@ class ZoneValidationsSpec "fail if there are multiple record types including PTR and mask is regex" in { val invalidMultipleTypeInfo = baseAclRuleInfo.copy( recordMask = Some("regex"), - recordTypes = Set(RecordType.A, RecordType.AAAA, RecordType.CNAME, RecordType.PTR)) + recordTypes = Set(RecordType.A, RecordType.AAAA, RecordType.CNAME, RecordType.PTR) + ) val error = leftValue(isValidAclRule(ACLRule(invalidMultipleTypeInfo))) error shouldBe a[InvalidRequest] } @@ -79,14 +81,16 @@ class ZoneValidationsSpec "fail if there are multiple record types including PTR and mask is cidr" in { val invalidMultipleTypeInfo = baseAclRuleInfo.copy( recordMask = Some("10.10.10.10/5"), - recordTypes = Set(RecordType.A, RecordType.AAAA, RecordType.CNAME, RecordType.PTR)) + recordTypes = Set(RecordType.A, RecordType.AAAA, RecordType.CNAME, RecordType.PTR) + ) val error = leftValue(isValidAclRule(ACLRule(invalidMultipleTypeInfo))) error shouldBe a[InvalidRequest] } "pass if there are multiple record types including PTR and mask is None" in { val validMultipleTypeNoneAclRuleInfo = baseAclRuleInfo.copy( - recordTypes = Set(RecordType.A, RecordType.AAAA, RecordType.CNAME, RecordType.PTR)) + recordTypes = Set(RecordType.A, RecordType.AAAA, RecordType.CNAME, RecordType.PTR) + ) isValidAclRule(ACLRule(validMultipleTypeNoneAclRuleInfo)) should be(right) } diff --git a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneViewLoaderSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneViewLoaderSpec.scala index 719b421e1..e0c2a005a 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneViewLoaderSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneViewLoaderSpec.scala @@ -38,7 +38,8 @@ class ZoneViewLoaderSpec extends WordSpec with Matchers with MockitoSugar with D val testZoneName = "vinyldns." val testZoneConnection: Option[ZoneConnection] = Some( - ZoneConnection(testZoneName, testZoneName, "nzisn+4G2ldMn0q1CV3vsg==", "127.0.0.1:19001")) + ZoneConnection(testZoneName, testZoneName, "nzisn+4G2ldMn0q1CV3vsg==", "127.0.0.1:19001") + ) private val testZone = Zone("vinyldns.", "test@test.com") private val records = List( @@ -49,7 +50,8 @@ class ZoneViewLoaderSpec extends WordSpec with Matchers with MockitoSugar with D ttl = 100, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("1.1.1.1"))), + records = List(AData("1.1.1.1")) + ), RecordSet( zoneId = testZone.id, name = "abc", @@ -57,7 +59,8 @@ class ZoneViewLoaderSpec extends WordSpec with Matchers with MockitoSugar with D ttl = 100, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("2.2.2.2"))), + records = List(AData("2.2.2.2")) + ), RecordSet( zoneId = testZone.id, name = "abc", @@ -74,7 +77,8 @@ class ZoneViewLoaderSpec extends WordSpec with Matchers with MockitoSugar with D ttl = 100, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("3.3.3.3"))) + records = List(AData("3.3.3.3")) + ) ) "VinylDNSZoneViewLoader" should { @@ -115,7 +119,8 @@ class ZoneViewLoaderSpec extends WordSpec with Matchers with MockitoSugar with D ttl = 38400, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("1.1.1.1"))), + records = List(AData("1.1.1.1")) + ), RecordSet( zoneId = testZone.id, name = "abc", @@ -123,7 +128,8 @@ class ZoneViewLoaderSpec extends WordSpec with Matchers with MockitoSugar with D ttl = 38400, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("2.2.2.2"))), + records = List(AData("2.2.2.2")) + ), RecordSet( zoneId = testZone.id, name = "abc", @@ -140,7 +146,8 @@ class ZoneViewLoaderSpec extends WordSpec with Matchers with MockitoSugar with D ttl = 38400, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("3.3.3.3"))) + records = List(AData("3.3.3.3")) + ) ) val dnsRecords = new mutable.ArrayBuffer[DNS.Record]() @@ -149,25 +156,33 @@ class ZoneViewLoaderSpec extends WordSpec with Matchers with MockitoSugar with D new Name("abc.vinyldns."), DNS.DClass.IN, 38400, - InetAddress.getByName("1.1.1.1"))) + InetAddress.getByName("1.1.1.1") + ) + ) dnsRecords.append( new DNS.ARecord( new Name("abc.vinyldns."), DNS.DClass.IN, 38400, - InetAddress.getByName("2.2.2.2"))) + InetAddress.getByName("2.2.2.2") + ) + ) dnsRecords.append( new DNS.AAAARecord( new Name("abc.vinyldns."), DNS.DClass.IN, 38400, - InetAddress.getByName("2001:db8:a0b:12f0::1"))) + InetAddress.getByName("2001:db8:a0b:12f0::1") + ) + ) dnsRecords.append( new DNS.ARecord( new Name("def.vinyldns."), DNS.DClass.IN, 38400, - InetAddress.getByName("3.3.3.3"))) + InetAddress.getByName("3.3.3.3") + ) + ) doReturn(dnsRecords.asJava).when(mockTransfer).getAXFR @@ -228,7 +243,8 @@ class ZoneViewLoaderSpec extends WordSpec with Matchers with MockitoSugar with D status = RecordSetStatus.Active, created = DateTime.now, records = List( - SOAData("172.17.42.1.", "admin.vinyldns.com.", 1439234395, 10800, 3600, 604800, 38400)) + SOAData("172.17.42.1.", "admin.vinyldns.com.", 1439234395, 10800, 3600, 604800, 38400) + ) ) ) @@ -244,37 +260,49 @@ class ZoneViewLoaderSpec extends WordSpec with Matchers with MockitoSugar with D 10800, 3600, 604800, - 38400)) + 38400 + ) + ) dnsRecords.append( new DNS.ARecord( new Name("abc.vinyldns."), DNS.DClass.IN, 38400, - InetAddress.getByName("1.1.1.1"))) + InetAddress.getByName("1.1.1.1") + ) + ) dnsRecords.append( new DNS.ARecord( new Name("abc.vinyldns."), DNS.DClass.IN, 38400, - InetAddress.getByName("1.1.1.1"))) + InetAddress.getByName("1.1.1.1") + ) + ) dnsRecords.append( new DNS.ARecord( new Name("abc.vinyldns."), DNS.DClass.IN, 38400, - InetAddress.getByName("1.1.1.1"))) + InetAddress.getByName("1.1.1.1") + ) + ) dnsRecords.append( new DNS.ARecord( new Name("abc.vinyldns."), DNS.DClass.IN, 38400, - InetAddress.getByName("1.1.1.1"))) + InetAddress.getByName("1.1.1.1") + ) + ) dnsRecords.append( new DNS.ARecord( new Name("abc.vinyldns."), DNS.DClass.IN, 38400, - InetAddress.getByName("2.2.2.2"))) + InetAddress.getByName("2.2.2.2") + ) + ) dnsRecords.append( new DNS.SOARecord( new Name("vinyldns."), @@ -286,7 +314,9 @@ class ZoneViewLoaderSpec extends WordSpec with Matchers with MockitoSugar with D 10800, 3600, 604800, - 38400)) + 38400 + ) + ) dnsRecords.append( new DNS.NULLRecord( new Name("some.unsupported.record.type."), diff --git a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneViewSpec.scala b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneViewSpec.scala index eae6c4644..ef0109643 100644 --- a/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneViewSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/domain/zone/ZoneViewSpec.scala @@ -35,7 +35,8 @@ class ZoneViewSpec extends WordSpec with Matchers with VinylDNSTestHelpers { ttl = 100, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("1.1.1.1"))), + records = List(AData("1.1.1.1")) + ), RecordSet( zoneId = testZone.id, name = "abc", @@ -43,7 +44,8 @@ class ZoneViewSpec extends WordSpec with Matchers with VinylDNSTestHelpers { ttl = 100, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("2.2.2.2"))), + records = List(AData("2.2.2.2")) + ), RecordSet( zoneId = testZone.id, name = "abc", @@ -71,7 +73,8 @@ class ZoneViewSpec extends WordSpec with Matchers with VinylDNSTestHelpers { ttl = 100, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("1.1.1.1"))), + records = List(AData("1.1.1.1")) + ), RecordSet( zoneId = testZone.id, name = "vinyldns.", @@ -93,7 +96,8 @@ class ZoneViewSpec extends WordSpec with Matchers with VinylDNSTestHelpers { case Some(records) => records.records should contain theSameElementsAs List( AData("1.1.1.1"), - AData("2.2.2.2")) + AData("2.2.2.2") + ) case None => fail() } @@ -193,7 +197,8 @@ class ZoneViewSpec extends WordSpec with Matchers with VinylDNSTestHelpers { ttl = 100, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("4.4.4.4"))) //updated + records = List(AData("4.4.4.4")) + ) //updated ) val dnsView = ZoneView(testZone, dnsRecords) @@ -268,7 +273,8 @@ class ZoneViewSpec extends WordSpec with Matchers with VinylDNSTestHelpers { ttl = 100, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("4.4.4.4"))) //updated + records = List(AData("4.4.4.4")) + ) //updated ) val dnsView = ZoneView(testZone, dnsRecords) diff --git a/modules/api/src/test/scala/vinyldns/api/engine/BatchChangeHandlerSpec.scala b/modules/api/src/test/scala/vinyldns/api/engine/BatchChangeHandlerSpec.scala index b299e6d5e..09b1521e5 100644 --- a/modules/api/src/test/scala/vinyldns/api/engine/BatchChangeHandlerSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/engine/BatchChangeHandlerSpec.scala @@ -66,7 +66,8 @@ class BatchChangeHandlerSpec DateTime.now, List(addChange), Some("ownerGroupId"), - BatchChangeApprovalStatus.AutoApproved) + BatchChangeApprovalStatus.AutoApproved + ) override protected def beforeEach(): Unit = batchRepo.clear() diff --git a/modules/api/src/test/scala/vinyldns/api/engine/RecordSetChangeHandlerSpec.scala b/modules/api/src/test/scala/vinyldns/api/engine/RecordSetChangeHandlerSpec.scala index 8bf99b140..3cf272fc4 100644 --- a/modules/api/src/test/scala/vinyldns/api/engine/RecordSetChangeHandlerSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/engine/RecordSetChangeHandlerSpec.scala @@ -73,7 +73,8 @@ class RecordSetChangeHandlerSpec SingleChangeStatus.Pending, None, None, - None) + None + ) } private val notUpdatedChange = SingleAddChange( Some("someId"), @@ -86,7 +87,8 @@ class RecordSetChangeHandlerSpec SingleChangeStatus.Pending, None, None, - None) + None + ) private val singleChanges = notUpdatedChange :: completeCreateAAAASingleChanges private val batchChange = BatchChange( "userId", @@ -94,7 +96,8 @@ class RecordSetChangeHandlerSpec None, DateTime.now, singleChanges, - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) private val rsChange = completeCreateAAAA.copy(singleBatchChangeIds = completeCreateAAAASingleChanges.map(_.id)) @@ -147,7 +150,8 @@ class RecordSetChangeHandlerSpec ch.copy( status = SingleChangeStatus.Complete, recordChangeId = Some(rsChange.id), - recordSetId = Some(rsChange.recordSet.id)) + recordSetId = Some(rsChange.recordSet.id) + ) } val scExpected = notUpdatedChange :: updatedSingleChanges batchChangeUpdates.get.changes shouldBe scExpected @@ -188,7 +192,8 @@ class RecordSetChangeHandlerSpec ch.copy( status = SingleChangeStatus.Complete, recordChangeId = Some(rsChange.id), - recordSetId = Some(rsChange.recordSet.id)) + recordSetId = Some(rsChange.recordSet.id) + ) } val scExpected = notUpdatedChange :: updatedSingleChanges batchChangeUpdates.get.changes shouldBe scExpected @@ -232,7 +237,8 @@ class RecordSetChangeHandlerSpec ch.copy( status = SingleChangeStatus.Failed, recordChangeId = Some(rsChange.id), - systemMessage = savedCs.changes.head.systemMessage) + systemMessage = savedCs.changes.head.systemMessage + ) } val scExpected = notUpdatedChange :: updatedSingleChanges batchChangeUpdates.get.changes shouldBe scExpected @@ -277,7 +283,8 @@ class RecordSetChangeHandlerSpec ch.copy( status = SingleChangeStatus.Complete, recordChangeId = Some(rsChange.id), - recordSetId = Some(rsChange.recordSet.id)) + recordSetId = Some(rsChange.recordSet.id) + ) } val scExpected = notUpdatedChange :: updatedSingleChanges batchChangeUpdates.get.changes shouldBe scExpected @@ -318,7 +325,8 @@ class RecordSetChangeHandlerSpec ch.copy( status = SingleChangeStatus.Failed, recordChangeId = Some(rsChange.id), - systemMessage = savedCs.changes.head.systemMessage) + systemMessage = savedCs.changes.head.systemMessage + ) } val scExpected = notUpdatedChange :: updatedSingleChanges batchChangeUpdates.get.changes shouldBe scExpected @@ -361,7 +369,8 @@ class RecordSetChangeHandlerSpec ch.copy( status = SingleChangeStatus.Failed, recordChangeId = Some(rsChange.id), - systemMessage = savedCs.changes.head.systemMessage) + systemMessage = savedCs.changes.head.systemMessage + ) } val scExpected = notUpdatedChange :: updatedSingleChanges batchChangeUpdates.get.changes shouldBe scExpected @@ -400,7 +409,8 @@ class RecordSetChangeHandlerSpec ch.copy( status = SingleChangeStatus.Failed, recordChangeId = Some(rsChange.id), - systemMessage = savedCs.changes.head.systemMessage) + systemMessage = savedCs.changes.head.systemMessage + ) } val scExpected = notUpdatedChange :: updatedSingleChanges batchChangeUpdates.get.changes shouldBe scExpected @@ -438,7 +448,8 @@ class RecordSetChangeHandlerSpec ch.copy( status = SingleChangeStatus.Failed, recordChangeId = Some(rsChange.id), - systemMessage = savedCs.changes.head.systemMessage) + systemMessage = savedCs.changes.head.systemMessage + ) } val scExpected = notUpdatedChange :: updatedSingleChanges batchChangeUpdates.get.changes shouldBe scExpected @@ -491,7 +502,8 @@ class RecordSetChangeHandlerSpec ch.copy( status = SingleChangeStatus.Complete, recordChangeId = Some(rsChange.id), - recordSetId = Some(rsChange.recordSet.id)) + recordSetId = Some(rsChange.recordSet.id) + ) } val scExpected = notUpdatedChange :: updatedSingleChanges batchChangeUpdates.get.changes shouldBe scExpected @@ -549,7 +561,8 @@ class RecordSetChangeHandlerSpec ch.copy( status = SingleChangeStatus.Complete, recordChangeId = Some(rsChange.id), - recordSetId = Some(rsChange.recordSet.id)) + recordSetId = Some(rsChange.recordSet.id) + ) } val scExpected = notUpdatedChange :: updatedSingleChanges batchChangeUpdates.get.changes shouldBe scExpected @@ -605,7 +618,8 @@ class RecordSetChangeHandlerSpec "complete an update successfully if the requested record set change matches the DNS backend" in { val updateChange = rsChange.copy( changeType = RecordSetChangeType.Update, - updates = Some(rsChange.recordSet.copy(ttl = 87))) + updates = Some(rsChange.recordSet.copy(ttl = 87)) + ) doReturn(Interfaces.result(Right(List(updateChange.recordSet)))) .when(mockConn) .resolve(rsChange.recordSet.name, rsChange.zone.name, rsChange.recordSet.typ) @@ -635,7 +649,8 @@ class RecordSetChangeHandlerSpec ch.copy( status = SingleChangeStatus.Complete, recordChangeId = Some(rsChange.id), - recordSetId = Some(rsChange.recordSet.id)) + recordSetId = Some(rsChange.recordSet.id) + ) } val scExpected = notUpdatedChange :: updatedSingleChanges batchChangeUpdates.get.changes shouldBe scExpected @@ -644,7 +659,8 @@ class RecordSetChangeHandlerSpec "fail an update if current record does not match the DNS backend and the change has not already been applied" in { val updateChange = rsChange.copy( changeType = RecordSetChangeType.Update, - updates = Some(rsChange.recordSet.copy(ttl = 87))) + updates = Some(rsChange.recordSet.copy(ttl = 87)) + ) doReturn(Interfaces.result(Right(List(updateChange.recordSet.copy(ttl = 30))))) .when(mockConn) .resolve(rsChange.recordSet.name, rsChange.zone.name, rsChange.recordSet.typ) @@ -669,7 +685,8 @@ class RecordSetChangeHandlerSpec changeSet.systemMessage shouldBe Some( s"Failed validating update to DNS for change ${changeSet.id}:${changeSet.recordSet.name}: " + s"This record set is out of sync with the DNS backend; sync this zone before attempting to " + - "update this record set.") + "update this record set." + ) val savedCs = changeRepoCaptor.getValue savedCs.status shouldBe ChangeSetStatus.Complete @@ -731,7 +748,8 @@ class RecordSetChangeHandlerSpec .getProcessingStatus( rsChange .copy(changeType = RecordSetChangeType.Update, updates = Some(rs.copy(ttl = 300))), - mockConn) + mockConn + ) .unsafeRunSync() processorStatus shouldBe a[ReadyToApply] } @@ -755,7 +773,8 @@ class RecordSetChangeHandlerSpec val processorStatus = RecordSetChangeHandler .getProcessingStatus( rsChange.copy(changeType = RecordSetChangeType.Update, updates = None), - mockConn) + mockConn + ) .unsafeRunSync() processorStatus shouldBe a[Failure] } diff --git a/modules/api/src/test/scala/vinyldns/api/engine/ZoneSyncHandlerSpec.scala b/modules/api/src/test/scala/vinyldns/api/engine/ZoneSyncHandlerSpec.scala index e16c68932..d188db4db 100644 --- a/modules/api/src/test/scala/vinyldns/api/engine/ZoneSyncHandlerSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/engine/ZoneSyncHandlerSpec.scala @@ -75,7 +75,8 @@ class ZoneSyncHandlerSpec ttl = 100, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("1.1.1.1"))) + records = List(AData("1.1.1.1")) + ) private val testRecord2 = RecordSet( zoneId = testZone.id, name = "def", @@ -83,7 +84,8 @@ class ZoneSyncHandlerSpec ttl = 100, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("2.2.2.2"))) + records = List(AData("2.2.2.2")) + ) private val testRecordDotted = RecordSet( zoneId = testZone.id, name = "gh.i.", @@ -91,7 +93,8 @@ class ZoneSyncHandlerSpec ttl = 100, status = RecordSetStatus.Active, created = DateTime.now, - records = List(AData("3.3.3.3"))) + records = List(AData("3.3.3.3")) + ) private val testRecordDottedOk = RecordSet( zoneId = testZone.id, name = s"ok-dotted.${testZone.name}", @@ -144,14 +147,16 @@ class ZoneSyncHandlerSpec zoneChangeRepo, zoneRepo, _ => mockDNSLoader, - (_, _) => mockVinylDNSLoader) + (_, _) => mockVinylDNSLoader + ) private val runSync = ZoneSyncHandler.runSync( recordSetRepo, recordChangeRepo, testZoneChange, _ => mockDNSLoader, - (_, _) => mockVinylDNSLoader) + (_, _) => mockVinylDNSLoader + ) override def beforeEach(): Unit = { reset(recordSetRepo) @@ -309,7 +314,8 @@ class ZoneSyncHandlerSpec recordChangeRepo, testZoneChange, dnsLoader, - (_, _) => mockVinylDNSLoader) + (_, _) => mockVinylDNSLoader + ) .unsafeRunSync() verify(dnsLoader).apply(captor.capture()) @@ -325,7 +331,8 @@ class ZoneSyncHandlerSpec recordChangeRepo, testZoneChange, _ => mockDNSLoader, - (_, _) => mockVinylDNSLoader) + (_, _) => mockVinylDNSLoader + ) .unsafeRunSync() verify(mockDNSLoader, times(1)).load @@ -344,7 +351,8 @@ class ZoneSyncHandlerSpec recordChangeRepo, testZoneChange, _ => mockDNSLoader, - vinyldnsLoader) + vinyldnsLoader + ) .unsafeRunSync() verify(vinyldnsLoader).apply(zoneCaptor.capture(), repoCaptor.capture()) @@ -444,7 +452,8 @@ class ZoneSyncHandlerSpec recordChangeRepo, zoneChange, _ => mockDNSLoader, - (_, _) => mockVinylDNSLoader) + (_, _) => mockVinylDNSLoader + ) .unsafeRunSync() captor.getValue.changes should contain theSameElementsAs expectedChanges diff --git a/modules/api/src/test/scala/vinyldns/api/metrics/APIMetricsSpec.scala b/modules/api/src/test/scala/vinyldns/api/metrics/APIMetricsSpec.scala index a878f711a..e51f0fa20 100644 --- a/modules/api/src/test/scala/vinyldns/api/metrics/APIMetricsSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/metrics/APIMetricsSpec.scala @@ -40,7 +40,8 @@ class APIMetricsSpec extends WordSpec with Matchers with MockitoSugar with Eithe """.stripMargin ) APIMetrics.loadSettings(config).attempt.unsafeRunSync() shouldBe Right( - APIMetricsSettings(MemoryMetricsSettings(logEnabled = true, logSeconds = 5))) + APIMetricsSettings(MemoryMetricsSettings(logEnabled = true, logSeconds = 5)) + ) } "fail with invalid config" in { val config = ConfigFactory.parseString( @@ -70,7 +71,8 @@ class APIMetricsSpec extends WordSpec with Matchers with MockitoSugar with Eithe APIMetrics .initialize( APIMetricsSettings(MemoryMetricsSettings(logEnabled = true, logSeconds = 5)), - reporter) + reporter + ) .unsafeRunSync() verify(reporter).start(5, TimeUnit.SECONDS) } @@ -79,7 +81,8 @@ class APIMetricsSpec extends WordSpec with Matchers with MockitoSugar with Eithe APIMetrics .initialize( APIMetricsSettings(MemoryMetricsSettings(logEnabled = false, logSeconds = 5)), - reporter) + reporter + ) .unsafeRunSync() verifyZeroInteractions(reporter) } diff --git a/modules/api/src/test/scala/vinyldns/api/notifier/email/EmailNotifierSpec.scala b/modules/api/src/test/scala/vinyldns/api/notifier/email/EmailNotifierSpec.scala index c9bd82064..3f30ea0a9 100644 --- a/modules/api/src/test/scala/vinyldns/api/notifier/email/EmailNotifierSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/notifier/email/EmailNotifierSpec.scala @@ -72,14 +72,17 @@ class EmailNotifierSpec "smtp", "vinyldns.api.notifier.email.MockTransport", "vinyl", - "1.0")) + "1.0" + ) + ) override protected def beforeEach(): Unit = reset(mockUserRepository, mockTransport) def batchChange( description: Option[String] = None, - changes: List[SingleChange] = List.empty): BatchChange = + changes: List[SingleChange] = List.empty + ): BatchChange = BatchChange( "test", "testUser", @@ -91,7 +94,8 @@ class EmailNotifierSpec None, None, None, - "testBatch") + "testBatch" + ) "Email Notifier" should { "do nothing for unsupported Notifications" in { @@ -100,7 +104,8 @@ class EmailNotifierSpec "from" -> "Testing ", "smtp.host" -> "wouldfail.mail.com", "smtp.auth.mechanisms" -> "PLAIN" - ).asJava) + ).asJava + ) val notifier = new EmailNotifierProvider() .load(NotifierConfig("", emailConfig), mockUserRepository) .unsafeRunSync() @@ -149,8 +154,8 @@ class EmailNotifierSpec ) doReturn( - IO.pure(Some(User("testUser", "access", "secret", None, None, Some("testuser@test.com"))))) - .when(mockUserRepository) + IO.pure(Some(User("testUser", "access", "secret", None, None, Some("testuser@test.com")))) + ).when(mockUserRepository) .getUser("test") val expectedAddresses = Array[Address](new InternetAddress("testuser@test.com")) @@ -176,7 +181,8 @@ class EmailNotifierSpec None, None, None, - List.empty), + List.empty + ), SingleDeleteRRSetChange( Some(""), Some(""), @@ -188,7 +194,8 @@ class EmailNotifierSpec Some("message for you"), None, None, - List.empty) + List.empty + ) ) val change = batchChange(Some(description), singleChanges) diff --git a/modules/api/src/test/scala/vinyldns/api/notifier/sns/SnsNotifierSpec.scala b/modules/api/src/test/scala/vinyldns/api/notifier/sns/SnsNotifierSpec.scala index d9dced533..b680dfbd9 100644 --- a/modules/api/src/test/scala/vinyldns/api/notifier/sns/SnsNotifierSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/notifier/sns/SnsNotifierSpec.scala @@ -56,7 +56,8 @@ class SnsNotifierSpec def batchChange( description: Option[String] = None, - changes: List[SingleChange] = List.empty): BatchChange = + changes: List[SingleChange] = List.empty + ): BatchChange = BatchChange( "test", "testUser", @@ -68,7 +69,8 @@ class SnsNotifierSpec None, None, None, - "testBatch") + "testBatch" + ) "Sns Notifier" should { "do nothing for unsupported Notifications" in { @@ -79,7 +81,8 @@ class SnsNotifierSpec "signing-region" -> "us-east-1", "access-key" -> "access", "secret-key" -> "secret" - ).asJava) + ).asJava + ) val notifier = new SnsNotifierProvider() .load(NotifierConfig("", snsConfig), mockUserRepository) .unsafeRunSync() @@ -111,7 +114,8 @@ class SnsNotifierSpec None, None, None, - List.empty), + List.empty + ), SingleDeleteRRSetChange( Some(""), Some(""), @@ -123,7 +127,8 @@ class SnsNotifierSpec Some("message for you"), None, None, - List.empty) + List.empty + ) ) val change = batchChange(Some(description), singleChanges) @@ -139,7 +144,8 @@ class SnsNotifierSpec request.getMessage should be( """{"userId":"test","userName":"testUser","comments":"notes",""" + """"createdTimestamp":"2019-07-22T17:01:19Z","status":"PartialFailure","approvalStatus":"AutoApproved",""" + - """"id":"testBatch"}""") + """"id":"testBatch"}""" + ) verify(mockSns).publish(any[PublishRequest]) diff --git a/modules/api/src/test/scala/vinyldns/api/repository/ApiDataAccessorProviderSpec.scala b/modules/api/src/test/scala/vinyldns/api/repository/ApiDataAccessorProviderSpec.scala index 77c367a67..8ec0c77f8 100644 --- a/modules/api/src/test/scala/vinyldns/api/repository/ApiDataAccessorProviderSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/repository/ApiDataAccessorProviderSpec.scala @@ -80,7 +80,8 @@ class ApiDataAccessorProviderSpec Some(zoneChange), Some(zone), Some(batchChange), - None) // API doesn't use Task repository + None + ) // API doesn't use Task repository ApiDataAccessorProvider.create(List((enabledConfig, enabledDataStore))) should be(valid) } @@ -89,7 +90,8 @@ class ApiDataAccessorProviderSpec DataStoreConfig( "some.datastore", placeholderConfig, - allEnabledReposConfig.copy(user = None)) + allEnabledReposConfig.copy(user = None) + ) val store = DataStore( Some(user), @@ -100,7 +102,8 @@ class ApiDataAccessorProviderSpec Some(recordChange), Some(zoneChange), Some(zone), - Some(batchChange)) + Some(batchChange) + ) ApiDataAccessorProvider.create(List((enabledConfig, store))) should be(invalid) } @@ -117,7 +120,8 @@ class ApiDataAccessorProviderSpec Some(recordChange), Some(zoneChange), None, - None) // API doesn't use Task repository + None + ) // API doesn't use Task repository ApiDataAccessorProvider.create(List((enabledConfig, store))) should be(invalid) } diff --git a/modules/api/src/test/scala/vinyldns/api/repository/EmptyRepositories.scala b/modules/api/src/test/scala/vinyldns/api/repository/EmptyRepositories.scala index 625fe2144..65d1af605 100644 --- a/modules/api/src/test/scala/vinyldns/api/repository/EmptyRepositories.scala +++ b/modules/api/src/test/scala/vinyldns/api/repository/EmptyRepositories.scala @@ -43,7 +43,8 @@ trait EmptyRecordSetRepo extends RecordSetRepository { zoneId: String, startFrom: Option[String], maxItems: Option[Int], - recordNameFilter: Option[String]): IO[ListRecordSetResults] = + recordNameFilter: Option[String] + ): IO[ListRecordSetResults] = IO.pure(ListRecordSetResults()) def getRecordSets(zoneId: String, name: String, typ: RecordType): IO[List[RecordSet]] = @@ -74,7 +75,8 @@ trait EmptyZoneRepo extends ZoneRepository { zoneNameFilter: Option[String] = None, startFrom: Option[String] = None, maxItems: Int = 100, - ignoreAccess: Boolean = false): IO[ListZonesResults] = IO.pure(ListZonesResults()) + ignoreAccess: Boolean = false + ): IO[ListZonesResults] = IO.pure(ListZonesResults()) def getZonesByAdminGroupId(adminGroupId: String): IO[List[Zone]] = IO.pure(List()) @@ -106,7 +108,8 @@ trait EmptyUserRepo extends UserRepository { def getUsers( userIds: Set[String], startFrom: Option[String], - maxItems: Option[Int]): IO[ListUsersResults] = IO.pure(ListUsersResults(List(), None)) + maxItems: Option[Int] + ): IO[ListUsersResults] = IO.pure(ListUsersResults(List(), None)) def getAllUsers: IO[List[User]] = IO.pure(List()) diff --git a/modules/api/src/test/scala/vinyldns/api/repository/InMemoryBatchChangeRepository.scala b/modules/api/src/test/scala/vinyldns/api/repository/InMemoryBatchChangeRepository.scala index 89951c31c..8b819dd44 100644 --- a/modules/api/src/test/scala/vinyldns/api/repository/InMemoryBatchChangeRepository.scala +++ b/modules/api/src/test/scala/vinyldns/api/repository/InMemoryBatchChangeRepository.scala @@ -39,7 +39,8 @@ class InMemoryBatchChangeRepository extends BatchChangeRepository { approvalStatus: BatchChangeApprovalStatus, reviewerId: Option[String], reviewComment: Option[String], - reviewTimestamp: Option[DateTime]) + reviewTimestamp: Option[DateTime] + ) object StoredBatchChange { def apply(batchChange: BatchChange): StoredBatchChange = new StoredBatchChange( @@ -113,7 +114,8 @@ class InMemoryBatchChangeRepository extends BatchChangeRepository { userId: Option[String], startFrom: Option[Int] = None, maxItems: Int = 100, - approvalStatus: Option[BatchChangeApprovalStatus] = None): IO[BatchChangeSummaryList] = { + approvalStatus: Option[BatchChangeApprovalStatus] = None + ): IO[BatchChangeSummaryList] = { val userBatchChanges = batches.values.toList .filter(b => userId.forall(_ == b.userId)) .filter(as => approvalStatus.forall(_ == as.approvalStatus)) @@ -148,7 +150,9 @@ class InMemoryBatchChangeRepository extends BatchChangeRepository { nextId = nextId, maxItems = maxItems, ignoreAccess = ignoreAccess, - approvalStatus = approvalStatus)) + approvalStatus = approvalStatus + ) + ) } def clear(): Unit = { diff --git a/modules/api/src/test/scala/vinyldns/api/route/BatchChangeJsonProtocolSpec.scala b/modules/api/src/test/scala/vinyldns/api/route/BatchChangeJsonProtocolSpec.scala index d64402310..8763995d4 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/BatchChangeJsonProtocolSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/BatchChangeJsonProtocolSpec.scala @@ -54,7 +54,8 @@ class BatchChangeJsonProtocolSpec inputName: Option[String] = None, typ: Option[RecordType] = None, ttl: Option[Int] = None, - record: Option[RecordData] = None): JObject = + record: Option[RecordData] = None + ): JObject = JObject( List( Some("changeType" -> decompose(Add)), @@ -62,19 +63,22 @@ class BatchChangeJsonProtocolSpec typ.map("type" -> decompose(_)), ttl.map("ttl" -> JInt(_)), record.map("record" -> decompose(_)) - ).flatten) + ).flatten + ) def buildDeleteRRSetInputJson( inputName: Option[String] = None, typ: Option[RecordType] = None, - record: Option[RecordData] = None): JObject = + record: Option[RecordData] = None + ): JObject = JObject( List( Some("changeType" -> decompose(DeleteRecordSet)), inputName.map("inputName" -> JString(_)), typ.map("type" -> decompose(_)), record.map("record" -> decompose(_)) - ).flatten) + ).flatten + ) val addAChangeInputJson: JObject = buildAddChangeInputJson(Some("foo."), Some(A), Some(3600), Some(AData("1.1.1.1"))) @@ -94,12 +98,14 @@ class BatchChangeJsonProtocolSpec addAChangeInputJson, addAAAAChangeInputJson, addCNAMEChangeInputJson, - addPTRChangeInputJson) + addPTRChangeInputJson + ) val addDeleteChangeList: JObject = "changes" -> List( deleteAChangeInputJson, addAAAAChangeInputJson, - addCNAMEChangeInputJson) + addCNAMEChangeInputJson + ) val addBatchChangeInputWithComment: JObject = ("comments" -> Some("some comment")) ~~ addChangeList @@ -110,7 +116,8 @@ class BatchChangeJsonProtocolSpec val changeInputWithManualReviewDisabled: JObject = "changes" -> List( deleteAChangeInputJson, addAAAAChangeInputJson, - addCNAMEChangeInputJson) + addCNAMEChangeInputJson + ) val addAChangeInput = AddChangeInput("foo.", A, Some(3600), AData("1.1.1.1")) @@ -165,7 +172,8 @@ class BatchChangeJsonProtocolSpec val result = ChangeInputSerializer.fromJson(json) result should haveInvalid( - s"Unsupported type $UNKNOWN, valid types include: A, AAAA, CNAME, PTR, TXT, and MX") + s"Unsupported type $UNKNOWN, valid types include: A, AAAA, CNAME, PTR, TXT, and MX" + ) } "return an error if the FQDN is not specified" in { @@ -180,7 +188,8 @@ class BatchChangeJsonProtocolSpec val json = buildAddChangeInputJson( inputName = Some("foo."), ttl = Some(3600), - record = Some(AData("1.1.1.1"))) + record = Some(AData("1.1.1.1")) + ) val result = ChangeInputSerializer.fromJson(json) result should haveInvalid("Missing BatchChangeInput.changes.type") @@ -190,7 +199,8 @@ class BatchChangeJsonProtocolSpec val json = buildAddChangeInputJson( inputName = Some("foo."), typ = Some(A), - record = Some(AData("1.1.1.1"))) + record = Some(AData("1.1.1.1")) + ) val result = ChangeInputSerializer.fromJson(json).value result shouldBe AddChangeInput("foo.", A, None, AData("1.1.1.1")) @@ -226,7 +236,8 @@ class BatchChangeJsonProtocolSpec result shouldBe BatchChangeInput( Some("some comment"), List(addAChangeInput, addAAAAChangeInput, addCNAMEChangeInput, addPTRChangeInput), - None) + None + ) } "successfully serialize valid add change data without comment and owner group ID" in { @@ -234,7 +245,8 @@ class BatchChangeJsonProtocolSpec result shouldBe BatchChangeInput( None, - List(addAChangeInput, addAAAAChangeInput, addCNAMEChangeInput, addPTRChangeInput)) + List(addAChangeInput, addAAAAChangeInput, addCNAMEChangeInput, addPTRChangeInput) + ) } "successfully serialize valid add and delete change data without comment and owner group ID" in { @@ -242,7 +254,8 @@ class BatchChangeJsonProtocolSpec result shouldBe BatchChangeInput( None, - List(deleteAChangeInput, addAAAAChangeInput, addCNAMEChangeInput)) + List(deleteAChangeInput, addAAAAChangeInput, addCNAMEChangeInput) + ) } "successfully serialize valid add and delete change with comment and owner group ID" in { @@ -253,7 +266,8 @@ class BatchChangeJsonProtocolSpec addAChangeInput, addAAAAChangeInput, addCNAMEChangeInput, - addPTRChangeInput), + addPTRChangeInput + ), Some("owner-group-id") ) @@ -270,7 +284,8 @@ class BatchChangeJsonProtocolSpec addAChangeInput, addAAAAChangeInput, addCNAMEChangeInput, - addPTRChangeInput), + addPTRChangeInput + ), Some("owner-group-id") ) @@ -412,7 +427,8 @@ class BatchChangeJsonProtocolSpec Some("systemMessage"), None, None, - id = "id") + id = "id" + ) val add = SingleAddChange( Some("zoneId"), Some("zoneName"), @@ -425,7 +441,8 @@ class BatchChangeJsonProtocolSpec Some("systemMessage"), None, None, - id = "id") + id = "id" + ) val time = DateTime.now val batchChange = BatchChange( @@ -439,7 +456,8 @@ class BatchChangeJsonProtocolSpec None, None, None, - "someId") + "someId" + ) val result = BatchChangeSerializer.toJson(batchChange) result shouldBe ("userId" -> "someUserId") ~ @@ -463,9 +481,11 @@ class BatchChangeJsonProtocolSpec "serialize changes for valid inputs" in { val onlyValid = List( AddChangeForValidation(okZone, "foo", addAChangeInput).validNel, - AddChangeForValidation(okZone, "bar", addAAAAChangeInput).validNel) + AddChangeForValidation(okZone, "bar", addAAAAChangeInput).validNel + ) val result = BatchChangeErrorListSerializer.toJson( - InvalidBatchChangeResponses(List(addAChangeInput, addAAAAChangeInput), onlyValid)) + InvalidBatchChangeResponses(List(addAChangeInput, addAAAAChangeInput), onlyValid) + ) result shouldBe decompose(List(addAChangeInput, addAAAAChangeInput)) } @@ -473,7 +493,8 @@ class BatchChangeJsonProtocolSpec "serialize BatchChangeErrors to their corresponding messages" in { val onlyErrors = List(fooDiscoveryError.invalidNel, barDiscoveryError.invalidNel) val result = BatchChangeErrorListSerializer.toJson( - InvalidBatchChangeResponses(List(addAChangeInput, addAAAAChangeInput), onlyErrors)) + InvalidBatchChangeResponses(List(addAChangeInput, addAAAAChangeInput), onlyErrors) + ) result shouldBe decompose( List( @@ -481,7 +502,8 @@ class BatchChangeJsonProtocolSpec .asInstanceOf[JObject] ~ ("errors" -> List(fooDiscoveryError.message)), decompose(addAAAAChangeInput) .asInstanceOf[JObject] ~ ("errors" -> List(barDiscoveryError.message)) - )) + ) + ) } "serializing a mix of valid inputs and BatchChangeErrors should return the appropriate success or error" in { @@ -489,7 +511,9 @@ class BatchChangeJsonProtocolSpec NonEmptyList.fromListUnsafe( List( InvalidIpv4Address("bad address"), - InvalidTTL(5, DomainValidations.TTL_MIN_LENGTH, DomainValidations.TTL_MAX_LENGTH))) + InvalidTTL(5, DomainValidations.TTL_MIN_LENGTH, DomainValidations.TTL_MAX_LENGTH) + ) + ) val validAddA = AddChangeForValidation(okZone, "foo", addAChangeInput).validNel val invalidAddA = errorList.invalid[ChangeForValidation] @@ -507,7 +531,8 @@ class BatchChangeJsonProtocolSpec decompose(addAChangeInput).asInstanceOf[JObject] ~ ("errors" -> List( InvalidIpv4Address("bad address").message, - InvalidTTL(5, DomainValidations.TTL_MIN_LENGTH, DomainValidations.TTL_MAX_LENGTH).message)), + InvalidTTL(5, DomainValidations.TTL_MIN_LENGTH, DomainValidations.TTL_MAX_LENGTH).message + )), decompose(addAAAAChangeInput).asInstanceOf[JObject] ~ ("errors" -> List(barDiscoveryError.message)), addAAAAChangeInput @@ -535,7 +560,8 @@ class BatchChangeJsonProtocolSpec None, None, None, - id = "id") + id = "id" + ) val add = SingleAddChange( Some("zoneId"), Some("zoneName"), @@ -564,7 +590,8 @@ class BatchChangeJsonProtocolSpec None, None, None, - "someId") + "someId" + ) val result = BatchChangeRevalidationErrorListSerializer.toJson(BatchChangeFailedApproval(batchChange)) @@ -593,7 +620,8 @@ class BatchChangeJsonProtocolSpec RejectBatchChangeInputSerializer .fromJson( RejectBatchChangeInputSerializer - .toJson(rejectBatchChangeInput)) shouldBe rejectBatchChangeInput.validNel + .toJson(rejectBatchChangeInput) + ) shouldBe rejectBatchChangeInput.validNel } "succeed if comments are provided" in { @@ -601,7 +629,8 @@ class BatchChangeJsonProtocolSpec RejectBatchChangeInputSerializer .fromJson( RejectBatchChangeInputSerializer - .toJson(rejectBatchChangeInput)) shouldBe rejectBatchChangeInput.validNel + .toJson(rejectBatchChangeInput) + ) shouldBe rejectBatchChangeInput.validNel } "fail if comments exceed MAX_COMMENT_LENGTH characters" in { @@ -609,7 +638,8 @@ class BatchChangeJsonProtocolSpec RejectBatchChangeInputSerializer .fromJson( RejectBatchChangeInputSerializer - .toJson(rejectBatchChangeInput)) shouldBe + .toJson(rejectBatchChangeInput) + ) shouldBe s"Comment length must not exceed $MAX_COMMENT_LENGTH characters.".invalidNel } } @@ -620,7 +650,8 @@ class BatchChangeJsonProtocolSpec ApproveBatchChangeInputSerializer .fromJson( ApproveBatchChangeInputSerializer - .toJson(approveBatchChangeInput)) shouldBe approveBatchChangeInput.validNel + .toJson(approveBatchChangeInput) + ) shouldBe approveBatchChangeInput.validNel } "succeed if comments are provided" in { @@ -628,7 +659,8 @@ class BatchChangeJsonProtocolSpec ApproveBatchChangeInputSerializer .fromJson( ApproveBatchChangeInputSerializer - .toJson(approveBatchChangeInput)) shouldBe approveBatchChangeInput.validNel + .toJson(approveBatchChangeInput) + ) shouldBe approveBatchChangeInput.validNel } "fail if comments exceed MAX_COMMENT_LENGTH characters" in { @@ -636,7 +668,8 @@ class BatchChangeJsonProtocolSpec ApproveBatchChangeInputSerializer .fromJson( ApproveBatchChangeInputSerializer - .toJson(approveBatchChangeInput)) shouldBe + .toJson(approveBatchChangeInput) + ) shouldBe s"Comment length must not exceed $MAX_COMMENT_LENGTH characters.".invalidNel } } diff --git a/modules/api/src/test/scala/vinyldns/api/route/BatchChangeRoutingSpec.scala b/modules/api/src/test/scala/vinyldns/api/route/BatchChangeRoutingSpec.scala index 9a7b4c2c5..1dd91e894 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/BatchChangeRoutingSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/BatchChangeRoutingSpec.scala @@ -70,7 +70,8 @@ class BatchChangeRoutingSpec() ownerGroupId: Option[String] = None, auth: AuthPrincipal = okAuth, approvalStatus: BatchChangeApprovalStatus = BatchChangeApprovalStatus.AutoApproved, - scheduledTime: Option[DateTime] = None): BatchChange = + scheduledTime: Option[DateTime] = None + ): BatchChange = BatchChange( auth.userId, auth.signedInUser.userName, @@ -89,7 +90,8 @@ class BatchChangeRoutingSpec() Some("systemMessage"), None, None, - id = "singleAddChangeId"), + id = "singleAddChangeId" + ), SingleDeleteRRSetChange( Some("zoneId"), Some("zoneName"), @@ -101,7 +103,8 @@ class BatchChangeRoutingSpec() Some("systemMessage"), None, None, - id = "singleDeleteChangeId") + id = "singleDeleteChangeId" + ) ), ownerGroupId, approvalStatus, @@ -115,27 +118,32 @@ class BatchChangeRoutingSpec() /* Builds BatchChange response */ def createBatchChangeInfoResponse( batchChange: BatchChange, - ownerGroupName: Option[String] = None): BatchChangeInfo = + ownerGroupName: Option[String] = None + ): BatchChangeInfo = BatchChangeInfo(batchChange, ownerGroupName) def buildAddChangeInput( inputName: Option[String] = None, typ: Option[RecordType] = None, ttl: Option[Int] = None, - record: Option[RecordData] = None): JObject = + record: Option[RecordData] = None + ): JObject = JObject( List( inputName.map("inputName" -> JString(_)), typ.map("type" -> Extraction.decompose(_)), ttl.map("ttl" -> JInt(_)), - record.map("record" -> Extraction.decompose(_))).flatten) + record.map("record" -> Extraction.decompose(_)) + ).flatten + ) def buildDeleteChangeInput( inputName: Option[String] = None, - typ: Option[RecordType] = None): JObject = - JObject(List( - inputName.map("inputName" -> JString(_)), - typ.map("type" -> Extraction.decompose(_))).flatten) + typ: Option[RecordType] = None + ): JObject = + JObject( + List(inputName.map("inputName" -> JString(_)), typ.map("type" -> Extraction.decompose(_))).flatten + ) val addAChangeInput: JObject = buildAddChangeInput(Some("bar."), Some(A), Some(3600), Some(AData("127.0.0.1"))) @@ -155,16 +163,21 @@ class BatchChangeRoutingSpec() val batchChangeSummaryInfo2 = BatchChangeSummary( createBatchChangeResponse( Some("second"), - approvalStatus = BatchChangeApprovalStatus.PendingReview)) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) + ) val batchChangeSummaryInfo3 = BatchChangeSummary(createBatchChangeResponse(Some("third"))) val batchChangeSummaryInfo4 = BatchChangeSummary( createBatchChangeResponse( Some("fourth"), auth = dummyAuth, - approvalStatus = BatchChangeApprovalStatus.PendingReview)) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) + ) val validResponseWithComments: BatchChange = createBatchChangeResponse( - Some("validChangeWithComments")) + Some("validChangeWithComments") + ) val validResponseWithoutComments: BatchChange = createBatchChangeResponse() val validResponseWithOwnerGroupId: BatchChange = createBatchChangeResponse(ownerGroupId = Some("some-group-id")) @@ -175,7 +188,8 @@ class BatchChangeRoutingSpec() scheduledTime = Some(testScheduledTime) ) val genericValidResponse: BatchChange = createBatchChangeResponse( - Some("generic valid response")) + Some("generic valid response") + ) val backwardsCompatibleDel = SingleDeleteRRSetChange( None, @@ -188,7 +202,8 @@ class BatchChangeRoutingSpec() Some("systemMessage"), None, None, - id = "singleDeleteChangeId") + id = "singleDeleteChangeId" + ) val backwardsCompatibleAdd = SingleDeleteRRSetChange( None, None, @@ -200,14 +215,17 @@ class BatchChangeRoutingSpec() Some("systemMessage"), None, None, - id = "singleDeleteChangeId") + id = "singleDeleteChangeId" + ) val backwardsCompatable: BatchChange = genericValidResponse.copy( id = "testBwComp", - changes = List(backwardsCompatibleAdd, backwardsCompatibleDel)) + changes = List(backwardsCompatibleAdd, backwardsCompatibleDel) + ) val validListBatchChangeSummariesResponse: BatchChangeSummaryList = BatchChangeSummaryList( - List(BatchChangeSummary(createBatchChangeResponse(None)))) + List(BatchChangeSummary(createBatchChangeResponse(None))) + ) } import TestData._ @@ -216,14 +234,17 @@ class BatchChangeRoutingSpec() def applyBatchChange( batchChangeInput: BatchChangeInput, auth: AuthPrincipal, - allowManualReview: Boolean): EitherT[IO, BatchChangeErrorResponse, BatchChange] = + allowManualReview: Boolean + ): EitherT[IO, BatchChangeErrorResponse, BatchChange] = batchChangeInput.comments match { case Some("validChangeWithComments") => EitherT[IO, BatchChangeErrorResponse, BatchChange]( - IO.pure(Right(validResponseWithComments))) + IO.pure(Right(validResponseWithComments)) + ) case None => EitherT[IO, BatchChangeErrorResponse, BatchChange]( - IO.pure(Right(validResponseWithoutComments))) + IO.pure(Right(validResponseWithoutComments)) + ) case Some("runtimeException") => throw new RuntimeException("Unexpected run-time exception has occurred!") case Some("emptyBatch") => @@ -232,10 +253,12 @@ class BatchChangeRoutingSpec() ) case Some("validChangeWithOwnerGroup") => EitherT[IO, BatchChangeErrorResponse, BatchChange]( - IO.pure(Right(validResponseWithOwnerGroupId))) + IO.pure(Right(validResponseWithOwnerGroupId)) + ) case Some("validChangeWithCommentsAndScheduled") => EitherT[IO, BatchChangeErrorResponse, BatchChange]( - IO.pure(Right(validResponseWithCommentsAndScheduled))) + IO.pure(Right(validResponseWithCommentsAndScheduled)) + ) case Some("scheduledDisabledRequest") => EitherT[IO, BatchChangeErrorResponse, BatchChange]( IO.pure(Left(ScheduledChangesDisabled)) @@ -246,7 +269,8 @@ class BatchChangeRoutingSpec() def getBatchChange( id: String, - auth: AuthPrincipal): EitherT[IO, BatchChangeErrorResponse, BatchChangeInfo] = + auth: AuthPrincipal + ): EitherT[IO, BatchChangeErrorResponse, BatchChangeInfo] = id match { case "batchId" => EitherT( @@ -265,8 +289,8 @@ class BatchChangeRoutingSpec() startFrom: Option[Int], maxItems: Int, ignoreAccess: Boolean = false, - approvalStatus: Option[BatchChangeApprovalStatus] = None) - : EitherT[IO, BatchChangeErrorResponse, BatchChangeSummaryList] = + approvalStatus: Option[BatchChangeApprovalStatus] = None + ): EitherT[IO, BatchChangeErrorResponse, BatchChangeSummaryList] = if (auth.userId == okAuth.userId) (auth, startFrom, maxItems, ignoreAccess, approvalStatus) match { case (_, None, 100, _, None) => @@ -319,7 +343,8 @@ class BatchChangeRoutingSpec() ) case _ => EitherT.rightT(BatchChangeSummaryList(List())) - } else if (auth.userId == superUserAuth.userId) + } + else if (auth.userId == superUserAuth.userId) (auth, startFrom, maxItems, ignoreAccess, approvalStatus) match { case (_, None, 100, true, None) => EitherT.rightT( @@ -328,7 +353,8 @@ class BatchChangeRoutingSpec() batchChangeSummaryInfo1, batchChangeSummaryInfo2, batchChangeSummaryInfo3, - batchChangeSummaryInfo4), + batchChangeSummaryInfo4 + ), startFrom = None, nextId = None, ignoreAccess = true @@ -367,14 +393,15 @@ class BatchChangeRoutingSpec() ) case _ => EitherT.rightT(BatchChangeSummaryList(List())) - } else + } + else EitherT.rightT(BatchChangeSummaryList(List())) def rejectBatchChange( batchChangeId: String, authPrincipal: AuthPrincipal, - rejectionComment: RejectBatchChangeInput) - : EitherT[IO, BatchChangeErrorResponse, BatchChange] = + rejectionComment: RejectBatchChangeInput + ): EitherT[IO, BatchChangeErrorResponse, BatchChange] = (batchChangeId, authPrincipal.isSystemAdmin) match { case ("pendingBatchId", true) => EitherT(IO.pure(genericValidResponse.asRight)) case ("pendingBatchId", false) => @@ -385,8 +412,8 @@ class BatchChangeRoutingSpec() def approveBatchChange( batchChangeId: String, authPrincipal: AuthPrincipal, - rejectionComment: ApproveBatchChangeInput) - : EitherT[IO, BatchChangeErrorResponse, BatchChange] = + rejectionComment: ApproveBatchChangeInput + ): EitherT[IO, BatchChangeErrorResponse, BatchChange] = (batchChangeId, authPrincipal.isSystemAdmin) match { case ("pendingBatchId", true) => EitherT(IO.pure(genericValidResponse.asRight)) case ("pendingBatchId", false) => @@ -400,7 +427,8 @@ class BatchChangeRoutingSpec() def cancelBatchChange( batchChangeId: String, - authPrincipal: AuthPrincipal): EitherT[IO, BatchChangeErrorResponse, BatchChange] = + authPrincipal: AuthPrincipal + ): EitherT[IO, BatchChangeErrorResponse, BatchChange] = (batchChangeId, authPrincipal.userId.equals("ok")) match { case ("pendingBatchId", true) => EitherT(IO.pure(genericValidResponse.asRight)) case ("pendingBatchId", false) => EitherT(IO.pure(UserNotAuthorizedError("support").asLeft)) @@ -415,7 +443,8 @@ class BatchChangeRoutingSpec() buildValidBatchChangeInputJson("validChangeWithComments") Post("/zones/batchrecordchanges").withEntity( - HttpEntity(ContentTypes.`application/json`, validRequestWithComments)) ~> + HttpEntity(ContentTypes.`application/json`, validRequestWithComments) + ) ~> batchChangeRoute ~> check { status shouldBe Accepted @@ -429,7 +458,8 @@ class BatchChangeRoutingSpec() val validRequestWithoutComments: String = compact(render(changeList)) Post("/zones/batchrecordchanges").withEntity( - HttpEntity(ContentTypes.`application/json`, validRequestWithoutComments)) ~> + HttpEntity(ContentTypes.`application/json`, validRequestWithoutComments) + ) ~> batchChangeRoute ~> check { status shouldBe Accepted @@ -442,11 +472,15 @@ class BatchChangeRoutingSpec() "return a 202 Accepted for valid add and delete request with owner group ID" in { val validRequestWithOwnerGroupId: String = compact( - render(("comments" -> "validChangeWithOwnerGroup") ~~ changeList ~~ - ("ownerGroupId" -> "some-group-id"))) + render( + ("comments" -> "validChangeWithOwnerGroup") ~~ changeList ~~ + ("ownerGroupId" -> "some-group-id") + ) + ) Post("/zones/batchrecordchanges").withEntity( - HttpEntity(ContentTypes.`application/json`, validRequestWithOwnerGroupId)) ~> + HttpEntity(ContentTypes.`application/json`, validRequestWithOwnerGroupId) + ) ~> batchChangeRoute ~> check { status shouldBe Accepted @@ -458,7 +492,8 @@ class BatchChangeRoutingSpec() "return a 202 Accepted for valid add and delete request with allowManualReview parameter" in { val validRequestWithoutComments: String = compact(render(changeList)) Post("/zones/batchrecordchanges?allowManualReview=false").withEntity( - HttpEntity(ContentTypes.`application/json`, validRequestWithoutComments)) ~> + HttpEntity(ContentTypes.`application/json`, validRequestWithoutComments) + ) ~> batchChangeRoute ~> check { status shouldBe Accepted @@ -478,14 +513,16 @@ class BatchChangeRoutingSpec() ) Post("/zones/batchrecordchanges").withEntity( - HttpEntity(ContentTypes.`application/json`, validRequestWithScheduledTime)) ~> + HttpEntity(ContentTypes.`application/json`, validRequestWithScheduledTime) + ) ~> batchChangeRoute ~> check { status shouldBe Accepted val change = responseAs[JValue] compact(change) shouldBe compact( - Extraction.decompose(validResponseWithCommentsAndScheduled)) + Extraction.decompose(validResponseWithCommentsAndScheduled) + ) } } @@ -495,7 +532,8 @@ class BatchChangeRoutingSpec() |}""".stripMargin Post("/zones/batchrecordchanges").withEntity( - HttpEntity(ContentTypes.`application/json`, emptyBatchRequest)) ~> + HttpEntity(ContentTypes.`application/json`, emptyBatchRequest) + ) ~> Route.seal(batchChangeRoute) ~> check { status shouldBe BadRequest @@ -506,7 +544,8 @@ class BatchChangeRoutingSpec() val scheduledDisabledRequest = buildValidBatchChangeInputJson("scheduledDisabledRequest") Post("/zones/batchrecordchanges").withEntity( - HttpEntity(ContentTypes.`application/json`, scheduledDisabledRequest)) ~> + HttpEntity(ContentTypes.`application/json`, scheduledDisabledRequest) + ) ~> Route.seal(batchChangeRoute) ~> check { response.entity.toString should include(ScheduledChangesDisabled.message) @@ -523,7 +562,8 @@ class BatchChangeRoutingSpec() |}""".stripMargin Post("/zones/batchrecordchanges").withEntity( - HttpEntity(ContentTypes.`application/json`, invalidRequestChangeType)) ~> + HttpEntity(ContentTypes.`application/json`, invalidRequestChangeType) + ) ~> Route.seal(batchChangeRoute) ~> check { status shouldBe BadRequest @@ -534,7 +574,8 @@ class BatchChangeRoutingSpec() val runtimeError: String = buildValidBatchChangeInputJson("runtimeException") Post("/zones/batchrecordchanges").withEntity( - HttpEntity(ContentTypes.`application/json`, runtimeError)) ~> + HttpEntity(ContentTypes.`application/json`, runtimeError) + ) ~> Route.seal(batchChangeRoute) ~> check { status shouldBe InternalServerError @@ -550,7 +591,8 @@ class BatchChangeRoutingSpec() val resp = responseAs[JValue] compact(resp) shouldBe compact( - Extraction.decompose(createBatchChangeInfoResponse(genericValidResponse))) + Extraction.decompose(createBatchChangeInfoResponse(genericValidResponse)) + ) } } @@ -657,7 +699,8 @@ class BatchChangeRoutingSpec() status shouldBe BadRequest responseEntity.toString should include( - "maxItems was 101, maxItems must be between 1 and 100, inclusive.") + "maxItems was 101, maxItems must be between 1 and 100, inclusive." + ) } } @@ -667,7 +710,8 @@ class BatchChangeRoutingSpec() val resp = responseAs[JValue] compact(resp) shouldBe compact( - Extraction.decompose(BatchChangeSummaryList(List(), maxItems = 100))) + Extraction.decompose(BatchChangeSummaryList(List(), maxItems = 100)) + ) } } @@ -704,9 +748,9 @@ class BatchChangeRoutingSpec() "POST reject batch change" should { "return OK if review comment is provided, batch change is PendingReview, and reviewer is authorized" in { - Post("/zones/batchrecordchanges/pendingBatchId/reject").withEntity(HttpEntity( - ContentTypes.`application/json`, - compact(render("comments" -> "some comments")))) ~> + Post("/zones/batchrecordchanges/pendingBatchId/reject").withEntity( + HttpEntity(ContentTypes.`application/json`, compact(render("comments" -> "some comments"))) + ) ~> superUserRoute ~> check { status shouldBe OK } @@ -714,7 +758,8 @@ class BatchChangeRoutingSpec() "return OK if comments are not provided, batch change is PendingReview, and reviewer is authorized" in { Post("/zones/batchrecordchanges/pendingBatchId/reject").withEntity( - HttpEntity(ContentTypes.`application/json`, compact(render("")))) ~> + HttpEntity(ContentTypes.`application/json`, compact(render(""))) + ) ~> supportUserRoute ~> check { status shouldBe OK } @@ -722,16 +767,17 @@ class BatchChangeRoutingSpec() "return Forbidden if user is not a super or support admin" in { Post("/zones/batchrecordchanges/pendingBatchId/reject").withEntity( - HttpEntity(ContentTypes.`application/json`, compact(render("")))) ~> + HttpEntity(ContentTypes.`application/json`, compact(render(""))) + ) ~> batchChangeRoute ~> check { status shouldBe Forbidden } } "return BadRequest if comments exceed 1024 characters" in { - Post("/zones/batchrecordchanges/pendingBatchId/reject").withEntity(HttpEntity( - ContentTypes.`application/json`, - compact(render("reviewComment" -> "a" * 1025)))) ~> Route.seal(batchChangeRoute) ~> check { + Post("/zones/batchrecordchanges/pendingBatchId/reject").withEntity( + HttpEntity(ContentTypes.`application/json`, compact(render("reviewComment" -> "a" * 1025))) + ) ~> Route.seal(batchChangeRoute) ~> check { status shouldBe BadRequest responseEntity.toString should include("Comment length must not exceed 1024 characters.") @@ -746,7 +792,8 @@ class BatchChangeRoutingSpec() "return BadRequest if batch change is not pending review" in { Post("/zones/batchrecordchanges/batchId/reject").withEntity( - HttpEntity(ContentTypes.`application/json`, compact(render("")))) ~> + HttpEntity(ContentTypes.`application/json`, compact(render(""))) + ) ~> supportUserRoute ~> check { status shouldBe BadRequest } @@ -755,9 +802,9 @@ class BatchChangeRoutingSpec() "POST approve batch change" should { "return Accepted if review comment is provided, batch change is PendingReview, and reviewer is authorized" in { - Post("/zones/batchrecordchanges/pendingBatchId/approve").withEntity(HttpEntity( - ContentTypes.`application/json`, - compact(render("comments" -> "some comments")))) ~> + Post("/zones/batchrecordchanges/pendingBatchId/approve").withEntity( + HttpEntity(ContentTypes.`application/json`, compact(render("comments" -> "some comments"))) + ) ~> supportUserRoute ~> check { status shouldBe Accepted } @@ -765,7 +812,8 @@ class BatchChangeRoutingSpec() "return Accepted if comments are not provided, batch change is PendingReview, and reviewer is authorized" in { Post("/zones/batchrecordchanges/pendingBatchId/approve").withEntity( - HttpEntity(ContentTypes.`application/json`, compact(render("")))) ~> + HttpEntity(ContentTypes.`application/json`, compact(render(""))) + ) ~> supportUserRoute ~> check { status shouldBe Accepted } @@ -773,7 +821,8 @@ class BatchChangeRoutingSpec() "return Forbidden if user is not a super or support admin" in { Post("/zones/batchrecordchanges/pendingBatchId/approve").withEntity( - HttpEntity(ContentTypes.`application/json`, compact(render("")))) ~> + HttpEntity(ContentTypes.`application/json`, compact(render(""))) + ) ~> batchChangeRoute ~> check { status shouldBe Forbidden } @@ -781,7 +830,8 @@ class BatchChangeRoutingSpec() "return Forbidden if scheduled change is not past due" in { Post("/zones/batchrecordchanges/schedNotPastDue/approve").withEntity( - HttpEntity(ContentTypes.`application/json`, compact(render("")))) ~> + HttpEntity(ContentTypes.`application/json`, compact(render(""))) + ) ~> batchChangeRoute ~> check { status shouldBe Forbidden response.entity.toString should include("scheduled date") @@ -789,9 +839,9 @@ class BatchChangeRoutingSpec() } "return BadRequest if comments exceed 1024 characters" in { - Post("/zones/batchrecordchanges/pendingBatchId/approve").withEntity(HttpEntity( - ContentTypes.`application/json`, - compact(render("reviewComment" -> "a" * 1025)))) ~> Route.seal(supportUserRoute) ~> check { + Post("/zones/batchrecordchanges/pendingBatchId/approve").withEntity( + HttpEntity(ContentTypes.`application/json`, compact(render("reviewComment" -> "a" * 1025))) + ) ~> Route.seal(supportUserRoute) ~> check { status shouldBe BadRequest responseEntity.toString should include("Comment length must not exceed 1024 characters.") @@ -806,16 +856,17 @@ class BatchChangeRoutingSpec() "return BadRequest if batch change is not pending review" in { Post("/zones/batchrecordchanges/batchId/approve").withEntity( - HttpEntity(ContentTypes.`application/json`, compact(render("")))) ~> + HttpEntity(ContentTypes.`application/json`, compact(render(""))) + ) ~> supportUserRoute ~> check { status shouldBe BadRequest } } "return NotFound if the requesting user cant be found" in { - Post("/zones/batchrecordchanges/notFoundUser/approve").withEntity(HttpEntity( - ContentTypes.`application/json`, - compact(render("comments" -> "some comments")))) ~> + Post("/zones/batchrecordchanges/notFoundUser/approve").withEntity( + HttpEntity(ContentTypes.`application/json`, compact(render("comments" -> "some comments"))) + ) ~> supportUserRoute ~> check { status shouldBe NotFound } diff --git a/modules/api/src/test/scala/vinyldns/api/route/CreateGroupInputSerializerSpec.scala b/modules/api/src/test/scala/vinyldns/api/route/CreateGroupInputSerializerSpec.scala index b1e1b1e89..6825c714d 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/CreateGroupInputSerializerSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/CreateGroupInputSerializerSpec.scala @@ -36,7 +36,8 @@ class CreateGroupInputSerializerSpec email: String, description: Option[String], members: Set[UserInfo] = Set.empty, - admins: Set[UserInfo] = Set.empty): JValue = + admins: Set[UserInfo] = Set.empty + ): JValue = ("name" -> name) ~~ ("email" -> email) ~~ ("description" -> Extraction.decompose(description)) ~~ diff --git a/modules/api/src/test/scala/vinyldns/api/route/JsonValidationSpec.scala b/modules/api/src/test/scala/vinyldns/api/route/JsonValidationSpec.scala index 067c8651b..b17638855 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/JsonValidationSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/JsonValidationSpec.scala @@ -133,7 +133,9 @@ class JsonValidationSpec "throw errors for requried values" in { val pet: JValue = ("key" -> "val") ~ ("other" -> "whatever") - val extracted = try { pet.extract[Pet].valid[Throwable] } catch { + val extracted = try { + pet.extract[Pet].valid[Throwable] + } catch { case e: Throwable => e.invalid[Pet] } extracted.isInvalid shouldBe true @@ -145,7 +147,9 @@ class JsonValidationSpec "throw errors for checked conditions" in { val pet: JValue = ("name" -> "fido") ~ ("other" -> "whatever") - val extracted = try { pet.extract[Pet].valid[Throwable] } catch { + val extracted = try { + pet.extract[Pet].valid[Throwable] + } catch { case e: Throwable => e.invalid[Pet] } extracted.isInvalid shouldBe true @@ -155,12 +159,15 @@ class JsonValidationSpec err.toSet shouldBe Set( "Missing Pet.type", "Pet.name must end with y", - "Pet.name is too short") + "Pet.name is too short" + ) } "throw errors for invalid Enumerations" in { val pet: JValue = ("name" -> "Scruffy") ~ ("typ" -> "Fish") - val extracted = try { pet.extract[Pet].valid[Throwable] } catch { + val extracted = try { + pet.extract[Pet].valid[Throwable] + } catch { case e: Throwable => e.invalid[Pet] } extracted.isInvalid shouldBe true @@ -181,7 +188,9 @@ class JsonValidationSpec ("typ" -> HomeType.Apartment.toString) ~ ("random" -> "other") )) - val extracted = try { user.extract[User].valid[Throwable] } catch { + val extracted = try { + user.extract[User].valid[Throwable] + } catch { case e: Throwable => e.invalid[User] } extracted.isInvalid shouldBe true @@ -198,7 +207,9 @@ class JsonValidationSpec "throw reasonable errors using default deserialization" in { val addr: JValue = ("key" -> "val") ~ ("other" -> "whatever") - val extracted = try { addr.extract[Address].valid[Throwable] } catch { + val extracted = try { + addr.extract[Address].valid[Throwable] + } catch { case e: Throwable => e.invalid[Address] } extracted.isInvalid shouldBe true @@ -210,7 +221,9 @@ class JsonValidationSpec "catch errors from the default parsers" in { val pet: JValue = ("name" -> ("unnecessary" -> "json")) ~ ("typ" -> "Dog") - val extracted = try { pet.extract[Pet].valid[Throwable] } catch { + val extracted = try { + pet.extract[Pet].valid[Throwable] + } catch { case e: Throwable => e.invalid[Pet] } extracted.isInvalid shouldBe true diff --git a/modules/api/src/test/scala/vinyldns/api/route/MembershipRoutingSpec.scala b/modules/api/src/test/scala/vinyldns/api/route/MembershipRoutingSpec.scala index 6eed8911a..72030bbab 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/MembershipRoutingSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/MembershipRoutingSpec.scala @@ -80,7 +80,8 @@ class MembershipRoutingSpec "test@test.com", Some("describe me"), Set(okUserInfo), - Set(okUserInfo)) + Set(okUserInfo) + ) val expected = GroupInfo(okGroup) doReturn(result(okGroup)).when(membershipService).createGroup(any[Group], any[AuthPrincipal]) @@ -105,7 +106,8 @@ class MembershipRoutingSpec "test@test.com", Some("describe me"), Set(okUserInfo), - Set(okUserInfo)) + Set(okUserInfo) + ) doReturn(result(GroupAlreadyExistsError("fail"))) .when(membershipService) .createGroup(any[Group], any[AuthPrincipal]) @@ -155,7 +157,8 @@ class MembershipRoutingSpec "test@test.com", Some("describe me"), Set(okUserInfo), - Set(okUserInfo)) + Set(okUserInfo) + ) doReturn(result(UserNotFoundError("not found"))) .when(membershipService) .createGroup(any[Group], any[AuthPrincipal]) @@ -172,7 +175,8 @@ class MembershipRoutingSpec "test@test.com", Some("describe me"), Set(okUserInfo), - Set(okUserInfo)) + Set(okUserInfo) + ) doReturn(result(new IllegalArgumentException("fail"))) .when(membershipService) .createGroup(any[Group], any[AuthPrincipal]) @@ -189,8 +193,9 @@ class MembershipRoutingSpec val twoUserGroupInfo = GroupInfo(twoUserGroup) doReturn( result( - ListMyGroupsResponse(Seq(okGroupInfo, twoUserGroupInfo), None, None, None, 100, false))) - .when(membershipService) + ListMyGroupsResponse(Seq(okGroupInfo, twoUserGroupInfo), None, None, None, 100, false) + ) + ).when(membershipService) .listMyGroups(None, None, 100, okAuth, false) Get("/groups") ~> Route.seal(membershipRoute) ~> check { status shouldBe StatusCodes.OK @@ -211,16 +216,20 @@ class MembershipRoutingSpec startFrom = Some("anyString"), nextId = None, maxItems = 100, - ignoreAccess = false))) - .when(membershipService) + ignoreAccess = false + ) + ) + ).when(membershipService) .listMyGroups( groupNameFilter = Some("ok"), startFrom = Some("anyString"), maxItems = 100, okAuth, - ignoreAccess = false) + ignoreAccess = false + ) Get("/groups?startFrom=anyString&maxItems=100&groupNameFilter=ok") ~> Route.seal( - membershipRoute) ~> check { + membershipRoute + ) ~> check { status shouldBe StatusCodes.OK val result = responseAs[ListMyGroupsResponse] @@ -230,7 +239,8 @@ class MembershipRoutingSpec startFrom = Some("anyString"), maxItems = 100, nextId = None, - ignoreAccess = false) + ignoreAccess = false + ) result shouldBe expected } @@ -336,7 +346,8 @@ class MembershipRoutingSpec "test@test.com", Some("describe me"), Set(okUserInfo), - Set(okUserInfo)) + Set(okUserInfo) + ) doReturn(result(okGroup)) .when(membershipService) @@ -347,7 +358,8 @@ class MembershipRoutingSpec any[Option[String]], any[Set[String]], any[Set[String]], - any[AuthPrincipal]) + any[AuthPrincipal] + ) Put("/groups/good").withEntity(HttpEntity(ContentTypes.`application/json`, js(goodRequest))) ~> Route .seal(membershipRoute) ~> check { @@ -370,7 +382,8 @@ class MembershipRoutingSpec "test@test.com", Some("describe me"), Set(okUserInfo), - Set(okUserInfo)) + Set(okUserInfo) + ) doReturn(result(GroupAlreadyExistsError("fail"))) .when(membershipService) .updateGroup( @@ -380,11 +393,12 @@ class MembershipRoutingSpec any[Option[String]], any[Set[String]], any[Set[String]], - any[AuthPrincipal]) + any[AuthPrincipal] + ) Put("/groups/duplicate").withEntity( - HttpEntity(ContentTypes.`application/json`, js(duplicateRequest))) ~> Route.seal( - membershipRoute) ~> check { + HttpEntity(ContentTypes.`application/json`, js(duplicateRequest)) + ) ~> Route.seal(membershipRoute) ~> check { status shouldBe StatusCodes.Conflict } } @@ -396,7 +410,8 @@ class MembershipRoutingSpec "test@test.com", Some("describe me"), Set.empty, - Set.empty) + Set.empty + ) doReturn(result(GroupNotFoundError("fail"))) .when(membershipService) .updateGroup( @@ -406,10 +421,11 @@ class MembershipRoutingSpec any[Option[String]], any[Set[String]], any[Set[String]], - any[AuthPrincipal]) + any[AuthPrincipal] + ) Put("/groups/notFound").withEntity( - HttpEntity(ContentTypes.`application/json`, js(notFoundRequest))) ~> Route.seal( - membershipRoute) ~> check { + HttpEntity(ContentTypes.`application/json`, js(notFoundRequest)) + ) ~> Route.seal(membershipRoute) ~> check { status shouldBe StatusCodes.NotFound } } @@ -421,7 +437,8 @@ class MembershipRoutingSpec "test@test.com", Some("describe me"), Set(okUserInfo), - Set(okUserInfo)) + Set(okUserInfo) + ) doReturn(result(NotAuthorizedError("fail"))) .when(membershipService) @@ -432,10 +449,11 @@ class MembershipRoutingSpec any[Option[String]], any[Set[String]], any[Set[String]], - any[AuthPrincipal]) + any[AuthPrincipal] + ) Put("/groups/forbidden").withEntity( - HttpEntity(ContentTypes.`application/json`, js(forbiddenRequest))) ~> Route.seal( - membershipRoute) ~> check { + HttpEntity(ContentTypes.`application/json`, js(forbiddenRequest)) + ) ~> Route.seal(membershipRoute) ~> check { status shouldBe StatusCodes.Forbidden } } @@ -452,7 +470,8 @@ class MembershipRoutingSpec any[Option[String]], any[Set[String]], any[Set[String]], - any[AuthPrincipal]) + any[AuthPrincipal] + ) Put("/groups/bad").withEntity(HttpEntity(ContentTypes.`application/json`, js(badRequest))) ~> Route .seal(Route.seal(membershipRoute)) ~> check { @@ -472,7 +491,8 @@ class MembershipRoutingSpec any[Option[String]], any[Set[String]], any[Set[String]], - any[AuthPrincipal]) + any[AuthPrincipal] + ) Put("/groups/bad").withEntity(HttpEntity(ContentTypes.`application/json`, js(badRequest))) ~> Route .seal(membershipRoute) ~> check { @@ -543,8 +563,10 @@ class MembershipRoutingSpec Seq(dummyMemberInfo, okMemberInfo), Some("dummy"), Some("ok"), - maxItems = 50))) - .when(membershipService) + maxItems = 50 + ) + ) + ).when(membershipService) .listMembers("goodQuery", Some("dummy"), 50, okAuth) Get(s"/groups/goodQuery/members?startFrom=dummy&maxItems=50") ~> Route.seal(membershipRoute) ~> check { @@ -574,7 +596,8 @@ class MembershipRoutingSpec anyString, any[Option[String]], maxItemsCaptor.capture(), - any[AuthPrincipal]) + any[AuthPrincipal] + ) maxItemsCaptor.getValue shouldBe 100 } @@ -626,7 +649,8 @@ class MembershipRoutingSpec Seq(okGroupChangeInfo, okGroupChangeUpdateInfo, okGroupChangeDeleteInfo), None, None, - 100) + 100 + ) doReturn(result(expected)) .when(membershipService) .getGroupActivity("ok", None, 100, okAuth) @@ -638,7 +662,8 @@ class MembershipRoutingSpec result.changes should contain theSameElementsAs Seq( okGroupChangeInfo, okGroupChangeUpdateInfo, - okGroupChangeDeleteInfo) + okGroupChangeDeleteInfo + ) result.maxItems shouldBe 100 result.nextId shouldBe None result.startFrom shouldBe None @@ -667,7 +692,8 @@ class MembershipRoutingSpec Seq(okGroupChangeInfo, okGroupChangeUpdateInfo, okGroupChangeDeleteInfo), None, None, - 100) + 100 + ) doReturn(result(expected)) .when(membershipService) .getGroupActivity(anyString, any[Option[String]], anyInt, any[AuthPrincipal]) @@ -679,7 +705,8 @@ class MembershipRoutingSpec anyString, any[Option[String]], maxItemsCaptor.capture(), - any[AuthPrincipal]) + any[AuthPrincipal] + ) maxItemsCaptor.getValue shouldBe 100 } diff --git a/modules/api/src/test/scala/vinyldns/api/route/RecordSetRoutingSpec.scala b/modules/api/src/test/scala/vinyldns/api/route/RecordSetRoutingSpec.scala index 4e4f778b9..d8cb5f641 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/RecordSetRoutingSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/RecordSetRoutingSpec.scala @@ -58,7 +58,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rsPendingUpdate = RecordSet( okZone.id, @@ -68,7 +69,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rsNotFound = RecordSet( okZone.id, @@ -78,7 +80,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rsOk = RecordSet( okZone.id, @@ -88,7 +91,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rsError = RecordSet( okZone.id, @@ -98,7 +102,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rsInvalidRequest = RecordSet( okZone.id, @@ -108,7 +113,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rsZoneNotFound = RecordSet( zoneNotFound.id, @@ -118,7 +124,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rsZoneDeleted = RecordSet( zoneDeleted.id, @@ -128,7 +135,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rsZoneSyncing = RecordSet( syncingZone.id, @@ -138,7 +146,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rsNotAuthorized = RecordSet( notAuthorizedZone.id, @@ -148,7 +157,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rs1 = RecordSet( okZone.id, @@ -158,7 +168,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rs2 = RecordSet( okZone.id, @@ -168,7 +179,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val rs3 = RecordSet( okZone.id, @@ -178,7 +190,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) private val aaaa = RecordSet( okZone.id, @@ -188,7 +201,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(AAAAData("1:2:3:4:5:6:7:8"))) + List(AAAAData("1:2:3:4:5:6:7:8")) + ) private val cname = RecordSet( okZone.id, @@ -198,7 +212,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(CNAMEData("cname."))) + List(CNAMEData("cname.")) + ) private val mx = RecordSet( okZone.id, @@ -208,7 +223,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(MXData(100, "exchange."))) + List(MXData(100, "exchange.")) + ) private val ns = RecordSet( okZone.id, @@ -218,7 +234,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(NSData("nsrecordname"))) + List(NSData("nsrecordname")) + ) private val ptr = RecordSet( okZone.id, @@ -228,7 +245,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(PTRData("ptr."))) + List(PTRData("ptr.")) + ) private val soa = RecordSet( okZone.id, @@ -238,7 +256,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(SOAData("name", "name", 1, 2, 3, 4, 5))) + List(SOAData("name", "name", 1, 2, 3, 4, 5)) + ) private val spf = RecordSet( okZone.id, @@ -248,7 +267,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(SPFData("spf"))) + List(SPFData("spf")) + ) private val srv = RecordSet( okZone.id, @@ -258,7 +278,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(SRVData(1, 2, 3, "target."))) + List(SRVData(1, 2, 3, "target.")) + ) private val naptr = RecordSet( okZone.id, @@ -268,7 +289,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(NAPTRData(1, 2, "U", "E2U+sip", "!.*!test.!", "target."))) + List(NAPTRData(1, 2, "U", "E2U+sip", "!.*!test.!", "target.")) + ) private val sshfp = RecordSet( okZone.id, @@ -278,7 +300,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(SSHFPData(1, 2, "fingerprint"))) + List(SSHFPData(1, 2, "fingerprint")) + ) private val txt = RecordSet( okZone.id, @@ -288,7 +311,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(TXTData("text"))) + List(TXTData("text")) + ) private val invalidCname = RecordSet( okZone.id, @@ -298,7 +322,8 @@ class RecordSetRoutingSpec RecordSetStatus.Active, DateTime.now, None, - List(CNAMEData("cname"), CNAMEData("cname2"))) + List(CNAMEData("cname"), CNAMEData("cname2")) + ) private val rsMissingData: JValue = ("key" -> "value") ~~ ("other" -> "val") @@ -346,13 +371,15 @@ class RecordSetRoutingSpec rs1, "system", RecordSetChangeType.Create, - RecordSetChangeStatus.Complete) + RecordSetChangeStatus.Complete + ) private val rsChange2 = RecordSetChange( okZone, rs2, "system", RecordSetChangeType.Create, - RecordSetChangeStatus.Complete) + RecordSetChangeStatus.Complete + ) private val changesWithUserName = List(RecordSetChangeInfo(rsChange1, Some("ok")), RecordSetChangeInfo(rsChange2, Some("ok"))) private val listRecordSetChangesResponse = ListRecordSetChangesResponse( @@ -360,7 +387,8 @@ class RecordSetRoutingSpec changesWithUserName, nextId = None, startFrom = None, - maxItems = 100) + maxItems = 100 + ) class TestService extends RecordSetServiceAlgebra { @@ -368,7 +396,8 @@ class RecordSetRoutingSpec rsId: String, zoneId: String, authPrincipal: AuthPrincipal, - chgType: RecordSetChangeType): Either[Throwable, RecordSetChange] = zoneId match { + chgType: RecordSetChangeType + ): Either[Throwable, RecordSetChange] = zoneId match { case zoneNotFound.id => Left(ZoneNotFoundError(zoneId)) case zoneDeleted.id => Left(ZoneInactiveError(zoneId)) case notAuthorizedZone.id => Left(NotAuthorizedError(zoneId)) @@ -381,11 +410,13 @@ class RecordSetRoutingSpec .copy( status = RecordSetStatus.Active, created = DateTime.now, - updated = Some(DateTime.now)), + updated = Some(DateTime.now) + ), status = RecordSetChangeStatus.Complete, changeType = chgType, userId = authPrincipal.userId - )) + ) + ) case okZone.id => rsId match { case rsError.id => Left(new RuntimeException("fail")) @@ -406,7 +437,8 @@ class RecordSetRoutingSpec status = RecordSetChangeStatus.Complete, changeType = chgType, userId = authPrincipal.userId - )) + ) + ) else Right( RecordSetChange( @@ -417,11 +449,13 @@ class RecordSetRoutingSpec .copy( status = RecordSetStatus.Active, created = DateTime.now, - updated = Some(DateTime.now)), + updated = Some(DateTime.now) + ), status = RecordSetChangeStatus.Complete, changeType = chgType, userId = authPrincipal.userId - )) + ) + ) } } @@ -436,14 +470,16 @@ class RecordSetRoutingSpec def deleteRecordSet( recordSetId: String, zoneId: String, - auth: AuthPrincipal): Result[ZoneCommandResult] = { + auth: AuthPrincipal + ): Result[ZoneCommandResult] = { evaluate(recordSetId, zoneId, auth, RecordSetChangeType.Delete) }.map(c => c.asInstanceOf[ZoneCommandResult]).toResult def getRecordSet( recordSetId: String, zoneId: String, - authPrincipal: AuthPrincipal): Result[RecordSetInfo] = { + authPrincipal: AuthPrincipal + ): Result[RecordSetInfo] = { if (zoneId == zoneNotFound.id) { Left(ZoneNotFoundError(s"$zoneId")) } else { @@ -460,7 +496,8 @@ class RecordSetRoutingSpec startFrom: Option[String], maxItems: Option[Int], recordNameFilter: Option[String], - authPrincipal: AuthPrincipal): Result[ListRecordSetsResponse] = { + authPrincipal: AuthPrincipal + ): Result[ListRecordSetsResponse] = { zoneId match { case zoneNotFound.id => Left(ZoneNotFoundError(s"$zoneId")) case okZone.id => @@ -472,14 +509,16 @@ class RecordSetRoutingSpec RecordSetListInfo(RecordSetInfo(rs3, None), AccessLevel.Read) ), None - )) + ) + ) } }.toResult def getRecordSetChange( zoneId: String, changeId: String, - authPrincipal: AuthPrincipal): Result[RecordSetChange] = { + authPrincipal: AuthPrincipal + ): Result[RecordSetChange] = { changeId match { case "changeNotFound" => Left(RecordSetChangeNotFoundError("")) case "zoneNotFound" => Left(ZoneNotFoundError("")) @@ -492,7 +531,8 @@ class RecordSetRoutingSpec zoneId: String, startFrom: Option[String], maxItems: Int, - authPrincipal: AuthPrincipal): Result[ListRecordSetChangesResponse] = { + authPrincipal: AuthPrincipal + ): Result[ListRecordSetChangesResponse] = { zoneId match { case zoneNotFound.id => Left(ZoneNotFoundError(s"$zoneId")) case notAuthorizedZone.id => Left(NotAuthorizedError("no way")) @@ -750,7 +790,9 @@ class RecordSetRoutingSpec .withEntity( HttpEntity( ContentTypes.`application/json`, - rsJson(rsOk.copy(zoneId = invalidChangeZone.id)))) ~> + rsJson(rsOk.copy(zoneId = invalidChangeZone.id)) + ) + ) ~> recordSetRoute ~> check { status shouldBe StatusCodes.UnprocessableEntity val error = responseAs[String] @@ -904,7 +946,8 @@ class RecordSetRoutingSpec "return an error if the ttl is too small" in { validateErrors( rsInvalidTTL, - "RecordSet.ttl must be a positive signed 32 bit number greater than or equal to 30") + "RecordSet.ttl must be a positive signed 32 bit number greater than or equal to 30" + ) } "return appropriate errors for missing information" in { @@ -913,7 +956,8 @@ class RecordSetRoutingSpec "Missing RecordSet.zoneId", "Missing RecordSet.name", "Missing RecordSet.type", - "Missing RecordSet.ttl") + "Missing RecordSet.ttl" + ) } "return appropriate errors for invalid information" in { @@ -942,7 +986,8 @@ class RecordSetRoutingSpec "returns an error for multiple records in a CNAME record set" in { validateErrors( render(Extraction.decompose(invalidCname)), - "CNAME record sets cannot contain multiple records") + "CNAME record sets cannot contain multiple records" + ) } "supports A" in { @@ -956,7 +1001,8 @@ class RecordSetRoutingSpec "return errors for invalid A record data" in { validateErrors( testRecordType(RecordType.A, "address" -> "invalid"), - "A must be a valid IPv4 Address") + "A must be a valid IPv4 Address" + ) } "supports AAAA" in { @@ -970,7 +1016,8 @@ class RecordSetRoutingSpec "return errors for invalid AAAA record data" in { validateErrors( testRecordType(RecordType.AAAA, "address" -> "invalid"), - "AAAA must be a valid IPv6 Address") + "AAAA must be a valid IPv6 Address" + ) } "supports CNAME" in { @@ -985,7 +1032,8 @@ class RecordSetRoutingSpec val data = "a." + Random.alphanumeric.take(260).mkString validateErrors( testRecordType(RecordType.CNAME, "cname" -> data), - "CNAME domain name must not exceed 255 characters") + "CNAME domain name must not exceed 255 characters" + ) } "supports MX" in { @@ -996,22 +1044,26 @@ class RecordSetRoutingSpec validateErrors( testRecordType(RecordType.MX, "key" -> "val"), "Missing MX.preference", - "Missing MX.exchange") + "Missing MX.exchange" + ) } "return errors for invalid MX record data" in { validateErrors( testRecordType( RecordType.MX, - ("exchange" -> Random.alphanumeric.take(260).mkString) ~~ ("preference" -> -1)), + ("exchange" -> Random.alphanumeric.take(260).mkString) ~~ ("preference" -> -1) + ), "MX.preference must be a 16 bit integer", "MX.exchange must be less than 255 characters" ) validateErrors( testRecordType( RecordType.MX, - ("exchange" -> Random.alphanumeric.take(10).mkString) ~~ ("preference" -> 700000)), - "MX.preference must be a 16 bit integer") + ("exchange" -> Random.alphanumeric.take(10).mkString) ~~ ("preference" -> 700000) + ), + "MX.preference must be a 16 bit integer" + ) } "supports NS" in { @@ -1026,7 +1078,8 @@ class RecordSetRoutingSpec val data = "a." + Random.alphanumeric.take(260).mkString validateErrors( testRecordType(RecordType.NS, "nsdname" -> data), - "NS must be less than 255 characters") + "NS must be less than 255 characters" + ) } "supports PTR" in { @@ -1040,7 +1093,8 @@ class RecordSetRoutingSpec "return errors for invalid PTR record data" in { validateErrors( testRecordType(RecordType.PTR, "ptrdname" -> Random.alphanumeric.take(260).mkString), - "PTR must be less than 255 characters") + "PTR must be less than 255 characters" + ) } "supports SOA" in { @@ -1089,7 +1143,8 @@ class RecordSetRoutingSpec ("refresh" -> -1) ~~ ("retry" -> -1) ~~ ("expire" -> -1) ~~ - ("minimum" -> -1)), + ("minimum" -> -1) + ), "SOA.serial must be an unsigned 32 bit number", "SOA.refresh must be an unsigned 32 bit number", "SOA.retry must be an unsigned 32 bit number", @@ -1109,7 +1164,8 @@ class RecordSetRoutingSpec "return errors for invalid SPF record data" in { validateErrors( testRecordType(RecordType.SPF, "text" -> Random.alphanumeric.take(70000).mkString), - "SPF record must be less than 64764 characters") + "SPF record must be less than 64764 characters" + ) } "supports SRV" in { @@ -1122,7 +1178,8 @@ class RecordSetRoutingSpec "Missing SRV.priority", "Missing SRV.weight", "Missing SRV.port", - "Missing SRV.target") + "Missing SRV.target" + ) } "return errors for invalid SRV record data" in { @@ -1132,7 +1189,8 @@ class RecordSetRoutingSpec ("target" -> Random.alphanumeric.take(260).mkString) ~~ ("priority" -> 50000000) ~~ ("weight" -> 50000000) ~~ - ("port" -> 50000000)), + ("port" -> 50000000) + ), "SRV.priority must be an unsigned 16 bit number", "SRV.weight must be an unsigned 16 bit number", "SRV.port must be an unsigned 16 bit number", @@ -1144,7 +1202,8 @@ class RecordSetRoutingSpec ("target" -> Random.alphanumeric.take(10).mkString) ~~ ("priority" -> -1) ~~ ("weight" -> -1) ~~ - ("port" -> -1)), + ("port" -> -1) + ), "SRV.priority must be an unsigned 16 bit number", "SRV.weight must be an unsigned 16 bit number", "SRV.port must be an unsigned 16 bit number" @@ -1210,7 +1269,8 @@ class RecordSetRoutingSpec testRecordType(RecordType.SSHFP, "key" -> "val"), "Missing SSHFP.algorithm", "Missing SSHFP.type", - "Missing SSHFP.fingerprint") + "Missing SSHFP.fingerprint" + ) } "return errors for invalid SSHFP record data" in { @@ -1219,7 +1279,8 @@ class RecordSetRoutingSpec RecordType.SSHFP, ("fingerprint" -> Random.alphanumeric.take(10).mkString) ~~ ("algorithm" -> 50000000) ~~ - ("type" -> 50000000)), + ("type" -> 50000000) + ), "SSHFP.algorithm must be an unsigned 8 bit number", "SSHFP.type must be an unsigned 8 bit number" ) @@ -1228,7 +1289,8 @@ class RecordSetRoutingSpec RecordType.SSHFP, ("fingerprint" -> Random.alphanumeric.take(10).mkString) ~~ ("algorithm" -> -1) ~~ - ("type" -> -1)), + ("type" -> -1) + ), "SSHFP.algorithm must be an unsigned 8 bit number", "SSHFP.type must be an unsigned 8 bit number" ) @@ -1245,7 +1307,8 @@ class RecordSetRoutingSpec "return errors for invalid TXT record data" in { validateErrors( testRecordType(RecordType.TXT, "text" -> Random.alphanumeric.take(70000).mkString), - "TXT record must be less than 64764 characters") + "TXT record must be less than 64764 characters" + ) } } } diff --git a/modules/api/src/test/scala/vinyldns/api/route/TestVinylDNSAuthenticator.scala b/modules/api/src/test/scala/vinyldns/api/route/TestVinylDNSAuthenticator.scala index 05910ea53..3a526e105 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/TestVinylDNSAuthenticator.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/TestVinylDNSAuthenticator.scala @@ -24,6 +24,7 @@ class TestVinylDNSAuthenticator(authPrincipal: AuthPrincipal) extends VinylDNSAu def authenticate( ctx: RequestContext, - content: String): IO[Either[VinylDNSAuthenticationError, AuthPrincipal]] = + content: String + ): IO[Either[VinylDNSAuthenticationError, AuthPrincipal]] = IO.pure(Right(authPrincipal)) } diff --git a/modules/api/src/test/scala/vinyldns/api/route/UpdateGroupInputSerializerSpec.scala b/modules/api/src/test/scala/vinyldns/api/route/UpdateGroupInputSerializerSpec.scala index f9fb1394b..2d8a4af36 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/UpdateGroupInputSerializerSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/UpdateGroupInputSerializerSpec.scala @@ -37,7 +37,8 @@ class UpdateGroupInputSerializerSpec email: String, description: Option[String], members: Set[UserInfo] = Set.empty, - admins: Set[UserInfo] = Set.empty): JValue = + admins: Set[UserInfo] = Set.empty + ): JValue = ("id" -> id) ~~ ("name" -> name) ~~ ("email" -> email) ~~ diff --git a/modules/api/src/test/scala/vinyldns/api/route/VinylDNSDirectivesSpec.scala b/modules/api/src/test/scala/vinyldns/api/route/VinylDNSDirectivesSpec.scala index 9ea07a0c6..a31e6af36 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/VinylDNSDirectivesSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/VinylDNSDirectivesSpec.scala @@ -146,7 +146,8 @@ class VinylDNSDirectivesSpec } "increment the latency and the errors when recording an exception" in { an[IOException] should be thrownBy record(testMonitor, System.nanoTime())( - Failure(new IOException("fail"))) + Failure(new IOException("fail")) + ) verify(mockLatency).+=(anyLong()) verify(mockErrors).mark() diff --git a/modules/api/src/test/scala/vinyldns/api/route/VinylDNSJsonProtocolSpec.scala b/modules/api/src/test/scala/vinyldns/api/route/VinylDNSJsonProtocolSpec.scala index 76b478079..ee72c07dd 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/VinylDNSJsonProtocolSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/VinylDNSJsonProtocolSpec.scala @@ -41,13 +41,17 @@ class VinylDNSJsonProtocolSpec "primaryConnection", "primaryConnectionKeyName", "primaryConnectionKey", - "10.1.1.1")), + "10.1.1.1" + ) + ), transferConnection = Some( ZoneConnection( "transferConnection", "transferConnectionKeyName", "transferConnectionKey", - "10.1.1.2")), + "10.1.1.2" + ) + ), adminGroupId = "admin-group-id" ) @@ -60,13 +64,17 @@ class VinylDNSJsonProtocolSpec "primaryConnection", "primaryConnectionKeyName", "primaryConnectionKey", - "10.1.1.1")), + "10.1.1.1" + ) + ), transferConnection = Some( ZoneConnection( "transferConnection", "transferConnectionKeyName", "transferConnectionKey", - "10.1.1.2")), + "10.1.1.2" + ) + ), adminGroupId = "updated-admin-group-id" ) @@ -143,7 +151,8 @@ class VinylDNSJsonProtocolSpec val expected = completeCreateZoneInput.copy( connection = None, transferConnection = None, - backendId = Some("test-backend-id")) + backendId = Some("test-backend-id") + ) val actual = createZoneInput.extract[CreateZoneInput] actual shouldBe expected } @@ -247,7 +256,8 @@ class VinylDNSJsonProtocolSpec val expected = completeUpdateZoneInput.copy( connection = None, transferConnection = None, - backendId = Some("test-backend-id")) + backendId = Some("test-backend-id") + ) val actual = updateZoneInput.extract[UpdateZoneInput] actual shouldBe expected } @@ -316,7 +326,8 @@ class VinylDNSJsonProtocolSpec 1000, RecordSetStatus.Pending, new DateTime(2010, 1, 1, 0, 0), - records = List(CNAMEData("cname."))) + records = List(CNAMEData("cname.")) + ) val actual = recordSetJValue.extract[RecordSet] anonymize(actual) shouldBe anonymize(expected) @@ -337,7 +348,8 @@ class VinylDNSJsonProtocolSpec 1000, RecordSetStatus.Pending, new DateTime(2010, 1, 1, 0, 0), - records = List(CNAMEData("cname.data."))) + records = List(CNAMEData("cname.data.")) + ) val actual = recordSetJValue.extract[RecordSet] anonymize(actual) shouldBe anonymize(expected) @@ -372,7 +384,8 @@ class VinylDNSJsonProtocolSpec 1000, RecordSetStatus.Pending, new DateTime(2010, 1, 1, 0, 0), - records = List(MXData(1, "mx."))) + records = List(MXData(1, "mx.")) + ) val actual = recordSetJValue.extract[RecordSet] anonymize(actual) shouldBe anonymize(expected) @@ -393,7 +406,8 @@ class VinylDNSJsonProtocolSpec 1000, RecordSetStatus.Pending, new DateTime(2010, 1, 1, 0, 0), - records = List(MXData(1, "mx."))) + records = List(MXData(1, "mx.")) + ) val actual = recordSetJValue.extract[RecordSet] anonymize(actual) shouldBe anonymize(expected) @@ -416,7 +430,8 @@ class VinylDNSJsonProtocolSpec 1000, RecordSetStatus.Pending, new DateTime(2010, 1, 1, 0, 0), - records = List(SRVData(1, 20, 5000, "srv."))) + records = List(SRVData(1, 20, 5000, "srv.")) + ) val actual = recordSetJValue.extract[RecordSet] anonymize(actual) shouldBe anonymize(expected) @@ -437,7 +452,8 @@ class VinylDNSJsonProtocolSpec 1000, RecordSetStatus.Pending, new DateTime(2010, 1, 1, 0, 0), - records = List(SRVData(1, 20, 5000, "srv."))) + records = List(SRVData(1, 20, 5000, "srv.")) + ) val actual = recordSetJValue.extract[RecordSet] anonymize(actual) shouldBe anonymize(expected) @@ -452,7 +468,8 @@ class VinylDNSJsonProtocolSpec ("ttl" -> 1000) ~~ ("status" -> "Pending") ~~ ("records" -> Extraction.decompose( - Set(NAPTRData(1, 20, "U", "E2U+sip", "!.*!test.!", "naptr.")))) + Set(NAPTRData(1, 20, "U", "E2U+sip", "!.*!test.!", "naptr.")) + )) val expected = RecordSet( "1", @@ -475,7 +492,8 @@ class VinylDNSJsonProtocolSpec ("ttl" -> 1000) ~~ ("status" -> "Pending") ~~ ("records" -> Extraction.decompose( - Set(NAPTRData(1, 20, "U", "E2U+sip", "!.*!test.!", "naptr")))) + Set(NAPTRData(1, 20, "U", "E2U+sip", "!.*!test.!", "naptr")) + )) val expected = RecordSet( "1", @@ -490,7 +508,8 @@ class VinylDNSJsonProtocolSpec val actual = recordSetJValue.extract[RecordSet] anonymize(actual) shouldBe anonymize(expected) anonymize(actual).records shouldBe List( - NAPTRData(1, 20, "U", "E2U+sip", "!.*!test.!", "naptr.")) + NAPTRData(1, 20, "U", "E2U+sip", "!.*!test.!", "naptr.") + ) } "parse a record set with an absolute PTR domain name" in { @@ -509,7 +528,8 @@ class VinylDNSJsonProtocolSpec 1000, RecordSetStatus.Pending, new DateTime(2010, 1, 1, 0, 0), - records = List(PTRData("ptr."))) + records = List(PTRData("ptr.")) + ) val actual = recordSetJValue.extract[RecordSet] anonymize(actual) shouldBe anonymize(expected) @@ -530,7 +550,8 @@ class VinylDNSJsonProtocolSpec 1000, RecordSetStatus.Pending, new DateTime(2010, 1, 1, 0, 0), - records = List(PTRData("ptr."))) + records = List(PTRData("ptr.")) + ) val actual = recordSetJValue.extract[RecordSet] anonymize(actual) shouldBe anonymize(expected) @@ -552,7 +573,8 @@ class VinylDNSJsonProtocolSpec 1000, RecordSetStatus.Pending, new DateTime(2010, 1, 1, 0, 0), - records = List(NSData("abs.data"))) + records = List(NSData("abs.data")) + ) val actual = recordSetJValue.extract[RecordSet] anonymize(actual) shouldBe anonymize(expected) @@ -580,7 +602,8 @@ class VinylDNSJsonProtocolSpec 1000, RecordSetStatus.Pending, new DateTime(2010, 1, 1, 0, 0), - records = List(dSDataSha1)) + records = List(dSDataSha1) + ) RecordSetSerializer.fromJson(RecordSetSerializer.toJson(rs)).value shouldBe rs } diff --git a/modules/api/src/test/scala/vinyldns/api/route/VinylDNSRouteTestHelper.scala b/modules/api/src/test/scala/vinyldns/api/route/VinylDNSRouteTestHelper.scala index 846aab70e..cda216a54 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/VinylDNSRouteTestHelper.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/VinylDNSRouteTestHelper.scala @@ -30,7 +30,8 @@ trait VinylDNSRouteTestHelper { HttpResponse( status = StatusCodes.BadRequest, entity = HttpEntity(ContentTypes.`application/json`, msg) - )) + ) + ) } .handleNotFound { extractUnmatchedPath { p => diff --git a/modules/api/src/test/scala/vinyldns/api/route/VinylDNSServiceSpec.scala b/modules/api/src/test/scala/vinyldns/api/route/VinylDNSServiceSpec.scala index 52de777ae..6a5e571bc 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/VinylDNSServiceSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/VinylDNSServiceSpec.scala @@ -33,7 +33,8 @@ class VinylDNSServiceSpec with VinylDNSDirectives[Throwable] { val vinylDNSAuthenticator: VinylDNSAuthenticator = new TestVinylDNSAuthenticator( - mock[AuthPrincipal]) + mock[AuthPrincipal] + ) def getRoutes: Route = mock[Route] @@ -43,14 +44,16 @@ class VinylDNSServiceSpec private def buildMockRequest( path: String = "/path/to/resource", - body: String = "request body") = { + body: String = "request body" + ) = { val requestHeaders = List[HttpHeader](RawHeader("Authorization", "fake_auth")) HttpRequest(uri = Uri(path), entity = HttpEntity(body), headers = requestHeaders) } private def buildUnloggedRequest( path: String = "/path/to/unlogged/resource", - body: String = "request body") = + body: String = "request body" + ) = HttpRequest(uri = Uri(path), entity = HttpEntity(body)) private def buildMockResponse(body: String = "results") = diff --git a/modules/api/src/test/scala/vinyldns/api/route/ZoneRoutingSpec.scala b/modules/api/src/test/scala/vinyldns/api/route/ZoneRoutingSpec.scala index 593743dc0..06fd10e49 100644 --- a/modules/api/src/test/scala/vinyldns/api/route/ZoneRoutingSpec.scala +++ b/modules/api/src/test/scala/vinyldns/api/route/ZoneRoutingSpec.scala @@ -54,21 +54,24 @@ class ZoneRoutingSpec Some("johnny"), None, Some("www-*"), - Set(RecordType.A, RecordType.AAAA, RecordType.CNAME)) + Set(RecordType.A, RecordType.AAAA, RecordType.CNAME) + ) private val userAclRuleInfo = ACLRuleInfo( AccessLevel.Read, Some("desc"), Some("johnny"), None, Some("www-*"), - Set(RecordType.A, RecordType.AAAA, RecordType.CNAME)) + Set(RecordType.A, RecordType.AAAA, RecordType.CNAME) + ) private val groupAclRule = ACLRule( AccessLevel.Read, Some("desc"), None, Some("group"), Some("www-*"), - Set(RecordType.A, RecordType.AAAA, RecordType.CNAME)) + Set(RecordType.A, RecordType.AAAA, RecordType.CNAME) + ) private val zoneAcl = ZoneACL(Set(userAclRule, groupAclRule)) private val ok = Zone("ok.", "ok@test.com", acl = zoneAcl, adminGroupId = "test") @@ -85,11 +88,13 @@ class ZoneRoutingSpec private val connectionFailed = Zone( "connection.fail", "connection-failed@test.com", - connection = Some(ZoneConnection("connection.fail", "keyName", "key", "10.1.1.1"))) + connection = Some(ZoneConnection("connection.fail", "keyName", "key", "10.1.1.1")) + ) private val zoneValidationFailed = Zone( "validation.fail", "zone-validation-failed@test.com", - connection = Some(ZoneConnection("validation.fail", "keyName", "key", "10.1.1.1"))) + connection = Some(ZoneConnection("validation.fail", "keyName", "key", "10.1.1.1")) + ) private val zone1 = Zone("zone1.", "zone1@test.com", ZoneStatus.Active) private val zoneSummaryInfo1 = ZoneSummaryInfo(zone1, okGroup.name, AccessLevel.NoAccess) private val zone2 = Zone("zone2.", "zone2@test.com", ZoneStatus.Active) @@ -121,7 +126,8 @@ class ZoneRoutingSpec List(zoneCreate, zoneUpdate), nextId = None, startFrom = None, - maxItems = 100) + maxItems = 100 + ) val zoneRoute: Route = new ZoneRoute(TestZoneService, new TestVinylDNSAuthenticator(okAuth)).getRoutes @@ -129,7 +135,8 @@ class ZoneRoutingSpec object TestZoneService extends ZoneServiceAlgebra { def connectToZone( createZoneInput: CreateZoneInput, - auth: AuthPrincipal): Result[ZoneCommandResult] = { + auth: AuthPrincipal + ): Result[ZoneCommandResult] = { val outcome = createZoneInput.email match { case alreadyExists.email => Left(ZoneAlreadyExistsError(s"$createZoneInput")) case notFound.email => Left(ZoneNotFoundError(s"$createZoneInput")) @@ -139,7 +146,9 @@ class ZoneRoutingSpec Right( zoneCreate.copy( status = ZoneChangeStatus.Complete, - zone = Zone(createZoneInput, false).copy(status = ZoneStatus.Active))) + zone = Zone(createZoneInput, false).copy(status = ZoneStatus.Active) + ) + ) case error.email => Left(new RuntimeException("fail")) case connectionFailed.email => Left(ConnectionFailed(Zone(createZoneInput, false), "fail")) case zoneValidationFailed.email => @@ -152,7 +161,8 @@ class ZoneRoutingSpec def updateZone( updateZoneInput: UpdateZoneInput, - auth: AuthPrincipal): Result[ZoneCommandResult] = { + auth: AuthPrincipal + ): Result[ZoneCommandResult] = { val outcome = updateZoneInput.email match { case alreadyExists.email => Left(ZoneAlreadyExistsError(s"$updateZoneInput")) case notFound.email => Left(ZoneNotFoundError(s"$updateZoneInput")) @@ -162,7 +172,9 @@ class ZoneRoutingSpec Right( zoneUpdate.copy( status = ZoneChangeStatus.Complete, - zone = Zone(updateZoneInput, zoneUpdate.zone).copy(status = ZoneStatus.Active))) + zone = Zone(updateZoneInput, zoneUpdate.zone).copy(status = ZoneStatus.Active) + ) + ) case error.email => Left(new RuntimeException("fail")) case zone1.email => Left(ZoneUnavailableError(s"$updateZoneInput")) case connectionFailed.email => @@ -172,7 +184,9 @@ class ZoneRoutingSpec ZoneValidationFailed( Zone(updateZoneInput, zoneUpdate.zone), List("fail"), - "failure message")) + "failure message" + ) + ) } outcome.map(c => c.asInstanceOf[ZoneCommandResult]).toResult } @@ -226,7 +240,8 @@ class ZoneRoutingSpec nameFilter: Option[String], startFrom: Option[String], maxItems: Int, - ignoreAccess: Boolean = false): Result[ListZonesResponse] = { + ignoreAccess: Boolean = false + ): Result[ListZonesResponse] = { val outcome = (authPrincipal, nameFilter, startFrom, maxItems, ignoreAccess) match { case (_, None, Some("zone3."), 3, false) => @@ -248,7 +263,8 @@ class ZoneRoutingSpec startFrom = Some("zone4."), nextId = None, maxItems = 4, - ignoreAccess = false) + ignoreAccess = false + ) ) case (_, None, None, 3, false) => @@ -259,7 +275,8 @@ class ZoneRoutingSpec startFrom = None, nextId = Some("zone3."), maxItems = 3, - ignoreAccess = false) + ignoreAccess = false + ) ) case (_, None, None, 5, true) => @@ -270,7 +287,8 @@ class ZoneRoutingSpec zoneSummaryInfo2, zoneSummaryInfo3, zoneSummaryInfo4, - zoneSummaryInfo5), + zoneSummaryInfo5 + ), nameFilter = None, startFrom = None, nextId = None, @@ -298,7 +316,8 @@ class ZoneRoutingSpec nameFilter = None, startFrom = None, nextId = None, - ignoreAccess = false) + ignoreAccess = false + ) ) case _ => Left(InvalidRequest("shouldnt get here")) @@ -311,7 +330,8 @@ class ZoneRoutingSpec zoneId: String, authPrincipal: AuthPrincipal, startFrom: Option[String], - maxItems: Int): Result[ListZoneChangesResponse] = { + maxItems: Int + ): Result[ListZoneChangesResponse] = { val outcome = zoneId match { case notFound.id => Left(ZoneNotFoundError(s"$zoneId")) case notAuthorized.id => Left(NotAuthorizedError("no way")) @@ -323,7 +343,8 @@ class ZoneRoutingSpec def addACLRule( zoneId: String, aclRuleInfo: ACLRuleInfo, - authPrincipal: AuthPrincipal): Result[ZoneCommandResult] = { + authPrincipal: AuthPrincipal + ): Result[ZoneCommandResult] = { val outcome = zoneId match { case badRegex.id => Left(InvalidRequest("record mask x{5,-3} is an invalid regex")) @@ -348,7 +369,8 @@ class ZoneRoutingSpec def deleteACLRule( zoneId: String, aclRuleInfo: ACLRuleInfo, - authPrincipal: AuthPrincipal): Result[ZoneCommandResult] = { + authPrincipal: AuthPrincipal + ): Result[ZoneCommandResult] = { val outcome = zoneId match { case notFound.id => Left(ZoneNotFoundError(s"$zoneId")) case notAuthorized.id => Left(NotAuthorizedError(s"$zoneId")) @@ -404,7 +426,8 @@ class ZoneRoutingSpec Some("user"), None, Some("www-*"), - Set(RecordType.AAAA, RecordType.CNAME)) + Set(RecordType.AAAA, RecordType.CNAME) + ) "return a 202 Accepted when the acl rule is good" in { Put(s"/zones/${ok.id}/acl/rules") .withEntity(HttpEntity(ContentTypes.`application/json`, js(goodRequest))) ~> zoneRoute ~> check { @@ -431,7 +454,8 @@ class ZoneRoutingSpec userId = None, groupId = None, recordMask = None, - recordTypes = Set()) + recordTypes = Set() + ) Put(s"/zones/${ok.id}/acl/rules") .withEntity(HttpEntity(ContentTypes.`application/json`, js(requestAllUsers))) ~> zoneRoute ~> check { @@ -475,9 +499,9 @@ class ZoneRoutingSpec ("userId" -> Extraction.decompose(Some("johnny"))) Put(s"/zones/${ok.id}/acl/rules") - .withEntity(HttpEntity( - ContentTypes.`application/json`, - compact(render(missingACLAccessLevel)))) ~> Route.seal(zoneRoute) ~> check { + .withEntity( + HttpEntity(ContentTypes.`application/json`, compact(render(missingACLAccessLevel))) + ) ~> Route.seal(zoneRoute) ~> check { status shouldBe BadRequest val result = responseAs[JValue] val errs = (result \ "errors").extractOpt[List[String]] @@ -516,7 +540,8 @@ class ZoneRoutingSpec Some("user"), None, Some("x{5,-3}"), - Set(RecordType.AAAA, RecordType.CNAME)) + Set(RecordType.AAAA, RecordType.CNAME) + ) Put(s"/zones/${badRegex.id}/acl/rules") .withEntity(HttpEntity(ContentTypes.`application/json`, js(badRequest))) ~> zoneRoute ~> check { @@ -534,7 +559,8 @@ class ZoneRoutingSpec Some("user"), None, Some("www-*"), - Set(RecordType.AAAA, RecordType.CNAME)) + Set(RecordType.AAAA, RecordType.CNAME) + ) "return a 202 Accepted when the acl rule is good" in { Delete(s"/zones/${ok.id}/acl/rules") .withEntity(HttpEntity(ContentTypes.`application/json`, js(goodRequest))) ~> zoneRoute ~> check { @@ -574,9 +600,9 @@ class ZoneRoutingSpec ("userId" -> Extraction.decompose(Some("johnny"))) Delete(s"/zones/${ok.id}/acl/rules") - .withEntity(HttpEntity( - ContentTypes.`application/json`, - compact(render(missingACLAccessLevel)))) ~> Route.seal(zoneRoute) ~> check { + .withEntity( + HttpEntity(ContentTypes.`application/json`, compact(render(missingACLAccessLevel))) + ) ~> Route.seal(zoneRoute) ~> check { status shouldBe BadRequest val result = responseAs[JValue] @@ -898,7 +924,8 @@ class ZoneRoutingSpec Get(s"/zones?maxItems=700") ~> zoneRoute ~> check { status shouldBe BadRequest responseEntity.toString should include( - "maxItems was 700, maxItems must be between 0 and 100") + "maxItems was 700, maxItems must be between 0 and 100" + ) } } } @@ -968,9 +995,9 @@ class ZoneRoutingSpec } "return 403 if the user is not authorized" in { - Put(s"/zones/${notAuthorized.id}").withEntity(HttpEntity( - ContentTypes.`application/json`, - zoneJson(notAuthorized))) ~> zoneRoute ~> check { + Put(s"/zones/${notAuthorized.id}").withEntity( + HttpEntity(ContentTypes.`application/json`, zoneJson(notAuthorized)) + ) ~> zoneRoute ~> check { status shouldBe Forbidden } } @@ -991,31 +1018,32 @@ class ZoneRoutingSpec "validate the connection when the update is posted" in { Put(s"/zones/${connectionOk.id}").withEntity( - HttpEntity(ContentTypes.`application/json`, zoneJson(connectionOk))) ~> zoneRoute ~> check { + HttpEntity(ContentTypes.`application/json`, zoneJson(connectionOk)) + ) ~> zoneRoute ~> check { status shouldBe Accepted } } "fail the update if the connection validation fails" in { - Put(s"/zones/${connectionFailed.id}").withEntity(HttpEntity( - ContentTypes.`application/json`, - zoneJson(connectionFailed))) ~> zoneRoute ~> check { + Put(s"/zones/${connectionFailed.id}").withEntity( + HttpEntity(ContentTypes.`application/json`, zoneJson(connectionFailed)) + ) ~> zoneRoute ~> check { status shouldBe BadRequest } } "fail the update if the zone validation fails" in { - Put(s"/zones/${zoneValidationFailed.id}").withEntity(HttpEntity( - ContentTypes.`application/json`, - zoneJson(zoneValidationFailed))) ~> zoneRoute ~> check { + Put(s"/zones/${zoneValidationFailed.id}").withEntity( + HttpEntity(ContentTypes.`application/json`, zoneJson(zoneValidationFailed)) + ) ~> zoneRoute ~> check { status shouldBe BadRequest } } "report missing data" in { Put(s"/zones/${ok.id}").withEntity( - HttpEntity(ContentTypes.`application/json`, compact(render(missingFields)))) ~> Route.seal( - zoneRoute) ~> check { + HttpEntity(ContentTypes.`application/json`, compact(render(missingFields))) + ) ~> Route.seal(zoneRoute) ~> check { status shouldBe BadRequest val result = responseAs[JValue] val errs = (result \ "errors").extractOpt[List[String]] @@ -1035,7 +1063,8 @@ class ZoneRoutingSpec "report type mismatch" in { Put(s"/zones/${ok.id}").withEntity( - HttpEntity(ContentTypes.`application/json`, compact(render(zoneWithInvalidId)))) ~> Route + HttpEntity(ContentTypes.`application/json`, compact(render(zoneWithInvalidId))) + ) ~> Route .seal(zoneRoute) ~> check { status shouldBe BadRequest val result = responseAs[JValue] diff --git a/modules/core/src/main/scala/vinyldns/core/crypto/CryptoAlgebra.scala b/modules/core/src/main/scala/vinyldns/core/crypto/CryptoAlgebra.scala index 50af1b40e..c797aef8d 100644 --- a/modules/core/src/main/scala/vinyldns/core/crypto/CryptoAlgebra.scala +++ b/modules/core/src/main/scala/vinyldns/core/crypto/CryptoAlgebra.scala @@ -33,6 +33,7 @@ object CryptoAlgebra { .forName(className) .getDeclaredConstructor(classOf[Config]) .newInstance(cryptoConfig) - .asInstanceOf[CryptoAlgebra]) + .asInstanceOf[CryptoAlgebra] + ) } yield classInstance } diff --git a/modules/core/src/main/scala/vinyldns/core/domain/DomainValidationErrors.scala b/modules/core/src/main/scala/vinyldns/core/domain/DomainValidationErrors.scala index 01627689f..591d5c7cd 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/DomainValidationErrors.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/DomainValidationErrors.scala @@ -131,8 +131,8 @@ final case class UserIsNotAuthorizedError( ownerGroupId: String, ownerType: OwnerType, contactEmail: Option[String] = None, - ownerGroupName: Option[String] = None) - extends DomainValidationError { + ownerGroupName: Option[String] = None +) extends DomainValidationError { def message: String = s"""User "$userName" is not authorized. Contact ${ownerType.toString.toLowerCase} owner group: |${ownerGroupName.getOrElse(ownerGroupId)} at ${contactEmail.getOrElse("")}.""".stripMargin diff --git a/modules/core/src/main/scala/vinyldns/core/domain/SingleChangeError.scala b/modules/core/src/main/scala/vinyldns/core/domain/SingleChangeError.scala index 79fa22e36..a7ed47b4e 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/SingleChangeError.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/SingleChangeError.scala @@ -25,6 +25,7 @@ object SingleChangeError { new SingleChangeError(DomainValidationErrorType.from(error), error.message) } +// format: off object DomainValidationErrorType extends Enumeration { type DomainValidationErrorType = Value // NOTE: once defined, an error code type cannot be changed! @@ -74,3 +75,4 @@ object DomainValidationErrorType extends Enumeration { } // $COVERAGE-ON$ } +// format: on diff --git a/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChange.scala b/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChange.scala index 2ae2a6290..8fdc7aced 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChange.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChange.scala @@ -50,7 +50,8 @@ case class BatchChange( hasPending, hasFailed, hasComplete, - isScheduled) + isScheduled + ) } } @@ -68,7 +69,7 @@ case class BatchChangeCommand(id: String) extends ZoneCommand with ZoneCommandRe object BatchChangeStatus extends Enumeration { type BatchChangeStatus = Value val Cancelled, Complete, Failed, PartialFailure, PendingProcessing, PendingReview, Rejected, - Scheduled = + Scheduled = Value def calculateBatchStatus( @@ -76,7 +77,8 @@ object BatchChangeStatus extends Enumeration { hasPending: Boolean, hasFailed: Boolean, hasComplete: Boolean, - isScheduled: Boolean): BatchChangeStatus = + isScheduled: Boolean + ): BatchChangeStatus = approvalStatus match { case BatchChangeApprovalStatus.PendingReview if isScheduled => BatchChangeStatus.Scheduled case BatchChangeApprovalStatus.PendingReview => BatchChangeStatus.PendingReview @@ -126,7 +128,8 @@ object BatchChangeInfo { def apply( batchChange: BatchChange, ownerGroupName: Option[String] = None, - reviewerUserName: Option[String] = None): BatchChangeInfo = { + reviewerUserName: Option[String] = None + ): BatchChangeInfo = { import batchChange._ BatchChangeInfo( userId, diff --git a/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChangeRepository.scala b/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChangeRepository.scala index 0227ab9f8..9901e171c 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChangeRepository.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChangeRepository.scala @@ -31,7 +31,8 @@ trait BatchChangeRepository extends Repository { userId: Option[String], startFrom: Option[Int] = None, maxItems: Int = 100, - approvalStatus: Option[BatchChangeApprovalStatus] = None): IO[BatchChangeSummaryList] + approvalStatus: Option[BatchChangeApprovalStatus] = None + ): IO[BatchChangeSummaryList] // updateSingleChanges updates status, recordSetId, recordChangeId and systemMessage (in data). def updateSingleChanges(singleChanges: List[SingleChange]): IO[Option[BatchChange]] diff --git a/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChangeSummary.scala b/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChangeSummary.scala index 2f1753944..f5f1e063b 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChangeSummary.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/batch/BatchChangeSummary.scala @@ -38,7 +38,8 @@ case class BatchChangeSummary( reviewComment: Option[String], reviewTimestamp: Option[DateTime], scheduledTime: Option[DateTime] = None, - cancelledTimestamp: Option[DateTime] = None) + cancelledTimestamp: Option[DateTime] = None +) object BatchChangeSummary { def apply(batchChange: BatchChange): BatchChangeSummary = @@ -90,4 +91,5 @@ case class BatchChangeSummaryList( nextId: Option[Int] = None, maxItems: Int = 100, ignoreAccess: Boolean = false, - approvalStatus: Option[BatchChangeApprovalStatus] = None) + approvalStatus: Option[BatchChangeApprovalStatus] = None +) diff --git a/modules/core/src/main/scala/vinyldns/core/domain/batch/SingleChange.scala b/modules/core/src/main/scala/vinyldns/core/domain/batch/SingleChange.scala index 2c0fdf52d..48d494485 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/batch/SingleChange.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/batch/SingleChange.scala @@ -53,12 +53,14 @@ sealed trait SingleChange { add.copy( status = SingleChangeStatus.Failed, systemMessage = message, - recordChangeId = Some(failedRecordChangeId)) + recordChangeId = Some(failedRecordChangeId) + ) case delete: SingleDeleteRRSetChange => delete.copy( status = SingleChangeStatus.Failed, systemMessage = message, - recordChangeId = Some(failedRecordChangeId)) + recordChangeId = Some(failedRecordChangeId) + ) } def complete(completeRecordChangeId: String, recordSetId: String): SingleChange = this match { @@ -66,12 +68,14 @@ sealed trait SingleChange { add.copy( status = SingleChangeStatus.Complete, recordChangeId = Some(completeRecordChangeId), - recordSetId = Some(recordSetId)) + recordSetId = Some(recordSetId) + ) case delete: SingleDeleteRRSetChange => delete.copy( status = SingleChangeStatus.Complete, recordChangeId = Some(completeRecordChangeId), - recordSetId = Some(recordSetId)) + recordSetId = Some(recordSetId) + ) } def reject: SingleChange = this match { @@ -104,8 +108,8 @@ final case class SingleAddChange( recordChangeId: Option[String], recordSetId: Option[String], validationErrors: List[SingleChangeError] = List.empty, - id: String = UUID.randomUUID().toString) - extends SingleChange + id: String = UUID.randomUUID().toString +) extends SingleChange final case class SingleDeleteRRSetChange( zoneId: Option[String], @@ -119,8 +123,8 @@ final case class SingleDeleteRRSetChange( recordChangeId: Option[String], recordSetId: Option[String], validationErrors: List[SingleChangeError] = List.empty, - id: String = UUID.randomUUID().toString) - extends SingleChange + id: String = UUID.randomUUID().toString +) extends SingleChange /* - Pending has not yet been processed diff --git a/modules/core/src/main/scala/vinyldns/core/domain/membership/Group.scala b/modules/core/src/main/scala/vinyldns/core/domain/membership/Group.scala index 305f5ab21..ddfafc892 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/membership/Group.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/membership/Group.scala @@ -69,11 +69,13 @@ case class Group( emailUpdate: String, descriptionUpdate: Option[String], memberIdsUpdate: Set[String], - adminUserIdsUpdate: Set[String]): Group = + adminUserIdsUpdate: Set[String] + ): Group = this.copy( name = nameUpdate, email = emailUpdate, description = descriptionUpdate, memberIds = memberIdsUpdate ++ adminUserIdsUpdate, - adminUserIds = adminUserIdsUpdate) + adminUserIds = adminUserIdsUpdate + ) } diff --git a/modules/core/src/main/scala/vinyldns/core/domain/membership/GroupChangeRepository.scala b/modules/core/src/main/scala/vinyldns/core/domain/membership/GroupChangeRepository.scala index 498cec172..fe99c351b 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/membership/GroupChangeRepository.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/membership/GroupChangeRepository.scala @@ -27,7 +27,8 @@ trait GroupChangeRepository extends Repository { def getGroupChanges( groupId: String, startFrom: Option[String], - maxItems: Int): IO[ListGroupChangesResults] + maxItems: Int + ): IO[ListGroupChangesResults] implicit def dateTimeOrdering: Ordering[DateTime] = Ordering.fromLessThan(_.isBefore(_)) } diff --git a/modules/core/src/main/scala/vinyldns/core/domain/membership/ListGroupChangesResults.scala b/modules/core/src/main/scala/vinyldns/core/domain/membership/ListGroupChangesResults.scala index af7da3bee..66b71c028 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/membership/ListGroupChangesResults.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/membership/ListGroupChangesResults.scala @@ -18,4 +18,5 @@ package vinyldns.core.domain.membership final case class ListGroupChangesResults( changes: Seq[GroupChange], - lastEvaluatedTimeStamp: Option[String]) + lastEvaluatedTimeStamp: Option[String] +) diff --git a/modules/core/src/main/scala/vinyldns/core/domain/membership/UserChange.scala b/modules/core/src/main/scala/vinyldns/core/domain/membership/UserChange.scala index f68dd6ab2..d2e6b1332 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/membership/UserChange.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/membership/UserChange.scala @@ -54,15 +54,15 @@ object UserChange { newUser: User, madeByUserId: String, created: DateTime, - id: String = UUID.randomUUID().toString) - extends UserChange + id: String = UUID.randomUUID().toString + ) extends UserChange final case class UpdateUser( newUser: User, madeByUserId: String, created: DateTime, oldUser: User, - id: String = UUID.randomUUID().toString) - extends UserChange + id: String = UUID.randomUUID().toString + ) extends UserChange def apply( id: String, @@ -70,14 +70,20 @@ object UserChange { madeByUserId: String, created: DateTime, oldUser: Option[User], - changeType: UserChangeType): Either[IllegalArgumentException, UserChange] = + changeType: UserChangeType + ): Either[IllegalArgumentException, UserChange] = changeType match { case UserChangeType.Create => Right(CreateUser(newUser, madeByUserId, created, id)) case UserChangeType.Update => oldUser .map(u => Right(UpdateUser(newUser, madeByUserId, created, u, id))) - .getOrElse(Left(new IllegalArgumentException( - s"Unable to create update user change, old user is not defined"))) + .getOrElse( + Left( + new IllegalArgumentException( + s"Unable to create update user change, old user is not defined" + ) + ) + ) } } diff --git a/modules/core/src/main/scala/vinyldns/core/domain/membership/UserRepository.scala b/modules/core/src/main/scala/vinyldns/core/domain/membership/UserRepository.scala index ffbc849cf..07a390338 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/membership/UserRepository.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/membership/UserRepository.scala @@ -27,7 +27,8 @@ trait UserRepository extends Repository { def getUsers( userIds: Set[String], startFrom: Option[String], - maxItems: Option[Int]): IO[ListUsersResults] + maxItems: Option[Int] + ): IO[ListUsersResults] def getAllUsers: IO[List[User]] diff --git a/modules/core/src/main/scala/vinyldns/core/domain/record/ChangeSet.scala b/modules/core/src/main/scala/vinyldns/core/domain/record/ChangeSet.scala index 695c3600a..fa8b04767 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/record/ChangeSet.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/record/ChangeSet.scala @@ -46,7 +46,8 @@ case class ChangeSet( createdTimestamp: Long, processingTimestamp: Long, changes: Seq[RecordSetChange], - status: ChangeSetStatus) { + status: ChangeSetStatus +) { def complete(change: RecordSetChange): ChangeSet = { val updatedChanges = this.changes.filterNot(_.id == change.id) :+ change diff --git a/modules/core/src/main/scala/vinyldns/core/domain/record/ListRecordSetChangesResults.scala b/modules/core/src/main/scala/vinyldns/core/domain/record/ListRecordSetChangesResults.scala index c93082988..b5d1141d5 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/record/ListRecordSetChangesResults.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/record/ListRecordSetChangesResults.scala @@ -20,4 +20,5 @@ case class ListRecordSetChangesResults( items: List[RecordSetChange] = List[RecordSetChange](), nextId: Option[String] = None, startFrom: Option[String] = None, - maxItems: Int = 100) + maxItems: Int = 100 +) diff --git a/modules/core/src/main/scala/vinyldns/core/domain/record/ListRecordSetResults.scala b/modules/core/src/main/scala/vinyldns/core/domain/record/ListRecordSetResults.scala index 46e076cc2..09a8373de 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/record/ListRecordSetResults.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/record/ListRecordSetResults.scala @@ -21,4 +21,5 @@ case class ListRecordSetResults( nextId: Option[String] = None, startFrom: Option[String] = None, maxItems: Option[Int] = None, - recordNameFilter: Option[String] = None) + recordNameFilter: Option[String] = None +) diff --git a/modules/core/src/main/scala/vinyldns/core/domain/record/RecordChangeRepository.scala b/modules/core/src/main/scala/vinyldns/core/domain/record/RecordChangeRepository.scala index 14436b722..c7e47dfe3 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/record/RecordChangeRepository.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/record/RecordChangeRepository.scala @@ -26,7 +26,8 @@ trait RecordChangeRepository extends Repository { def listRecordSetChanges( zoneId: String, startFrom: Option[String] = None, - maxItems: Int = 100): IO[ListRecordSetChangesResults] + maxItems: Int = 100 + ): IO[ListRecordSetChangesResults] def getRecordSetChange(zoneId: String, changeId: String): IO[Option[RecordSetChange]] } diff --git a/modules/core/src/main/scala/vinyldns/core/domain/record/RecordData.scala b/modules/core/src/main/scala/vinyldns/core/domain/record/RecordData.scala index 8dde5d1ef..52198b1f6 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/record/RecordData.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/record/RecordData.scala @@ -60,8 +60,8 @@ final case class SOAData( refresh: Long, retry: Long, expire: Long, - minimum: Long) - extends RecordData + minimum: Long +) extends RecordData final case class SPFData(text: String) extends RecordData @@ -79,8 +79,8 @@ final case class NAPTRData( flags: String, service: String, regexp: String, - replacement: String) - extends RecordData + replacement: String +) extends RecordData object NAPTRData { def apply( @@ -89,7 +89,8 @@ object NAPTRData { flags: String, service: String, regexp: String, - replacement: String): NAPTRData = + replacement: String + ): NAPTRData = new NAPTRData(order, preference, flags, service, regexp, ensureTrailingDot(replacement)) } @@ -157,5 +158,5 @@ final case class DSData( keyTag: Integer, // footprint in DNSJava algorithm: DnsSecAlgorithm, digestType: DigestType, //digestid in DNSJava - digest: ByteVector) - extends RecordData + digest: ByteVector +) extends RecordData diff --git a/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSet.scala b/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSet.scala index ea56f074a..007248bcb 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSet.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSet.scala @@ -44,7 +44,8 @@ case class RecordSet( records: List[RecordData] = List.empty, id: String = UUID.randomUUID().toString, account: String = "system", - ownerGroupId: Option[String] = None) { + ownerGroupId: Option[String] = None +) { def isPending: Boolean = (status == RecordSetStatus.Pending diff --git a/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSetChange.scala b/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSetChange.scala index e0884bf6b..afe9a63b2 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSetChange.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSetChange.scala @@ -45,8 +45,8 @@ case class RecordSetChange( systemMessage: Option[String] = None, updates: Option[RecordSet] = None, id: String = UUID.randomUUID().toString, - singleBatchChangeIds: List[String] = List()) - extends ZoneCommand + singleBatchChangeIds: List[String] = List() +) extends ZoneCommand with ZoneCommandResult { val zoneId: String = zone.id @@ -56,7 +56,8 @@ case class RecordSetChange( status = RecordSetChangeStatus.Complete, systemMessage = None, recordSet = recordSet - .copy(status = RecordSetStatus.Active, updated = Some(DateTime.now))) + .copy(status = RecordSetStatus.Active, updated = Some(DateTime.now)) + ) def failed(message: String): RecordSetChange = failed(Some(message)) @@ -65,7 +66,8 @@ case class RecordSetChange( status = RecordSetChangeStatus.Failed, systemMessage = message, recordSet = recordSet - .copy(status = RecordSetStatus.Inactive, updated = Some(DateTime.now))) + .copy(status = RecordSetStatus.Inactive, updated = Some(DateTime.now)) + ) def isDone: Boolean = RecordSetChangeStatus.isDone(status) diff --git a/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSetRepository.scala b/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSetRepository.scala index 4a8cc4d82..36530b8b0 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSetRepository.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/record/RecordSetRepository.scala @@ -28,7 +28,8 @@ trait RecordSetRepository extends Repository { zoneId: String, startFrom: Option[String], maxItems: Option[Int], - recordNameFilter: Option[String]): IO[ListRecordSetResults] + recordNameFilter: Option[String] + ): IO[ListRecordSetResults] def getRecordSets(zoneId: String, name: String, typ: RecordType): IO[List[RecordSet]] diff --git a/modules/core/src/main/scala/vinyldns/core/domain/zone/ACLRule.scala b/modules/core/src/main/scala/vinyldns/core/domain/zone/ACLRule.scala index f2a115f24..de9b7dfc8 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/zone/ACLRule.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/zone/ACLRule.scala @@ -43,5 +43,6 @@ object ACLRule { aclRuleInfo.userId, aclRuleInfo.groupId, aclRuleInfo.recordMask, - aclRuleInfo.recordTypes) + aclRuleInfo.recordTypes + ) } diff --git a/modules/core/src/main/scala/vinyldns/core/domain/zone/ListZoneChangesResults.scala b/modules/core/src/main/scala/vinyldns/core/domain/zone/ListZoneChangesResults.scala index a89145175..5011a79d6 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/zone/ListZoneChangesResults.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/zone/ListZoneChangesResults.scala @@ -20,4 +20,5 @@ case class ListZoneChangesResults( items: List[ZoneChange] = List[ZoneChange](), nextId: Option[String] = None, startFrom: Option[String] = None, - maxItems: Int = 100) + maxItems: Int = 100 +) diff --git a/modules/core/src/main/scala/vinyldns/core/domain/zone/ListZonesResults.scala b/modules/core/src/main/scala/vinyldns/core/domain/zone/ListZonesResults.scala index 24e713bda..8d03b0073 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/zone/ListZonesResults.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/zone/ListZonesResults.scala @@ -22,4 +22,5 @@ case class ListZonesResults( startFrom: Option[String] = None, maxItems: Int = 100, ignoreAccess: Boolean = false, - zonesFilter: Option[String] = None) + zonesFilter: Option[String] = None +) diff --git a/modules/core/src/main/scala/vinyldns/core/domain/zone/Zone.scala b/modules/core/src/main/scala/vinyldns/core/domain/zone/Zone.scala index dcb3f27c5..212f8bb44 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/zone/Zone.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/zone/Zone.scala @@ -43,7 +43,8 @@ final case class Zone( adminGroupId: String = "system", latestSync: Option[DateTime] = None, isTest: Boolean = false, - backendId: Option[String] = None) { + backendId: Option[String] = None +) { val isIPv4: Boolean = name.endsWith("in-addr.arpa.") val isIPv6: Boolean = name.endsWith("ip6.arpa.") val isReverse: Boolean = isIPv4 || isIPv6 @@ -103,7 +104,8 @@ object Zone { shared = shared, acl = acl, adminGroupId = adminGroupId, - backendId = backendId) + backendId = backendId + ) } } @@ -115,7 +117,8 @@ final case class CreateZoneInput( shared: Boolean = false, acl: ZoneACL = ZoneACL(), adminGroupId: String, - backendId: Option[String] = None) + backendId: Option[String] = None +) final case class UpdateZoneInput( id: String, @@ -126,7 +129,8 @@ final case class UpdateZoneInput( shared: Boolean = false, acl: ZoneACL = ZoneACL(), adminGroupId: String, - backendId: Option[String] = None) + backendId: Option[String] = None +) final case class ZoneACL(rules: Set[ACLRule] = Set.empty) { @@ -147,7 +151,8 @@ case class ZoneConnection(name: String, keyName: String, key: String, primarySer final case class DnsBackend( id: String, zoneConnection: ZoneConnection, - transferConnection: ZoneConnection) { + transferConnection: ZoneConnection +) { def encrypted(crypto: CryptoAlgebra): DnsBackend = copy( zoneConnection = zoneConnection.encrypted(crypto), @@ -158,4 +163,5 @@ final case class DnsBackend( final case class ConfiguredDnsConnections( defaultZoneConnection: ZoneConnection, defaultTransferConnection: ZoneConnection, - dnsBackends: List[DnsBackend]) + dnsBackends: List[DnsBackend] +) diff --git a/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneChange.scala b/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneChange.scala index b1f0195b8..4c6533ba1 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneChange.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneChange.scala @@ -40,8 +40,8 @@ case class ZoneChange( status: ZoneChangeStatus = ZoneChangeStatus.Pending, created: DateTime = DateTime.now, systemMessage: Option[String] = None, - id: String = UUID.randomUUID().toString) - extends ZoneCommand + id: String = UUID.randomUUID().toString +) extends ZoneCommand with ZoneCommandResult { val zoneId: String = zone.id diff --git a/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneChangeRepository.scala b/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneChangeRepository.scala index 8a08fab71..57a44e217 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneChangeRepository.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneChangeRepository.scala @@ -26,5 +26,6 @@ trait ZoneChangeRepository extends Repository { def listZoneChanges( zoneId: String, startFrom: Option[String] = None, - maxItems: Int = 100): IO[ListZoneChangesResults] + maxItems: Int = 100 + ): IO[ListZoneChangesResults] } diff --git a/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneRepository.scala b/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneRepository.scala index f71821c1e..f5f3fec18 100644 --- a/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneRepository.scala +++ b/modules/core/src/main/scala/vinyldns/core/domain/zone/ZoneRepository.scala @@ -38,7 +38,8 @@ trait ZoneRepository extends Repository { zoneNameFilter: Option[String] = None, startFrom: Option[String] = None, maxItems: Int = 100, - ignoreAccess: Boolean = false): IO[ListZonesResults] + ignoreAccess: Boolean = false + ): IO[ListZonesResults] def getZonesByAdminGroupId(adminGroupId: String): IO[List[Zone]] diff --git a/modules/core/src/main/scala/vinyldns/core/notifier/NotifierLoader.scala b/modules/core/src/main/scala/vinyldns/core/notifier/NotifierLoader.scala index e460d1758..78a65cc4a 100644 --- a/modules/core/src/main/scala/vinyldns/core/notifier/NotifierLoader.scala +++ b/modules/core/src/main/scala/vinyldns/core/notifier/NotifierLoader.scala @@ -23,7 +23,8 @@ import cats.effect.ContextShift object NotifierLoader { def loadAll(configs: List[NotifierConfig], userRepository: UserRepository)( - implicit cs: ContextShift[IO]): IO[AllNotifiers] = + implicit cs: ContextShift[IO] + ): IO[AllNotifiers] = for { notifiers <- configs.parTraverse(load(_, userRepository)) } yield AllNotifiers(notifiers) @@ -35,7 +36,8 @@ object NotifierLoader { .forName(config.className) .getDeclaredConstructor() .newInstance() - .asInstanceOf[NotifierProvider]) + .asInstanceOf[NotifierProvider] + ) notifier <- provider.load(config, userRepository) } yield notifier diff --git a/modules/core/src/main/scala/vinyldns/core/protobuf/BatchChangeProtobufConversions.scala b/modules/core/src/main/scala/vinyldns/core/protobuf/BatchChangeProtobufConversions.scala index 0f13b4ef6..f86882f7a 100644 --- a/modules/core/src/main/scala/vinyldns/core/protobuf/BatchChangeProtobufConversions.scala +++ b/modules/core/src/main/scala/vinyldns/core/protobuf/BatchChangeProtobufConversions.scala @@ -45,7 +45,8 @@ trait BatchChangeProtobufConversions extends ProtobufConversions { def fromPB( changeType: SingleChangeType, errors: List[SingleChangeError], - change: VinylDNSProto.SingleChange): Either[Throwable, SingleChange] = + change: VinylDNSProto.SingleChange + ): Either[Throwable, SingleChange] = Either.catchNonFatal { changeType match { case SingleAddType => @@ -94,7 +95,8 @@ trait BatchChangeProtobufConversions extends ProtobufConversions { } def fromPB( - errors: List[VinylDNSProto.SingleChangeError]): Either[Throwable, List[SingleChangeError]] = + errors: List[VinylDNSProto.SingleChangeError] + ): Either[Throwable, List[SingleChangeError]] = Either.catchNonFatal { errors.map { e => val errorType = DomainValidationErrorType.withName(e.getErrorType) @@ -148,7 +150,8 @@ trait BatchChangeProtobufConversions extends ProtobufConversions { def addCommonSingleChangeFields( sc: VinylDNSProto.SingleChange.Builder, - change: SingleChange): Unit = { + change: SingleChange + ): Unit = { sc.setId(change.id) .setInputName(change.inputName) .setRecordType(change.typ.toString) diff --git a/modules/core/src/main/scala/vinyldns/core/protobuf/ProtobufConversions.scala b/modules/core/src/main/scala/vinyldns/core/protobuf/ProtobufConversions.scala index fe24d6f60..03e84f76d 100644 --- a/modules/core/src/main/scala/vinyldns/core/protobuf/ProtobufConversions.scala +++ b/modules/core/src/main/scala/vinyldns/core/protobuf/ProtobufConversions.scala @@ -56,7 +56,8 @@ trait ProtobufConversions { val status = Try(RecordSetChangeStatus.withName(chg.getStatus)) .getOrElse { protoLogger.error( - s"Encountered unexpected status in RecordSetChange.fromPB: ${chg.getStatus}") + s"Encountered unexpected status in RecordSetChange.fromPB: ${chg.getStatus}" + ) // deprecated Submitted, Validated, Applied, Verified -- setting all to "Pending" RecordSetChangeStatus.Pending } @@ -181,7 +182,8 @@ trait ProtobufConversions { data.getKeyTag, DnsSecAlgorithm(data.getAlgorithm), DigestType(data.getDigestType), - ByteVector.apply(data.getDigest.asReadOnlyByteBuffer())) + ByteVector.apply(data.getDigest.asReadOnlyByteBuffer()) + ) def fromPB(data: VinylDNSProto.MXData): MXData = MXData(data.getPreference, data.getExchange) @@ -197,7 +199,8 @@ trait ProtobufConversions { data.getRefresh, data.getRetry, data.getExpire, - data.getMinimum) + data.getMinimum + ) def fromPB(data: VinylDNSProto.SPFData): SPFData = SPFData(data.getText) @@ -211,7 +214,8 @@ trait ProtobufConversions { data.getFlags, data.getService, data.getRegexp, - data.getReplacement) + data.getReplacement + ) def fromPB(data: VinylDNSProto.SSHFPData): SSHFPData = SSHFPData(data.getAlgorithm, data.getTyp, data.getFingerPrint) diff --git a/modules/core/src/main/scala/vinyldns/core/queue/MessageQueue.scala b/modules/core/src/main/scala/vinyldns/core/queue/MessageQueue.scala index 72cd4ca9f..b5138e88f 100644 --- a/modules/core/src/main/scala/vinyldns/core/queue/MessageQueue.scala +++ b/modules/core/src/main/scala/vinyldns/core/queue/MessageQueue.scala @@ -33,7 +33,8 @@ trait CommandMessage { // need to encode the possibility of one or more commands failing to send final case class SendBatchResult[A <: ZoneCommand]( successes: List[A], - failures: List[(Exception, A)]) + failures: List[(Exception, A)] +) // Using types here to ensure we cannot pass in a negative or 0 count final case class MessageCount private (value: Int) diff --git a/modules/core/src/main/scala/vinyldns/core/queue/MessageQueueConfig.scala b/modules/core/src/main/scala/vinyldns/core/queue/MessageQueueConfig.scala index 79a2728bb..b1f8ba90d 100644 --- a/modules/core/src/main/scala/vinyldns/core/queue/MessageQueueConfig.scala +++ b/modules/core/src/main/scala/vinyldns/core/queue/MessageQueueConfig.scala @@ -24,4 +24,5 @@ final case class MessageQueueConfig( className: String, pollingInterval: FiniteDuration, messagesPerPoll: Int, - settings: Config) + settings: Config +) diff --git a/modules/core/src/main/scala/vinyldns/core/queue/MessageQueueLoader.scala b/modules/core/src/main/scala/vinyldns/core/queue/MessageQueueLoader.scala index eb5b429b6..8dcfd15d6 100644 --- a/modules/core/src/main/scala/vinyldns/core/queue/MessageQueueLoader.scala +++ b/modules/core/src/main/scala/vinyldns/core/queue/MessageQueueLoader.scala @@ -31,7 +31,8 @@ object MessageQueueLoader { .forName(config.className) .getDeclaredConstructor() .newInstance() - .asInstanceOf[MessageQueueProvider]) + .asInstanceOf[MessageQueueProvider] + ) queue <- provider.load(config) } yield queue } diff --git a/modules/core/src/main/scala/vinyldns/core/repository/DataStore.scala b/modules/core/src/main/scala/vinyldns/core/repository/DataStore.scala index e4a86f19d..cbeb1b9d8 100644 --- a/modules/core/src/main/scala/vinyldns/core/repository/DataStore.scala +++ b/modules/core/src/main/scala/vinyldns/core/repository/DataStore.scala @@ -30,7 +30,8 @@ import scala.reflect.ClassTag class LoadedDataStore( val dataStore: DataStore, val shutdownHook: IO[Unit], - val healthCheck: HealthCheck) + val healthCheck: HealthCheck +) object DataStore { def apply( diff --git a/modules/core/src/main/scala/vinyldns/core/repository/DataStoreConfig.scala b/modules/core/src/main/scala/vinyldns/core/repository/DataStoreConfig.scala index 5fae58a97..44a87deb7 100644 --- a/modules/core/src/main/scala/vinyldns/core/repository/DataStoreConfig.scala +++ b/modules/core/src/main/scala/vinyldns/core/repository/DataStoreConfig.scala @@ -22,7 +22,8 @@ import vinyldns.core.repository.RepositoryName.RepositoryName final case class DataStoreConfig( className: String, settings: Config, - repositories: RepositoriesConfig) + repositories: RepositoriesConfig +) final case class RepositoriesConfig( user: Option[Config], @@ -35,7 +36,8 @@ final case class RepositoriesConfig( zone: Option[Config], batchChange: Option[Config], userChange: Option[Config], - task: Option[Config]) { + task: Option[Config] +) { lazy val configMap: Map[RepositoryName, Config] = List( user.map(RepositoryName.user -> _), diff --git a/modules/core/src/main/scala/vinyldns/core/repository/DataStoreLoader.scala b/modules/core/src/main/scala/vinyldns/core/repository/DataStoreLoader.scala index 163a02207..fa267fdf6 100644 --- a/modules/core/src/main/scala/vinyldns/core/repository/DataStoreLoader.scala +++ b/modules/core/src/main/scala/vinyldns/core/repository/DataStoreLoader.scala @@ -32,14 +32,16 @@ object DataStoreLoader { val dataStoreConfig: DataStoreConfig, val dataStore: DataStore, val shutdownHook: IO[Unit], - val healthCheck: HealthCheck) { + val healthCheck: HealthCheck + ) { val accessorTuple: (DataStoreConfig, DataStore) = (dataStoreConfig, dataStore) } class DataLoaderResponse[A]( val accessor: A, shutdownHook: List[IO[Unit]], - val healthChecks: List[HealthCheck]) { + val healthChecks: List[HealthCheck] + ) { def shutdown(): Unit = shutdownHook.parSequence.unsafeRunSync() } @@ -49,36 +51,38 @@ object DataStoreLoader { def loadAll[A <: DataAccessor]( configs: List[DataStoreConfig], crypto: CryptoAlgebra, - dataAccessorProvider: DataAccessorProvider[A]): IO[DataLoaderResponse[A]] = + dataAccessorProvider: DataAccessorProvider[A] + ): IO[DataLoaderResponse[A]] = for { activeConfigs <- IO.fromEither(getValidatedConfigs(configs, dataAccessorProvider.repoNames)) dataStores <- activeConfigs.map(load(_, crypto)).parSequence accessor <- IO.fromEither(generateAccessor(dataStores, dataAccessorProvider)) - } yield - new DataLoaderResponse[A]( - accessor, - dataStores.map(_.shutdownHook), - dataStores.map(_.healthCheck) - ) + } yield new DataLoaderResponse[A]( + accessor, + dataStores.map(_.shutdownHook), + dataStores.map(_.healthCheck) + ) def load(config: DataStoreConfig, crypto: CryptoAlgebra): IO[DataStoreInfo] = for { _ <- IO( - logger.error( - s"Attempting to load repos ${config.repositories.keys} from ${config.className}")) + logger + .error(s"Attempting to load repos ${config.repositories.keys} from ${config.className}") + ) provider <- IO( Class .forName(config.className) .getDeclaredConstructor() .newInstance() - .asInstanceOf[DataStoreProvider]) + .asInstanceOf[DataStoreProvider] + ) loadResponse <- provider.load(config, crypto) - } yield - new DataStoreInfo( - config, - loadResponse.dataStore, - loadResponse.shutdownHook, - loadResponse.healthCheck) + } yield new DataStoreInfo( + config, + loadResponse.dataStore, + loadResponse.shutdownHook, + loadResponse.healthCheck + ) /* * Validates that there's exactly one repo defined across all datastore configs. Returns only @@ -86,7 +90,8 @@ object DataStoreLoader { */ def getValidatedConfigs( configs: List[DataStoreConfig], - repoNames: List[RepositoryName]): Either[DataStoreStartupError, List[DataStoreConfig]] = { + repoNames: List[RepositoryName] + ): Either[DataStoreStartupError, List[DataStoreConfig]] = { val repoConfigs = configs.map(_.repositories) @@ -113,7 +118,8 @@ object DataStoreLoader { def getRepoOf[A <: Repository: ClassTag]( responses: List[(DataStoreConfig, DataStore)], - repoName: RepositoryName): ValidatedNel[String, A] = { + repoName: RepositoryName + ): ValidatedNel[String, A] = { val matched = responses.find { case (c, _) => c.repositories.hasKey(repoName) @@ -138,7 +144,8 @@ object DataStoreLoader { def generateAccessor[A <: DataAccessor]( responses: List[DataStoreInfo], - dataAccessorProvider: DataAccessorProvider[A]): Either[DataStoreStartupError, A] = { + dataAccessorProvider: DataAccessorProvider[A] + ): Either[DataStoreStartupError, A] = { val accessor = dataAccessorProvider .create(responses.map(_.accessorTuple)) accessor.toEither.leftMap(errors => DataStoreStartupError(errors.toList.mkString(", "))) diff --git a/modules/core/src/main/scala/vinyldns/core/repository/Repository.scala b/modules/core/src/main/scala/vinyldns/core/repository/Repository.scala index 4d73c95d3..96abc772b 100644 --- a/modules/core/src/main/scala/vinyldns/core/repository/Repository.scala +++ b/modules/core/src/main/scala/vinyldns/core/repository/Repository.scala @@ -21,6 +21,6 @@ trait Repository object RepositoryName extends Enumeration { type RepositoryName = Value val user, group, membership, groupChange, recordSet, recordChange, zoneChange, zone, batchChange, - userChange, task = + userChange, task = Value } diff --git a/modules/core/src/main/scala/vinyldns/core/task/TaskRepository.scala b/modules/core/src/main/scala/vinyldns/core/task/TaskRepository.scala index a65c8fdc0..c13c389b2 100644 --- a/modules/core/src/main/scala/vinyldns/core/task/TaskRepository.scala +++ b/modules/core/src/main/scala/vinyldns/core/task/TaskRepository.scala @@ -26,7 +26,8 @@ trait TaskRepository extends Repository { def claimTask( name: String, taskTimeout: FiniteDuration, - pollingInterval: FiniteDuration): IO[Boolean] + pollingInterval: FiniteDuration + ): IO[Boolean] def releaseTask(name: String): IO[Unit] diff --git a/modules/core/src/main/scala/vinyldns/core/task/TaskScheduler.scala b/modules/core/src/main/scala/vinyldns/core/task/TaskScheduler.scala index 508cbfbb3..32f8c5cad 100644 --- a/modules/core/src/main/scala/vinyldns/core/task/TaskScheduler.scala +++ b/modules/core/src/main/scala/vinyldns/core/task/TaskScheduler.scala @@ -58,9 +58,10 @@ object TaskScheduler extends Monitored { * @return a Stream that when run will awake on the interval defined on the Task provided, and * run the task.run() */ - def schedule(task: Task, taskRepository: TaskRepository)( - implicit t: Timer[IO], - cs: ContextShift[IO]): Stream[IO, Unit] = { + def schedule( + task: Task, + taskRepository: TaskRepository + )(implicit t: Timer[IO], cs: ContextShift[IO]): Stream[IO, Unit] = { def claimTask(): IO[Option[Task]] = taskRepository.claimTask(task.name, task.timeout, task.runEvery).map { @@ -79,7 +80,8 @@ object TaskScheduler extends Monitored { t => taskRepository .releaseTask(t.name) - .as(logger.info(s"""Released task; taskName="${task.name}" """))) + .as(logger.info(s"""Released task; taskName="${task.name}" """)) + ) .getOrElse(IO.unit) } diff --git a/modules/core/src/test/scala/vinyldns/core/TestMembershipData.scala b/modules/core/src/test/scala/vinyldns/core/TestMembershipData.scala index 7cca5b8e4..36ba54ec0 100644 --- a/modules/core/src/test/scala/vinyldns/core/TestMembershipData.scala +++ b/modules/core/src/test/scala/vinyldns/core/TestMembershipData.scala @@ -57,14 +57,16 @@ object TestMembershipData { Some("a test group"), memberIds = Set(okUser.id), adminUserIds = Set(okUser.id), - created = DateTime.now.secondOfDay().roundFloorCopy()) + created = DateTime.now.secondOfDay().roundFloorCopy() + ) val dummyGroup: Group = Group( "dummy", "test@test.com", Some("has the dummy users"), adminUserIds = listOfDummyUsers.map(_.id).toSet, - memberIds = listOfDummyUsers.map(_.id).toSet) + memberIds = listOfDummyUsers.map(_.id).toSet + ) val twoUserGroup: Group = Group( "twoUsers", @@ -86,14 +88,16 @@ object TestMembershipData { "dummy", "test@test.com", Some("has a dummy user"), - memberIds = Set(listOfDummyUsers(0).id)) + memberIds = Set(listOfDummyUsers(0).id) + ) val listOfDummyGroups: List[Group] = List.range(0, 200).map { i => Group( name = "name-dummy%03d".format(i), id = "dummy%03d".format(i), email = "test@test.com", - created = DateTime.now.secondOfDay().roundFloorCopy()) + created = DateTime.now.secondOfDay().roundFloorCopy() + ) } val xyzGroup: Group = Group("xyz", "xyz", id = "xyz", memberIds = Set("xyz")) @@ -126,18 +130,21 @@ object TestMembershipData { okGroup, GroupChangeType.Create, okUser.id, - created = DateTime.now.secondOfDay().roundFloorCopy()) + created = DateTime.now.secondOfDay().roundFloorCopy() + ) val okGroupChangeUpdate: GroupChange = GroupChange( okGroup, GroupChangeType.Update, okUser.id, Some(okGroup), - created = DateTime.now.secondOfDay().roundFloorCopy()) + created = DateTime.now.secondOfDay().roundFloorCopy() + ) val okGroupChangeDelete: GroupChange = GroupChange( okGroup, GroupChangeType.Delete, okUser.id, - created = DateTime.now.secondOfDay().roundFloorCopy()) + created = DateTime.now.secondOfDay().roundFloorCopy() + ) // changes added in reverse order val now: DateTime = DateTime.now().secondOfDay().roundFloorCopy() @@ -147,6 +154,7 @@ object TestMembershipData { GroupChangeType.Update, dummyUser.id, created = now.minusSeconds(i), - id = s"$i") + id = s"$i" + ) } } diff --git a/modules/core/src/test/scala/vinyldns/core/TestRecordSetData.scala b/modules/core/src/test/scala/vinyldns/core/TestRecordSetData.scala index 00acd5fe1..17fe13f4b 100644 --- a/modules/core/src/test/scala/vinyldns/core/TestRecordSetData.scala +++ b/modules/core/src/test/scala/vinyldns/core/TestRecordSetData.scala @@ -36,7 +36,8 @@ object TestRecordSetData { RecordSetStatus.Active, DateTime.now, None, - List(AData("10.1.1.1"))) + List(AData("10.1.1.1")) + ) val abcRecord: RecordSet = RecordSet( abcZone.id, @@ -46,7 +47,8 @@ object TestRecordSetData { RecordSetStatus.Pending, DateTime.now, None, - List(AAAAData("1:2:3:4:5:6:7:8"))) + List(AAAAData("1:2:3:4:5:6:7:8")) + ) val aaaa: RecordSet = RecordSet( okZone.id, @@ -56,7 +58,8 @@ object TestRecordSetData { RecordSetStatus.Pending, DateTime.now, None, - List(AAAAData("1:2:3:4:5:6:7:8"))) + List(AAAAData("1:2:3:4:5:6:7:8")) + ) val aaaaOrigin: RecordSet = RecordSet( okZone.id, @@ -66,7 +69,8 @@ object TestRecordSetData { RecordSetStatus.Pending, DateTime.now, None, - List(AAAAData("1:2:3:4:5:6:7:8"))) + List(AAAAData("1:2:3:4:5:6:7:8")) + ) val cname: RecordSet = RecordSet( okZone.id, @@ -76,7 +80,8 @@ object TestRecordSetData { RecordSetStatus.Pending, DateTime.now, None, - List(CNAMEData("cname"))) + List(CNAMEData("cname")) + ) val ptrIp4: RecordSet = RecordSet( zoneIp4.id, @@ -86,7 +91,8 @@ object TestRecordSetData { RecordSetStatus.Active, DateTime.now, None, - List(PTRData("ptr"))) + List(PTRData("ptr")) + ) val ptrIp6: RecordSet = RecordSet( zoneIp6.id, @@ -96,7 +102,8 @@ object TestRecordSetData { RecordSetStatus.Active, DateTime.now, None, - List(PTRData("ptr"))) + List(PTRData("ptr")) + ) val srv: RecordSet = RecordSet( okZone.id, @@ -106,7 +113,8 @@ object TestRecordSetData { RecordSetStatus.Active, DateTime.now, None, - List(SRVData(1, 2, 3, "target"))) + List(SRVData(1, 2, 3, "target")) + ) val naptr: RecordSet = RecordSet( okZone.id, @@ -116,7 +124,8 @@ object TestRecordSetData { RecordSetStatus.Active, DateTime.now, None, - List(NAPTRData(1, 2, "S", "E2U+sip", "", "target"))) + List(NAPTRData(1, 2, "S", "E2U+sip", "", "target")) + ) val mx: RecordSet = RecordSet( okZone.id, @@ -126,7 +135,8 @@ object TestRecordSetData { RecordSetStatus.Pending, DateTime.now, None, - List(MXData(3, "mx"))) + List(MXData(3, "mx")) + ) val ns: RecordSet = RecordSet( okZone.id, @@ -136,7 +146,8 @@ object TestRecordSetData { RecordSetStatus.Active, DateTime.now, None, - records = List(NSData("ns1.test.com"), NSData("ns2.test.com"))) + records = List(NSData("ns1.test.com"), NSData("ns2.test.com")) + ) val txt: RecordSet = RecordSet( okZone.id, @@ -146,7 +157,8 @@ object TestRecordSetData { RecordSetStatus.Pending, DateTime.now, None, - List(TXTData("txt"))) + List(TXTData("txt")) + ) // example at https://tools.ietf.org/html/rfc4034#page-18 val dSDataSha1 = @@ -154,7 +166,8 @@ object TestRecordSetData { 60485, DnsSecAlgorithm.RSASHA1, DigestType.SHA1, - ByteVector.fromValidHex("2BB183AF5F22588179A53B0A98631FAD1A292118")) + ByteVector.fromValidHex("2BB183AF5F22588179A53B0A98631FAD1A292118") + ) // example at https://tools.ietf.org/html/rfc4509#page-3 val dSDataSha256 = @@ -162,7 +175,8 @@ object TestRecordSetData { 60485, DnsSecAlgorithm.RSASHA1, DigestType.SHA256, - ByteVector.fromValidHex("D4B7D520E7BB5F0F67674A0CCEB1E3E0614B93C4F9E99B8383F6A1E4469DA50A")) + ByteVector.fromValidHex("D4B7D520E7BB5F0F67674A0CCEB1E3E0614B93C4F9E99B8383F6A1E4469DA50A") + ) val ds: RecordSet = RecordSet( okZone.id, @@ -171,7 +185,8 @@ object TestRecordSetData { 200, RecordSetStatus.Pending, DateTime.now(), - records = List(dSDataSha1, dSDataSha256)) + records = List(dSDataSha1, dSDataSha256) + ) val sharedZoneRecord: RecordSet = RecordSet( sharedZone.id, @@ -182,7 +197,8 @@ object TestRecordSetData { DateTime.now, None, List(AAAAData("1:2:3:4:5:6:7:8")), - ownerGroupId = Some(okGroup.id)) + ownerGroupId = Some(okGroup.id) + ) val sharedZoneRecordNoOwnerGroup: RecordSet = sharedZoneRecord.copy(name = "records", ownerGroupId = None) @@ -202,14 +218,16 @@ object TestRecordSetData { RecordSetStatus.Pending, DateTime.now, None, - List(MXData(3, "mx"))) + List(MXData(3, "mx")) + ) /* RECORDSET CHANGES */ def makeTestAddChange( recordSet: RecordSet, zone: Zone = okZone, - userId: String = okUser.id): RecordSetChange = + userId: String = okUser.id + ): RecordSetChange = RecordSetChange( zone, recordSet.copy( @@ -226,13 +244,15 @@ object TestRecordSetData { oldRecordSet: RecordSet, newRecordSet: RecordSet, zone: Zone = okZone, - userId: String = okUser.id): RecordSetChange = + userId: String = okUser.id + ): RecordSetChange = RecordSetChange( zone, newRecordSet.copy( id = oldRecordSet.id, status = RecordSetStatus.PendingUpdate, - updated = Some(DateTime.now)), + updated = Some(DateTime.now) + ), userId, RecordSetChangeType.Update, RecordSetChangeStatus.Pending, @@ -243,7 +263,8 @@ object TestRecordSetData { oldRecordSet: RecordSet, newRecordSet: RecordSet, zone: Zone = okZone, - userId: String = okUser.id): RecordSetChange = + userId: String = okUser.id + ): RecordSetChange = RecordSetChange( zone, newRecordSet @@ -257,7 +278,8 @@ object TestRecordSetData { def makePendingTestDeleteChange( recordSet: RecordSet, zone: Zone = okZone, - userId: String = okUser.id): RecordSetChange = + userId: String = okUser.id + ): RecordSetChange = RecordSetChange( zone, recordSet.copy( diff --git a/modules/core/src/test/scala/vinyldns/core/TestZoneData.scala b/modules/core/src/test/scala/vinyldns/core/TestZoneData.scala index 46512e5ff..751d44359 100644 --- a/modules/core/src/test/scala/vinyldns/core/TestZoneData.scala +++ b/modules/core/src/test/scala/vinyldns/core/TestZoneData.scala @@ -24,14 +24,16 @@ object TestZoneData { /* ZONE CONNECTIONS */ val testConnection: Option[ZoneConnection] = Some( - ZoneConnection("vinyldns.", "vinyldns.", "nzisn+4G2ldMn0q1CV3vsg==", "10.1.1.1")) + ZoneConnection("vinyldns.", "vinyldns.", "nzisn+4G2ldMn0q1CV3vsg==", "10.1.1.1") + ) /* ZONES */ val okZone: Zone = Zone( "ok.zone.recordsets.", "test@test.com", adminGroupId = okGroup.id, - connection = testConnection) + connection = testConnection + ) val abcZone: Zone = Zone("abc.zone.recordsets.", "test@test.com", adminGroupId = abcGroup.id) val xyzZone: Zone = Zone("xyz.", "abc@xyz.com", adminGroupId = xyzGroup.id) val zoneIp4: Zone = Zone("0.162.198.in-addr.arpa.", "test@test.com", adminGroupId = abcGroup.id) @@ -43,13 +45,15 @@ object TestZoneData { "test@test.com", adminGroupId = okGroup.id, status = ZoneStatus.Active, - connection = testConnection) + connection = testConnection + ) val zoneDeleted: Zone = Zone( "some.deleted.zone.", "test@test.com", status = ZoneStatus.Deleted, - connection = testConnection) + connection = testConnection + ) val zoneNotAuthorized: Zone = Zone("not.auth.zone.", "test@test.com", adminGroupId = "no-id") @@ -76,7 +80,8 @@ object TestZoneData { "ok", ZoneChangeType.Create, ZoneChangeStatus.Complete, - created = DateTime.now.minus(1000)) + created = DateTime.now.minus(1000) + ) val zoneUpdate: ZoneChange = zoneChangePending.copy(status = ZoneChangeStatus.Complete) diff --git a/modules/core/src/test/scala/vinyldns/core/domain/batch/BatchChangeSpec.scala b/modules/core/src/test/scala/vinyldns/core/domain/batch/BatchChangeSpec.scala index eb9a1ad31..2028a6192 100644 --- a/modules/core/src/test/scala/vinyldns/core/domain/batch/BatchChangeSpec.scala +++ b/modules/core/src/test/scala/vinyldns/core/domain/batch/BatchChangeSpec.scala @@ -32,7 +32,8 @@ class BatchChangeSpec extends WordSpec with Matchers { SingleChangeStatus.Pending, None, None, - None) + None + ) private val failedChange = pendingChange.copy(status = SingleChangeStatus.Failed) private val completeChange = pendingChange.copy(status = SingleChangeStatus.Complete) @@ -42,7 +43,8 @@ class BatchChangeSpec extends WordSpec with Matchers { None, DateTime.now, List(pendingChange, failedChange, completeChange), - approvalStatus = BatchChangeApprovalStatus.AutoApproved) + approvalStatus = BatchChangeApprovalStatus.AutoApproved + ) "BatchChange" should { "calculate Pending status based on SingleChanges" in { @@ -80,7 +82,8 @@ class BatchChangeSpec extends WordSpec with Matchers { batchChangeBase .copy( approvalStatus = BatchChangeApprovalStatus.PendingReview, - scheduledTime = Some(DateTime.now)) + scheduledTime = Some(DateTime.now) + ) .status shouldBe BatchChangeStatus.Scheduled } } diff --git a/modules/core/src/test/scala/vinyldns/core/domain/batch/BatchChangeSummarySpec.scala b/modules/core/src/test/scala/vinyldns/core/domain/batch/BatchChangeSummarySpec.scala index 1feb8b56e..4e21e3bf3 100644 --- a/modules/core/src/test/scala/vinyldns/core/domain/batch/BatchChangeSummarySpec.scala +++ b/modules/core/src/test/scala/vinyldns/core/domain/batch/BatchChangeSummarySpec.scala @@ -32,7 +32,8 @@ class BatchChangeSummarySpec extends WordSpec with Matchers { SingleChangeStatus.Pending, None, None, - None) + None + ) private val failedChange = pendingChange.copy(status = SingleChangeStatus.Failed) private val completeChange = pendingChange.copy(status = SingleChangeStatus.Complete) diff --git a/modules/core/src/test/scala/vinyldns/core/domain/zone/ZoneChangeSpec.scala b/modules/core/src/test/scala/vinyldns/core/domain/zone/ZoneChangeSpec.scala index 0e3d9e280..13a864351 100644 --- a/modules/core/src/test/scala/vinyldns/core/domain/zone/ZoneChangeSpec.scala +++ b/modules/core/src/test/scala/vinyldns/core/domain/zone/ZoneChangeSpec.scala @@ -26,7 +26,8 @@ class ZoneChangeSpec extends WordSpec with Matchers { "ok", ZoneChangeType.Create, ZoneChangeStatus.Complete, - created = DateTime.now.minus(1000)) + created = DateTime.now.minus(1000) + ) "ZoneChange" should { "toString" should { diff --git a/modules/core/src/test/scala/vinyldns/core/protobuf/GroupProtobufConversionsSpec.scala b/modules/core/src/test/scala/vinyldns/core/protobuf/GroupProtobufConversionsSpec.scala index 3b2c73376..c9d7c3bf9 100644 --- a/modules/core/src/test/scala/vinyldns/core/protobuf/GroupProtobufConversionsSpec.scala +++ b/modules/core/src/test/scala/vinyldns/core/protobuf/GroupProtobufConversionsSpec.scala @@ -29,7 +29,8 @@ class GroupProtobufConversionsSpec extends WordSpec with Matchers with GroupProt "test@test.com", Some("a test group"), memberIds = Set("foo", "bar"), - adminUserIds = Set("foo", "bar")) + adminUserIds = Set("foo", "bar") + ) val roundTrip = fromPB(toPB(group)) @@ -43,7 +44,8 @@ class GroupProtobufConversionsSpec extends WordSpec with Matchers with GroupProt "test@test.com", description = None, memberIds = Set("foo", "bar"), - adminUserIds = Set("foo", "bar")) + adminUserIds = Set("foo", "bar") + ) val roundTrip = fromPB(toPB(group)) @@ -58,13 +60,15 @@ class GroupProtobufConversionsSpec extends WordSpec with Matchers with GroupProt "test@test.com", Some("a test group"), memberIds = Set("foo", "bar"), - adminUserIds = Set("foo", "bar")) + adminUserIds = Set("foo", "bar") + ) val oldGroup = Group( "ok", "changed@test.com", Some("a changed group"), memberIds = Set("foo"), - adminUserIds = Set("foo")) + adminUserIds = Set("foo") + ) val groupChange = GroupChange( @@ -85,7 +89,8 @@ class GroupProtobufConversionsSpec extends WordSpec with Matchers with GroupProt "test@test.com", Some("a test group"), memberIds = Set("foo", "bar"), - adminUserIds = Set("foo", "bar")) + adminUserIds = Set("foo", "bar") + ) val groupChange = GroupChange( diff --git a/modules/core/src/test/scala/vinyldns/core/protobuf/ProtobufConversionsSpec.scala b/modules/core/src/test/scala/vinyldns/core/protobuf/ProtobufConversionsSpec.scala index ad4127b8a..98c9fa8e3 100644 --- a/modules/core/src/test/scala/vinyldns/core/protobuf/ProtobufConversionsSpec.scala +++ b/modules/core/src/test/scala/vinyldns/core/protobuf/ProtobufConversionsSpec.scala @@ -43,7 +43,8 @@ class ProtobufConversionsSpec Some("johnny"), None, Some("www-*"), - Set(RecordType.A, RecordType.AAAA, RecordType.CNAME)) + Set(RecordType.A, RecordType.AAAA, RecordType.CNAME) + ) private val groupAclRule = ACLRule( AccessLevel.Read, @@ -51,7 +52,8 @@ class ProtobufConversionsSpec None, Some("group"), Some("www-*"), - Set(RecordType.A, RecordType.AAAA, RecordType.CNAME)) + Set(RecordType.A, RecordType.AAAA, RecordType.CNAME) + ) private val zoneAcl = ZoneACL(Set(userAclRule, groupAclRule)) @@ -71,7 +73,8 @@ class ProtobufConversionsSpec ZoneChangeType.Update, ZoneChangeStatus.Complete, DateTime.now, - Some("hello")) + Some("hello") + ) private val aRs = RecordSet( "id", "test.rs", @@ -80,7 +83,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, Some(DateTime.now), - List(AData("10.1.1.1"), AData("10.2.2.2"))) + List(AData("10.1.1.1"), AData("10.2.2.2")) + ) private val aaaa = RecordSet( zone.id, "aaaa", @@ -89,7 +93,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(AAAAData("10.1.1.1"))) + List(AAAAData("10.1.1.1")) + ) private val cname = RecordSet( zone.id, "cname", @@ -98,7 +103,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(CNAMEData("cname"))) + List(CNAMEData("cname")) + ) private val mx = RecordSet( zone.id, "mx", @@ -107,7 +113,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(MXData(100, "exchange"))) + List(MXData(100, "exchange")) + ) private val ns = RecordSet( zone.id, "ns", @@ -116,7 +123,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(NSData("nsrecordname"))) + List(NSData("nsrecordname")) + ) private val ptr = RecordSet( zone.id, "ptr", @@ -125,7 +133,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(PTRData("ptr"))) + List(PTRData("ptr")) + ) private val soa = RecordSet( zone.id, "soa", @@ -134,7 +143,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(SOAData("name", "name", 1, 2, 3, 4, 5))) + List(SOAData("name", "name", 1, 2, 3, 4, 5)) + ) private val spf = RecordSet( zone.id, "soa", @@ -143,7 +153,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(SPFData("spf"))) + List(SPFData("spf")) + ) private val srv = RecordSet( zone.id, "srv", @@ -152,7 +163,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(SRVData(1, 2, 3, "target"))) + List(SRVData(1, 2, 3, "target")) + ) private val naptr = RecordSet( zone.id, "naptr", @@ -161,7 +173,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(NAPTRData(1, 2, "U", "E2U+sip", "!.*!test.!", "target"))) + List(NAPTRData(1, 2, "U", "E2U+sip", "!.*!test.!", "target")) + ) private val sshfp = RecordSet( zone.id, "sshfp", @@ -170,7 +183,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(SSHFPData(1, 2, "fingerprint"))) + List(SSHFPData(1, 2, "fingerprint")) + ) private val txt = RecordSet( zone.id, "txt", @@ -179,7 +193,8 @@ class ProtobufConversionsSpec RecordSetStatus.Active, DateTime.now, None, - List(TXTData("text"))) + List(TXTData("text")) + ) private val singleBatchChangeIds = List("batch1", "batch2") @@ -926,7 +941,8 @@ class ProtobufConversionsSpec pb.getNewUser.getAccessKey, pb.getNewUser.getSecretKey, created = user.created, - id = user.id) shouldBe user + id = user.id + ) shouldBe user pb.getMadeByUserId shouldBe createChange.madeByUserId pb.getCreated shouldBe createChange.created.getMillis @@ -948,7 +964,8 @@ class ProtobufConversionsSpec pb.getNewUser.getAccessKey, pb.getNewUser.getSecretKey, created = newUser.created, - id = newUser.id) shouldBe newUser + id = newUser.id + ) shouldBe newUser pb.getMadeByUserId shouldBe updateChange.madeByUserId pb.getCreated shouldBe updateChange.created.getMillis @@ -958,7 +975,8 @@ class ProtobufConversionsSpec pb.getOldUser.getAccessKey, pb.getOldUser.getSecretKey, created = oldUser.created, - id = oldUser.id) shouldBe oldUser + id = oldUser.id + ) shouldBe oldUser pb.getId shouldBe updateChange.id diff --git a/modules/core/src/test/scala/vinyldns/core/queue/MessageQueueLoaderSpec.scala b/modules/core/src/test/scala/vinyldns/core/queue/MessageQueueLoaderSpec.scala index 2c93969dc..0b54d8f2c 100644 --- a/modules/core/src/test/scala/vinyldns/core/queue/MessageQueueLoaderSpec.scala +++ b/modules/core/src/test/scala/vinyldns/core/queue/MessageQueueLoaderSpec.scala @@ -56,7 +56,8 @@ class MessageQueueLoaderSpec extends WordSpec with Matchers { "vinyldns.core.queue.MockMessageQueueProvider", pollingInterval, messagesPerPoll, - placeholderConfig) + placeholderConfig + ) val loadCall = MessageQueueLoader.load(config) loadCall.unsafeRunSync() shouldBe MockMessageQueueProvider.mockMessageQueue @@ -75,7 +76,8 @@ class MessageQueueLoaderSpec extends WordSpec with Matchers { "vinyldns.core.queue.FailMessageQueueProvider", pollingInterval, messagesPerPoll, - placeholderConfig) + placeholderConfig + ) val loadCall = MessageQueueLoader.load(config) diff --git a/modules/core/src/test/scala/vinyldns/core/repository/DataStoreLoaderSpec.scala b/modules/core/src/test/scala/vinyldns/core/repository/DataStoreLoaderSpec.scala index 375082b13..3cf1ff285 100644 --- a/modules/core/src/test/scala/vinyldns/core/repository/DataStoreLoaderSpec.scala +++ b/modules/core/src/test/scala/vinyldns/core/repository/DataStoreLoaderSpec.scala @@ -72,21 +72,24 @@ class DataStoreLoaderSpec val goodConfig = DataStoreConfig( "vinyldns.core.repository.MockDataStoreProvider", placeholderConfig, - allEnabledReposConfig) + allEnabledReposConfig + ) class TestDataAccessor extends DataAccessor object TestAccessorProvider extends DataAccessorProvider[TestDataAccessor] { override def repoNames: List[RepositoryName] = RepositoryName.values.toList override def create( - responses: List[(DataStoreConfig, DataStore)]): ValidatedNel[String, TestDataAccessor] = + responses: List[(DataStoreConfig, DataStore)] + ): ValidatedNel[String, TestDataAccessor] = new TestDataAccessor().validNel } object FailAccessorProvider extends DataAccessorProvider[TestDataAccessor] { override def repoNames: List[RepositoryName] = RepositoryName.values.toList override def create( - responses: List[(DataStoreConfig, DataStore)]): ValidatedNel[String, TestDataAccessor] = + responses: List[(DataStoreConfig, DataStore)] + ): ValidatedNel[String, TestDataAccessor] = "create failure".invalidNel[TestDataAccessor] } @@ -107,12 +110,14 @@ class DataStoreLoaderSpec val config1 = DataStoreConfig( "vinyldns.core.repository.MockDataStoreProvider", placeholderConfig, - allEnabledReposConfig.copy(user = None)) + allEnabledReposConfig.copy(user = None) + ) val config2 = DataStoreConfig( "vinyldns.core.repository.AlternateMockDataStoreProvider", placeholderConfig, - allDisabledReposConfig.copy(user = enabled)) + allDisabledReposConfig.copy(user = enabled) + ) val loadCall = DataStoreLoader.loadAll(List(config1, config2), crypto, TestAccessorProvider) val loaderResponse = loadCall.unsafeRunSync() @@ -125,7 +130,8 @@ class DataStoreLoaderSpec DataStoreLoader.loadAll( List(goodConfig.copy(repositories = allDisabledReposConfig)), crypto, - TestAccessorProvider) + TestAccessorProvider + ) val thrown = the[DataStoreStartupError] thrownBy loadCall.unsafeRunSync() thrown.msg should include("Config validation error") } @@ -134,7 +140,8 @@ class DataStoreLoaderSpec val loadCall = DataStoreLoader.loadAll( List(goodConfig.copy(className = "vinyldns.core.repository.FailDataStoreProvider")), crypto, - TestAccessorProvider) + TestAccessorProvider + ) val thrown = the[RuntimeException] thrownBy loadCall.unsafeRunSync() thrown.getMessage should include("ruh roh") } @@ -149,7 +156,8 @@ class DataStoreLoaderSpec val config = DataStoreConfig( "vinyldns.core.repository.AlternateMockDataStoreProvider", placeholderConfig, - allEnabledReposConfig) + allEnabledReposConfig + ) val loadCall = DataStoreLoader.loadAll(List(config), crypto, TestAccessorProvider) val thrown = the[RuntimeException] thrownBy loadCall.unsafeRunSync().shutdown() @@ -167,7 +175,8 @@ class DataStoreLoaderSpec val outcome = DataStoreLoader.getValidatedConfigs( List(config1, config2, emptyConfig), - TestAccessorProvider.repoNames) + TestAccessorProvider.repoNames + ) outcome.value should contain(config1) outcome.value should contain(config2) outcome.value should not contain emptyConfig @@ -176,7 +185,8 @@ class DataStoreLoaderSpec val config1 = goodConfig.copy(repositories = allEnabledReposConfig) val config2 = goodConfig.copy( repositories = allDisabledReposConfig - .copy(membership = enabled, group = enabled)) + .copy(membership = enabled, group = enabled) + ) val outcome = DataStoreLoader.getValidatedConfigs(List(config1, config2), List(user, membership, group)) @@ -225,7 +235,8 @@ class DataStoreLoaderSpec val config = DataStoreConfig( "some.class.name", placeholderConfig, - allDisabledReposConfig.copy(user = enabled)) + allDisabledReposConfig.copy(user = enabled) + ) val store = DataStore(Some(mockUserRepo)) val outcome = DataStoreLoader.getRepoOf[UserRepository](List((config, store)), user) @@ -239,13 +250,15 @@ class DataStoreLoaderSpec .getRepoOf[UserRepository](List((config, store)), user) outcome should haveInvalid( - "Repo user was not returned by configured database: Unknown Configured Database") + "Repo user was not returned by configured database: Unknown Configured Database" + ) } "fail if not returned by datastore" in { val config = DataStoreConfig( "some.class.name", placeholderConfig, - allDisabledReposConfig.copy(user = enabled)) + allDisabledReposConfig.copy(user = enabled) + ) val store = DataStore() val outcome = DataStoreLoader diff --git a/modules/core/src/test/scala/vinyldns/core/repository/MockDataStoreProvider.scala b/modules/core/src/test/scala/vinyldns/core/repository/MockDataStoreProvider.scala index 013fd25e1..f203e5d30 100644 --- a/modules/core/src/test/scala/vinyldns/core/repository/MockDataStoreProvider.scala +++ b/modules/core/src/test/scala/vinyldns/core/repository/MockDataStoreProvider.scala @@ -56,7 +56,8 @@ class MockDataStoreProvider extends DataStoreProvider with MockitoSugar { recordChange, zoneChange, zone, - batchChange), + batchChange + ), IO.unit, checkHealth() ) diff --git a/modules/core/src/test/scala/vinyldns/core/task/TaskSchedulerSpec.scala b/modules/core/src/test/scala/vinyldns/core/task/TaskSchedulerSpec.scala index df7fa78cc..857d122c2 100644 --- a/modules/core/src/test/scala/vinyldns/core/task/TaskSchedulerSpec.scala +++ b/modules/core/src/test/scala/vinyldns/core/task/TaskSchedulerSpec.scala @@ -36,8 +36,8 @@ class TaskSchedulerSpec extends WordSpec with Matchers with MockitoSugar with Be val timeout: FiniteDuration, val runEvery: FiniteDuration, val checkInterval: FiniteDuration, - testResult: IO[Unit] = IO.unit) - extends Task { + testResult: IO[Unit] = IO.unit + ) extends Task { def run(): IO[Unit] = testResult } @@ -66,7 +66,8 @@ class TaskSchedulerSpec extends WordSpec with Matchers with MockitoSugar with Be 5.seconds, 500.millis, 500.millis, - IO.raiseError(new RuntimeException("fail"))) + IO.raiseError(new RuntimeException("fail")) + ) doReturn(IO.unit).when(mockRepo).saveTask(task.name) doReturn(IO.pure(true)).when(mockRepo).claimTask(task.name, task.timeout, task.runEvery) doReturn(IO.unit).when(mockRepo).releaseTask(task.name) diff --git a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProviderIntegrationSpec.scala b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProviderIntegrationSpec.scala index 195f9b2eb..e3ffd8e8a 100644 --- a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProviderIntegrationSpec.scala +++ b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProviderIntegrationSpec.scala @@ -28,7 +28,6 @@ import vinyldns.core.domain.zone.{ZoneChangeRepository, ZoneRepository} import vinyldns.core.repository.{DataStore, DataStoreConfig, LoadedDataStore} import vinyldns.core.repository.RepositoryName._ - class DynamoDBDataStoreProviderIntegrationSpec extends DynamoDBIntegrationSpec { private implicit val cs: ContextShift[IO] = diff --git a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepositoryIntegrationSpec.scala b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepositoryIntegrationSpec.scala index 8d04fae1e..0ef59ec71 100644 --- a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepositoryIntegrationSpec.scala +++ b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepositoryIntegrationSpec.scala @@ -42,7 +42,8 @@ class DynamoDBGroupChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSp "randomTime", "test@test.com", Some("changes have random time stamp"), - memberIds = Set(listOfDummyUsers(0).id)) + memberIds = Set(listOfDummyUsers(0).id) + ) // making distinct, multiple changes with the same time throws this test private val randomTimes: List[Int] = List.range(0, 200).map(_ => Random.nextInt(1000)).distinct @@ -53,7 +54,8 @@ class DynamoDBGroupChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSp GroupChangeType.Update, dummyUser.id, created = now.minusSeconds(randomTime), - id = s"random-time-$i") + id = s"random-time-$i" + ) } private val groupChanges = Seq(okGroupChange, okGroupChangeUpdate, okGroupChangeDelete) ++ @@ -112,7 +114,8 @@ class DynamoDBGroupChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSp val retrieved = repo.getGroupChanges(oneUserDummyGroup.id, None, 100).unsafeRunSync() retrieved.changes should contain theSameElementsAs listOfDummyGroupChanges.slice(0, 100) retrieved.lastEvaluatedTimeStamp shouldBe Some( - listOfDummyGroupChanges(99).created.getMillis.toString) + listOfDummyGroupChanges(99).created.getMillis.toString + ) } "getGroupChanges should start using the time startFrom" in { @@ -120,11 +123,13 @@ class DynamoDBGroupChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSp .getGroupChanges( oneUserDummyGroup.id, Some(listOfDummyGroupChanges(50).created.getMillis.toString), - 100) + 100 + ) .unsafeRunSync() retrieved.changes should contain theSameElementsAs listOfDummyGroupChanges.slice(51, 151) retrieved.lastEvaluatedTimeStamp shouldBe Some( - listOfDummyGroupChanges(150).created.getMillis.toString) + listOfDummyGroupChanges(150).created.getMillis.toString + ) } "getGroupChanges returns entire page and nextId = None if there are less than maxItems left" in { @@ -132,7 +137,8 @@ class DynamoDBGroupChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSp .getGroupChanges( oneUserDummyGroup.id, Some(listOfDummyGroupChanges(200).created.getMillis.toString), - 100) + 100 + ) .unsafeRunSync() retrieved.changes should contain theSameElementsAs listOfDummyGroupChanges.slice(201, 300) retrieved.lastEvaluatedTimeStamp shouldBe None @@ -140,23 +146,28 @@ class DynamoDBGroupChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSp "getGroupChanges returns 3 pages of items" in { val page1 = repo.getGroupChanges(oneUserDummyGroup.id, None, 100).unsafeRunSync() - val page2 = repo.getGroupChanges(oneUserDummyGroup.id, page1.lastEvaluatedTimeStamp, 100).unsafeRunSync() - val page3 = repo.getGroupChanges(oneUserDummyGroup.id, page2.lastEvaluatedTimeStamp, 100).unsafeRunSync() - val page4 = repo.getGroupChanges(oneUserDummyGroup.id, page3.lastEvaluatedTimeStamp, 100).unsafeRunSync() + val page2 = repo + .getGroupChanges(oneUserDummyGroup.id, page1.lastEvaluatedTimeStamp, 100) + .unsafeRunSync() + val page3 = repo + .getGroupChanges(oneUserDummyGroup.id, page2.lastEvaluatedTimeStamp, 100) + .unsafeRunSync() + val page4 = repo + .getGroupChanges(oneUserDummyGroup.id, page3.lastEvaluatedTimeStamp, 100) + .unsafeRunSync() page1.changes should contain theSameElementsAs listOfDummyGroupChanges.slice(0, 100) page1.lastEvaluatedTimeStamp shouldBe Some( - listOfDummyGroupChanges(99).created.getMillis.toString) - page2.changes should contain theSameElementsAs listOfDummyGroupChanges.slice( - 100, - 200) + listOfDummyGroupChanges(99).created.getMillis.toString + ) + page2.changes should contain theSameElementsAs listOfDummyGroupChanges.slice(100, 200) page2.lastEvaluatedTimeStamp shouldBe Some( - listOfDummyGroupChanges(199).created.getMillis.toString) - page3.changes should contain theSameElementsAs listOfDummyGroupChanges.slice( - 200, - 300) + listOfDummyGroupChanges(199).created.getMillis.toString + ) + page3.changes should contain theSameElementsAs listOfDummyGroupChanges.slice(200, 300) page3.lastEvaluatedTimeStamp shouldBe Some( - listOfDummyGroupChanges(299).created.getMillis.toString) // the limit was reached before the end of list + listOfDummyGroupChanges(299).created.getMillis.toString + ) // the limit was reached before the end of list page4.changes should contain theSameElementsAs List() // no matches found in the rest of the list page4.lastEvaluatedTimeStamp shouldBe None } @@ -165,7 +176,8 @@ class DynamoDBGroupChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSp val retrieved = repo.getGroupChanges(oneUserDummyGroup.id, None, 5).unsafeRunSync() retrieved.changes should contain theSameElementsAs listOfDummyGroupChanges.slice(0, 5) retrieved.lastEvaluatedTimeStamp shouldBe Some( - listOfDummyGroupChanges(4).created.getMillis.toString) + listOfDummyGroupChanges(4).created.getMillis.toString + ) } "getGroupChanges should handle changes inserted in random order" in { diff --git a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepositoryIntegrationSpec.scala b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepositoryIntegrationSpec.scala index 463523c50..8d6cf1178 100644 --- a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepositoryIntegrationSpec.scala +++ b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepositoryIntegrationSpec.scala @@ -37,15 +37,14 @@ class DynamoDBGroupRepositoryIntegrationSpec extends DynamoDBIntegrationSpec { private val activeGroups = for (i <- 1 to 10) - yield - Group( - s"live-test-group$i", - s"test$i@test.com", - Some(s"description$i"), - memberIds = Set(s"member$i", s"member2$i"), - adminUserIds = Set(s"member$i", s"member2$i"), - id = "id-%03d".format(i) - ) + yield Group( + s"live-test-group$i", + s"test$i@test.com", + Some(s"description$i"), + memberIds = Set(s"member$i", s"member2$i"), + adminUserIds = Set(s"member$i", s"member2$i"), + id = "id-%03d".format(i) + ) private val inDbDeletedGroup = Group( s"live-test-group-deleted", @@ -134,7 +133,8 @@ class DynamoDBGroupRepositoryIntegrationSpec extends DynamoDBIntegrationSpec { val deleted = deletedGroup.copy( id = "test-deleted-group-get-groups", memberIds = Set("foo"), - adminUserIds = Set("foo")) + adminUserIds = Set("foo") + ) val f = for { _ <- repo.save(deleted) @@ -155,7 +155,8 @@ class DynamoDBGroupRepositoryIntegrationSpec extends DynamoDBIntegrationSpec { "test@test.com", None, memberIds = Set("foo"), - adminUserIds = Set("bar")) + adminUserIds = Set("bar") + ) val test = for { @@ -170,7 +171,8 @@ class DynamoDBGroupRepositoryIntegrationSpec extends DynamoDBIntegrationSpec { val deleted = deletedGroup.copy( id = "test-deleted-group-get-groups", memberIds = Set("foo"), - adminUserIds = Set("foo")) + adminUserIds = Set("foo") + ) val f = for { _ <- repo.save(deleted) diff --git a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBIntegrationSpec.scala b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBIntegrationSpec.scala index 9e853860f..2af904fab 100644 --- a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBIntegrationSpec.scala +++ b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBIntegrationSpec.scala @@ -32,17 +32,16 @@ trait DynamoDBIntegrationSpec val logger: Logger = LoggerFactory.getLogger("DynamoDBIntegrationSpec") // only used for teardown - lazy val testDynamoDBHelper: DynamoDBHelper = new DynamoDBHelper( - DynamoDBClient(dynamoIntegrationConfig), - logger) + lazy val testDynamoDBHelper: DynamoDBHelper = + new DynamoDBHelper(DynamoDBClient(dynamoIntegrationConfig), logger) - - def getDynamoConfig(port: Int): DynamoDBDataStoreSettings = { - DynamoDBDataStoreSettings("vinyldnsTest", + def getDynamoConfig(port: Int): DynamoDBDataStoreSettings = + DynamoDBDataStoreSettings( + "vinyldnsTest", "notNeededForDynamoDbLocal", s"http://localhost:$port", - "us-east-1") - } + "us-east-1" + ) override protected def beforeAll(): Unit = setup() diff --git a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepositoryIntegrationSpec.scala b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepositoryIntegrationSpec.scala index a0b751c28..1f75d1939 100644 --- a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepositoryIntegrationSpec.scala +++ b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepositoryIntegrationSpec.scala @@ -29,8 +29,7 @@ import vinyldns.core.TestRecordSetData._ import scala.concurrent.duration._ -class DynamoDBRecordChangeRepositoryIntegrationSpec - extends DynamoDBIntegrationSpec { +class DynamoDBRecordChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSpec { private val recordChangeTable = "record-change-live" @@ -45,48 +44,47 @@ class DynamoDBRecordChangeRepositoryIntegrationSpec s"live-test-$user.zone-small.", "test@test.com", status = ZoneStatus.Active, - connection = testConnection) + connection = testConnection + ) private val zoneB = Zone( s"live-test-$user.zone-large.", "test@test.com", status = ZoneStatus.Active, - connection = testConnection) + connection = testConnection + ) private val recordSetA = for { rsTemplate <- Seq(rsOk, aaaa, cname) - } yield - rsTemplate.copy( - zoneId = zoneA.id, - name = s"${rsTemplate.typ.toString}-${zoneA.account}.", - ttl = 100, - created = DateTime.now(), - id = UUID.randomUUID().toString - ) + } yield rsTemplate.copy( + zoneId = zoneA.id, + name = s"${rsTemplate.typ.toString}-${zoneA.account}.", + ttl = 100, + created = DateTime.now(), + id = UUID.randomUUID().toString + ) private val recordSetB = for { i <- 1 to 3 - } yield - rsOk.copy( - zoneId = zoneB.id, - name = s"${rsOk.typ.toString}-${zoneB.account}-$i.", - ttl = 100, - created = DateTime.now(), - id = UUID.randomUUID().toString - ) + } yield rsOk.copy( + zoneId = zoneB.id, + name = s"${rsOk.typ.toString}-${zoneB.account}-$i.", + ttl = 100, + created = DateTime.now(), + id = UUID.randomUUID().toString + ) private val updateRecordSetA = for { rsTemplate <- Seq(rsOk, aaaa, cname) - } yield - rsTemplate.copy( - zoneId = zoneA.id, - name = s"${rsTemplate.typ.toString}-${zoneA.account}.", - ttl = 1000, - created = DateTime.now(), - id = UUID.randomUUID().toString - ) + } yield rsTemplate.copy( + zoneId = zoneA.id, + name = s"${rsTemplate.typ.toString}-${zoneA.account}.", + ttl = 1000, + created = DateTime.now(), + id = UUID.randomUUID().toString + ) private val recordSetChangesA = { for { @@ -126,7 +124,8 @@ class DynamoDBRecordChangeRepositoryIntegrationSpec s"live-test-$user.record-changes.", "test@test.com", status = ZoneStatus.Active, - connection = testConnection) + connection = testConnection + ) private val baseTime = DateTime.now() private val timeOrder = List( baseTime.minusSeconds(8000), @@ -143,24 +142,22 @@ class DynamoDBRecordChangeRepositoryIntegrationSpec private val recordSetsC = for { rsTemplate <- Seq(rsOk, aaaa, cname) - } yield - rsTemplate.copy( - zoneId = zoneC.id, - name = s"${rsTemplate.typ.toString}-${zoneC.account}.", - ttl = 100, - id = UUID.randomUUID().toString - ) + } yield rsTemplate.copy( + zoneId = zoneC.id, + name = s"${rsTemplate.typ.toString}-${zoneC.account}.", + ttl = 100, + id = UUID.randomUUID().toString + ) private val updateRecordSetsC = for { rsTemplate <- Seq(rsOk, aaaa, cname) - } yield - rsTemplate.copy( - zoneId = zoneC.id, - name = s"${rsTemplate.typ.toString}-${zoneC.account}.", - ttl = 1000, - id = UUID.randomUUID().toString - ) + } yield rsTemplate.copy( + zoneId = zoneC.id, + name = s"${rsTemplate.typ.toString}-${zoneC.account}.", + ttl = 1000, + id = UUID.randomUUID().toString + ) private val recordSetChangesCreateC = { for { @@ -171,9 +168,8 @@ class DynamoDBRecordChangeRepositoryIntegrationSpec private val recordSetChangesUpdateC = { for { (rs, index) <- recordSetsC.zipWithIndex - } yield - makePendingTestUpdateChange(rs, updateRecordSetsC(index), zoneC, auth.userId) - .copy(created = timeOrder(index + 3)) + } yield makePendingTestUpdateChange(rs, updateRecordSetsC(index), zoneC, auth.userId) + .copy(created = timeOrder(index + 3)) } private val recordSetChangesDeleteC = { diff --git a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepositoryIntegrationSpec.scala b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepositoryIntegrationSpec.scala index fe618a864..885d6d861 100644 --- a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepositoryIntegrationSpec.scala +++ b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepositoryIntegrationSpec.scala @@ -43,19 +43,20 @@ class DynamoDBRecordSetRepositoryIntegrationSpec private var repo: DynamoDBRecordSetRepository = _ - private val users = for (i <- 1 to 3) - yield User(s"live-test-acct$i", "key", "secret") + private val users = + for (i <- 1 to 3) + yield User(s"live-test-acct$i", "key", "secret") private val zones = for { acct <- users i <- 1 to 3 - } yield - Zone( - s"live-test-${acct.userName}.zone$i.", - "test@test.com", - status = ZoneStatus.Active, - connection = testConnection) + } yield Zone( + s"live-test-${acct.userName}.zone$i.", + "test@test.com", + status = ZoneStatus.Active, + connection = testConnection + ) private val rsTemplates = Seq(rsOk, aaaa, cname) @@ -66,14 +67,13 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zone <- zones rsTemplate <- rsTemplates rsQualifiedStatus <- rsQualifiedStatus - } yield - rsTemplate.copy( - zoneId = zone.id, - name = s"${rsTemplate.typ.toString}-${zone.account}$rsQualifiedStatus", - ttl = 100, - created = DateTime.now(), - id = UUID.randomUUID().toString - ) + } yield rsTemplate.copy( + zoneId = zone.id, + name = s"${rsTemplate.typ.toString}-${zone.account}$rsQualifiedStatus", + ttl = 100, + created = DateTime.now(), + id = UUID.randomUUID().toString + ) def setup(): Unit = { repo = DynamoDBRecordSetRepository(tableConfig, dynamoIntegrationConfig).unsafeRunSync() @@ -90,7 +90,6 @@ class DynamoDBRecordSetRepositoryIntegrationSpec repo.dynamoDBHelper.deleteTable(request).unsafeRunSync() } - "DynamoDBRecordSetRepository" should { "get a record set by id" in { val testRecordSet = recordSets.head @@ -98,7 +97,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = None, maxItems = None, - recordNameFilter = None) + recordNameFilter = None + ) testFuture.unsafeRunSync().recordSets should contain(testRecordSet) } @@ -128,7 +128,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec val testFuture = repo.getRecordSets( testRecordSet.zoneId, testRecordSet.name.toUpperCase(), - testRecordSet.typ) + testRecordSet.typ + ) testFuture.unsafeRunSync() shouldBe List(testRecordSet) } @@ -179,7 +180,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = None, maxItems = Some(1), - recordNameFilter = None) + recordNameFilter = None + ) val foundRecordSet = testFuture.unsafeRunSync() @@ -194,7 +196,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = None, maxItems = Some(1), - recordNameFilter = None) + recordNameFilter = None + ) val foundRecordSet = testFutureOne.unsafeRunSync() @@ -205,7 +208,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = key, maxItems = Some(1), - recordNameFilter = None) + recordNameFilter = None + ) val foundRecordSetTwo = testFutureTwo.unsafeRunSync() @@ -221,7 +225,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = None, maxItems = Some(1), - recordNameFilter = None) + recordNameFilter = None + ) val foundRecordSet = testFutureOne.unsafeRunSync() foundRecordSet.recordSets should contain(recordSets(0)) @@ -231,7 +236,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = key, maxItems = Some(2), - recordNameFilter = None) + recordNameFilter = None + ) val foundRecordSetTwo = testFutureTwo.unsafeRunSync() foundRecordSetTwo.recordSets shouldNot contain(recordSets(0)) @@ -246,7 +252,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = None, maxItems = Some(6), - recordNameFilter = None) + recordNameFilter = None + ) val foundRecordSet = testFutureOne.unsafeRunSync() @@ -262,7 +269,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = key, maxItems = Some(6), - recordNameFilter = None) + recordNameFilter = None + ) val foundRecordSetTwo = testFutureTwo.unsafeRunSync() foundRecordSetTwo.recordSets shouldBe List() @@ -275,7 +283,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = None, maxItems = Some(7), - recordNameFilter = None) + recordNameFilter = None + ) val foundRecordSet = testFuture.unsafeRunSync() foundRecordSet.recordSets should contain(recordSets(0)) @@ -293,7 +302,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = None, maxItems = None, - recordNameFilter = Some("AAAA")) + recordNameFilter = Some("AAAA") + ) val foundRecordSet = testFuture.unsafeRunSync() foundRecordSet.recordSets shouldNot contain(recordSets(0)) @@ -308,7 +318,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = None, maxItems = None, - recordNameFilter = Some("A")) + recordNameFilter = Some("A") + ) val foundRecordSet = testFuture.unsafeRunSync() foundRecordSet.recordSets should contain(recordSets(0)) @@ -325,7 +336,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = testRecordSet.zoneId, startFrom = None, maxItems = None, - recordNameFilter = Some("Dummy")) + recordNameFilter = Some("Dummy") + ) testFuture.unsafeRunSync().recordSets shouldBe List() } @@ -334,11 +346,11 @@ class DynamoDBRecordSetRepositoryIntegrationSpec val newRecordSets = for { i <- 1 to 1000 - } yield - aaaa.copy( - zoneId = "big-apply-zone", - name = s"$i.apply.test.", - id = UUID.randomUUID().toString) + } yield aaaa.copy( + zoneId = "big-apply-zone", + name = s"$i.apply.test.", + id = UUID.randomUUID().toString + ) val pendingChanges = newRecordSets.map(makeTestAddChange(_, zones.head)) @@ -375,7 +387,8 @@ class DynamoDBRecordSetRepositoryIntegrationSpec zoneId = "big-apply-zone", startFrom = None, maxItems = None, - recordNameFilter = None) + recordNameFilter = None + ) recordSetsResult = rsQuery.unsafeRunTimed(30.seconds) match { case Some(result) => result.recordSets @@ -401,12 +414,30 @@ class DynamoDBRecordSetRepositoryIntegrationSpec "apply successful and pending creates, and delete failed creates" in { val zone = okZone - val recordForSuccess = RecordSet("test-create-converter", "createSuccess", RecordType.A, 123, - RecordSetStatus.Active, DateTime.now) - val recordForPending = RecordSet("test-create-converter", "createPending", RecordType.A, 123, - RecordSetStatus.Pending, DateTime.now) - val recordForFailed = RecordSet("test-create-converter", "failed", RecordType.A, 123, - RecordSetStatus.Inactive, DateTime.now) + val recordForSuccess = RecordSet( + "test-create-converter", + "createSuccess", + RecordType.A, + 123, + RecordSetStatus.Active, + DateTime.now + ) + val recordForPending = RecordSet( + "test-create-converter", + "createPending", + RecordType.A, + 123, + RecordSetStatus.Pending, + DateTime.now + ) + val recordForFailed = RecordSet( + "test-create-converter", + "failed", + RecordType.A, + 123, + RecordSetStatus.Inactive, + DateTime.now + ) val successfulChange = RecordSetChange( @@ -414,14 +445,19 @@ class DynamoDBRecordSetRepositoryIntegrationSpec recordForSuccess, "abc", RecordSetChangeType.Create, - RecordSetChangeStatus.Complete) + RecordSetChangeStatus.Complete + ) - val pendingChange = successfulChange.copy(recordSet = recordForPending, status = RecordSetChangeStatus.Pending) - val failedChange = successfulChange.copy(recordSet = recordForFailed, status = RecordSetChangeStatus.Failed) + val pendingChange = + successfulChange.copy(recordSet = recordForPending, status = RecordSetChangeStatus.Pending) + val failedChange = + successfulChange.copy(recordSet = recordForFailed, status = RecordSetChangeStatus.Failed) // to be deleted - assume this was already saved as pending - val existingPending = failedChange.copy(recordSet = recordForFailed.copy(status = RecordSetStatus.Pending), - status = RecordSetChangeStatus.Pending) + val existingPending = failedChange.copy( + recordSet = recordForFailed.copy(status = RecordSetStatus.Pending), + status = RecordSetChangeStatus.Pending + ) repo.apply(ChangeSet(existingPending)).unsafeRunSync() repo.getRecordSet(recordForFailed.zoneId, failedChange.recordSet.id).unsafeRunSync() shouldBe Some(existingPending.recordSet) @@ -429,13 +465,19 @@ class DynamoDBRecordSetRepositoryIntegrationSpec repo.apply(ChangeSet(Seq(successfulChange, pendingChange, failedChange))).unsafeRunSync() // success and pending changes have records saved - repo.getRecordSet(successfulChange.recordSet.zoneId, successfulChange.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(successfulChange.recordSet.zoneId, successfulChange.recordSet.id) + .unsafeRunSync() shouldBe Some(successfulChange.recordSet) - repo.getRecordSet(pendingChange.recordSet.zoneId, pendingChange.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(pendingChange.recordSet.zoneId, pendingChange.recordSet.id) + .unsafeRunSync() shouldBe Some(pendingChange.recordSet) // check that the pending record was deleted because of failed record change - repo.getRecordSet(failedChange.recordSet.zoneId, failedChange.recordSet.id).unsafeRunSync() shouldBe None + repo + .getRecordSet(failedChange.recordSet.zoneId, failedChange.recordSet.id) + .unsafeRunSync() shouldBe None } "apply successful updates and revert records for failed updates" in { @@ -453,13 +495,16 @@ class DynamoDBRecordSetRepositoryIntegrationSpec val failedUpdate = pendingUpdate.copy( recordSet = updateFailure, updates = Some(oldFailure), - status = RecordSetChangeStatus.Failed) + status = RecordSetChangeStatus.Failed + ) val updateChanges = Seq(successfulUpdate, pendingUpdate, failedUpdate) val updateChangeSet = ChangeSet(updateChanges) // save old recordsets val oldAddChanges = updateChanges - .map(_.copy(changeType = RecordSetChangeType.Create, status = RecordSetChangeStatus.Complete)) + .map( + _.copy(changeType = RecordSetChangeType.Create, status = RecordSetChangeStatus.Complete) + ) val oldChangeSet = ChangeSet(oldAddChanges) repo.apply(oldChangeSet).unsafeRunSync() shouldBe oldChangeSet @@ -467,16 +512,24 @@ class DynamoDBRecordSetRepositoryIntegrationSpec repo.apply(updateChangeSet).unsafeRunSync() shouldBe updateChangeSet // ensure that success and pending updates store the new recordsets - repo.getRecordSet(successfulUpdate.recordSet.zoneId, successfulUpdate.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(successfulUpdate.recordSet.zoneId, successfulUpdate.recordSet.id) + .unsafeRunSync() shouldBe Some(successfulUpdate.recordSet) - repo.getRecordSet(pendingUpdate.recordSet.zoneId, pendingUpdate.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(pendingUpdate.recordSet.zoneId, pendingUpdate.recordSet.id) + .unsafeRunSync() shouldBe Some(pendingUpdate.recordSet) // ensure that failure update store the old recordset - repo.getRecordSet(failedUpdate.recordSet.zoneId, failedUpdate.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(failedUpdate.recordSet.zoneId, failedUpdate.recordSet.id) + .unsafeRunSync() shouldBe failedUpdate.updates - repo.getRecordSet(failedUpdate.recordSet.zoneId, failedUpdate.recordSet.id).unsafeRunSync() shouldNot + repo + .getRecordSet(failedUpdate.recordSet.zoneId, failedUpdate.recordSet.id) + .unsafeRunSync() shouldNot be(Some(failedUpdate.recordSet)) } @@ -485,16 +538,21 @@ class DynamoDBRecordSetRepositoryIntegrationSpec val oldPending = aaaa.copy(zoneId = "test-update-converter", id = "pending") val oldFailure = aaaa.copy(zoneId = "test-update-converter", id = "failed") - val successfulDelete = makePendingTestDeleteChange(oldSuccess).copy(status = RecordSetChangeStatus.Complete) - val pendingDelete = makePendingTestDeleteChange(oldPending).copy(status = RecordSetChangeStatus.Pending) - val failedDelete = makePendingTestDeleteChange(oldFailure).copy(status = RecordSetChangeStatus.Failed) + val successfulDelete = + makePendingTestDeleteChange(oldSuccess).copy(status = RecordSetChangeStatus.Complete) + val pendingDelete = + makePendingTestDeleteChange(oldPending).copy(status = RecordSetChangeStatus.Pending) + val failedDelete = + makePendingTestDeleteChange(oldFailure).copy(status = RecordSetChangeStatus.Failed) val deleteChanges = Seq(successfulDelete, pendingDelete, failedDelete) val deleteChangeSet = ChangeSet(deleteChanges) // save old recordsets val oldAddChanges = deleteChanges - .map(_.copy(changeType = RecordSetChangeType.Create, status = RecordSetChangeStatus.Complete)) + .map( + _.copy(changeType = RecordSetChangeType.Create, status = RecordSetChangeStatus.Complete) + ) val oldChangeSet = ChangeSet(oldAddChanges) repo.apply(oldChangeSet).unsafeRunSync() shouldBe oldChangeSet @@ -502,14 +560,20 @@ class DynamoDBRecordSetRepositoryIntegrationSpec repo.apply(deleteChangeSet).unsafeRunSync() shouldBe deleteChangeSet // ensure that successful change deletes the recordset - repo.getRecordSet(successfulDelete.recordSet.zoneId, successfulDelete.recordSet.id).unsafeRunSync() shouldBe None + repo + .getRecordSet(successfulDelete.recordSet.zoneId, successfulDelete.recordSet.id) + .unsafeRunSync() shouldBe None // ensure that pending change saves the recordset - repo.getRecordSet(pendingDelete.recordSet.zoneId, pendingDelete.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(pendingDelete.recordSet.zoneId, pendingDelete.recordSet.id) + .unsafeRunSync() shouldBe Some(pendingDelete.recordSet) // ensure that failed delete keeps the recordset - repo.getRecordSet(failedDelete.recordSet.zoneId, failedDelete.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(failedDelete.recordSet.zoneId, failedDelete.recordSet.id) + .unsafeRunSync() shouldBe failedDelete.updates } } diff --git a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBUserChangeRepositoryIntegrationSpec.scala b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBUserChangeRepositoryIntegrationSpec.scala index 1ebb12091..2237537ba 100644 --- a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBUserChangeRepositoryIntegrationSpec.scala +++ b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBUserChangeRepositoryIntegrationSpec.scala @@ -41,7 +41,11 @@ class DynamoDBUserChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSpe ) private val repo: DynamoDBUserChangeRepository = - DynamoDBUserChangeRepository(tableConfig, dynamoIntegrationConfig, new NoOpCrypto(ConfigFactory.load())).unsafeRunSync() + DynamoDBUserChangeRepository( + tableConfig, + dynamoIntegrationConfig, + new NoOpCrypto(ConfigFactory.load()) + ).unsafeRunSync() def setup(): Unit = () diff --git a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBUserRepositoryIntegrationSpec.scala b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBUserRepositoryIntegrationSpec.scala index c13beb8a2..ff0843ebe 100644 --- a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBUserRepositoryIntegrationSpec.scala +++ b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBUserRepositoryIntegrationSpec.scala @@ -35,13 +35,17 @@ class DynamoDBUserRepositoryIntegrationSpec extends DynamoDBIntegrationSpec { private var repo: DynamoDBUserRepository = _ - private val testUserIds = (for {i <- 0 to 100} yield s"test-user-$i").toList.sorted + private val testUserIds = (for { i <- 0 to 100 } yield s"test-user-$i").toList.sorted private val users = testUserIds.map { id => User(id = id, userName = "name" + id, accessKey = s"abc$id", secretKey = "123") } def setup(): Unit = { - repo = DynamoDBUserRepository(tableConfig, dynamoIntegrationConfig, new NoOpCrypto(ConfigFactory.load())).unsafeRunSync() + repo = DynamoDBUserRepository( + tableConfig, + dynamoIntegrationConfig, + new NoOpCrypto(ConfigFactory.load()) + ).unsafeRunSync() // Create all the items val results = users.map(repo.save(_)).parSequence @@ -123,7 +127,8 @@ class DynamoDBUserRepositoryIntegrationSpec extends DynamoDBIntegrationSpec { userName = "testSuper", accessKey = "testSuper", secretKey = "testUser", - isSuper = true) + isSuper = true + ) val saved = repo.save(testUser).unsafeRunSync() val result = repo.getUser(saved.id).unsafeRunSync() @@ -143,7 +148,8 @@ class DynamoDBUserRepositoryIntegrationSpec extends DynamoDBIntegrationSpec { userName = "testSuper", accessKey = "testSuper", secretKey = "testUser", - lockStatus = LockStatus.Locked) + lockStatus = LockStatus.Locked + ) val saved = repo.save(testUser).unsafeRunSync() val result = repo.getUser(saved.id).unsafeRunSync() @@ -162,7 +168,8 @@ class DynamoDBUserRepositoryIntegrationSpec extends DynamoDBIntegrationSpec { userName = "testSuper", accessKey = "testSuper", secretKey = "testUser", - isSupport = true) + isSupport = true + ) val saved = repo.save(testUser).unsafeRunSync() val result = repo.getUser(saved.id).unsafeRunSync() @@ -177,11 +184,7 @@ class DynamoDBUserRepositoryIntegrationSpec extends DynamoDBIntegrationSpec { f.get.isSupport shouldBe false } "returns the test flag when true" in { - val testUser = User( - userName = "test", - accessKey = "test", - secretKey = "test", - isTest = true) + val testUser = User(userName = "test", accessKey = "test", secretKey = "test", isTest = true) val saved = repo.save(testUser).unsafeRunSync() val result = repo.getUser(saved.id).unsafeRunSync() diff --git a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBZoneChangeRepositoryIntegrationSpec.scala b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBZoneChangeRepositoryIntegrationSpec.scala index da2099066..a15bfe079 100644 --- a/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBZoneChangeRepositoryIntegrationSpec.scala +++ b/modules/dynamodb/src/it/scala/vinyldns/dynamodb/repository/DynamoDBZoneChangeRepositoryIntegrationSpec.scala @@ -32,7 +32,7 @@ class DynamoDBZoneChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSpe private implicit val cs: ContextShift[IO] = IO.contextShift(scala.concurrent.ExecutionContext.global) - + private val zoneChangeTable = "zone-changes-live" private val tableConfig = DynamoDBRepositorySettings(s"$zoneChangeTable", 30, 30) @@ -41,12 +41,12 @@ class DynamoDBZoneChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSpe private val goodUser = User(s"live-test-acct", "key", "secret") - private val okZones = for {i <- 1 to 3} yield - Zone( - s"${goodUser.userName}.zone$i.", - "test@test.com", - status = ZoneStatus.Active, - connection = testConnection) + private val okZones = for { i <- 1 to 3 } yield Zone( + s"${goodUser.userName}.zone$i.", + "test@test.com", + status = ZoneStatus.Active, + connection = testConnection + ) private val zones = okZones @@ -54,13 +54,13 @@ class DynamoDBZoneChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSpe import vinyldns.core.domain.zone.ZoneChangeStatus._ Pending :: Complete :: Failed :: Synced :: Nil } - private val changes = for {zone <- zones; status <- statuses} yield - ZoneChange( - zone, - zone.account, - ZoneChangeType.Update, - status, - created = now.minusSeconds(Random.nextInt(1000))) + private val changes = for { zone <- zones; status <- statuses } yield ZoneChange( + zone, + zone.account, + ZoneChangeType.Update, + status, + created = now.minusSeconds(Random.nextInt(1000)) + ) def setup(): Unit = { repo = DynamoDBZoneChangeRepository(tableConfig, dynamoIntegrationConfig).unsafeRunSync() @@ -76,7 +76,6 @@ class DynamoDBZoneChangeRepositoryIntegrationSpec extends DynamoDBIntegrationSpe repo.dynamoDBHelper.deleteTable(request).unsafeRunSync() } - "DynamoDBRepository" should { implicit def dateTimeOrdering: Ordering[DateTime] = Ordering.fromLessThan(_.isAfter(_)) diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProvider.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProvider.scala index 178248671..a74f9078d 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProvider.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProvider.scala @@ -58,10 +58,12 @@ class DynamoDBDataStoreProvider extends DataStoreProvider { } def loadRepoConfigs( - config: RepositoriesConfig): IO[Map[RepositoryName, DynamoDBRepositorySettings]] = { + config: RepositoriesConfig + ): IO[Map[RepositoryName, DynamoDBRepositorySettings]] = { def loadConfigIfDefined( - repositoryName: RepositoryName): Option[IO[(RepositoryName, DynamoDBRepositorySettings)]] = + repositoryName: RepositoryName + ): Option[IO[(RepositoryName, DynamoDBRepositorySettings)]] = config.get(repositoryName).map { repoConf => loadConfigF[IO, DynamoDBRepositorySettings](repoConf).map(repositoryName -> _) } @@ -74,11 +76,13 @@ class DynamoDBDataStoreProvider extends DataStoreProvider { def initializeRepos( dynamoConfig: DynamoDBDataStoreSettings, repoSettings: Map[RepositoryName, DynamoDBRepositorySettings], - crypto: CryptoAlgebra): IO[DataStore] = { + crypto: CryptoAlgebra + ): IO[DataStore] = { def initializeSingleRepo[T <: Repository]( repoName: RepositoryName, - fn: DynamoDBRepositorySettings => IO[T]): IO[Option[T]] = + fn: DynamoDBRepositorySettings => IO[T] + ): IO[Option[T]] = repoSettings .get(repoName) .map { configuredOn => @@ -93,28 +97,35 @@ class DynamoDBDataStoreProvider extends DataStoreProvider { ( initializeSingleRepo[UserRepository]( user, - DynamoDBUserRepository.apply(_, dynamoConfig, crypto)), + DynamoDBUserRepository.apply(_, dynamoConfig, crypto) + ), initializeSingleRepo[GroupRepository](group, DynamoDBGroupRepository.apply(_, dynamoConfig)), initializeSingleRepo[MembershipRepository]( membership, - DynamoDBMembershipRepository.apply(_, dynamoConfig)), + DynamoDBMembershipRepository.apply(_, dynamoConfig) + ), initializeSingleRepo[GroupChangeRepository]( groupChange, - DynamoDBGroupChangeRepository.apply(_, dynamoConfig)), + DynamoDBGroupChangeRepository.apply(_, dynamoConfig) + ), initializeSingleRepo[RecordSetRepository]( recordSet, - DynamoDBRecordSetRepository.apply(_, dynamoConfig)), + DynamoDBRecordSetRepository.apply(_, dynamoConfig) + ), initializeSingleRepo[RecordChangeRepository]( recordChange, - DynamoDBRecordChangeRepository.apply(_, dynamoConfig)), + DynamoDBRecordChangeRepository.apply(_, dynamoConfig) + ), initializeSingleRepo[ZoneChangeRepository]( zoneChange, - DynamoDBZoneChangeRepository.apply(_, dynamoConfig)), + DynamoDBZoneChangeRepository.apply(_, dynamoConfig) + ), IO.pure[Option[ZoneRepository]](None), IO.pure[Option[BatchChangeRepository]](None), initializeSingleRepo[UserChangeRepository]( userChange, - DynamoDBUserChangeRepository.apply(_, dynamoConfig, crypto)), + DynamoDBUserChangeRepository.apply(_, dynamoConfig, crypto) + ), IO.pure[Option[TaskRepository]](None) ).parMapN { DataStore.apply diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreSettings.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreSettings.scala index 951aeca3b..ab913699f 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreSettings.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreSettings.scala @@ -20,9 +20,11 @@ final case class DynamoDBDataStoreSettings( key: String, secret: String, endpoint: String, - region: String) + region: String +) final case class DynamoDBRepositorySettings( tableName: String, provisionedReads: Long, - provisionedWrites: Long) + provisionedWrites: Long +) diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepository.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepository.scala index 800204e28..240e7ac91 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepository.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepository.scala @@ -41,11 +41,13 @@ object DynamoDBGroupChangeRepository { def apply( config: DynamoDBRepositorySettings, - dynamoConfig: DynamoDBDataStoreSettings): IO[DynamoDBGroupChangeRepository] = { + dynamoConfig: DynamoDBDataStoreSettings + ): IO[DynamoDBGroupChangeRepository] = { val dynamoDBHelper = new DynamoDBHelper( DynamoDBClient(dynamoConfig), - LoggerFactory.getLogger(classOf[DynamoDBGroupChangeRepository])) + LoggerFactory.getLogger(classOf[DynamoDBGroupChangeRepository]) + ) val dynamoReads = config.provisionedReads val dynamoWrites = config.provisionedWrites @@ -63,7 +65,8 @@ object DynamoDBGroupChangeRepository { .withProvisionedThroughput(new ProvisionedThroughput(dynamoReads, dynamoWrites)) .withKeySchema( new KeySchemaElement(GROUP_ID, KeyType.HASH), - new KeySchemaElement(CREATED, KeyType.RANGE)) + new KeySchemaElement(CREATED, KeyType.RANGE) + ) .withProjection(new Projection().withProjectionType("ALL")) ) @@ -82,8 +85,8 @@ object DynamoDBGroupChangeRepository { class DynamoDBGroupChangeRepository private[repository] ( groupChangeTableName: String, - val dynamoDBHelper: DynamoDBHelper) - extends GroupChangeRepository + val dynamoDBHelper: DynamoDBHelper +) extends GroupChangeRepository with Monitored with GroupProtobufConversions { @@ -114,7 +117,8 @@ class DynamoDBGroupChangeRepository private[repository] ( def getGroupChanges( groupId: String, startFrom: Option[String], - maxItems: Int): IO[ListGroupChangesResults] = + maxItems: Int + ): IO[ListGroupChangesResults] = monitor("repo.GroupChange.getGroupChanges") { log.info("Getting groupChanges") @@ -143,8 +147,8 @@ class DynamoDBGroupChangeRepository private[repository] ( dynamoDBHelper.query(queryRequest).map { queryResult => val items = queryResult.getItems().asScala.map(fromItem).toList - val lastEvaluatedId = Option(queryResult.getLastEvaluatedKey).flatMap(key => - key.asScala.get(CREATED).map(_.getN)) + val lastEvaluatedId = Option(queryResult.getLastEvaluatedKey) + .flatMap(key => key.asScala.get(CREATED).map(_.getN)) ListGroupChangesResults(items, lastEvaluatedId) } } diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepository.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepository.scala index 82e5cf1b5..a68fd93a4 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepository.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepository.scala @@ -44,11 +44,13 @@ object DynamoDBGroupRepository { def apply( config: DynamoDBRepositorySettings, - dynamoConfig: DynamoDBDataStoreSettings): IO[DynamoDBGroupRepository] = { + dynamoConfig: DynamoDBDataStoreSettings + ): IO[DynamoDBGroupRepository] = { val dynamoDBHelper = new DynamoDBHelper( DynamoDBClient(dynamoConfig), - LoggerFactory.getLogger(classOf[DynamoDBGroupRepository])) + LoggerFactory.getLogger(classOf[DynamoDBGroupRepository]) + ) val dynamoReads = config.provisionedReads val dynamoWrites = config.provisionedWrites @@ -82,8 +84,8 @@ object DynamoDBGroupRepository { class DynamoDBGroupRepository private[repository] ( groupTableName: String, - val dynamoDBHelper: DynamoDBHelper) - extends GroupRepository + val dynamoDBHelper: DynamoDBHelper +) extends GroupRepository with Monitored { import DynamoDBGroupRepository._ diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBHelper.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBHelper.scala index a8eb6afde..5f5a36b5a 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBHelper.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBHelper.scala @@ -64,14 +64,16 @@ class DynamoDBHelper(dynamoDB: AmazonDynamoDBClient, log: Logger) { def createTableIfNotExists( dynamoDB: AmazonDynamoDBClient, - req: CreateTableRequest): IO[Boolean] = + req: CreateTableRequest + ): IO[Boolean] = IO(TableUtils.createTableIfNotExists(dynamoDB, req)) } def shutdown(): Unit = dynamoDB.shutdown() private[repository] def send[In <: AmazonWebServiceRequest, Out](aws: In, func: In => Out)( - implicit d: Describe[_ >: In]): IO[Out] = { + implicit d: Describe[_ >: In] + ): IO[Out] = { def name = d.desc(aws) @@ -198,7 +200,8 @@ class DynamoDBHelper(dynamoDB: AmazonDynamoDBClient, log: Logger) { private def continueScanning( request: ScanRequest, result: ScanResult, - acc: (List[ScanResult], Int)): IO[(List[ScanResult], Int)] = + acc: (List[ScanResult], Int) + ): IO[(List[ScanResult], Int)] = result.getLastEvaluatedKey match { case lastEvaluatedKey if lastEvaluatedKey == null || lastEvaluatedKey.isEmpty => @@ -227,7 +230,8 @@ class DynamoDBHelper(dynamoDB: AmazonDynamoDBClient, log: Logger) { private def continueQuerying( request: QueryRequest, result: QueryResult, - acc: List[QueryResult]): IO[List[QueryResult]] = { + acc: List[QueryResult] + ): IO[List[QueryResult]] = { val lastCount = result.getCount val limit = @@ -253,8 +257,10 @@ class DynamoDBHelper(dynamoDB: AmazonDynamoDBClient, log: Logger) { // re-run the query, continue querying if need be, be sure to accumulate the result query(continuedQuery) - .flatMap(continuedResult => - continueQuerying(continuedQuery, continuedResult, acc :+ continuedResult)) + .flatMap( + continuedResult => + continueQuerying(continuedQuery, continuedResult, acc :+ continuedResult) + ) } } @@ -265,7 +271,8 @@ class DynamoDBHelper(dynamoDB: AmazonDynamoDBClient, log: Logger) { table: String, aws: BatchWriteItemRequest, retries: Int = 10, - backoff: FiniteDuration = 1.millis): IO[BatchWriteItemResult] = + backoff: FiniteDuration = 1.millis + ): IO[BatchWriteItemResult] = send[BatchWriteItemRequest, BatchWriteItemResult](aws, dynamoDB.batchWriteItem) .flatMap(r => sendUnprocessedBatchWriteItems(table, r, retries, backoff)) @@ -273,7 +280,8 @@ class DynamoDBHelper(dynamoDB: AmazonDynamoDBClient, log: Logger) { toBatchWriteItemRequest(Collections.singletonMap(tableName, writes.asJava)) def toBatchWriteItemRequest( - writes: java.util.Map[String, java.util.List[WriteRequest]]): BatchWriteItemRequest = + writes: java.util.Map[String, java.util.List[WriteRequest]] + ): BatchWriteItemRequest = new BatchWriteItemRequest() .withRequestItems(writes) .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL) @@ -302,12 +310,14 @@ class DynamoDBHelper(dynamoDB: AmazonDynamoDBClient, log: Logger) { // there are unprocessed items still remaining, but we have exhausted our retries, consider this FAILED log.error("Exhausted retries while sending batch write") throw DynamoDBRetriesExhaustedException( - s"Unable to batch write for table $tableName after retries") + s"Unable to batch write for table $tableName after retries" + ) } else { // there are unprocessed items and we have retries left, let's retry those items we haven't yet processed log.warn( s"Unable to process all items in batch for table $tableName, resubmitting new batch with $unprocessed " + - s"items remaining") + s"items remaining" + ) val nextBatch = toBatchWriteItemRequest(result.getUnprocessedItems) IO.sleep(backoff) *> batchWriteItem(tableName, nextBatch, retriesRemaining - 1, backoff * 2) } diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBMembershipRepository.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBMembershipRepository.scala index 027e79fb3..bbaccf0e4 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBMembershipRepository.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBMembershipRepository.scala @@ -34,11 +34,13 @@ object DynamoDBMembershipRepository { def apply( config: DynamoDBRepositorySettings, - dynamoConfig: DynamoDBDataStoreSettings): IO[DynamoDBMembershipRepository] = { + dynamoConfig: DynamoDBDataStoreSettings + ): IO[DynamoDBMembershipRepository] = { val dynamoDBHelper = new DynamoDBHelper( DynamoDBClient(dynamoConfig), - LoggerFactory.getLogger("DynamoDBMembershipRepository")) + LoggerFactory.getLogger("DynamoDBMembershipRepository") + ) val dynamoReads = config.provisionedReads val dynamoWrites = config.provisionedWrites @@ -55,7 +57,8 @@ object DynamoDBMembershipRepository { .withAttributeDefinitions(tableAttributes: _*) .withKeySchema( new KeySchemaElement(USER_ID, KeyType.HASH), - new KeySchemaElement(GROUP_ID, KeyType.RANGE)) + new KeySchemaElement(GROUP_ID, KeyType.RANGE) + ) .withProvisionedThroughput(new ProvisionedThroughput(dynamoReads, dynamoWrites)) ) @@ -65,8 +68,8 @@ object DynamoDBMembershipRepository { class DynamoDBMembershipRepository private[repository] ( membershipTable: String, - dynamoDBHelper: DynamoDBHelper) - extends MembershipRepository + dynamoDBHelper: DynamoDBHelper +) extends MembershipRepository with Monitored { import DynamoDBMembershipRepository._ @@ -123,8 +126,9 @@ class DynamoDBMembershipRepository private[repository] ( result.map(_ => memberUserIds) } - private def executeBatch(items: Iterable[java.util.Map[String, AttributeValue]])( - f: java.util.Map[String, AttributeValue] => WriteRequest): IO[List[BatchWriteItemResult]] = { + private def executeBatch( + items: Iterable[java.util.Map[String, AttributeValue]] + )(f: java.util.Map[String, AttributeValue] => WriteRequest): IO[List[BatchWriteItemResult]] = { val MaxDynamoBatchWriteSize = 25 val batchWrites = items.toList @@ -134,7 +138,8 @@ class DynamoDBMembershipRepository private[repository] ( itemGroup => new BatchWriteItemRequest() .withRequestItems(Collections.singletonMap(membershipTable, itemGroup.asJava)) - .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL)) + .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL) + ) // Fold left will attempt each batch sequentially, and fail fast on error batchWrites.foldLeft(IO.pure(List.empty[BatchWriteItemResult])) { @@ -147,7 +152,8 @@ class DynamoDBMembershipRepository private[repository] ( private[repository] def toItem( userId: String, - groupId: String): java.util.Map[String, AttributeValue] = { + groupId: String + ): java.util.Map[String, AttributeValue] = { val item = new java.util.HashMap[String, AttributeValue]() item.put(USER_ID, new AttributeValue(userId)) item.put(GROUP_ID, new AttributeValue(groupId)) diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepository.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepository.scala index bec2b6272..fc8699516 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepository.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepository.scala @@ -48,11 +48,13 @@ object DynamoDBRecordChangeRepository { def apply( config: DynamoDBRepositorySettings, - dynamoConfig: DynamoDBDataStoreSettings): IO[DynamoDBRecordChangeRepository] = { + dynamoConfig: DynamoDBDataStoreSettings + ): IO[DynamoDBRecordChangeRepository] = { val dynamoDBHelper = new DynamoDBHelper( DynamoDBClient(dynamoConfig), - LoggerFactory.getLogger("DynamoDBRecordChangeRepository")) + LoggerFactory.getLogger("DynamoDBRecordChangeRepository") + ) val dynamoReads = config.provisionedReads val dynamoWrites = config.provisionedWrites @@ -72,14 +74,16 @@ object DynamoDBRecordChangeRepository { .withProvisionedThroughput(new ProvisionedThroughput(dynamoReads, dynamoWrites)) .withKeySchema( new KeySchemaElement(ZONE_ID, KeyType.HASH), - new KeySchemaElement(RECORD_SET_CHANGE_ID, KeyType.RANGE)) + new KeySchemaElement(RECORD_SET_CHANGE_ID, KeyType.RANGE) + ) .withProjection(new Projection().withProjectionType("ALL")), new GlobalSecondaryIndex() .withIndexName(ZONE_ID_CREATED_INDEX) .withProvisionedThroughput(new ProvisionedThroughput(dynamoReads, dynamoWrites)) .withKeySchema( new KeySchemaElement(ZONE_ID, KeyType.HASH), - new KeySchemaElement(RECORD_SET_CHANGE_CREATED_TIMESTAMP, KeyType.RANGE)) + new KeySchemaElement(RECORD_SET_CHANGE_CREATED_TIMESTAMP, KeyType.RANGE) + ) .withProjection(new Projection().withProjectionType("ALL")) ) @@ -98,8 +102,8 @@ object DynamoDBRecordChangeRepository { class DynamoDBRecordChangeRepository private[repository] ( recordChangeTable: String, - val dynamoDBHelper: DynamoDBHelper) - extends RecordChangeRepository + val dynamoDBHelper: DynamoDBHelper +) extends RecordChangeRepository with ProtobufConversions with Monitored { @@ -137,7 +141,8 @@ class DynamoDBRecordChangeRepository private[repository] ( def listRecordSetChanges( zoneId: String, startFrom: Option[String] = None, - maxItems: Int = 100): IO[ListRecordSetChangesResults] = + maxItems: Int = 100 + ): IO[ListRecordSetChangesResults] = monitor("repo.RecordChange.getRecordSetChanges") { log.info(s"Getting record set changes for zone $zoneId") @@ -171,7 +176,8 @@ class DynamoDBRecordChangeRepository private[repository] ( val nextId = Try( resultList.last.getLastEvaluatedKey .get("record_set_change_created_timestamp") - .getN).toOption + .getN + ).toOption ListRecordSetChangesResults(items, nextId, startFrom, maxItems) } } @@ -214,7 +220,8 @@ class DynamoDBRecordChangeRepository private[repository] ( def toItem( changeSet: ChangeSet, - change: RecordSetChange): java.util.HashMap[String, AttributeValue] = { + change: RecordSetChange + ): java.util.HashMap[String, AttributeValue] = { val item = new java.util.HashMap[String, AttributeValue]() item.put(CHANGE_SET_ID, new AttributeValue(changeSet.id)) item.put(ZONE_ID, new AttributeValue(changeSet.zoneId)) @@ -222,7 +229,8 @@ class DynamoDBRecordChangeRepository private[repository] ( item.put(CREATED_TIMESTAMP, new AttributeValue(changeSet.createdTimestamp.toString)) item.put( RECORD_SET_CHANGE_CREATED_TIMESTAMP, - new AttributeValue().withN(change.created.getMillis.toString)) + new AttributeValue().withN(change.created.getMillis.toString) + ) item.put(PROCESSING_TIMESTAMP, new AttributeValue(changeSet.processingTimestamp.toString)) val recordSetChangeBlob = toPB(change).toByteArray diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepository.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepository.scala index 7e952854d..eb89829c6 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepository.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepository.scala @@ -41,11 +41,13 @@ object DynamoDBRecordSetRepository extends ProtobufConversions { def apply( config: DynamoDBRepositorySettings, - dynamoConfig: DynamoDBDataStoreSettings): IO[DynamoDBRecordSetRepository] = { + dynamoConfig: DynamoDBDataStoreSettings + ): IO[DynamoDBRecordSetRepository] = { val dynamoDBHelper = new DynamoDBHelper( DynamoDBClient(dynamoConfig), - LoggerFactory.getLogger("DynamoDBRecordSetRepository")) + LoggerFactory.getLogger("DynamoDBRecordSetRepository") + ) val dynamoReads = config.provisionedReads val dynamoWrites = config.provisionedWrites @@ -64,14 +66,16 @@ object DynamoDBRecordSetRepository extends ProtobufConversions { .withProvisionedThroughput(new ProvisionedThroughput(dynamoReads, dynamoWrites)) .withKeySchema( new KeySchemaElement(ZONE_ID, KeyType.HASH), - new KeySchemaElement(RECORD_SET_NAME, KeyType.RANGE)) + new KeySchemaElement(RECORD_SET_NAME, KeyType.RANGE) + ) .withProjection(new Projection().withProjectionType("ALL")), new GlobalSecondaryIndex() .withIndexName(ZONE_ID_RECORD_SET_SORT_INDEX) .withProvisionedThroughput(new ProvisionedThroughput(dynamoReads, dynamoWrites)) .withKeySchema( new KeySchemaElement(ZONE_ID, KeyType.HASH), - new KeySchemaElement(RECORD_SET_SORT, KeyType.RANGE)) + new KeySchemaElement(RECORD_SET_SORT, KeyType.RANGE) + ) .withProjection(new Projection().withProjectionType("ALL")) ) @@ -90,8 +94,8 @@ object DynamoDBRecordSetRepository extends ProtobufConversions { class DynamoDBRecordSetRepository private[repository] ( val recordSetTableName: String, - val dynamoDBHelper: DynamoDBHelper) - extends RecordSetRepository + val dynamoDBHelper: DynamoDBHelper +) extends RecordSetRepository with DynamoDBRecordSetConversions with Monitored with QueryHelper { @@ -103,7 +107,8 @@ class DynamoDBRecordSetRepository private[repository] ( def apply(changeSet: ChangeSet): IO[ChangeSet] = monitor("repo.RecordSet.apply") { log.info( - s"Applying change set for zone ${changeSet.zoneId} with size ${changeSet.changes.size}") + s"Applying change set for zone ${changeSet.zoneId} with size ${changeSet.changes.size}" + ) // The BatchWriteItem max size is 25, so we need to group by that number val MaxBatchWriteGroup = 25 @@ -134,20 +139,23 @@ class DynamoDBRecordSetRepository private[repository] ( zoneId: String, startFrom: Option[String], maxItems: Option[Int], - recordNameFilter: Option[String]): IO[ListRecordSetResults] = + recordNameFilter: Option[String] + ): IO[ListRecordSetResults] = monitor("repo.RecordSet.listRecordSets") { log.info(s"Getting recordSets for zone $zoneId") val keyConditions = Map[String, String](ZONE_ID -> zoneId) - val filterExpression = recordNameFilter.map(filter => - ContainsFilter(RECORD_SET_SORT, omitTrailingDot(filter.toLowerCase))) + val filterExpression = recordNameFilter.map( + filter => ContainsFilter(RECORD_SET_SORT, omitTrailingDot(filter.toLowerCase)) + ) val startKey = startFrom.map { inputString => val attributes = inputString.split('~') Map( ZONE_ID -> attributes(0), RECORD_SET_NAME -> attributes(1), - RECORD_SET_ID -> attributes(2)) + RECORD_SET_ID -> attributes(2) + ) } val responseFuture = doQuery( recordSetTableName, @@ -155,7 +163,8 @@ class DynamoDBRecordSetRepository private[repository] ( keyConditions, filterExpression, startKey, - maxItems)(dynamoDBHelper) + maxItems + )(dynamoDBHelper) for { resp <- responseFuture @@ -165,7 +174,8 @@ class DynamoDBRecordSetRepository private[repository] ( List( keyMap.get(ZONE_ID).getS, keyMap.get(RECORD_SET_NAME).getS, - keyMap.get(RECORD_SET_ID).getS).mkString("~") + keyMap.get(RECORD_SET_ID).getS + ).mkString("~") } } yield ListRecordSetResults(rs, nextId, startFrom, maxItems, recordNameFilter) } @@ -176,7 +186,8 @@ class DynamoDBRecordSetRepository private[repository] ( val keyConditions = Map[String, String]( ZONE_ID -> zoneId, - RECORD_SET_SORT -> omitTrailingDot(name.toLowerCase())) + RECORD_SET_SORT -> omitTrailingDot(name.toLowerCase()) + ) val responseFuture = doQuery(recordSetTableName, ZONE_ID_RECORD_SET_SORT_INDEX, keyConditions)(dynamoDBHelper) @@ -192,11 +203,13 @@ class DynamoDBRecordSetRepository private[repository] ( val keyConditions = Map[String, String]( ZONE_ID -> zoneId, - RECORD_SET_SORT -> omitTrailingDot(name.toLowerCase())) + RECORD_SET_SORT -> omitTrailingDot(name.toLowerCase()) + ) val filterExpression = Some(EqualsFilter(RECORD_SET_TYPE, typ.toString)) val responseFuture = doQuery(recordSetTableName, ZONE_ID_RECORD_SET_SORT_INDEX, keyConditions, filterExpression)( - dynamoDBHelper) + dynamoDBHelper + ) for { resp <- responseFuture @@ -230,7 +243,8 @@ class DynamoDBRecordSetRepository private[repository] ( recordSetTableName, ZONE_ID_RECORD_SET_NAME_INDEX, keyConditions, - isCountQuery = true)(dynamoDBHelper) + isCountQuery = true + )(dynamoDBHelper) responseFuture.map(resp => resp.asInstanceOf[QueryResponseCount].count) } diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBUserChangeRepository.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBUserChangeRepository.scala index 6afaccc4d..ca579cd21 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBUserChangeRepository.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBUserChangeRepository.scala @@ -69,13 +69,15 @@ object DynamoDBUserChangeRepository { item.put(CREATED, new AttributeValue().withN(change.created.getMillis.toString)) item.put( NEW_USER, - new AttributeValue().withM(DynamoDBUserRepository.toItem(crypto, change.newUser))) + new AttributeValue().withM(DynamoDBUserRepository.toItem(crypto, change.newUser)) + ) change match { case UserChange.UpdateUser(_, _, _, oldUser, _) => item.put( OLD_USER, - new AttributeValue().withM(DynamoDBUserRepository.toItem(crypto, oldUser))) + new AttributeValue().withM(DynamoDBUserRepository.toItem(crypto, oldUser)) + ) case _ => () } item @@ -84,11 +86,13 @@ object DynamoDBUserChangeRepository { def apply( config: DynamoDBRepositorySettings, dynamoConfig: DynamoDBDataStoreSettings, - crypto: CryptoAlgebra): IO[DynamoDBUserChangeRepository] = { + crypto: CryptoAlgebra + ): IO[DynamoDBUserChangeRepository] = { val dynamoDBHelper = new DynamoDBHelper( DynamoDBClient(dynamoConfig), - LoggerFactory.getLogger("DynamoDBUserChangeRepository")) + LoggerFactory.getLogger("DynamoDBUserChangeRepository") + ) val setup = dynamoDBHelper.setupTable( @@ -97,13 +101,15 @@ object DynamoDBUserChangeRepository { .withAttributeDefinitions(TABLE_ATTRIBUTES: _*) .withKeySchema(new KeySchemaElement(USER_CHANGE_ID, KeyType.HASH)) .withProvisionedThroughput( - new ProvisionedThroughput(config.provisionedReads, config.provisionedWrites)) + new ProvisionedThroughput(config.provisionedReads, config.provisionedWrites) + ) ) val serialize: UserChange => java.util.Map[String, AttributeValue] = toItem(crypto, _) val deserialize: java.util.Map[String, AttributeValue] => IO[UserChange] = fromItem setup.as( - new DynamoDBUserChangeRepository(config.tableName, dynamoDBHelper, serialize, deserialize)) + new DynamoDBUserChangeRepository(config.tableName, dynamoDBHelper, serialize, deserialize) + ) } } @@ -111,8 +117,8 @@ class DynamoDBUserChangeRepository private[repository] ( tableName: String, val dynamoDBHelper: DynamoDBHelper, serialize: UserChange => java.util.Map[String, AttributeValue], - deserialize: java.util.Map[String, AttributeValue] => IO[UserChange]) - extends UserChangeRepository + deserialize: java.util.Map[String, AttributeValue] => IO[UserChange] +) extends UserChangeRepository with Monitored { import DynamoDBUserChangeRepository._ diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBUserRepository.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBUserRepository.scala index 80e1e5133..5f41f0980 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBUserRepository.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBUserRepository.scala @@ -56,11 +56,13 @@ object DynamoDBUserRepository { def apply( config: DynamoDBRepositorySettings, dynamoConfig: DynamoDBDataStoreSettings, - crypto: CryptoAlgebra): IO[DynamoDBUserRepository] = { + crypto: CryptoAlgebra + ): IO[DynamoDBUserRepository] = { val dynamoDBHelper = new DynamoDBHelper( DynamoDBClient(dynamoConfig), - LoggerFactory.getLogger("DynamoDBUserRepository")) + LoggerFactory.getLogger("DynamoDBUserRepository") + ) val dynamoReads = config.provisionedReads val dynamoWrites = config.provisionedWrites @@ -149,8 +151,8 @@ class DynamoDBUserRepository private[repository] ( userTableName: String, val dynamoDBHelper: DynamoDBHelper, serialize: User => java.util.Map[String, AttributeValue], - deserialize: java.util.Map[String, AttributeValue] => IO[User]) - extends UserRepository + deserialize: java.util.Map[String, AttributeValue] => IO[User] +) extends UserRepository with Monitored { import DynamoDBUserRepository._ @@ -198,7 +200,8 @@ class DynamoDBUserRepository private[repository] ( def getUsers( userIds: Set[String], startFrom: Option[String], - maxItems: Option[Int]): IO[ListUsersResults] = { + maxItems: Option[Int] + ): IO[ListUsersResults] = { def toBatchGetItemRequest(userIds: List[String]): BatchGetItemRequest = { val allKeys = new util.ArrayList[util.Map[String, AttributeValue]]() @@ -274,7 +277,8 @@ class DynamoDBUserRepository private[repository] ( monitor("repo.User.getAllUsers") { IO.raiseError( UnsupportedDynamoDBRepoFunction( - "getAllUsers is not supported by VinylDNS DynamoDB UserRepository") + "getAllUsers is not supported by VinylDNS DynamoDB UserRepository" + ) ) } @@ -312,7 +316,8 @@ class DynamoDBUserRepository private[repository] ( monitor("repo.User.save") { IO.raiseError( UnsupportedDynamoDBRepoFunction( - "batch save is not supported by VinylDNS DynamoDb UserRepository") + "batch save is not supported by VinylDNS DynamoDb UserRepository" + ) ) } } diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBZoneChangeRepository.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBZoneChangeRepository.scala index f7606050b..3bdce54b3 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBZoneChangeRepository.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/DynamoDBZoneChangeRepository.scala @@ -42,11 +42,13 @@ object DynamoDBZoneChangeRepository extends ProtobufConversions { def apply( config: DynamoDBRepositorySettings, - dynamoConfig: DynamoDBDataStoreSettings): IO[DynamoDBZoneChangeRepository] = { + dynamoConfig: DynamoDBDataStoreSettings + ): IO[DynamoDBZoneChangeRepository] = { val dynamoDBHelper = new DynamoDBHelper( DynamoDBClient(dynamoConfig), - LoggerFactory.getLogger("DynamoDBZoneChangeRepository")) + LoggerFactory.getLogger("DynamoDBZoneChangeRepository") + ) val dynamoReads = config.provisionedReads val dynamoWrites = config.provisionedWrites @@ -64,7 +66,8 @@ object DynamoDBZoneChangeRepository extends ProtobufConversions { .withProvisionedThroughput(new ProvisionedThroughput(dynamoReads, dynamoWrites)) .withKeySchema( new KeySchemaElement(ZONE_ID, KeyType.HASH), - new KeySchemaElement(CREATED, KeyType.RANGE)) + new KeySchemaElement(CREATED, KeyType.RANGE) + ) .withProjection(new Projection().withProjectionType("ALL")) ) @@ -74,7 +77,8 @@ object DynamoDBZoneChangeRepository extends ProtobufConversions { .withAttributeDefinitions(tableAttributes: _*) .withKeySchema( new KeySchemaElement(ZONE_ID, KeyType.HASH), - new KeySchemaElement(CHANGE_ID, KeyType.RANGE)) + new KeySchemaElement(CHANGE_ID, KeyType.RANGE) + ) .withGlobalSecondaryIndexes(secondaryIndexes: _*) .withProvisionedThroughput(new ProvisionedThroughput(dynamoReads, dynamoWrites)) ) @@ -85,8 +89,8 @@ object DynamoDBZoneChangeRepository extends ProtobufConversions { class DynamoDBZoneChangeRepository private[repository] ( zoneChangeTable: String, - val dynamoDBHelper: DynamoDBHelper) - extends ZoneChangeRepository + val dynamoDBHelper: DynamoDBHelper +) extends ZoneChangeRepository with ProtobufConversions with Monitored { @@ -109,7 +113,8 @@ class DynamoDBZoneChangeRepository private[repository] ( def listZoneChanges( zoneId: String, startFrom: Option[String] = None, - maxItems: Int = 100): IO[ListZoneChangesResults] = + maxItems: Int = 100 + ): IO[ListZoneChangesResults] = monitor("repo.ZoneChange.getChanges") { log.info(s"Getting zone changes for zone $zoneId") diff --git a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/QueryHelper.scala b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/QueryHelper.scala index 9e83e0018..5d9901d30 100644 --- a/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/QueryHelper.scala +++ b/modules/dynamodb/src/main/scala/vinyldns/dynamodb/repository/QueryHelper.scala @@ -32,8 +32,8 @@ trait ResponseItems { case class QueryResponseItems( items: List[java.util.Map[String, AttributeValue]] = List(), - lastEvaluatedKey: Option[java.util.Map[String, AttributeValue]] = None) - extends ResponseItems { + lastEvaluatedKey: Option[java.util.Map[String, AttributeValue]] = None +) extends ResponseItems { override def addResult(newResult: QueryResult): QueryResponseItems = QueryResponseItems(items ++ newResult.getItems.asScala, Option(newResult.getLastEvaluatedKey)) @@ -58,8 +58,8 @@ case class QueryResponseItems( case class QueryResponseCount( count: Int = 0, - lastEvaluatedKey: Option[java.util.Map[String, AttributeValue]] = None) - extends ResponseItems { + lastEvaluatedKey: Option[java.util.Map[String, AttributeValue]] = None +) extends ResponseItems { override def addResult(newResult: QueryResult): QueryResponseCount = QueryResponseCount(count + newResult.getCount, Option(newResult.getLastEvaluatedKey)) @@ -93,7 +93,8 @@ object QueryManager { filter: Option[FilterType], initialStartKey: Option[Map[String, String]], maxItems: Option[Int], - isCountQuery: Boolean): QueryManager = { + isCountQuery: Boolean + ): QueryManager = { val expressionAttributeValues = new HashMap[String, AttributeValue] val expressionAttributeNames = new HashMap[String, String] @@ -129,7 +130,8 @@ object QueryManager { start, filterExpression, maxItems, - isCountQuery) + isCountQuery + ) } } @@ -142,7 +144,8 @@ case class QueryManager( startKey: Option[util.Map[String, AttributeValue]], filterExpression: Option[String], maxItems: Option[Int], - isCountQuery: Boolean) { + isCountQuery: Boolean +) { def build(): QueryRequest = { val request = new QueryRequest() @@ -170,7 +173,8 @@ trait QueryHelper { filter: Option[FilterType] = None, startKey: Option[Map[String, String]] = None, maxItems: Option[Int] = None, - isCountQuery: Boolean = false): DynamoDBHelper => IO[ResponseItems] = dynamoDbHelper => { + isCountQuery: Boolean = false + ): DynamoDBHelper => IO[ResponseItems] = dynamoDbHelper => { // do not limit items when there is a filter - filters are applied after limits val itemsToRetrieve = filter match { case Some(_) => None @@ -190,7 +194,8 @@ trait QueryHelper { dynamoDbHelper: DynamoDBHelper, dynamoQuery: QueryManager, acc: ResponseItems, - limit: Option[Int]): IO[ResponseItems] = + limit: Option[Int] + ): IO[ResponseItems] = dynamoDbHelper.query(dynamoQuery.build()).flatMap { queryResult => val accumulatedResults = acc.addResult(queryResult) if (accumulatedResults.isComplete(limit)) @@ -200,6 +205,7 @@ trait QueryHelper { dynamoDbHelper, dynamoQuery.copy(startKey = Some(queryResult.getLastEvaluatedKey)), accumulatedResults, - limit) + limit + ) } } diff --git a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProviderSpec.scala b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProviderSpec.scala index 545c2cd74..20dd00949 100644 --- a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProviderSpec.scala +++ b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBDataStoreProviderSpec.scala @@ -51,7 +51,8 @@ class DynamoDBDataStoreProviderSpec extends WordSpec with Matchers { | provisioned-writes = 30 | } | } - | """.stripMargin) + | """.stripMargin + ) val badSettings = pureconfig.loadConfigOrThrow[DataStoreConfig](badConfig) @@ -99,7 +100,8 @@ class DynamoDBDataStoreProviderSpec extends WordSpec with Matchers { None, None, None, - None) + None + ) val response = underTest .loadRepoConfigs(repoSettings) .unsafeRunSync() @@ -126,7 +128,8 @@ class DynamoDBDataStoreProviderSpec extends WordSpec with Matchers { None, None, None, - None) + None + ) a[pureconfig.error.ConfigReaderException[DynamoDBRepositorySettings]] should be thrownBy underTest .loadRepoConfigs(repoSettings) diff --git a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepositorySpec.scala b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepositorySpec.scala index b7b1af205..59c9b26ed 100644 --- a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepositorySpec.scala +++ b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBGroupChangeRepositorySpec.scala @@ -130,7 +130,8 @@ class DynamoDBGroupChangeRepositorySpec response.changes should contain theSameElementsAs listOfDummyGroupChanges.take(100) response.lastEvaluatedTimeStamp shouldBe Some( - listOfDummyGroupChanges(99).created.getMillis.toString) + listOfDummyGroupChanges(99).created.getMillis.toString + ) } "returns an empty list when no matching changes are found" in { val dynamoResponse = mock[QueryResult] @@ -167,12 +168,14 @@ class DynamoDBGroupChangeRepositorySpec .getGroupChanges( oneUserDummyGroup.id, Some(listOfDummyGroupChanges(50).created.getMillis.toString), - 100) + 100 + ) .unsafeRunSync() response.changes should contain theSameElementsAs listOfDummyGroupChanges.slice(51, 151) response.lastEvaluatedTimeStamp shouldBe Some( - listOfDummyGroupChanges(150).created.getMillis.toString) + listOfDummyGroupChanges(150).created.getMillis.toString + ) } "returns `maxItems` items" in { val dynamoResponse = mock[QueryResult] @@ -189,7 +192,8 @@ class DynamoDBGroupChangeRepositorySpec response.changes should contain theSameElementsAs listOfDummyGroupChanges.take(50) response.lastEvaluatedTimeStamp shouldBe Some( - listOfDummyGroupChanges(49).created.getMillis.toString) + listOfDummyGroupChanges(49).created.getMillis.toString + ) } "returns entire page and nextId = None if there are less than maxItems left" in { diff --git a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepositorySpec.scala b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepositorySpec.scala index 3c1e296ff..dee271635 100644 --- a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepositorySpec.scala +++ b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBGroupRepositorySpec.scala @@ -191,7 +191,8 @@ class DynamoDBGroupRepositorySpec groupsTable -> listOfDummyGroups .slice(0, 100) .map(underTest.toItem) - .asJava).asJava + .asJava + ).asJava doReturn(firstPage).when(firstResponse).getResponses val secondResponse = mock[BatchGetItemResult] @@ -199,7 +200,8 @@ class DynamoDBGroupRepositorySpec groupsTable -> listOfDummyGroups .slice(100, 200) .map(underTest.toItem) - .asJava).asJava + .asJava + ).asJava doReturn(secondPage).when(secondResponse).getResponses doReturn(IO.pure(firstResponse)) diff --git a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBHelperSpec.scala b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBHelperSpec.scala index b0e800573..6b1833553 100644 --- a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBHelperSpec.scala +++ b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBHelperSpec.scala @@ -47,7 +47,8 @@ class DynamoDBHelperSpec private val mockDynamoUtils = mock[DynamoUtils] private val ptee: Throwable = new ProvisionedThroughputExceededException( - "provisioned throughput exceeded test") + "provisioned throughput exceeded test" + ) private val testTableName = "test-table" private def excessivelyFail = doThrow(ptee) @@ -88,7 +89,8 @@ class DynamoDBHelperSpec mockRetriesExceededMeter, mockDynamoUnexpectedFailuresMeter, mockCallRateMeter, - mockDynamoUtils) + mockDynamoUtils + ) "DynamoDBHelper" should { "Using Monitoring" should { diff --git a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBMembershipRepositorySpec.scala b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBMembershipRepositorySpec.scala index 4b4f8fd37..05b14f001 100644 --- a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBMembershipRepositorySpec.scala +++ b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBMembershipRepositorySpec.scala @@ -68,7 +68,8 @@ class DynamoDBMembershipRepositorySpec any[String], batchCaptor.capture(), any[Int], - any[FiniteDuration]) + any[FiniteDuration] + ) // we should have 3 batches val batchWrites = batchCaptor.getAllValues @@ -99,7 +100,8 @@ class DynamoDBMembershipRepositorySpec any[String], batchCaptor.capture(), any[Int], - any[FiniteDuration]) + any[FiniteDuration] + ) val batchWrites = batchCaptor.getAllValues batchWrites.get(0).getRequestItems.get(membershipTable).size() shouldBe 20 @@ -144,7 +146,8 @@ class DynamoDBMembershipRepositorySpec any[String], batchCaptor.capture(), any[Int], - any[FiniteDuration]) + any[FiniteDuration] + ) // we should have 3 batches val batchWrites = batchCaptor.getAllValues @@ -175,7 +178,8 @@ class DynamoDBMembershipRepositorySpec any[String], batchCaptor.capture(), any[Int], - any[FiniteDuration]) + any[FiniteDuration] + ) val batchWrites = batchCaptor.getAllValues batchWrites.get(0).getRequestItems.get(membershipTable).size() shouldBe 20 diff --git a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepositorySpec.scala b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepositorySpec.scala index ef22cc560..5b5322ff6 100644 --- a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepositorySpec.scala +++ b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBRecordChangeRepositorySpec.scala @@ -112,8 +112,8 @@ class DynamoDBRecordChangeRepositorySpec when( dynamoDBHelper - .batchWriteItem(any[String], any[BatchWriteItemRequest], any[Int], any[FiniteDuration])) - .thenReturn(IO.pure(dynamoResponse)) + .batchWriteItem(any[String], any[BatchWriteItemRequest], any[Int], any[FiniteDuration]) + ).thenReturn(IO.pure(dynamoResponse)) .thenThrow(new RuntimeException("failed")) //fail on the second batch val result = store.save(changeSet) @@ -144,7 +144,8 @@ class DynamoDBRecordChangeRepositorySpec a[ResourceNotFoundException] should be thrownBy store.getRecordSetChange( zoneActive.id, - pendingCreateAAAA.id) + pendingCreateAAAA.id + ) } "return None if not found" in { val dynamoResponse = mock[QueryResult] diff --git a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepositorySpec.scala b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepositorySpec.scala index 2edd2cb9a..313cbd88e 100644 --- a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepositorySpec.scala +++ b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBRecordSetRepositorySpec.scala @@ -66,7 +66,8 @@ class DynamoDBRecordSetRepositorySpec any[String], any[BatchWriteItemRequest], any[Int], - any[FiniteDuration]) + any[FiniteDuration] + ) response shouldBe pendingChangeSet } @@ -93,7 +94,8 @@ class DynamoDBRecordSetRepositorySpec any[String], any[BatchWriteItemRequest], any[Int], - any[FiniteDuration]) + any[FiniteDuration] + ) verify(dynamoDBHelper, times(3)).toBatchWriteItemRequest(batchCaptor.capture(), anyString) // we should have 3 batches @@ -181,7 +183,8 @@ class DynamoDBRecordSetRepositorySpec zoneId = rsOk.zoneId, startFrom = None, maxItems = None, - recordNameFilter = None) + recordNameFilter = None + ) .unsafeRunSync() verify(dynamoDBHelper).query(any[QueryRequest]) @@ -217,7 +220,8 @@ class DynamoDBRecordSetRepositorySpec zoneId = rsOk.zoneId, startFrom = None, maxItems = None, - recordNameFilter = None) + recordNameFilter = None + ) } } @@ -300,7 +304,8 @@ class DynamoDBRecordSetRepositorySpec a[ResourceNotFoundException] should be thrownBy store.getRecordSets( rsOk.zoneId, rsOk.name, - rsOk.typ) + rsOk.typ + ) } } diff --git a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBUserRepositorySpec.scala b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBUserRepositorySpec.scala index 5c8ea76e3..6e6aba527 100644 --- a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBUserRepositorySpec.scala +++ b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/DynamoDBUserRepositorySpec.scala @@ -51,7 +51,8 @@ class DynamoDBUserRepositorySpec userTable, dynamoDBHelper, DynamoDBUserRepository.toItem(crypto, _), - DynamoDBUserRepository.fromItem) + DynamoDBUserRepository.fromItem + ) override def beforeEach(): Unit = reset(dynamoDBHelper) @@ -232,7 +233,8 @@ class DynamoDBUserRepositorySpec userTable -> listOfDummyUsers .slice(100, 200) .map(toItem(crypto, _)) - .asJava).asJava + .asJava + ).asJava doReturn(secondPage).when(secondResponse).getResponses doReturn(IO.pure(firstResponse)) @@ -303,7 +305,8 @@ class DynamoDBUserRepositorySpec userTable -> listOfDummyUsers .slice(151, 200) .map(toItem(crypto, _)) - .asJava).asJava + .asJava + ).asJava doReturn(firstPage).when(firstResponse).getResponses doReturn(IO.pure(firstResponse)) diff --git a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/QueryHelperSpec.scala b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/QueryHelperSpec.scala index 80449c672..f9e9a7d12 100644 --- a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/QueryHelperSpec.scala +++ b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/QueryHelperSpec.scala @@ -66,7 +66,9 @@ class QueryHelperSpec val result = await[QueryResponseItems]( underTest.doQuery("testName", "testIndex", keyConditions, None, None, Some(3))( - dynamoDBHelper)) + dynamoDBHelper + ) + ) result.lastEvaluatedKey shouldBe None result.items shouldBe expectedItems.asScala @@ -88,7 +90,9 @@ class QueryHelperSpec val result = await[QueryResponseItems]( underTest.doQuery("testName", "testIndex", keyConditions, None, None, Some(3))( - dynamoDBHelper)) + dynamoDBHelper + ) + ) result.lastEvaluatedKey shouldBe Some(key) result.items shouldBe expectedItems.asScala @@ -108,7 +112,8 @@ class QueryHelperSpec filterExpression, Some(Map("key" -> "item3")), None, - false).build() + false + ).build() val firstResponse = mock[QueryResult] val items1 = new util.ArrayList[util.HashMap[String, AttributeValue]]() @@ -130,7 +135,9 @@ class QueryHelperSpec val result = await[QueryResponseItems]( underTest.doQuery("testName", "testIndex", keyConditions, filterExpression, None, Some(4))( - dynamoDBHelper)) + dynamoDBHelper + ) + ) result.lastEvaluatedKey shouldBe Some(makeJavaItem("item4")) result.items shouldBe (items1.asScala ++ items2.asScala).take(4) @@ -150,7 +157,8 @@ class QueryHelperSpec filterExpression, Some(Map("key" -> "item3")), None, - false).build() + false + ).build() val firstResponse = mock[QueryResult] val items1 = new util.ArrayList[util.HashMap[String, AttributeValue]]() @@ -173,7 +181,9 @@ class QueryHelperSpec val result = await[QueryResponseItems]( underTest.doQuery("testName", "testIndex", keyConditions, filterExpression, None, Some(6))( - dynamoDBHelper)) + dynamoDBHelper + ) + ) result.lastEvaluatedKey shouldBe None result.items shouldBe items1.asScala ++ items2.asScala @@ -190,7 +200,9 @@ class QueryHelperSpec val result = await[QueryResponseCount]( underTest .doQuery("testName", "testIndex", keyConditions, None, None, None, isCountQuery = true)( - dynamoDBHelper)) + dynamoDBHelper + ) + ) result.count shouldBe 5 } @@ -214,7 +226,9 @@ class QueryHelperSpec val result = await[QueryResponseCount]( underTest .doQuery("testName", "testIndex", keyConditions, None, None, None, isCountQuery = true)( - dynamoDBHelper)) + dynamoDBHelper + ) + ) result.count shouldBe 7 } diff --git a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/TestDynamoDBHelper.scala b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/TestDynamoDBHelper.scala index 01a918f29..4e05e5a55 100644 --- a/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/TestDynamoDBHelper.scala +++ b/modules/dynamodb/src/test/scala/vinyldns/dynamodb/repository/TestDynamoDBHelper.scala @@ -27,6 +27,7 @@ class TestDynamoDBHelper(dynamoDB: AmazonDynamoDBClient, log: Logger) override private[repository] def send[In <: AmazonWebServiceRequest, Out]( aws: In, - func: (In) => Out)(implicit d: Describe[_ >: In]): IO[Out] = + func: (In) => Out + )(implicit d: Describe[_ >: In]): IO[Out] = IO(func(aws)) } diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/MySqlIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/MySqlIntegrationSpec.scala index 778b12b62..23b1cecb5 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/MySqlIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/MySqlIntegrationSpec.scala @@ -29,11 +29,13 @@ import vinyldns.mysql.repository.MySqlDataStoreProvider trait MySqlIntegrationSpec { def mysqlConfig: Config - lazy val dataStoreConfig: DataStoreConfig = pureconfig.loadConfigOrThrow[DataStoreConfig](mysqlConfig) + lazy val dataStoreConfig: DataStoreConfig = + pureconfig.loadConfigOrThrow[DataStoreConfig](mysqlConfig) lazy val provider = new MySqlDataStoreProvider() - lazy val providerLoad: LoadedDataStore = provider.load(dataStoreConfig, new NoOpCrypto()).unsafeRunSync() + lazy val providerLoad: LoadedDataStore = + provider.load(dataStoreConfig, new NoOpCrypto()).unsafeRunSync() lazy val instance: DataStore = providerLoad.dataStore lazy val batchChangeRepository: BatchChangeRepository = diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/queue/MySqlMessageQueueIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/queue/MySqlMessageQueueIntegrationSpec.scala index 296a14d76..713ac7fb9 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/queue/MySqlMessageQueueIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/queue/MySqlMessageQueueIntegrationSpec.scala @@ -29,26 +29,40 @@ import vinyldns.core.domain.record.RecordSetChange import vinyldns.core.domain.zone.{ZoneChange, ZoneCommand} import vinyldns.core.protobuf.ProtobufConversions import vinyldns.core.queue._ -import vinyldns.mysql.queue.MessageType.{InvalidMessageType, RecordChangeMessageType, ZoneChangeMessageType} -import vinyldns.mysql.queue.MySqlMessageQueue.{InvalidMessageTimeout, MessageAttemptsExceeded, QUEUE_CONNECTION_NAME} +import vinyldns.mysql.queue.MessageType.{ + InvalidMessageType, + RecordChangeMessageType, + ZoneChangeMessageType +} +import vinyldns.mysql.queue.MySqlMessageQueue.{ + InvalidMessageTimeout, + MessageAttemptsExceeded, + QUEUE_CONNECTION_NAME +} import scala.concurrent.duration._ final case class RowData( - id: String, - messageType: Int, - inFlight: Boolean, - createdTime: DateTime, - updatedTime: DateTime, - timeoutSecs: Int, - attempts: Int) + id: String, + messageType: Int, + inFlight: Boolean, + createdTime: DateTime, + updatedTime: DateTime, + timeoutSecs: Int, + attempts: Int +) final case class InvalidMessage(command: ZoneCommand) extends CommandMessage { def id: MessageId = MessageId(command.id) } -class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers - with BeforeAndAfterEach with EitherMatchers with EitherValues with ProtobufConversions { +class MySqlMessageQueueIntegrationSpec + extends WordSpec + with Matchers + with BeforeAndAfterEach + with EitherMatchers + with EitherValues + with ProtobufConversions { import vinyldns.core.TestRecordSetData._ import vinyldns.core.TestZoneData._ @@ -66,7 +80,8 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers private val rsChangeBytes = toPB(rsChange).toByteArray - private val testMessage: MySqlMessage = MySqlMessage(MessageId(rsChange.id), 0, 20.seconds, rsChange) + private val testMessage: MySqlMessage = + MySqlMessage(MessageId(rsChange.id), 0, 20.seconds, rsChange) private val zoneChange: ZoneChange = zoneChangePending @@ -77,24 +92,24 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers override protected def beforeEach(): Unit = clear() - private def insert(id: String, messageType: Int, inFlight: Boolean, - data: Array[Byte], created: DateTime, updated: DateTime, - timeoutSeconds: Int, attempts: Int): Unit = { + private def insert( + id: String, + messageType: Int, + inFlight: Boolean, + data: Array[Byte], + created: DateTime, + updated: DateTime, + timeoutSeconds: Int, + attempts: Int + ): Unit = { NamedDB(QUEUE_CONNECTION_NAME).localTx { implicit s => val inF = if (inFlight) 1 else 0 val insertSql = sql""" |INSERT INTO message_queue(id, message_type, in_flight, created, updated, timeout_seconds, attempts, data) | VALUES (?, ?, ?, ?, ?, ?, ?, ?) """.stripMargin - insertSql.bind( - id, - messageType, - inF, - created, - updated, - timeoutSeconds, - attempts, - data) + insertSql + .bind(id, messageType, inF, created, updated, timeoutSeconds, attempts, data) .update() .apply() } @@ -110,18 +125,22 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers | WhERE id = ? """.stripMargin - findSql.bind(id).map { rs => - RowData( - rs.string(1), - rs.int(2), - rs.boolean(3), - new DateTime(rs.timestamp(4).getTime), - new DateTime(rs.timestamp(5).getTime), - rs.int(6), - rs.int(7) - ) - }.toOption().apply() - } + findSql + .bind(id) + .map { rs => + RowData( + rs.string(1), + rs.int(2), + rs.boolean(3), + new DateTime(rs.timestamp(4).getTime), + new DateTime(rs.timestamp(5).getTime), + rs.int(6), + rs.int(7) + ) + } + .toOption() + .apply() + } "send receive" should { "handle a record change" in { @@ -157,7 +176,7 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers underTest.sendBatch(NonEmptyList.of(rsChange)).unsafeRunSync() underTest.sendBatch(NonEmptyList.of(rsChange)).unsafeRunSync() val r = underTest.receive(MessageCount(8).right.value).unsafeRunSync() - r should have length 1 + (r should have).length(1) r.headOption.map(_.command) shouldBe Some(rsChange) } "be idempotent for a batch" in { @@ -174,7 +193,7 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers // Receive a batch, make sure we only get 4 out, no duplicates val batch = underTest.receive(MessageCount(10).right.value).unsafeRunSync() - batch should have length 4 + (batch should have).length(4) batch.map(_.command) should contain theSameElementsAs List(first, second, third, fourth) } "work in parallel" in { @@ -186,7 +205,8 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers val gets = for { _ <- 0 to 8 } yield underTest.receive(MessageCount(1).right.value) // let's fire them both off, doesn't matter who finishes, as long as the IO does not fail - val result = IO.race(sends.toList.parSequence, gets.toList.parSequence).attempt.unsafeRunSync() + val result = + IO.race(sends.toList.parSequence, gets.toList.parSequence).attempt.unsafeRunSync() result shouldBe right } } @@ -197,17 +217,30 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers result.left.value shouldBe (InvalidMessageType(-2), MessageId("foo")) } "fail on invalid bytes" in { - val result = underTest.parseMessage(MessageId("foo"), ZoneChangeMessageType.value, "bar".getBytes, 1, 10) + val result = + underTest.parseMessage(MessageId("foo"), ZoneChangeMessageType.value, "bar".getBytes, 1, 10) val (err, id) = result.left.value id shouldBe MessageId("foo") err shouldBe an[Exception] } "fail if attempts exceeds 100" in { - val result = underTest.parseMessage(MessageId("foo"), RecordChangeMessageType.value, rsChangeBytes, 200, 10) + val result = underTest.parseMessage( + MessageId("foo"), + RecordChangeMessageType.value, + rsChangeBytes, + 200, + 10 + ) result.left.value shouldBe (MessageAttemptsExceeded("foo"), MessageId("foo")) } "fail on invalid timeout" in { - val result = underTest.parseMessage(MessageId("foo"), RecordChangeMessageType.value, rsChangeBytes, 1, -1) + val result = underTest.parseMessage( + MessageId("foo"), + RecordChangeMessageType.value, + rsChangeBytes, + 1, + -1 + ) result.left.value shouldBe (InvalidMessageTimeout(-1), MessageId("foo")) } } @@ -220,13 +253,31 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers findMessage("foo") should not be defined } "drop messages that have invalid message data" in { - insert(rsChange.id, RecordChangeMessageType.value, false, "blah".getBytes, DateTime.now, DateTime.now, 100, 0) + insert( + rsChange.id, + RecordChangeMessageType.value, + false, + "blah".getBytes, + DateTime.now, + DateTime.now, + 100, + 0 + ) underTest.receive(MessageCount(1).right.value).unsafeRunSync() findMessage(rsChange.id) should not be defined } "drop messages that have expired" in { - insert(rsChange.id, RecordChangeMessageType.value, false, "blah".getBytes, DateTime.now, DateTime.now, 100, 101) + insert( + rsChange.id, + RecordChangeMessageType.value, + false, + "blah".getBytes, + DateTime.now, + DateTime.now, + 100, + 101 + ) underTest.receive(MessageCount(1).right.value).unsafeRunSync() findMessage(rsChange.id) should not be defined @@ -234,8 +285,16 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers "increment the attempt, timestamp, and in flight status" in { val initialAttempts = 0 val initialTs = DateTime.now.minusSeconds(20) - insert(rsChange.id, RecordChangeMessageType.value, false, rsChangeBytes, initialTs, initialTs, 100, - initialAttempts) + insert( + rsChange.id, + RecordChangeMessageType.value, + false, + rsChangeBytes, + initialTs, + initialTs, + 100, + initialAttempts + ) val oldMsg = findMessage(rsChange.id).getOrElse(fail) underTest.receive(MessageCount(1).right.value).unsafeRunSync() @@ -248,9 +307,18 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers "grab messages that are in flight but expired" in { // put a message in whose updated timestamp was 100 seconds ago, set the timeout to 30 seconds val initialTs = DateTime.now.minusSeconds(100) - insert(rsChange.id, RecordChangeMessageType.value, true, rsChangeBytes, initialTs, initialTs, 30, 1) + insert( + rsChange.id, + RecordChangeMessageType.value, + true, + rsChangeBytes, + initialTs, + initialTs, + 30, + 1 + ) val msgs = underTest.receive(MessageCount(1).right.value).unsafeRunSync() - msgs should have length 1 + (msgs should have).length(1) } } @@ -272,7 +340,7 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers underTest.changeMessageTimeout(testMessage, 1.seconds).unsafeRunSync() Thread.sleep(2000) val r2 = underTest.receive(MessageCount(1).right.value).unsafeRunSync() - r2 should have length 1 + (r2 should have).length(1) r.headOption.map(_.id) shouldBe r2.headOption.map(_.id) } "do nothing if the message does not exist" in { @@ -297,7 +365,16 @@ class MySqlMessageQueueIntegrationSpec extends WordSpec with Matchers "requeue" should { "reset the message in the database" in { val initialTs = DateTime.now.minusSeconds(20) - insert(rsChange.id, RecordChangeMessageType.value, false, rsChangeBytes, initialTs, initialTs, 100, 0) + insert( + rsChange.id, + RecordChangeMessageType.value, + false, + rsChangeBytes, + initialTs, + initialTs, + 100, + 0 + ) val r = underTest.receive(MessageCount(1).right.value).unsafeRunSync() val msg = r.headOption.getOrElse(fail) underTest.requeue(msg).unsafeRunSync() diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlBatchChangeRepositoryIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlBatchChangeRepositoryIntegrationSpec.scala index ff1548460..e45667bbb 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlBatchChangeRepositoryIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlBatchChangeRepositoryIntegrationSpec.scala @@ -47,7 +47,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec recordType: RecordType, recordData: RecordData, status: SingleChangeStatus = Pending, - errors: List[SingleChangeError] = List.empty): SingleAddChange = + errors: List[SingleChangeError] = List.empty + ): SingleAddChange = SingleAddChange( Some(okZone.id), Some(okZone.name), @@ -60,7 +61,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec None, None, None, - errors) + errors + ) val deleteChange: SingleDeleteRRSetChange = SingleDeleteRRSetChange( @@ -73,7 +75,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec Pending, None, None, - None) + None + ) def randomChangeList: List[SingleChange] = List( @@ -81,7 +84,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec A, AData("1.2.3.4"), NeedsReview, - List(SingleChangeError(ZoneDiscoveryError("test err")))), + List(SingleChangeError(ZoneDiscoveryError("test err"))) + ), generateSingleAddChange(A, AData("1.2.3.40"), Complete), generateSingleAddChange(AAAA, AAAAData("2001:558:feed:beef:0:0:0:1"), Pending), deleteChange.copy(id = UUID.randomUUID().toString) @@ -109,8 +113,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec val pendingBatchChange: BatchChange = randomBatchChange().copy(createdTimestamp = DateTime.now) val completeBatchChange: BatchChange = randomBatchChangeWithList( - randomBatchChange().changes.map(_.complete("recordChangeId", "recordSetId"))) - .copy(createdTimestamp = DateTime.now.plusMillis(1000)) + randomBatchChange().changes.map(_.complete("recordChangeId", "recordSetId")) + ).copy(createdTimestamp = DateTime.now.plusMillis(1000)) val failedBatchChange: BatchChange = randomBatchChangeWithList(randomBatchChange().changes.map(_.withFailureMessage("failed"))) @@ -121,15 +125,16 @@ class MySqlBatchChangeRepositoryIntegrationSpec ++ randomBatchChange().changes.drop(2).map(_.withFailureMessage("failed")) ).copy(createdTimestamp = DateTime.now.plusMillis(1000000)) - val rejectedBatchChange: BatchChange = randomBatchChangeWithList( - randomBatchChange().changes.map(_.reject)) - .copy(createdTimestamp = DateTime.now.plusMillis(10000000)) + val rejectedBatchChange: BatchChange = + randomBatchChangeWithList(randomBatchChange().changes.map(_.reject)) + .copy(createdTimestamp = DateTime.now.plusMillis(10000000)) // listing/ordering changes val timeBase: DateTime = DateTime.now val change_one: BatchChange = pendingBatchChange.copy( createdTimestamp = timeBase, - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) val change_two: BatchChange = completeBatchChange.copy(createdTimestamp = timeBase.plus(1000), ownerGroupId = None) val otherUserBatchChange: BatchChange = @@ -138,8 +143,10 @@ class MySqlBatchChangeRepositoryIntegrationSpec val change_four: BatchChange = partialFailureBatchChange.copy(createdTimestamp = timeBase.plus(1000000)) val change_five: BatchChange = - rejectedBatchChange.copy(createdTimestamp = timeBase.plus(10000000), - approvalStatus = BatchChangeApprovalStatus.ManuallyRejected) + rejectedBatchChange.copy( + createdTimestamp = timeBase.plus(10000000), + approvalStatus = BatchChangeApprovalStatus.ManuallyRejected + ) } import TestData._ @@ -195,7 +202,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec private def areSame( actual: BatchChangeSummaryList, - expected: BatchChangeSummaryList): Assertion = { + expected: BatchChangeSummaryList + ): Assertion = { forAll(actual.batchChanges.zip(expected.batchChanges)) { case (a, e) => areSame(a, e) } actual.batchChanges.length shouldBe expected.batchChanges.length actual.startFrom shouldBe expected.startFrom @@ -251,7 +259,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec ownerGroupId = None, reviewerId = None, reviewComment = None, - reviewTimestamp = None) + reviewTimestamp = None + ) val f = for { _ <- repo.save(testBatch) @@ -313,7 +322,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec val savedTs = DateTime.now.secondOfDay().roundFloorCopy() val chg = randomBatchChange().copy( scheduledTime = Some(savedTs), - approvalStatus = BatchChangeApprovalStatus.PendingReview) + approvalStatus = BatchChangeApprovalStatus.PendingReview + ) val saved = for { @@ -487,7 +497,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec retrieved <- repo.getBatchChangeSummaries( None, - approvalStatus = Some(BatchChangeApprovalStatus.PendingReview)) + approvalStatus = Some(BatchChangeApprovalStatus.PendingReview) + ) } yield retrieved // from most recent descending @@ -516,7 +527,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec BatchChangeSummary(change_four), BatchChangeSummary(change_three), BatchChangeSummary(change_two), - BatchChangeSummary(change_one)) + BatchChangeSummary(change_one) + ) ) areSame(f.unsafeRunSync(), expectedChanges) @@ -539,7 +551,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec List( BatchChangeSummary(change_four), BatchChangeSummary(change_three), - BatchChangeSummary(change_two)), + BatchChangeSummary(change_two) + ), None, Some(3), 3 @@ -560,7 +573,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec retrieved <- repo.getBatchChangeSummaries( Some(pendingBatchChange.userId), startFrom = Some(1), - maxItems = 3) + maxItems = 3 + ) } yield retrieved // sorted from most recent descending. startFrom uses zero-based indexing. @@ -570,7 +584,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec List( BatchChangeSummary(change_three), BatchChangeSummary(change_two), - BatchChangeSummary(change_one)), + BatchChangeSummary(change_one) + ), Some(1), None, 3 @@ -591,7 +606,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec retrieved <- repo.getBatchChangeSummaries( Some(pendingBatchChange.userId), startFrom = Some(1), - maxItems = 1) + maxItems = 1 + ) } yield retrieved // sorted from most recent descending. startFrom uses zero-based indexing. @@ -615,7 +631,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec retrieved1 <- repo.getBatchChangeSummaries(Some(pendingBatchChange.userId), maxItems = 1) retrieved2 <- repo.getBatchChangeSummaries( Some(pendingBatchChange.userId), - startFrom = retrieved1.nextId) + startFrom = retrieved1.nextId + ) } yield (retrieved1, retrieved2) val expectedChanges = @@ -625,7 +642,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec List( BatchChangeSummary(change_three), BatchChangeSummary(change_two), - BatchChangeSummary(change_one)), + BatchChangeSummary(change_one) + ), Some(1), None ) @@ -645,7 +663,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec retrieved <- repo.getBatchChangeSummaries( Some(pendingBatchChange.userId), - approvalStatus = Some(BatchChangeApprovalStatus.AutoApproved)) + approvalStatus = Some(BatchChangeApprovalStatus.AutoApproved) + ) } yield retrieved // from most recent descending @@ -653,7 +672,8 @@ class MySqlBatchChangeRepositoryIntegrationSpec List( BatchChangeSummary(change_four), BatchChangeSummary(change_three), - BatchChangeSummary(change_two)) + BatchChangeSummary(change_two) + ) ) areSame(f.unsafeRunSync(), expectedChanges) diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlGroupChangeRepositoryIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlGroupChangeRepositoryIntegrationSpec.scala index ef04cee17..a87d4892a 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlGroupChangeRepositoryIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlGroupChangeRepositoryIntegrationSpec.scala @@ -24,7 +24,7 @@ import vinyldns.mysql.TestMySqlInstance import org.joda.time.DateTime class MySqlGroupChangeRepositoryIntegrationSpec - extends WordSpec + extends WordSpec with BeforeAndAfterAll with BeforeAndAfterEach with Matchers { @@ -46,8 +46,12 @@ class MySqlGroupChangeRepositoryIntegrationSpec val group = Group(name = "test", id = groupId, email = "test@test.com") for { i <- 1 to numChanges - } yield GroupChange(group, GroupChangeType.Create, s"user-$i", - created = DateTime.now().plusSeconds(i)) + } yield GroupChange( + group, + GroupChangeType.Create, + s"user-$i", + created = DateTime.now().plusSeconds(i) + ) } "MySqlGroupChangeRepository.save" should { @@ -62,7 +66,8 @@ class MySqlGroupChangeRepositoryIntegrationSpec repo.save(groupChange).unsafeRunSync() shouldBe groupChange repo.getGroupChange(groupChange.id).unsafeRunSync() shouldBe Some(groupChange) - val groupChangeUpdate = groupChange.copy(created = DateTime.now().plusSeconds(10000), userId = "updated") + val groupChangeUpdate = + groupChange.copy(created = DateTime.now().plusSeconds(10000), userId = "updated") repo.save(groupChangeUpdate).unsafeRunSync() shouldBe groupChangeUpdate repo.getGroupChange(groupChangeUpdate.id).unsafeRunSync() shouldBe Some(groupChangeUpdate) } @@ -110,9 +115,12 @@ class MySqlGroupChangeRepositoryIntegrationSpec val expectedChanges = Seq(changesSorted(0)) - val listResponse = repo.getGroupChanges(groupId, startFrom = None, maxItems = 1).unsafeRunSync() + val listResponse = + repo.getGroupChanges(groupId, startFrom = None, maxItems = 1).unsafeRunSync() listResponse.changes shouldBe expectedChanges - listResponse.lastEvaluatedTimeStamp shouldBe Some(expectedChanges.head.created.getMillis.toString) + listResponse.lastEvaluatedTimeStamp shouldBe Some( + expectedChanges.head.created.getMillis.toString + ) } "page group changes using a startFrom and maxItems" in { @@ -139,13 +147,17 @@ class MySqlGroupChangeRepositoryIntegrationSpec // get second page val pageTwo = - repo.getGroupChanges(groupId, startFrom = pageOne.lastEvaluatedTimeStamp, maxItems = 1).unsafeRunSync() + repo + .getGroupChanges(groupId, startFrom = pageOne.lastEvaluatedTimeStamp, maxItems = 1) + .unsafeRunSync() pageTwo.changes shouldBe expectedPageTwo pageTwo.lastEvaluatedTimeStamp shouldBe expectedPageTwoNext // get final page val pageThree = - repo.getGroupChanges(groupId, startFrom = pageTwo.lastEvaluatedTimeStamp, maxItems = 1).unsafeRunSync() + repo + .getGroupChanges(groupId, startFrom = pageTwo.lastEvaluatedTimeStamp, maxItems = 1) + .unsafeRunSync() pageThree.changes shouldBe expectedPageThree pageThree.lastEvaluatedTimeStamp shouldBe expectedPageThreeNext } diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlGroupRepositoryIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlGroupRepositoryIntegrationSpec.scala index 13db28970..0bc07ed4d 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlGroupRepositoryIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlGroupRepositoryIntegrationSpec.scala @@ -22,7 +22,7 @@ import vinyldns.core.domain.membership.{Group, GroupRepository, GroupStatus} import vinyldns.mysql.TestMySqlInstance class MySqlGroupRepositoryIntegrationSpec - extends WordSpec + extends WordSpec with BeforeAndAfterAll with BeforeAndAfterEach with Matchers @@ -31,7 +31,7 @@ class MySqlGroupRepositoryIntegrationSpec private val repo: GroupRepository = TestMySqlInstance.groupRepository - private val testGroupNames = (for {i <- 0 to 100} yield s"test-group-$i").toList.sorted + private val testGroupNames = (for { i <- 0 to 100 } yield s"test-group-$i").toList.sorted private val groups = testGroupNames.map { testName => Group(name = testName, email = "test@email.com") } diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlRecordChangeRepositoryIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlRecordChangeRepositoryIntegrationSpec.scala index 3a2c508e2..8b3e70b73 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlRecordChangeRepositoryIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlRecordChangeRepositoryIntegrationSpec.scala @@ -21,20 +21,28 @@ import java.util.UUID import cats.scalatest.EitherMatchers import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, Matchers, WordSpec} import scalikejdbc._ -import vinyldns.core.domain.record.{ChangeSet, RecordChangeRepository, RecordSetChange, RecordSetChangeType} +import vinyldns.core.domain.record.{ + ChangeSet, + RecordChangeRepository, + RecordSetChange, + RecordSetChangeType +} import vinyldns.core.domain.zone.Zone import vinyldns.mysql.TestMySqlInstance class MySqlRecordChangeRepositoryIntegrationSpec - extends WordSpec with Matchers with BeforeAndAfterAll with BeforeAndAfterEach with EitherMatchers { + extends WordSpec + with Matchers + with BeforeAndAfterAll + with BeforeAndAfterEach + with EitherMatchers { import vinyldns.core.TestRecordSetData._ import vinyldns.core.TestZoneData._ private var repo: RecordChangeRepository = _ - override protected def beforeAll(): Unit = { + override protected def beforeAll(): Unit = repo = TestMySqlInstance.recordChangeRepository - } override protected def beforeEach(): Unit = clear() @@ -50,11 +58,7 @@ class MySqlRecordChangeRepositoryIntegrationSpec val newRecordSets = for { i <- 1 to count - } yield - aaaa.copy( - zoneId = zone.id, - name = s"$i-apply-test", - id = UUID.randomUUID().toString) + } yield aaaa.copy(zoneId = zone.id, name = s"$i-apply-test", id = UUID.randomUUID().toString) newRecordSets.map(makeTestAddChange(_, zone)).toList } @@ -84,12 +88,14 @@ class MySqlRecordChangeRepositoryIntegrationSpec val result = repo.listRecordSetChanges(okZone.id, None, 5).unsafeRunSync() result.nextId shouldBe defined result.maxItems shouldBe 5 - result.items should have length 5 + (result.items should have).length(5) } "page through record changes" in { // sort by created desc, so adding additional seconds makes it more current, the last val timeSpaced = - generateInserts(okZone, 5).zipWithIndex.map { case (c, i) => c.copy(created = c.created.plusSeconds(i)) } + generateInserts(okZone, 5).zipWithIndex.map { + case (c, i) => c.copy(created = c.created.plusSeconds(i)) + } // expect to be sorted by created descending so reverse that val expectedOrder = timeSpaced.sortBy(_.created.getMillis).reverse @@ -99,12 +105,12 @@ class MySqlRecordChangeRepositoryIntegrationSpec val page1 = repo.listRecordSetChanges(okZone.id, None, 2).unsafeRunSync() page1.nextId shouldBe Some(expectedOrder(1).created.getMillis.toString) page1.maxItems shouldBe 2 - page1.items should contain theSameElementsInOrderAs expectedOrder.take(2) + (page1.items should contain).theSameElementsInOrderAs(expectedOrder.take(2)) val page2 = repo.listRecordSetChanges(okZone.id, page1.nextId, 2).unsafeRunSync() page2.nextId shouldBe Some(expectedOrder(3).created.getMillis.toString) page2.maxItems shouldBe 2 - page2.items should contain theSameElementsInOrderAs expectedOrder.slice(2, 4) + (page2.items should contain).theSameElementsInOrderAs(expectedOrder.slice(2, 4)) val page3 = repo.listRecordSetChanges(okZone.id, page2.nextId, 2).unsafeRunSync() page3.nextId shouldBe None diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlRecordSetRepositoryIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlRecordSetRepositoryIntegrationSpec.scala index 8d49383d8..ff7d91f2e 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlRecordSetRepositoryIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlRecordSetRepositoryIntegrationSpec.scala @@ -27,7 +27,7 @@ import vinyldns.mysql.TestMySqlInstance import vinyldns.mysql.repository.MySqlRecordSetRepository.PagingKey class MySqlRecordSetRepositoryIntegrationSpec - extends WordSpec + extends WordSpec with BeforeAndAfterEach with BeforeAndAfterAll with Matchers @@ -50,11 +50,7 @@ class MySqlRecordSetRepositoryIntegrationSpec val newRecordSets = for { i <- 1 to count - } yield - aaaa.copy( - zoneId = zone.id, - name = s"$i-apply-test", - id = UUID.randomUUID().toString) + } yield aaaa.copy(zoneId = zone.id, name = s"$i-apply-test", id = UUID.randomUUID().toString) newRecordSets.map(makeTestAddChange(_, zone)).toList } @@ -78,25 +74,48 @@ class MySqlRecordSetRepositoryIntegrationSpec val addChange = makeTestAddChange(rsOk.copy(id = UUID.randomUUID().toString)) .copy(status = RecordSetChangeStatus.Failed) - val updateChange = makePendingTestUpdateChange(existing(0), existing(0).copy(name = "updated-name")) - .copy(status = RecordSetChangeStatus.Failed) + val updateChange = + makePendingTestUpdateChange(existing(0), existing(0).copy(name = "updated-name")) + .copy(status = RecordSetChangeStatus.Failed) val deleteChange = makePendingTestDeleteChange(existing(1)) .copy(status = RecordSetChangeStatus.Failed) repo.apply(ChangeSet(Seq(addChange, updateChange, deleteChange))).unsafeRunSync() repo.getRecordSet(rsOk.zoneId, rsOk.id).unsafeRunSync() shouldBe None - repo.getRecordSet(existing(0).zoneId, existing(0).id).unsafeRunSync() shouldBe Some(existing(0)) - repo.getRecordSet(existing(1).zoneId, existing(1).id).unsafeRunSync() shouldBe Some(existing(1)) + repo.getRecordSet(existing(0).zoneId, existing(0).id).unsafeRunSync() shouldBe Some( + existing(0) + ) + repo.getRecordSet(existing(1).zoneId, existing(1).id).unsafeRunSync() shouldBe Some( + existing(1) + ) } "apply successful and pending creates, and delete failed creates" in { val zone = okZone - val recordForSuccess = RecordSet("test-create-converter", "createSuccess", RecordType.A, 123, - RecordSetStatus.Active, DateTime.now) - val recordForPending = RecordSet("test-create-converter", "createPending", RecordType.A, 123, - RecordSetStatus.Pending, DateTime.now) - val recordForFailed = RecordSet("test-create-converter", "failed", RecordType.A, 123, - RecordSetStatus.Inactive, DateTime.now) + val recordForSuccess = RecordSet( + "test-create-converter", + "createSuccess", + RecordType.A, + 123, + RecordSetStatus.Active, + DateTime.now + ) + val recordForPending = RecordSet( + "test-create-converter", + "createPending", + RecordType.A, + 123, + RecordSetStatus.Pending, + DateTime.now + ) + val recordForFailed = RecordSet( + "test-create-converter", + "failed", + RecordType.A, + 123, + RecordSetStatus.Inactive, + DateTime.now + ) val successfulChange = RecordSetChange( @@ -104,14 +123,19 @@ class MySqlRecordSetRepositoryIntegrationSpec recordForSuccess, "abc", RecordSetChangeType.Create, - RecordSetChangeStatus.Complete) + RecordSetChangeStatus.Complete + ) - val pendingChange = successfulChange.copy(recordSet = recordForPending, status = RecordSetChangeStatus.Pending) - val failedChange = successfulChange.copy(recordSet = recordForFailed, status = RecordSetChangeStatus.Failed) + val pendingChange = + successfulChange.copy(recordSet = recordForPending, status = RecordSetChangeStatus.Pending) + val failedChange = + successfulChange.copy(recordSet = recordForFailed, status = RecordSetChangeStatus.Failed) // to be deleted - assume this was already saved as pending - val existingPending = failedChange.copy(recordSet = recordForFailed.copy(status = RecordSetStatus.Pending), - status = RecordSetChangeStatus.Pending) + val existingPending = failedChange.copy( + recordSet = recordForFailed.copy(status = RecordSetStatus.Pending), + status = RecordSetChangeStatus.Pending + ) repo.apply(ChangeSet(existingPending)).unsafeRunSync() repo.getRecordSet(recordForFailed.zoneId, failedChange.recordSet.id).unsafeRunSync() shouldBe Some(existingPending.recordSet) @@ -119,13 +143,19 @@ class MySqlRecordSetRepositoryIntegrationSpec repo.apply(ChangeSet(Seq(successfulChange, pendingChange, failedChange))).unsafeRunSync() // success and pending changes have records saved - repo.getRecordSet(successfulChange.recordSet.zoneId, successfulChange.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(successfulChange.recordSet.zoneId, successfulChange.recordSet.id) + .unsafeRunSync() shouldBe Some(successfulChange.recordSet) - repo.getRecordSet(pendingChange.recordSet.zoneId, pendingChange.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(pendingChange.recordSet.zoneId, pendingChange.recordSet.id) + .unsafeRunSync() shouldBe Some(pendingChange.recordSet) // check that the pending record was deleted because of failed record change - repo.getRecordSet(failedChange.recordSet.zoneId, failedChange.recordSet.id).unsafeRunSync() shouldBe None + repo + .getRecordSet(failedChange.recordSet.zoneId, failedChange.recordSet.id) + .unsafeRunSync() shouldBe None } "apply successful updates and revert records for failed updates" in { @@ -143,13 +173,16 @@ class MySqlRecordSetRepositoryIntegrationSpec val failedUpdate = pendingUpdate.copy( recordSet = updateFailure, updates = Some(oldFailure), - status = RecordSetChangeStatus.Failed) + status = RecordSetChangeStatus.Failed + ) val updateChanges = Seq(successfulUpdate, pendingUpdate, failedUpdate) val updateChangeSet = ChangeSet(updateChanges) // save old recordsets val oldAddChanges = updateChanges - .map(_.copy(changeType = RecordSetChangeType.Create, status = RecordSetChangeStatus.Complete)) + .map( + _.copy(changeType = RecordSetChangeType.Create, status = RecordSetChangeStatus.Complete) + ) val oldChangeSet = ChangeSet(oldAddChanges) repo.apply(oldChangeSet).unsafeRunSync() shouldBe oldChangeSet @@ -157,16 +190,24 @@ class MySqlRecordSetRepositoryIntegrationSpec repo.apply(updateChangeSet).unsafeRunSync() shouldBe updateChangeSet // ensure that success and pending updates store the new recordsets - repo.getRecordSet(successfulUpdate.recordSet.zoneId, successfulUpdate.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(successfulUpdate.recordSet.zoneId, successfulUpdate.recordSet.id) + .unsafeRunSync() shouldBe Some(successfulUpdate.recordSet) - repo.getRecordSet(pendingUpdate.recordSet.zoneId, pendingUpdate.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(pendingUpdate.recordSet.zoneId, pendingUpdate.recordSet.id) + .unsafeRunSync() shouldBe Some(pendingUpdate.recordSet) // ensure that failure update store the old recordset - repo.getRecordSet(failedUpdate.recordSet.zoneId, failedUpdate.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(failedUpdate.recordSet.zoneId, failedUpdate.recordSet.id) + .unsafeRunSync() shouldBe failedUpdate.updates - repo.getRecordSet(failedUpdate.recordSet.zoneId, failedUpdate.recordSet.id).unsafeRunSync() shouldNot + repo + .getRecordSet(failedUpdate.recordSet.zoneId, failedUpdate.recordSet.id) + .unsafeRunSync() shouldNot be(Some(failedUpdate.recordSet)) } @@ -175,16 +216,21 @@ class MySqlRecordSetRepositoryIntegrationSpec val oldPending = aaaa.copy(zoneId = "test-update-converter", id = "pending") val oldFailure = aaaa.copy(zoneId = "test-update-converter", id = "failed") - val successfulDelete = makePendingTestDeleteChange(oldSuccess).copy(status = RecordSetChangeStatus.Complete) - val pendingDelete = makePendingTestDeleteChange(oldPending).copy(status = RecordSetChangeStatus.Pending) - val failedDelete = makePendingTestDeleteChange(oldFailure).copy(status = RecordSetChangeStatus.Failed) + val successfulDelete = + makePendingTestDeleteChange(oldSuccess).copy(status = RecordSetChangeStatus.Complete) + val pendingDelete = + makePendingTestDeleteChange(oldPending).copy(status = RecordSetChangeStatus.Pending) + val failedDelete = + makePendingTestDeleteChange(oldFailure).copy(status = RecordSetChangeStatus.Failed) val deleteChanges = Seq(successfulDelete, pendingDelete, failedDelete) val deleteChangeSet = ChangeSet(deleteChanges) // save old recordsets val oldAddChanges = deleteChanges - .map(_.copy(changeType = RecordSetChangeType.Create, status = RecordSetChangeStatus.Complete)) + .map( + _.copy(changeType = RecordSetChangeType.Create, status = RecordSetChangeStatus.Complete) + ) val oldChangeSet = ChangeSet(oldAddChanges) repo.apply(oldChangeSet).unsafeRunSync() shouldBe oldChangeSet @@ -192,14 +238,20 @@ class MySqlRecordSetRepositoryIntegrationSpec repo.apply(deleteChangeSet).unsafeRunSync() shouldBe deleteChangeSet // ensure that successful change deletes the recordset - repo.getRecordSet(successfulDelete.recordSet.zoneId, successfulDelete.recordSet.id).unsafeRunSync() shouldBe None + repo + .getRecordSet(successfulDelete.recordSet.zoneId, successfulDelete.recordSet.id) + .unsafeRunSync() shouldBe None // ensure that pending change saves the recordset - repo.getRecordSet(pendingDelete.recordSet.zoneId, pendingDelete.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(pendingDelete.recordSet.zoneId, pendingDelete.recordSet.id) + .unsafeRunSync() shouldBe Some(pendingDelete.recordSet) // ensure that failed delete keeps the recordset - repo.getRecordSet(failedDelete.recordSet.zoneId, failedDelete.recordSet.id).unsafeRunSync() shouldBe + repo + .getRecordSet(failedDelete.recordSet.zoneId, failedDelete.recordSet.id) + .unsafeRunSync() shouldBe failedDelete.updates } } @@ -208,7 +260,9 @@ class MySqlRecordSetRepositoryIntegrationSpec "properly add and delete DS records" in { val addChange = makeTestAddChange(ds, okZone) val testRecord = addChange.recordSet - val deleteChange = makePendingTestDeleteChange(testRecord, okZone).copy(status = RecordSetChangeStatus.Complete) + val deleteChange = makePendingTestDeleteChange(testRecord, okZone).copy( + status = RecordSetChangeStatus.Complete + ) val dbCalls = for { _ <- repo.apply(ChangeSet(addChange)) @@ -242,7 +296,9 @@ class MySqlRecordSetRepositoryIntegrationSpec val existing = insert(okZone, 10).map(_.recordSet) // update a few, delete a few - val deletes = existing.take(2).map(makePendingTestDeleteChange(_, okZone).copy(status = RecordSetChangeStatus.Complete)) + val deletes = existing + .take(2) + .map(makePendingTestDeleteChange(_, okZone).copy(status = RecordSetChangeStatus.Complete)) // updates we will just add the letter u to val updates = existing.slice(3, 5).map { rs => @@ -291,8 +347,9 @@ class MySqlRecordSetRepositoryIntegrationSpec val addChange = makeTestAddChange(ds, okZone) val testRecord = addChange.recordSet - val updatedRecordSet = testRecord.copy(name = "updated-name", ownerGroupId = Some("someOwner")) - val updateChange = makeCompleteTestUpdateChange(testRecord,updatedRecordSet, okZone) + val updatedRecordSet = + testRecord.copy(name = "updated-name", ownerGroupId = Some("someOwner")) + val updateChange = makeCompleteTestUpdateChange(testRecord, updatedRecordSet, okZone) val dbCalls = for { _ <- repo.apply(ChangeSet(addChange)) @@ -306,8 +363,11 @@ class MySqlRecordSetRepositoryIntegrationSpec finalGet.flatMap(_.ownerGroupId) shouldBe Some("someOwner") //Update the owner-group-id to None to check if its null in the db - val updateChangeNone = makeCompleteTestUpdateChange(updatedRecordSet, - updatedRecordSet.copy(ownerGroupId = None), okZone) + val updateChangeNone = makeCompleteTestUpdateChange( + updatedRecordSet, + updatedRecordSet.copy(ownerGroupId = None), + okZone + ) val updateToNone = for { _ <- repo.apply(ChangeSet(updateChangeNone)) @@ -331,7 +391,7 @@ class MySqlRecordSetRepositoryIntegrationSpec val startFrom = Some(PagingKey.toNextId(existing(2))) val found = repo.listRecordSets(okZone.id, startFrom, None, None).unsafeRunSync() - found.recordSets should contain theSameElementsInOrderAs existing.drop(3) + (found.recordSets should contain).theSameElementsInOrderAs(existing.drop(3)) } "return the record sets after the startFrom respecting maxItems" in { // load 5, start after the 2nd, take 2, we should get back the 3rd and 4th @@ -339,27 +399,24 @@ class MySqlRecordSetRepositoryIntegrationSpec val startFrom = Some(PagingKey.toNextId(existing(1))) val found = repo.listRecordSets(okZone.id, startFrom, Some(2), None).unsafeRunSync() - found.recordSets should contain theSameElementsInOrderAs existing.slice(2, 4) + (found.recordSets should contain).theSameElementsInOrderAs(existing.slice(2, 4)) } "return the record sets after startFrom respecting maxItems and filter" in { - val recordNames = List("aaa", "bbb", "ccc", "ddd", "eeez", "fffz", "ggg", "hhhz", "iii", "jjj") + val recordNames = + List("aaa", "bbb", "ccc", "ddd", "eeez", "fffz", "ggg", "hhhz", "iii", "jjj") val expectedNames = recordNames.filter(_.contains("z")) val newRecordSets = for { n <- recordNames - } yield - aaaa.copy( - zoneId = okZone.id, - name = n, - id = UUID.randomUUID().toString) + } yield aaaa.copy(zoneId = okZone.id, name = n, id = UUID.randomUUID().toString) val changes = newRecordSets.map(makeTestAddChange(_, okZone)) insert(changes) val startFrom = Some(PagingKey.toNextId(newRecordSets(1))) val found = repo.listRecordSets(okZone.id, startFrom, Some(3), Some("*z*")).unsafeRunSync() - found.recordSets.map(_.name) should contain theSameElementsInOrderAs expectedNames + (found.recordSets.map(_.name) should contain).theSameElementsInOrderAs(expectedNames) } "return record sets using starts with wildcard" in { val recordNames = List("aaa", "aab", "ccc") @@ -368,17 +425,13 @@ class MySqlRecordSetRepositoryIntegrationSpec val newRecordSets = for { n <- recordNames - } yield - aaaa.copy( - zoneId = okZone.id, - name = n, - id = UUID.randomUUID().toString) + } yield aaaa.copy(zoneId = okZone.id, name = n, id = UUID.randomUUID().toString) val changes = newRecordSets.map(makeTestAddChange(_, okZone)) insert(changes) val found = repo.listRecordSets(okZone.id, None, Some(3), Some("aa*")).unsafeRunSync() - found.recordSets.map(_.name) should contain theSameElementsInOrderAs expectedNames + (found.recordSets.map(_.name) should contain).theSameElementsInOrderAs(expectedNames) } "return record sets using ends with wildcard" in { val recordNames = List("aaa", "aab", "ccb") @@ -393,7 +446,7 @@ class MySqlRecordSetRepositoryIntegrationSpec insert(changes) val found = repo.listRecordSets(okZone.id, None, Some(3), Some("*b")).unsafeRunSync() - found.recordSets.map(_.name) should contain theSameElementsInOrderAs expectedNames + (found.recordSets.map(_.name) should contain).theSameElementsInOrderAs(expectedNames) } "return record sets exact match with no wildcards" in { // load some deterministic names so we can filter and respect max items @@ -409,21 +462,21 @@ class MySqlRecordSetRepositoryIntegrationSpec insert(changes) val found = repo.listRecordSets(okZone.id, None, Some(3), Some("aaa")).unsafeRunSync() - found.recordSets.map(_.name) should contain theSameElementsInOrderAs expectedNames + (found.recordSets.map(_.name) should contain).theSameElementsInOrderAs(expectedNames) } "pages through the list properly" in { // load 5 records, pages of 2, last page should have 1 result and no next id val existing = insert(okZone, 5).map(_.recordSet).sortBy(_.name) val page1 = repo.listRecordSets(okZone.id, None, Some(2), None).unsafeRunSync() - page1.recordSets should contain theSameElementsInOrderAs existing.slice(0, 2) + (page1.recordSets should contain).theSameElementsInOrderAs(existing.slice(0, 2)) page1.nextId shouldBe Some(PagingKey.toNextId(page1.recordSets(1))) val page2 = repo.listRecordSets(okZone.id, page1.nextId, Some(2), None).unsafeRunSync() - page2.recordSets should contain theSameElementsInOrderAs existing.slice(2, 4) + (page2.recordSets should contain).theSameElementsInOrderAs(existing.slice(2, 4)) page2.nextId shouldBe Some(PagingKey.toNextId(page2.recordSets(1))) val page3 = repo.listRecordSets(okZone.id, page2.nextId, Some(2), None).unsafeRunSync() - page3.recordSets should contain theSameElementsInOrderAs existing.slice(4, 5) + (page3.recordSets should contain).theSameElementsInOrderAs(existing.slice(4, 5)) page3.nextId shouldBe None } @@ -441,15 +494,15 @@ class MySqlRecordSetRepositoryIntegrationSpec val existing = editedChanges.map(_.recordSet) val page1 = repo.listRecordSets(okZone.id, None, Some(2), None).unsafeRunSync() - page1.recordSets should contain theSameElementsInOrderAs List(existing(0), existing(1)) + (page1.recordSets should contain).theSameElementsInOrderAs(List(existing(0), existing(1))) page1.nextId shouldBe Some(PagingKey.toNextId(page1.recordSets.last)) val page2 = repo.listRecordSets(okZone.id, page1.nextId, Some(2), None).unsafeRunSync() - page2.recordSets should contain theSameElementsInOrderAs List(existing(2), existing(3)) + (page2.recordSets should contain).theSameElementsInOrderAs(List(existing(2), existing(3))) page2.nextId shouldBe Some(PagingKey.toNextId(page2.recordSets.last)) val page3 = repo.listRecordSets(okZone.id, page2.nextId, Some(2), None).unsafeRunSync() - page3.recordSets should contain theSameElementsInOrderAs List(existing(4)) + (page3.recordSets should contain).theSameElementsInOrderAs(List(existing(4))) page3.nextId shouldBe None } } @@ -509,8 +562,8 @@ class MySqlRecordSetRepositoryIntegrationSpec val fqdn1 = s"$rname1.${okZone.name}" val fqdn2 = s"$rname2.${okZone.name}" - val change1 = makeTestAddChange(aaaa.copy(name=rname1), okZone) - val change2 = makeTestAddChange(aaaa.copy(name=rname2), okZone) + val change1 = makeTestAddChange(aaaa.copy(name = rname1), okZone) + val change2 = makeTestAddChange(aaaa.copy(name = rname2), okZone) insert(List(change1, change2)) val result = repo.getRecordSetsByFQDNs(Set("no-existo", fqdn1, fqdn2)).unsafeRunSync() @@ -521,8 +574,8 @@ class MySqlRecordSetRepositoryIntegrationSpec val rname = "test-fqdn-same-type" val fqdn = s"$rname.${okZone.name}" - val aaaaChange = makeTestAddChange(aaaa.copy(name=rname), okZone) - val mxChange = makeTestAddChange(mx.copy(name=rname), okZone) + val aaaaChange = makeTestAddChange(aaaa.copy(name = rname), okZone) + val mxChange = makeTestAddChange(mx.copy(name = rname), okZone) insert(List(aaaaChange, mxChange)) val result = repo.getRecordSetsByFQDNs(Set(fqdn)).unsafeRunSync() @@ -541,8 +594,8 @@ class MySqlRecordSetRepositoryIntegrationSpec val fqdn1 = s"$rname1.${okZone.name}" val fqdn2 = s"$rname2.${okZone.name}" - val change1 = makeTestAddChange(aaaa.copy(name=rname1), okZone) - val change2 = makeTestAddChange(mx.copy(name=rname2), okZone) + val change1 = makeTestAddChange(aaaa.copy(name = rname1), okZone) + val change2 = makeTestAddChange(mx.copy(name = rname2), okZone) insert(List(change1, change2)) val result1 = repo.getRecordSetsByFQDNs(Set(fqdn1)).unsafeRunSync() diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlTaskRepositoryIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlTaskRepositoryIntegrationSpec.scala index cb549752e..866f079a1 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlTaskRepositoryIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlTaskRepositoryIntegrationSpec.scala @@ -25,7 +25,11 @@ import vinyldns.mysql.TestMySqlInstance import scala.concurrent.duration._ -class MySqlTaskRepositoryIntegrationSpec extends WordSpec with BeforeAndAfterAll with BeforeAndAfterEach with Matchers { +class MySqlTaskRepositoryIntegrationSpec + extends WordSpec + with BeforeAndAfterAll + with BeforeAndAfterEach + with Matchers { private val repo = TestMySqlInstance.taskRepository.asInstanceOf[MySqlTaskRepository] private val TASK_NAME = "task_name" @@ -56,7 +60,8 @@ class MySqlTaskRepositoryIntegrationSpec extends WordSpec with BeforeAndAfterAll .bindByName('taskName -> name) .map(rs => TaskInfo(rs.boolean(1), rs.timestampOpt(2).map(_.toInstant))) .first() - .apply().getOrElse(throw new RuntimeException(s"TASK $name NOT FOUND")) + .apply() + .getOrElse(throw new RuntimeException(s"TASK $name NOT FOUND")) } } @@ -162,7 +167,7 @@ class MySqlTaskRepositoryIntegrationSpec extends WordSpec with BeforeAndAfterAll newTaskInfo.updated shouldBe defined oldTaskInfo.updated.zip(newTaskInfo.updated).foreach { case (claimTime, releaseTime) => - releaseTime should be > claimTime + releaseTime should be > claimTime } } } diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlUserChangeRepositoryIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlUserChangeRepositoryIntegrationSpec.scala index 209d767b0..701c0da8b 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlUserChangeRepositoryIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlUserChangeRepositoryIntegrationSpec.scala @@ -31,7 +31,8 @@ class MySqlUserChangeRepositoryIntegrationSpec private val repo: UserChangeRepository = TestMySqlInstance.userChangeRepository private val user: User = User("user-id", "access-key", "secret-key") private val createUser = CreateUser(user, "creator-id", user.created) - private val updateUser = UpdateUser(user.copy(userName = "new-username"), "creator-id", user.created, user) + private val updateUser = + UpdateUser(user.copy(userName = "new-username"), "creator-id", user.created, user) def clear(): Unit = DB.localTx { implicit s => diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlUserRepositoryIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlUserRepositoryIntegrationSpec.scala index 494eb97ce..d92a1f415 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlUserRepositoryIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlUserRepositoryIntegrationSpec.scala @@ -22,7 +22,7 @@ import vinyldns.core.domain.membership.{LockStatus, User, UserRepository} import vinyldns.mysql.TestMySqlInstance class MySqlUserRepositoryIntegrationSpec - extends WordSpec + extends WordSpec with BeforeAndAfterAll with BeforeAndAfterEach with Matchers @@ -31,7 +31,7 @@ class MySqlUserRepositoryIntegrationSpec private var repo: UserRepository = _ - private val testUserIds = (for {i <- 0 to 100} yield s"test-user-$i").toList.sorted + private val testUserIds = (for { i <- 0 to 100 } yield s"test-user-$i").toList.sorted private val users = testUserIds.map { id => User(id = id, userName = "name" + id, accessKey = s"abc$id", secretKey = "123") } @@ -95,7 +95,8 @@ class MySqlUserRepositoryIntegrationSpec } "save locked user with locked status" in { - val lockedUser = User("lockedName", "lockedAccess", "lockedSecret", lockStatus = LockStatus.Locked) + val lockedUser = + User("lockedName", "lockedAccess", "lockedSecret", lockStatus = LockStatus.Locked) repo.save(lockedUser).unsafeRunSync() shouldBe lockedUser val result = repo.getUser(lockedUser.id).unsafeRunSync() result shouldBe Some(lockedUser) diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlZoneChangeRepositoryIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlZoneChangeRepositoryIntegrationSpec.scala index 9c8daa706..3e09c5273 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlZoneChangeRepositoryIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlZoneChangeRepositoryIntegrationSpec.scala @@ -58,23 +58,24 @@ class MySqlZoneChangeRepositoryIntegrationSpec val goodUser: User = User(s"live-test-acct", "key", "secret") - val zones: IndexedSeq[Zone] = for { i <- 1 to 3 } yield - Zone( - s"${goodUser.userName}.zone$i.", - "test@test.com", - status = ZoneStatus.Active, - connection = testConnection) + val zones: IndexedSeq[Zone] = for { i <- 1 to 3 } yield Zone( + s"${goodUser.userName}.zone$i.", + "test@test.com", + status = ZoneStatus.Active, + connection = testConnection + ) val statuses: List[ZoneChangeStatus] = ZoneChangeStatus.Pending :: ZoneChangeStatus.Failed :: ZoneChangeStatus.Synced :: Nil - val changes: IndexedSeq[ZoneChange] = for { zone <- zones; status <- statuses } yield - ZoneChange( - zone, - zone.account, - ZoneChangeType.Update, - status, - created = DateTime.now().minusSeconds(Random.nextInt(1000))) + val changes + : IndexedSeq[ZoneChange] = for { zone <- zones; status <- statuses } yield ZoneChange( + zone, + zone.account, + ZoneChangeType.Update, + status, + created = DateTime.now().minusSeconds(Random.nextInt(1000)) + ) } import TestData._ @@ -127,7 +128,8 @@ class MySqlZoneChangeRepositoryIntegrationSpec changeSetupResults .unsafeRunTimed(5.minutes) .getOrElse( - fail("timeout waiting for changes to save in MySqlZoneChangeRepositoryIntegrationSpec")) + fail("timeout waiting for changes to save in MySqlZoneChangeRepositoryIntegrationSpec") + ) val expectedChanges = changes @@ -147,7 +149,8 @@ class MySqlZoneChangeRepositoryIntegrationSpec changeSetupResults .unsafeRunTimed(5.minutes) .getOrElse( - fail("timeout waiting for changes to save in MySqlZoneChangeRepositoryIntegrationSpec")) + fail("timeout waiting for changes to save in MySqlZoneChangeRepositoryIntegrationSpec") + ) val zoneOneChanges = changes .filter(_.zoneId == zones(1).id) @@ -169,7 +172,8 @@ class MySqlZoneChangeRepositoryIntegrationSpec changeSetupResults .unsafeRunTimed(5.minutes) .getOrElse( - fail("timeout waiting for changes to save in MySqlZoneChangeRepositoryIntegrationSpec")) + fail("timeout waiting for changes to save in MySqlZoneChangeRepositoryIntegrationSpec") + ) val zoneOneChanges = changes .filter(_.zoneId == zones(1).id) diff --git a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlZoneRepositoryIntegrationSpec.scala b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlZoneRepositoryIntegrationSpec.scala index 75b3dadbd..fdd376c40 100644 --- a/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlZoneRepositoryIntegrationSpec.scala +++ b/modules/mysql/src/it/scala/vinyldns/mysql/repository/MySqlZoneRepositoryIntegrationSpec.scala @@ -63,7 +63,8 @@ class MySqlZoneRepositoryIntegrationSpec ACLRule( accessLevel = AccessLevel.Read, groupId = Some(g.id) - )) + ) + ) private val userOnlyAclRule = ACLRule( @@ -160,8 +161,12 @@ class MySqlZoneRepositoryIntegrationSpec val names1 = testZonesList1.map(zone => zone.name) val names2 = testZonesList2.map(zone => zone.name) - repo.getZonesByNames(names1.toSet).unsafeRunSync() should contain theSameElementsAs testZonesList1 - repo.getZonesByNames(names2.toSet).unsafeRunSync() should contain theSameElementsAs testZonesList2 + repo + .getZonesByNames(names1.toSet) + .unsafeRunSync() should contain theSameElementsAs testZonesList1 + repo + .getZonesByNames(names2.toSet) + .unsafeRunSync() should contain theSameElementsAs testZonesList2 } "return empty list if zones are not found by names" in { @@ -181,7 +186,8 @@ class MySqlZoneRepositoryIntegrationSpec val expectedZones = List(testZones(0), testZones(1), testZones(3)) saveZones(testZones).unsafeRunSync() - repo.getZonesByFilters(Set("67.345.12.in-addr.arpa.", "extraZone")) + repo + .getZonesByFilters(Set("67.345.12.in-addr.arpa.", "extraZone")) .unsafeRunSync() should contain theSameElementsAs expectedZones } @@ -200,7 +206,7 @@ class MySqlZoneRepositoryIntegrationSpec repo.listZones(okUserAuth).unsafeRunSync().zones should contain theSameElementsAs testZones // dummy user only has access to one zone - repo.listZones(dummyAuth).unsafeRunSync().zones should contain only testZones.head + (repo.listZones(dummyAuth).unsafeRunSync().zones should contain).only(testZones.head) } "get all zones" in { @@ -218,7 +224,7 @@ class MySqlZoneRepositoryIntegrationSpec shared = true ) - val testZones = Seq(privateZone,sharedZone) + val testZones = Seq(privateZone, sharedZone) val f = saveZones(testZones) @@ -229,10 +235,16 @@ class MySqlZoneRepositoryIntegrationSpec ) f.unsafeRunSync() - repo.listZones(okUserAuth, ignoreAccess=true).unsafeRunSync().zones should contain theSameElementsAs testZones + repo + .listZones(okUserAuth, ignoreAccess = true) + .unsafeRunSync() + .zones should contain theSameElementsAs testZones // dummy user only have all of the zones returned - repo.listZones(dummyAuth, ignoreAccess=true).unsafeRunSync().zones should contain theSameElementsAs testZones + repo + .listZones(dummyAuth, ignoreAccess = true) + .unsafeRunSync() + .zones should contain theSameElementsAs testZones } "get zones that are accessible by everyone" in { @@ -267,7 +279,7 @@ class MySqlZoneRepositoryIntegrationSpec everyoneZones <- repo.listZones(dummyAuth) } yield everyoneZones - f.unsafeRunSync().zones should contain only allAccess + (f.unsafeRunSync().zones should contain).only(allAccess) } "not return deleted zones" in { @@ -301,7 +313,7 @@ class MySqlZoneRepositoryIntegrationSpec retrieved <- repo.getZone(deleted.id) } yield retrieved - // the result should be None + // the result should be None del.unsafeRunSync() shouldBe empty } @@ -331,17 +343,18 @@ class MySqlZoneRepositoryIntegrationSpec ) addACL.unsafeRunSync() - repo.listZones(okUserAuth).unsafeRunSync().zones should contain allElementsOf zones + (repo.listZones(okUserAuth).unsafeRunSync().zones should contain).allElementsOf(zones) // dummy user only has access to first zone - repo.listZones(dummyAuth).unsafeRunSync().zones should contain only zones.head + (repo.listZones(dummyAuth).unsafeRunSync().zones should contain).only(zones.head) // revoke the access for the dummy user val revoked = zones(0).deleteACLRule(dummyAclRule) repo.save(revoked).unsafeRunSync() // ok user can still access zones - repo.listZones(okUserAuth).unsafeRunSync().zones should contain allElementsOf Seq(revoked, zones(1)) + (repo.listZones(okUserAuth).unsafeRunSync().zones should contain) + .allElementsOf(Seq(revoked, zones(1))) // dummy user can not access the revoked zone repo.listZones(dummyAuth).unsafeRunSync().zones shouldBe empty @@ -440,7 +453,7 @@ class MySqlZoneRepositoryIntegrationSpec retrieved <- repo.listZones(auth, zoneNameFilter = Some("system*")) } yield retrieved - f.unsafeRunSync().zones should contain theSameElementsInOrderAs expectedZones + (f.unsafeRunSync().zones should contain).theSameElementsInOrderAs(expectedZones) } "support starts with wildcard" in { @@ -461,7 +474,7 @@ class MySqlZoneRepositoryIntegrationSpec retrieved <- repo.listZones(auth, zoneNameFilter = Some("system*")) } yield retrieved - f.unsafeRunSync().zones should contain theSameElementsInOrderAs expectedZones + (f.unsafeRunSync().zones should contain).theSameElementsInOrderAs(expectedZones) } "support ends with wildcard" in { @@ -482,7 +495,7 @@ class MySqlZoneRepositoryIntegrationSpec retrieved <- repo.listZones(auth, zoneNameFilter = Some("*test")) } yield retrieved - f.unsafeRunSync().zones should contain theSameElementsInOrderAs expectedZones + (f.unsafeRunSync().zones should contain).theSameElementsInOrderAs(expectedZones) } "support contains wildcard" in { @@ -502,7 +515,7 @@ class MySqlZoneRepositoryIntegrationSpec retrieved <- repo.listZones(auth, zoneNameFilter = Some("*wild*")) } yield retrieved - f.unsafeRunSync().zones should contain theSameElementsInOrderAs expectedZones + (f.unsafeRunSync().zones should contain).theSameElementsInOrderAs(expectedZones) } "apply paging when searching as a super user" in { @@ -514,17 +527,25 @@ class MySqlZoneRepositoryIntegrationSpec saveZones(testZones).unsafeRunSync() - repo.listZones(superUserAuth,None, None, 4) - .unsafeRunSync().zones should contain theSameElementsInOrderAs expectedFirstPage + (repo + .listZones(superUserAuth, None, None, 4) + .unsafeRunSync() + .zones should contain).theSameElementsInOrderAs(expectedFirstPage) - repo.listZones(superUserAuth, None, Some(sorted(3).name), 4) - .unsafeRunSync().zones should contain theSameElementsInOrderAs expectedSecondPage + (repo + .listZones(superUserAuth, None, Some(sorted(3).name), 4) + .unsafeRunSync() + .zones should contain).theSameElementsInOrderAs(expectedSecondPage) - repo.listZones(superUserAuth, None, Some(sorted(7).name), 4) - .unsafeRunSync().zones should contain theSameElementsInOrderAs expectedThirdPage + (repo + .listZones(superUserAuth, None, Some(sorted(7).name), 4) + .unsafeRunSync() + .zones should contain).theSameElementsInOrderAs(expectedThirdPage) - repo.listZones(superUserAuth, None, Some(sorted(7).name), 4) - .unsafeRunSync().nextId shouldBe None + repo + .listZones(superUserAuth, None, Some(sorted(7).name), 4) + .unsafeRunSync() + .nextId shouldBe None } "apply paging when doing an authorized zone search" in { @@ -555,14 +576,20 @@ class MySqlZoneRepositoryIntegrationSpec saveZones(testZones).unsafeRunSync() - repo.listZones(auth, None, None, 2) - .unsafeRunSync().zones should contain theSameElementsInOrderAs expectedFirstPage + (repo + .listZones(auth, None, None, 2) + .unsafeRunSync() + .zones should contain).theSameElementsInOrderAs(expectedFirstPage) - repo.listZones(auth, None, Some(filtered(1).name), 2) - .unsafeRunSync().zones should contain theSameElementsInOrderAs expectedSecondPage + (repo + .listZones(auth, None, Some(filtered(1).name), 2) + .unsafeRunSync() + .zones should contain).theSameElementsInOrderAs(expectedSecondPage) - repo.listZones(auth, None, Some(filtered(3).name), 2) - .unsafeRunSync().zones should contain theSameElementsInOrderAs expectedThirdPage + (repo + .listZones(auth, None, Some(filtered(3).name), 2) + .unsafeRunSync() + .zones should contain).theSameElementsInOrderAs(expectedThirdPage) } "apply paging when doing a zone search as a zone admin with ACL rules" in { @@ -601,14 +628,20 @@ class MySqlZoneRepositoryIntegrationSpec saveZones(testZones).unsafeRunSync() - repo.listZones(auth, None, None, 2) - .unsafeRunSync().zones should contain theSameElementsInOrderAs expectedFirstPage + (repo + .listZones(auth, None, None, 2) + .unsafeRunSync() + .zones should contain).theSameElementsInOrderAs(expectedFirstPage) - repo.listZones(auth, None, Some(filtered(1).name), 2) - .unsafeRunSync().zones should contain theSameElementsInOrderAs expectedSecondPage + (repo + .listZones(auth, None, Some(filtered(1).name), 2) + .unsafeRunSync() + .zones should contain).theSameElementsInOrderAs(expectedSecondPage) - repo.listZones(auth, None, Some(filtered(3).name), 2) - .unsafeRunSync().zones should contain theSameElementsInOrderAs expectedThirdPage + (repo + .listZones(auth, None, Some(filtered(3).name), 2) + .unsafeRunSync() + .zones should contain).theSameElementsInOrderAs(expectedThirdPage) } "get zones by admin group" in { @@ -643,12 +676,12 @@ class MySqlZoneRepositoryIntegrationSpec val zoneId = UUID.randomUUID().toString val testZones = (1 until 3).map { num => - okZone.copy( - name = num.toString + ".", - id = zoneId, - adminGroupId = testZoneAdminGroupId, - acl = testZoneAcl - ) + okZone.copy( + name = num.toString + ".", + id = zoneId, + adminGroupId = testZoneAdminGroupId, + acl = testZoneAcl + ) } val f = diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/MySqlConnector.scala b/modules/mysql/src/main/scala/vinyldns/mysql/MySqlConnector.scala index 41471033f..013eb7e6e 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/MySqlConnector.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/MySqlConnector.scala @@ -34,7 +34,8 @@ object MySqlConnector { config.migrationUrl, config.user, config.password, - minimumIdle = Some(3)) + minimumIdle = Some(3) + ) getDataSource(migrationConnectionSettings).map { migrationDataSource => logger.info("Running migrations to ready the databases") diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessage.scala b/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessage.scala index 4d361b793..2f32d001c 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessage.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessage.scala @@ -25,5 +25,5 @@ final case class MySqlMessage( id: MessageId, attempts: Int, timeout: FiniteDuration, - command: ZoneCommand) - extends CommandMessage + command: ZoneCommand +) extends CommandMessage diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessageQueue.scala b/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessageQueue.scala index 00ce03063..356fdea87 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessageQueue.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessageQueue.scala @@ -106,7 +106,8 @@ class MySqlMessageQueue extends MessageQueue with Monitored with ProtobufConvers typ: Int, data: Array[Byte], attempts: Int, - timeoutSeconds: Int): Either[(Throwable, MessageId), MySqlMessage] = { + timeoutSeconds: Int + ): Either[(Throwable, MessageId), MySqlMessage] = { // parse the type, if it cannot parse we fail with the message id, same with the data for { messageType <- MessageType.fromInt(typ) @@ -121,14 +122,16 @@ class MySqlMessageQueue extends MessageQueue with Monitored with ProtobufConvers _ <- Either.cond( timeoutSeconds > 0, (), - MySqlMessageQueue.InvalidMessageTimeout(timeoutSeconds)) + MySqlMessageQueue.InvalidMessageTimeout(timeoutSeconds) + ) } yield MySqlMessage(id, attempts, timeoutSeconds.seconds, cmd) }.leftMap { e => (e, id) } - def fetchUnclaimed(numMessages: Int)( - implicit s: DBSession): List[Either[(Throwable, MessageId), MySqlMessage]] = + def fetchUnclaimed( + numMessages: Int + )(implicit s: DBSession): List[Either[(Throwable, MessageId), MySqlMessage]] = FETCH_UNCLAIMED .bind(numMessages) .map { rs => diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessageQueueProvider.scala b/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessageQueueProvider.scala index 8f124ae2e..d5c5aaa7b 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessageQueueProvider.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/queue/MySqlMessageQueueProvider.scala @@ -53,7 +53,8 @@ class MySqlMessageQueueProvider extends MessageQueueProvider { // Configure the connection pool ConnectionPool.add( MySqlMessageQueue.QUEUE_CONNECTION_NAME, - new DataSourceConnectionPool(dataSource, closer = new HikariCloser(dataSource))) + new DataSourceConnectionPool(dataSource, closer = new HikariCloser(dataSource)) + ) logger.error("queue connection pool init complete") } diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlBatchChangeRepository.scala b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlBatchChangeRepository.scala index a024707d3..73b21d2d6 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlBatchChangeRepository.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlBatchChangeRepository.scala @@ -138,7 +138,8 @@ class MySqlBatchChangeRepository val batchChangeFuture = for { batchChangeMeta <- OptionT[IO, BatchChange](getBatchChangeMetadata(batchChangeId)) singleChanges <- OptionT.liftF[IO, List[SingleChange]]( - getSingleChangesByBatchChangeId(batchChangeId)) + getSingleChangesByBatchChangeId(batchChangeId) + ) } yield { batchChangeMeta.copy(changes = singleChanges) } @@ -163,8 +164,9 @@ class MySqlBatchChangeRepository case Left(e) => throw e } - def getBatchFromSingleChangeId(singleChangeId: String)( - implicit s: DBSession): Option[BatchChange] = + def getBatchFromSingleChangeId( + singleChangeId: String + )(implicit s: DBSession): Option[BatchChange] = GET_BATCH_CHANGE_METADATA_FROM_SINGLE_CHANGE .bind(singleChangeId) .map(extractBatchChange(None)) @@ -182,7 +184,8 @@ class MySqlBatchChangeRepository monitor("repo.BatchChangeJDBC.updateSingleChanges") { IO { logger.info( - s"Updating single change statuses: ${singleChanges.map(ch => (ch.id, ch.status))}") + s"Updating single change statuses: ${singleChanges.map(ch => (ch.id, ch.status))}" + ) DB.localTx { implicit s => for { headChange <- singleChanges.headOption @@ -219,7 +222,8 @@ class MySqlBatchChangeRepository // log 1st 5; we shouldn't need all, and if there's a ton it could get long logger.error( s"!!! Could not find all SingleChangeIds in getSingleChanges call; missing IDs: ${notFound - .take(5)} !!!") + .take(5)} !!!" + ) } inDbChanges } @@ -230,7 +234,8 @@ class MySqlBatchChangeRepository userId: Option[String], startFrom: Option[Int] = None, maxItems: Int = 100, - approvalStatus: Option[BatchChangeApprovalStatus]): IO[BatchChangeSummaryList] = + approvalStatus: Option[BatchChangeApprovalStatus] + ): IO[BatchChangeSummaryList] = monitor("repo.BatchChangeJDBC.getBatchChangeSummaries") { IO { DB.readOnly { implicit s => @@ -272,7 +277,8 @@ class MySqlBatchChangeRepository pending > 0, failed > 0, complete > 0, - schedTime.isDefined), + schedTime.isDefined + ), Option(res.string("owner_group_id")), res.string("id"), None, @@ -296,7 +302,8 @@ class MySqlBatchChangeRepository nextId, maxItems, ignoreAccess, - approvalStatus) + approvalStatus + ) } } } @@ -334,8 +341,9 @@ class MySqlBatchChangeRepository ) } - private def saveBatchChange(batchChange: BatchChange)( - implicit session: DBSession): BatchChange = { + private def saveBatchChange( + batchChange: BatchChange + )(implicit session: DBSession): BatchChange = { PUT_BATCH_CHANGE .bindByName( Seq( diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlDataStoreProvider.scala b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlDataStoreProvider.scala index 690b6c8e1..a2d75e83b 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlDataStoreProvider.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlDataStoreProvider.scala @@ -82,7 +82,8 @@ class MySqlDataStoreProvider extends DataStoreProvider { // Configure the connection pool ConnectionPool.singleton( - new DataSourceConnectionPool(dataSource, closer = new HikariCloser(dataSource))) + new DataSourceConnectionPool(dataSource, closer = new HikariCloser(dataSource)) + ) logger.error("database init complete") } diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlGroupChangeRepository.scala b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlGroupChangeRepository.scala index 45a465e6a..a23a8d3cd 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlGroupChangeRepository.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlGroupChangeRepository.scala @@ -66,7 +66,8 @@ class MySqlGroupChangeRepository extends GroupChangeRepository with Monitored { IO { logger.info( s"Saving group change with (group_change_id, group_id): " + - s"(${groupChange.id}, ${groupChange.newGroup.id})") + s"(${groupChange.id}, ${groupChange.newGroup.id})" + ) DB.localTx { implicit s => PUT_GROUP_CHANGE .bindByName( @@ -100,11 +101,13 @@ class MySqlGroupChangeRepository extends GroupChangeRepository with Monitored { def getGroupChanges( groupId: String, startFrom: Option[String], - maxItems: Int): IO[ListGroupChangesResults] = + maxItems: Int + ): IO[ListGroupChangesResults] = monitor("repo.GroupChange.getGroupChanges") { IO { logger.info( - s"Getting group changes with (groupId, startFrom, maxItems): ($groupId, $startFrom, $maxItems)") + s"Getting group changes with (groupId, startFrom, maxItems): ($groupId, $startFrom, $maxItems)" + ) DB.readOnly { implicit s => val query = startFrom match { case Some(start) => diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlRecordChangeRepository.scala b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlRecordChangeRepository.scala index f8f576da3..c1c790e86 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlRecordChangeRepository.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlRecordChangeRepository.scala @@ -91,7 +91,8 @@ class MySqlRecordChangeRepository def listRecordSetChanges( zoneId: String, startFrom: Option[String], - maxItems: Int): IO[ListRecordSetChangesResults] = + maxItems: Int + ): IO[ListRecordSetChangesResults] = monitor("repo.RecordChange.listRecordSetChanges") { IO { DB.readOnly { implicit s => diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlRecordSetRepository.scala b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlRecordSetRepository.scala index b5393c8c9..13fb67a1e 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlRecordSetRepository.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlRecordSetRepository.scala @@ -109,7 +109,8 @@ class MySqlRecordSetRepository extends RecordSetRepository with Monitored { toPB(oldRs).toByteArray, toFQDN(change.zone.name, oldRs.name), oldRs.ownerGroupId, - oldRs.id) + oldRs.id + ) } } @@ -181,7 +182,8 @@ class MySqlRecordSetRepository extends RecordSetRepository with Monitored { zoneId: String, startFrom: Option[String], maxItems: Option[Int], - recordNameFilter: Option[String]): IO[ListRecordSetResults] = + recordNameFilter: Option[String] + ): IO[ListRecordSetResults] = monitor("repo.RecordSet.listRecordSets") { IO { DB.readOnly { implicit s => @@ -190,7 +192,8 @@ class MySqlRecordSetRepository extends RecordSetRepository with Monitored { // make sure we sort ascending, so we can do the correct comparison later val opts = (pagingKey.as( - "AND ((name >= {startFromName} AND type > {startFromType}) OR name > {startFromName})") ++ + "AND ((name >= {startFromName} AND type > {startFromType}) OR name > {startFromName})" + ) ++ recordNameFilter.as("AND name LIKE {nameFilter}") ++ Some("ORDER BY name ASC, type ASC") ++ maxItems.as("LIMIT {maxItems}")).toList.mkString(" ") diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlTaskRepository.scala b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlTaskRepository.scala index be7b12f2f..719566133 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlTaskRepository.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlTaskRepository.scala @@ -68,7 +68,8 @@ class MySqlTaskRepository extends TaskRepository { def claimTask( name: String, taskTimeout: FiniteDuration, - pollingInterval: FiniteDuration): IO[Boolean] = + pollingInterval: FiniteDuration + ): IO[Boolean] = IO { DB.localTx { implicit s => val adjustedPollingInterval = @@ -77,7 +78,8 @@ class MySqlTaskRepository extends TaskRepository { .bindByName( 'timeoutSeconds -> taskTimeout.toSeconds, 'pollingInterval -> adjustedPollingInterval.toSeconds, - 'taskName -> name) + 'taskName -> name + ) .first() .update() .apply() diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlUserRepository.scala b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlUserRepository.scala index d988c9829..937c433b7 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlUserRepository.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlUserRepository.scala @@ -83,7 +83,8 @@ class MySqlUserRepository(cryptoAlgebra: CryptoAlgebra) def getUsers( userIds: Set[String], startFrom: Option[String], - maxItems: Option[Int]): IO[ListUsersResults] = + maxItems: Option[Int] + ): IO[ListUsersResults] = monitor("repo.User.getUsers") { logger.info(s"Getting users with ids: $userIds") IO { diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlZoneChangeRepository.scala b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlZoneChangeRepository.scala index e1005f058..f0676683f 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlZoneChangeRepository.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlZoneChangeRepository.scala @@ -69,7 +69,8 @@ class MySqlZoneChangeRepository override def listZoneChanges( zoneId: String, startFrom: Option[String], - maxItems: Int): IO[ListZoneChangesResults] = + maxItems: Int + ): IO[ListZoneChangesResults] = // sorted from most recent, startFrom is an offset from the most recent change monitor("repo.ZoneChange.listZoneChanges") { IO { diff --git a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlZoneRepository.scala b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlZoneRepository.scala index 563ddca39..c94231d0b 100644 --- a/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlZoneRepository.scala +++ b/modules/mysql/src/main/scala/vinyldns/mysql/repository/MySqlZoneRepository.scala @@ -164,9 +164,10 @@ class MySqlZoneRepository extends ZoneRepository with ProtobufConversions with M IO { DB.readOnly { implicit s => val questionMarks = List.fill(zoneNames.size)("?").mkString(",") - SQL(BASE_GET_ZONES_SQL + - s"""WHERE name in ($questionMarks)""".stripMargin) - .bind(zoneNames: _*) + SQL( + BASE_GET_ZONES_SQL + + s"""WHERE name in ($questionMarks)""".stripMargin + ).bind(zoneNames: _*) .map(extractZone(1)) .list() .apply() @@ -199,8 +200,10 @@ class MySqlZoneRepository extends ZoneRepository with ProtobufConversions with M val whereClause = clause.mkString(" OR ") val zn = zoneNameList.map(name => s"%$name%") - SQL(BASE_GET_ZONES_SQL + - " WHERE " + whereClause).bind(zn: _*).map(extractZone(1)).list().apply() + SQL( + BASE_GET_ZONES_SQL + + " WHERE " + whereClause + ).bind(zn: _*).map(extractZone(1)).list().apply() }.toSet } } @@ -220,7 +223,8 @@ class MySqlZoneRepository extends ZoneRepository with ProtobufConversions with M zoneNameFilter: Option[String] = None, startFrom: Option[String] = None, maxItems: Int = 100, - ignoreAccess: Boolean = false): IO[ListZonesResults] = + ignoreAccess: Boolean = false + ): IO[ListZonesResults] = monitor("repo.ZoneJDBC.listZones") { IO { DB.readOnly { implicit s => @@ -292,7 +296,8 @@ class MySqlZoneRepository extends ZoneRepository with ProtobufConversions with M private def withAccessors( user: User, groupIds: Seq[String], - ignoreAccessZones: Boolean): (String, Seq[Any]) = + ignoreAccessZones: Boolean + ): (String, Seq[Any]) = // Super users do not need to join across to check zone access as they have access to all of the zones if (ignoreAccessZones || user.isSuper || user.isSupport) { (BASE_ZONE_SEARCH_SQL, Seq.empty) @@ -315,7 +320,8 @@ class MySqlZoneRepository extends ZoneRepository with ProtobufConversions with M if (allAccessors.length > MAX_ACCESSORS) { logger.warn( - s"User ${user.userName} with id ${user.id} is in more than $MAX_ACCESSORS groups, no all zones maybe returned!") + s"User ${user.userName} with id ${user.id} is in more than $MAX_ACCESSORS groups, no all zones maybe returned!" + ) } // Take the top 30 accessors, but add "EVERYONE" to the list so that we include zones that have everyone access @@ -407,7 +413,8 @@ class MySqlZoneRepository extends ZoneRepository with ProtobufConversions with M f: A => IO[Either[E, A]], a: A, delay: FiniteDuration, - maxRetries: Int): IO[Either[E, A]] = + maxRetries: Int + ): IO[Either[E, A]] = f(a).handleErrorWith { error => if (maxRetries > 0) IO.sleep(delay) *> retryWithBackoff(f, a, delay * 2, maxRetries - 1) diff --git a/modules/mysql/src/test/scala/vinyldns/mysql/repository/MySqlDataStoreProviderSpec.scala b/modules/mysql/src/test/scala/vinyldns/mysql/repository/MySqlDataStoreProviderSpec.scala index 764ab382b..e6e350ee7 100644 --- a/modules/mysql/src/test/scala/vinyldns/mysql/repository/MySqlDataStoreProviderSpec.scala +++ b/modules/mysql/src/test/scala/vinyldns/mysql/repository/MySqlDataStoreProviderSpec.scala @@ -53,7 +53,8 @@ class MySqlDataStoreProviderSpec extends WordSpec with Matchers { | zone {}, | batch-change {} | } - | """.stripMargin) + | """.stripMargin + ) val badSettings = pureconfig.loadConfigOrThrow[DataStoreConfig](badConfig) diff --git a/modules/mysql/src/test/scala/vinyldns/mysql/repository/MySqlZoneRepositorySpec.scala b/modules/mysql/src/test/scala/vinyldns/mysql/repository/MySqlZoneRepositorySpec.scala index ae9e4bea3..02ffa4c3d 100644 --- a/modules/mysql/src/test/scala/vinyldns/mysql/repository/MySqlZoneRepositorySpec.scala +++ b/modules/mysql/src/test/scala/vinyldns/mysql/repository/MySqlZoneRepositorySpec.scala @@ -51,7 +51,8 @@ class MySqlZoneRepositorySpec any[Zone => IO[Either[DuplicateZoneError, Zone]]](), any[Zone], any[FiniteDuration], - any[Int]) + any[Int] + ) verify(repo).saveTx(zoneInput) result shouldEqual Right(zoneInput) @@ -73,7 +74,8 @@ class MySqlZoneRepositorySpec any[Zone => IO[Either[DuplicateZoneError, Zone]]](), any[Zone], any[FiniteDuration], - any[Int]) + any[Int] + ) verify(repo, times(repo.MAX_RETRIES + 1)).saveTx(zoneInput) } @@ -93,7 +95,8 @@ class MySqlZoneRepositorySpec any[Zone => IO[Either[DuplicateZoneError, Zone]]](), any[Zone], any[FiniteDuration], - any[Int]) + any[Int] + ) verify(repo, times(3)).saveTx(zoneInput) result shouldEqual Right(zoneInput) @@ -113,7 +116,8 @@ class MySqlZoneRepositorySpec any[Zone => IO[Either[DuplicateZoneError, Zone]]](), any[Zone], any[FiniteDuration], - any[Int]) + any[Int] + ) verify(repo).deleteTx(zoneInput) result shouldEqual Right(zoneInput) @@ -135,7 +139,8 @@ class MySqlZoneRepositorySpec any[Zone => IO[Either[DuplicateZoneError, Zone]]](), any[Zone], any[FiniteDuration], - any[Int]) + any[Int] + ) verify(repo, times(repo.MAX_RETRIES + 1)).deleteTx(zoneInput) } @@ -155,7 +160,8 @@ class MySqlZoneRepositorySpec any[Zone => IO[Either[DuplicateZoneError, Zone]]](), any[Zone], any[FiniteDuration], - any[Int]) + any[Int] + ) verify(repo, times(3)).deleteTx(zoneInput) result shouldEqual Right(zoneInput) diff --git a/modules/portal/app/actions/ApiAction.scala b/modules/portal/app/actions/ApiAction.scala index 3f4499ede..4045172e0 100644 --- a/modules/portal/app/actions/ApiAction.scala +++ b/modules/portal/app/actions/ApiAction.scala @@ -33,11 +33,11 @@ import scala.concurrent.{ExecutionContext, Future} * If the user is locked out, return Forbidden message * Otherwise, load the account into a custom UserAccountRequest and pass into the action */ -class LegacyApiAction @Inject()( +class LegacyApiAction @Inject() ( val userLookup: String => IO[Option[User]], val oidcAuthenticator: OidcAuthenticator, - val parser: BodyParser[AnyContent]) - extends VinylDnsAction + val parser: BodyParser[AnyContent] +) extends VinylDnsAction with ApiActionBuilder with CacheHeader { @@ -46,13 +46,14 @@ class LegacyApiAction @Inject()( def notLoggedInResult: Future[Result] = Future.successful( - Unauthorized("You are not logged in. Please login to continue.").withHeaders( - cacheHeaders: _*)) + Unauthorized("You are not logged in. Please login to continue.").withHeaders(cacheHeaders: _*) + ) def cantFindAccountResult(un: String): Future[Result] = Future.successful( NotFound(s"Unable to find user account for user name '$un'") - .withHeaders(cacheHeaders: _*)) + .withHeaders(cacheHeaders: _*) + ) def lockedUserResult(un: String): Future[Result] = Future.successful(Forbidden(s"User account for `$un` is locked.").withHeaders(cacheHeaders: _*)) diff --git a/modules/portal/app/actions/FrontendAction.scala b/modules/portal/app/actions/FrontendAction.scala index a094e1acc..315dc7338 100644 --- a/modules/portal/app/actions/FrontendAction.scala +++ b/modules/portal/app/actions/FrontendAction.scala @@ -35,8 +35,8 @@ import scala.concurrent.{ExecutionContext, Future} class LegacyFrontendAction( val userLookup: String => IO[Option[User]], val oidcAuthenticator: OidcAuthenticator, - val parser: BodyParser[AnyContent]) - extends VinylDnsAction + val parser: BodyParser[AnyContent] +) extends VinylDnsAction with FrontendActionBuilder with CacheHeader { @@ -48,17 +48,20 @@ class LegacyFrontendAction( Redirect("/login") .flashing(VinylDNS.Alerts.error("You are not logged in. Please login to continue.")) .withNewSession - .withHeaders(cacheHeaders: _*)) + .withHeaders(cacheHeaders: _*) + ) def cantFindAccountResult(un: String): Future[Result] = Future.successful( Redirect("/login") .flashing(VinylDNS.Alerts.error(s"Unable to find user account for user name '$un'")) .withNewSession - .withHeaders(cacheHeaders: _*)) + .withHeaders(cacheHeaders: _*) + ) def lockedUserResult(un: String): Future[Result] = Future.successful( Redirect("/noaccess").withNewSession - .withHeaders(cacheHeaders: _*)) + .withHeaders(cacheHeaders: _*) + ) } diff --git a/modules/portal/app/actions/LegacySecuritySupport.scala b/modules/portal/app/actions/LegacySecuritySupport.scala index 5984cd07a..41b87aa7c 100644 --- a/modules/portal/app/actions/LegacySecuritySupport.scala +++ b/modules/portal/app/actions/LegacySecuritySupport.scala @@ -22,12 +22,12 @@ import org.slf4j.LoggerFactory import play.api.Configuration import play.api.mvc._ -class LegacySecuritySupport @Inject()( +class LegacySecuritySupport @Inject() ( components: ControllerComponents, userAccountAccessor: UserAccountAccessor, configuration: Configuration, - oidcAuthenticator: OidcAuthenticator) - extends AbstractController(components) + oidcAuthenticator: OidcAuthenticator +) extends AbstractController(components) with SecuritySupport { private val logger = LoggerFactory.getLogger(classOf[LegacySecuritySupport]) @@ -35,7 +35,8 @@ class LegacySecuritySupport @Inject()( new LegacyFrontendAction( userAccountAccessor.get, oidcAuthenticator, - components.parsers.anyContent) + components.parsers.anyContent + ) def apiAction: ApiActionBuilder = new LegacyApiAction(userAccountAccessor.get, oidcAuthenticator, components.parsers.anyContent) @@ -92,6 +93,8 @@ class LegacySecuritySupport @Inject()( views.html.systemMessage( """ |Account locked. Please contact your VinylDNS administrators for more information. - """.stripMargin)) + """.stripMargin + ) + ) } } diff --git a/modules/portal/app/actions/VinylDnsAction.scala b/modules/portal/app/actions/VinylDnsAction.scala index e68ef0eb9..1ef03b377 100644 --- a/modules/portal/app/actions/VinylDnsAction.scala +++ b/modules/portal/app/actions/VinylDnsAction.scala @@ -50,7 +50,8 @@ trait VinylDnsAction extends ActionFunction[Request, UserRequest] { def invokeBlock[A]( request: Request[A], - block: UserRequest[A] => Future[Result]): Future[Result] = { + block: UserRequest[A] => Future[Result] + ): Future[Result] = { // if the user name is not in session, or token is invalid reject val userName = if (oidcEnabled) { getValidUsernameOidc(request.session) diff --git a/modules/portal/app/controllers/CacheHeader.scala b/modules/portal/app/controllers/CacheHeader.scala index 07b0abd56..87d9beeea 100644 --- a/modules/portal/app/controllers/CacheHeader.scala +++ b/modules/portal/app/controllers/CacheHeader.scala @@ -20,5 +20,6 @@ trait CacheHeader { val cacheHeaders = Seq( ("Cache-Control", "no-cache, no-store, must-revalidate"), ("Pragma", "no-cache"), - ("Expires", "0")) + ("Expires", "0") + ) } diff --git a/modules/portal/app/controllers/FrontendController.scala b/modules/portal/app/controllers/FrontendController.scala index c90bf3a86..5ec9f1bd1 100644 --- a/modules/portal/app/controllers/FrontendController.scala +++ b/modules/portal/app/controllers/FrontendController.scala @@ -30,7 +30,7 @@ import scala.concurrent.Future * Controller for specific pages - sends requests along to views */ @Singleton -class FrontendController @Inject()( +class FrontendController @Inject() ( components: ControllerComponents, configuration: Configuration, securitySupport: SecuritySupport @@ -50,8 +50,11 @@ class FrontendController @Inject()( def index(): Action[AnyContent] = userAction.async { implicit request => val canReview = request.user.isSuper || request.user.isSupport Future( - Ok(views.html.dnsChanges - .dnsChanges(request.user.userName, canReview))) + Ok( + views.html.dnsChanges + .dnsChanges(request.user.userName, canReview) + ) + ) } def viewAllGroups(): Action[AnyContent] = userAction.async { implicit request => @@ -74,16 +77,22 @@ class FrontendController @Inject()( def viewAllBatchChanges(): Action[AnyContent] = userAction.async { implicit request => val canReview = request.user.isSuper || request.user.isSupport Future( - Ok(views.html.dnsChanges - .dnsChanges(request.user.userName, canReview))) + Ok( + views.html.dnsChanges + .dnsChanges(request.user.userName, canReview) + ) + ) } def viewBatchChange(batchId: String): Action[AnyContent] = userAction.async { implicit request => logger.info(s"View Batch Change for $batchId") val canReview = request.user.isSuper || request.user.isSupport Future( - Ok(views.html.dnsChanges - .dnsChangeDetail(request.user.userName, canReview))) + Ok( + views.html.dnsChanges + .dnsChangeDetail(request.user.userName, canReview) + ) + ) } def viewNewBatchChange(): Action[AnyContent] = userAction.async { implicit request => diff --git a/modules/portal/app/controllers/HealthController.scala b/modules/portal/app/controllers/HealthController.scala index 942f517d5..0067cb8fe 100644 --- a/modules/portal/app/controllers/HealthController.scala +++ b/modules/portal/app/controllers/HealthController.scala @@ -21,7 +21,7 @@ import play.api.mvc.{AbstractController, Action, AnyContent, ControllerComponent import vinyldns.core.health.HealthService @Singleton -class HealthController @Inject()(components: ControllerComponents, healthService: HealthService) +class HealthController @Inject() (components: ControllerComponents, healthService: HealthService) extends AbstractController(components) with CacheHeader { diff --git a/modules/portal/app/controllers/LdapAuthenticator.scala b/modules/portal/app/controllers/LdapAuthenticator.scala index 78823a326..2ccf7edf7 100644 --- a/modules/portal/app/controllers/LdapAuthenticator.scala +++ b/modules/portal/app/controllers/LdapAuthenticator.scala @@ -36,8 +36,8 @@ case class LdapUserDetails( username: String, email: Option[String], firstName: Option[String], - lastName: Option[String]) - extends UserDetails + lastName: Option[String] +) extends UserDetails object LdapUserDetails { private def getValue(attributes: Attributes, attributeName: String): Option[String] = @@ -88,7 +88,7 @@ object LdapAuthenticator { case Failure(e) => Left(LdapServiceException(e.toString)) } - } + } // $COVERAGE-ON$ private[controllers] object LdapByDomainAuthenticator { @@ -104,7 +104,8 @@ object LdapAuthenticator { */ private[controllers] class LdapByDomainAuthenticator( settings: Settings, - createContext: ContextCreator) { + createContext: ContextCreator + ) { private val SEARCH_BASE = settings.ldapSearchBase .map(searchDomain ⇒ searchDomain.organization → searchDomain.domainName) @@ -113,13 +114,15 @@ object LdapAuthenticator { def searchContext( dirContext: DirContext, organization: String, - lookupUserName: String): Either[LdapException, LdapUserDetails] = + lookupUserName: String + ): Either[LdapException, LdapUserDetails] = try { val searchControls = new SearchControls() searchControls.setSearchScope(2) logger.info( - s"LDAP Search: org='${SEARCH_BASE(organization)}'; userName='$lookupUserName'; field='${settings.ldapUserNameAttribute}'") + s"LDAP Search: org='${SEARCH_BASE(organization)}'; userName='$lookupUserName'; field='${settings.ldapUserNameAttribute}'" + ) val result = dirContext.search( SEARCH_BASE(organization), @@ -133,7 +136,8 @@ object LdapAuthenticator { case unexpectedError: Throwable => logger.error( s"LDAP Unexpected Error searching for user; userName='$lookupUserName'", - unexpectedError) + unexpectedError + ) Left(LdapServiceException(unexpectedError.getMessage)) } finally { Try(dirContext.close()) @@ -142,7 +146,8 @@ object LdapAuthenticator { private[controllers] def authenticate( searchDomain: LdapSearchDomain, username: String, - password: String): Either[LdapException, LdapUserDetails] = { + password: String + ): Either[LdapException, LdapUserDetails] = { // Login as the service account val qualifiedName = @@ -164,7 +169,8 @@ object LdapAuthenticator { private[controllers] def lookup( searchDomain: LdapSearchDomain, user: String, - serviceAccount: ServiceAccount): Either[LdapException, LdapUserDetails] = { + serviceAccount: ServiceAccount + ): Either[LdapException, LdapUserDetails] = { // User lookup is done using the service account val qualifiedName = @@ -189,12 +195,15 @@ object LdapAuthenticator { new LdapAuthenticator( settings.ldapSearchBase, LdapByDomainAuthenticator(settings), - serviceAccount)) + serviceAccount + ) + ) else new LdapAuthenticator( settings.ldapSearchBase, LdapByDomainAuthenticator(settings), - serviceAccount) + serviceAccount + ) } } @@ -217,8 +226,8 @@ final case class NoLdapSearchDomainsConfigured() class LdapAuthenticator( searchBase: List[LdapSearchDomain], authenticator: LdapByDomainAuthenticator, - serviceAccount: ServiceAccount) - extends Authenticator { + serviceAccount: ServiceAccount +) extends Authenticator { private val logger = LoggerFactory.getLogger(classOf[LdapAuthenticator]) private implicit val cs: ContextShift[IO] = @@ -241,7 +250,8 @@ class LdapAuthenticator( domains: List[LdapSearchDomain], userName: String, f: LdapSearchDomain => Either[LdapException, LdapUserDetails], - allDomainConnectionsUp: Boolean): Either[LdapException, LdapUserDetails] = + allDomainConnectionsUp: Boolean + ): Either[LdapException, LdapUserDetails] = domains match { case Nil => if (allDomainConnectionsUp) @@ -249,7 +259,9 @@ class LdapAuthenticator( else Left( LdapServiceException( - "Unable to successfully perform search in at least one LDAP domain")) + "Unable to successfully perform search in at least one LDAP domain" + ) + ) case h :: t => f(h).recoverWith { case _: UserDoesNotExistException => @@ -314,19 +326,22 @@ class TestAuthenticator(authenticator: Authenticator) extends Authenticator { "testuser", Some("test@test.test"), Some("Test"), - Some("User")) + Some("User") + ) private val recordPagingTestUserDetails = LdapUserDetails( "O=test,OU=testdata,CN=recordPagingTestUser", "recordPagingTestUser", Some("test@test.test"), Some("Test"), - Some("User")) + Some("User") + ) private val supportTestUserDetails = LdapUserDetails( "O=test,OU=testdata,CN=supportTestUser", "support-user", Some("test@test.test"), Some("Support"), - Some("User")) + Some("User") + ) def authenticate(username: String, password: String): Either[LdapException, LdapUserDetails] = (username, password) match { diff --git a/modules/portal/app/controllers/OidcAuthenticator.scala b/modules/portal/app/controllers/OidcAuthenticator.scala index 5fd01b73d..ee0ff1485 100644 --- a/modules/portal/app/controllers/OidcAuthenticator.scala +++ b/modules/portal/app/controllers/OidcAuthenticator.scala @@ -59,19 +59,20 @@ object OidcAuthenticator { jwtFirstnameField: String, jwtLastnameField: String, jwtEmailField: String = "email", - scope: String = "openid profile email") + scope: String = "openid profile email" + ) final case class OidcUserDetails( username: String, email: Option[String], firstName: Option[String], - lastName: Option[String]) - extends UserDetails + lastName: Option[String] + ) extends UserDetails final case class ErrorResponse(code: Int, message: String) } @Singleton -class OidcAuthenticator @Inject()(wsClient: WSClient, configuration: Configuration) { +class OidcAuthenticator @Inject() (wsClient: WSClient, configuration: Configuration) { import OidcAuthenticator._ @@ -203,7 +204,8 @@ class OidcAuthenticator @Inject()(wsClient: WSClient, configuration: Configurati for { username <- getStringFieldOption(claimsSet, oidcInfo.jwtUsernameField) .toRight[ErrorResponse]( - ErrorResponse(500, "Username field not included in token from from OIDC provider")) + ErrorResponse(500, "Username field not included in token from from OIDC provider") + ) email = getStringFieldOption(claimsSet, oidcInfo.jwtEmailField) firstname = getStringFieldOption(claimsSet, oidcInfo.jwtFirstnameField) lastname = getStringFieldOption(claimsSet, oidcInfo.jwtLastnameField) @@ -238,7 +240,8 @@ class OidcAuthenticator @Inject()(wsClient: WSClient, configuration: Configurati } def oidcCallback(code: AuthorizationCode, loginId: String)( - implicit executionContext: ExecutionContext): EitherT[IO, ErrorResponse, JWTClaimsSet] = + implicit executionContext: ExecutionContext + ): EitherT[IO, ErrorResponse, JWTClaimsSet] = EitherT { val redirectUriString = s"${oidcInfo.redirectUri}/callback/$loginId" val redirectUri = new URI(redirectUriString) diff --git a/modules/portal/app/controllers/UserAccountAccessor.scala b/modules/portal/app/controllers/UserAccountAccessor.scala index 80314eb37..ee6c0d978 100644 --- a/modules/portal/app/controllers/UserAccountAccessor.scala +++ b/modules/portal/app/controllers/UserAccountAccessor.scala @@ -23,7 +23,7 @@ import org.joda.time.DateTime import vinyldns.core.domain.membership._ @Singleton -class UserAccountAccessor @Inject()(users: UserRepository, changes: UserChangeRepository) { +class UserAccountAccessor @Inject() (users: UserRepository, changes: UserChangeRepository) { implicit val cs: ContextShift[IO] = IO.contextShift(scala.concurrent.ExecutionContext.global) diff --git a/modules/portal/app/controllers/VinylDNS.scala b/modules/portal/app/controllers/VinylDNS.scala index ca42fbb4c..9e609e001 100644 --- a/modules/portal/app/controllers/VinylDNS.scala +++ b/modules/portal/app/controllers/VinylDNS.scala @@ -69,7 +69,8 @@ object VinylDNS { isSuper: Boolean, isSupport: Boolean, id: String, - lockStatus: LockStatus) + lockStatus: LockStatus + ) object UserInfo { def fromUser(user: User): UserInfo = UserInfo( @@ -93,7 +94,7 @@ object VinylDNS { } @Singleton -class VinylDNS @Inject()( +class VinylDNS @Inject() ( configuration: Configuration, authenticator: Authenticator, userAccountAccessor: UserAccountAccessor, @@ -101,8 +102,8 @@ class VinylDNS @Inject()( components: ControllerComponents, crypto: CryptoAlgebra, oidcAuthenticator: OidcAuthenticator, - securitySupport: SecuritySupport) - extends AbstractController(components) + securitySupport: SecuritySupport +) extends AbstractController(components) with CacheHeader { import VinylDNS._ @@ -152,7 +153,8 @@ class VinylDNS @Inject()( .map { case Right((user, token)) => logger.info( - s"LoginId [$loginId] complete: --LOGIN-- user [${user.userName}] logged in with id ${user.id}") + s"LoginId [$loginId] complete: --LOGIN-- user [${user.userName}] logged in with id ${user.id}" + ) Redirect("/index").withSession(ID_TOKEN -> token.toString) case Left(err) => logger.error(s"LoginId [$loginId] failed with error: $err") @@ -161,7 +163,8 @@ class VinylDNS @Inject()( |There was an issue when logging in. |Please try again by clicking this link. |If the issue persists, contact your VinylDNS Administrators - """.stripMargin)).withNewSession + """.stripMargin) + ).withNewSession } .unsafeToFuture() } @@ -250,15 +253,17 @@ class VinylDNS @Inject()( private def processCsv(user: User): Result = { logger.info( - s"Sending credentials for user=${user.userName} with key accessKey=${user.accessKey}") + s"Sending credentials for user=${user.userName} with key accessKey=${user.accessKey}" + ) Ok( s"NT ID, access key, secret key,api url\n%s,%s,%s,%s" .format( user.userName, user.accessKey, crypto.decrypt(user.secretKey), - vinyldnsServiceBackend)) - .as("text/csv") + vinyldnsServiceBackend + ) + ).as("text/csv") } def serveCredsFile(fileName: String): Action[AnyContent] = frontendAction.async { @@ -300,7 +305,8 @@ class VinylDNS @Inject()( User.generateKey, details.firstName, details.lastName, - details.email) + details.email + ) userAccountAccessor.create(newUser).map { u => logger.info(s"User account for ${u.userName} created with id ${u.id}") @@ -336,18 +342,22 @@ class VinylDNS @Inject()( case Left(error: UserDoesNotExistException) => logger.error(s"Authentication failed for [$username]", error) Redirect("/login").flashing( - VinylDNS.Alerts.error("Authentication failed, please try again")) + VinylDNS.Alerts.error("Authentication failed, please try again") + ) case Left(error: LdapException) => logger.error( "An unexpected error occurred when authenticating, please contact your VinylDNS " + "administrators", - error) + error + ) Redirect("/login").flashing( - VinylDNS.Alerts.error( - "Authentication failed, please contact your VinylDNS administrators")) + VinylDNS.Alerts + .error("Authentication failed, please contact your VinylDNS administrators") + ) case Right(userDetails: LdapUserDetails) => logger.info( - s"user [${userDetails.username}] logged in with ldap path [${userDetails.nameInNamespace}]") + s"user [${userDetails.username}] logged in with ldap path [${userDetails.nameInNamespace}]" + ) val user = processLoginWithDetails(userDetails).unsafeRunSync() logger.info(s"--LOGIN-- user [${user.userName}] logged in with id [${user.id}]") Redirect("/index") @@ -420,7 +430,8 @@ class VinylDNS @Inject()( "GET", s"$vinyldnsServiceBackend", s"zones/$id/recordsets", - parameters = queryParameters) + parameters = queryParameters + ) executeRequest(vinyldnsRequest, request.user).map(response => { Status(response.status)(response.body) .withHeaders(cacheHeaders: _*) @@ -438,7 +449,8 @@ class VinylDNS @Inject()( "GET", s"$vinyldnsServiceBackend", s"zones/$id/recordsetchanges", - parameters = queryParameters) + parameters = queryParameters + ) executeRequest(vinyldnsRequest, request.user).map(response => { Status(response.status)(response.body) .withHeaders(cacheHeaders: _*) @@ -505,7 +517,8 @@ class VinylDNS @Inject()( "PUT", s"$vinyldnsServiceBackend", s"zones/$zid/recordsets/$rid", - payload) + payload + ) executeRequest(vinyldnsRequest, request.user).map(response => { Status(response.status)(response.body) .withHeaders(cacheHeaders: _*) @@ -526,7 +539,8 @@ class VinylDNS @Inject()( } private def extractParameters( - params: util.Map[String, util.List[String]]): Seq[(String, String)] = + params: util.Map[String, util.List[String]] + ): Seq[(String, String)] = params.asScala.foldLeft(Seq[(String, String)]()) { case (acc, (key, values)) => acc ++ values.asScala.map(v => key -> v) @@ -544,7 +558,8 @@ class VinylDNS @Inject()( signableRequest.getOriginalRequestObject .asInstanceOf[VinylDNSRequest] .payload - .getOrElse("")) + .getOrElse("") + ) .withHttpHeaders(signableRequest.getHeaders.asScala.toSeq: _*) .withMethod(signableRequest.getHttpMethod.name()) .withQueryStringParameters(extractParameters(signableRequest.getParameters): _*) @@ -561,7 +576,8 @@ class VinylDNS @Inject()( "GET", s"$vinyldnsServiceBackend", s"groups/$groupId/members", - parameters = queryParameters) + parameters = queryParameters + ) executeRequest(vinyldnsRequest, request.user).map(response => { Status(response.status)(response.body) .withHeaders(cacheHeaders: _*) @@ -575,7 +591,8 @@ class VinylDNS @Inject()( new VinylDNSRequest( "GET", s"$vinyldnsServiceBackend", - s"zones/batchrecordchanges/$batchChangeId") + s"zones/batchrecordchanges/$batchChangeId" + ) executeRequest(vinyldnsRequest, request.user).map(response => { Status(response.status)(response.body) .withHeaders(cacheHeaders: _*) @@ -597,7 +614,8 @@ class VinylDNS @Inject()( s"$vinyldnsServiceBackend", "zones/batchrecordchanges", payload, - parameters = queryParameters) + parameters = queryParameters + ) executeRequest(vinyldnsRequest, request.user).map(response => { logger.info(response.body) Status(response.status)(response.body) @@ -616,7 +634,8 @@ class VinylDNS @Inject()( "GET", s"$vinyldnsServiceBackend", "zones/batchrecordchanges", - parameters = queryParameters) + parameters = queryParameters + ) executeRequest(vinyldnsRequest, request.user).map(response => { logger.info(response.body) Status(response.status)(response.body) @@ -632,7 +651,8 @@ class VinylDNS @Inject()( new VinylDNSRequest( "POST", s"$vinyldnsServiceBackend", - s"zones/batchrecordchanges/$batchChangeId/cancel") + s"zones/batchrecordchanges/$batchChangeId/cancel" + ) executeRequest(vinyldnsRequest, request.user).map(response => { Status(response.status)(response.body) .withHeaders(cacheHeaders: _*) @@ -650,7 +670,8 @@ class VinylDNS @Inject()( "POST", s"$vinyldnsServiceBackend", s"zones/batchrecordchanges/$batchChangeId/approve", - payload) + payload + ) executeRequest(vinyldnsRequest, request.user).map(response => { Status(response.status)(response.body) .withHeaders(cacheHeaders: _*) @@ -668,7 +689,8 @@ class VinylDNS @Inject()( "POST", s"$vinyldnsServiceBackend", s"zones/batchrecordchanges/$batchChangeId/reject", - payload) + payload + ) executeRequest(vinyldnsRequest, request.user).map(response => { Status(response.status)(response.body) .withHeaders(cacheHeaders: _*) @@ -686,7 +708,8 @@ class VinylDNS @Inject()( }) } else { Future.successful( - Forbidden("Request restricted to super users only.").withHeaders(cacheHeaders: _*)) + Forbidden("Request restricted to super users only.").withHeaders(cacheHeaders: _*) + ) } } @@ -700,7 +723,8 @@ class VinylDNS @Inject()( }) } else { Future.successful( - Forbidden("Request restricted to super users only.").withHeaders(cacheHeaders: _*)) + Forbidden("Request restricted to super users only.").withHeaders(cacheHeaders: _*) + ) } } } diff --git a/modules/portal/app/controllers/repository/PortalDataAccessor.scala b/modules/portal/app/controllers/repository/PortalDataAccessor.scala index 17cb4039c..9455ea8e2 100644 --- a/modules/portal/app/controllers/repository/PortalDataAccessor.scala +++ b/modules/portal/app/controllers/repository/PortalDataAccessor.scala @@ -23,5 +23,5 @@ import vinyldns.core.task.TaskRepository final case class PortalDataAccessor( userRepository: UserRepository, userChangeRepository: UserChangeRepository, - taskRepository: TaskRepository) - extends DataAccessor + taskRepository: TaskRepository +) extends DataAccessor diff --git a/modules/portal/app/controllers/repository/PortalDataAccessorProvider.scala b/modules/portal/app/controllers/repository/PortalDataAccessorProvider.scala index fd8adacee..c2251ab29 100644 --- a/modules/portal/app/controllers/repository/PortalDataAccessorProvider.scala +++ b/modules/portal/app/controllers/repository/PortalDataAccessorProvider.scala @@ -30,7 +30,8 @@ object PortalDataAccessorProvider extends DataAccessorProvider[PortalDataAccesso List(user, userChange) def create( - dataStores: List[(DataStoreConfig, DataStore)]): ValidatedNel[String, PortalDataAccessor] = + dataStores: List[(DataStoreConfig, DataStore)] + ): ValidatedNel[String, PortalDataAccessor] = ( getRepoOf[UserRepository](dataStores, user), getRepoOf[UserChangeRepository](dataStores, userChange), diff --git a/modules/portal/app/filters/AccessLoggingFilter.scala b/modules/portal/app/filters/AccessLoggingFilter.scala index e25e8d637..f8de203e0 100644 --- a/modules/portal/app/filters/AccessLoggingFilter.scala +++ b/modules/portal/app/filters/AccessLoggingFilter.scala @@ -24,10 +24,10 @@ import play.mvc.Http import scala.concurrent.{ExecutionContext, Future} -class AccessLoggingFilter @Inject()( +class AccessLoggingFilter @Inject() ( implicit val mat: Materializer, - executionContext: ExecutionContext) - extends Filter { + executionContext: ExecutionContext +) extends Filter { private val logger = LoggerFactory.getLogger(classOf[AccessLoggingFilter]) diff --git a/modules/portal/app/models/CustomLinks.scala b/modules/portal/app/models/CustomLinks.scala index 6e1fdfce2..b51325535 100644 --- a/modules/portal/app/models/CustomLinks.scala +++ b/modules/portal/app/models/CustomLinks.scala @@ -46,4 +46,5 @@ case class CustomLink( displayOnLoginScreen: Boolean, title: String, href: String, - icon: String) + icon: String +) diff --git a/modules/portal/app/models/Meta.scala b/modules/portal/app/models/Meta.scala index b69edaeb6..f1e4cbf9a 100644 --- a/modules/portal/app/models/Meta.scala +++ b/modules/portal/app/models/Meta.scala @@ -23,7 +23,8 @@ case class Meta( batchChangeLimit: Int, defaultTtl: Long, manualBatchChangeReviewEnabled: Boolean, - scheduledBatchChangesEnabled: Boolean) + scheduledBatchChangesEnabled: Boolean +) object Meta { def apply(config: Configuration): Meta = Meta( diff --git a/modules/portal/app/models/VinylRequest.scala b/modules/portal/app/models/VinylRequest.scala index a958cc574..cbf5d16c2 100644 --- a/modules/portal/app/models/VinylRequest.scala +++ b/modules/portal/app/models/VinylRequest.scala @@ -32,7 +32,8 @@ case class VinylDNSRequest( path: String = "", payload: Option[String] = None, parameters: util.HashMap[String, java.util.List[String]] = - new util.HashMap[String, java.util.List[String]]()) + new util.HashMap[String, java.util.List[String]]() +) class SignableVinylDNSRequest(origReq: VinylDNSRequest) extends SignableRequest[VinylDNSRequest] { @@ -46,7 +47,8 @@ class SignableVinylDNSRequest(origReq: VinylDNSRequest) extends SignableRequest[ // I hate to do this, but need to be able to set the content after creation to // implement the interface properly private var contentStream: InputStream = new ByteArrayInputStream( - origReq.payload.getOrElse("").getBytes("UTF-8")) + origReq.payload.getOrElse("").getBytes("UTF-8") + ) override def addHeader(name: String, value: String): Unit = headers.put(name, value) override def getHeaders: java.util.Map[String, String] = headers diff --git a/modules/portal/app/modules/VinylDNSModule.scala b/modules/portal/app/modules/VinylDNSModule.scala index 03b8f3e4a..889153d6c 100644 --- a/modules/portal/app/modules/VinylDNSModule.scala +++ b/modules/portal/app/modules/VinylDNSModule.scala @@ -66,7 +66,8 @@ class VinylDNSModule(environment: Environment, configuration: Configuration) repositories = loaderResponse.accessor userAccessor = new UserAccountAccessor( repositories.userRepository, - repositories.userChangeRepository) + repositories.userChangeRepository + ) _ <- if (settings.ldapSyncEnabled) { TaskScheduler .schedule( diff --git a/modules/portal/app/tasks/UserSyncTask.scala b/modules/portal/app/tasks/UserSyncTask.scala index e7897eddc..052046bea 100644 --- a/modules/portal/app/tasks/UserSyncTask.scala +++ b/modules/portal/app/tasks/UserSyncTask.scala @@ -29,8 +29,8 @@ class UserSyncTask( authenticator: Authenticator, val runEvery: FiniteDuration = 24.hours, val timeout: FiniteDuration = 24.hours, - val checkInterval: FiniteDuration = 1.minute) - extends Task { + val checkInterval: FiniteDuration = 1.minute +) extends Task { val name: String = "user_sync" private val logger: Logger = LoggerFactory.getLogger("UserSyncTask") diff --git a/modules/portal/test/controllers/FrontendControllerSpec.scala b/modules/portal/test/controllers/FrontendControllerSpec.scala index fa5776c6f..da7cc5c97 100644 --- a/modules/portal/test/controllers/FrontendControllerSpec.scala +++ b/modules/portal/test/controllers/FrontendControllerSpec.scala @@ -105,7 +105,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "render the DNS Changes page when the user is logged in" in new WithApplication(app) { val result = underTest.index()( - FakeRequest(GET, "/index").withSession("username" -> "frodo").withCSRFToken) + FakeRequest(GET, "/index").withSession("username" -> "frodo").withCSRFToken + ) status(result) must beEqualTo(OK) contentType(result) must beSome.which(_ == "text/html") contentAsString(result) must contain("Are you sure you want to log out") @@ -114,7 +115,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "redirect to the no access page when a user is locked out" in new WithApplication(app) { val result = lockedUserUnderTest.index()( - FakeRequest(GET, "/index").withSession("username" -> "lockedFbaggins").withCSRFToken) + FakeRequest(GET, "/index").withSession("username" -> "lockedFbaggins").withCSRFToken + ) headers(result) must contain("Location" -> "/noaccess") } } @@ -127,7 +129,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "render the DNS Changes page when the user is logged in" in new WithApplication(app) { val result = oidcUnderTest.index()( - FakeRequest(GET, "/index").withSession(VinylDNS.ID_TOKEN -> "test").withCSRFToken) + FakeRequest(GET, "/index").withSession(VinylDNS.ID_TOKEN -> "test").withCSRFToken + ) status(result) must beEqualTo(OK) contentType(result) must beSome.which(_ == "text/html") @@ -146,7 +149,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "render the groups view page when the user is logged in" in new WithApplication(app) { val result = underTest.viewAllGroups()( - FakeRequest(GET, "/groups").withSession("username" -> "frodo").withCSRFToken) + FakeRequest(GET, "/groups").withSession("username" -> "frodo").withCSRFToken + ) status(result) must beEqualTo(OK) contentType(result) must beSome.which(_ == "text/html") contentAsString(result) must contain("Groups | VinylDNS") @@ -154,7 +158,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "redirect to the no access page when a user is locked out" in new WithApplication(app) { val result = lockedUserUnderTest.viewAllGroups()( - FakeRequest(GET, "/groups").withSession("username" -> "lockedFbaggins").withCSRFToken) + FakeRequest(GET, "/groups").withSession("username" -> "lockedFbaggins").withCSRFToken + ) headers(result) must contain("Location" -> "/noaccess") } } @@ -168,7 +173,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "render the groups view page when the user is logged in" in new WithApplication(app) { val result = underTest.viewGroup("some-id")( - FakeRequest(GET, "/groups").withSession("username" -> "frodo").withCSRFToken) + FakeRequest(GET, "/groups").withSession("username" -> "frodo").withCSRFToken + ) status(result) must beEqualTo(OK) contentType(result) must beSome.which(_ == "text/html") contentAsString(result) must contain("Group | VinylDNS") @@ -176,7 +182,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "redirect to the no access page when a user is locked out" in new WithApplication(app) { val result = lockedUserUnderTest.viewGroup("some-id")( - FakeRequest(GET, "/groups").withSession("username" -> "lockedFbaggins").withCSRFToken) + FakeRequest(GET, "/groups").withSession("username" -> "lockedFbaggins").withCSRFToken + ) headers(result) must contain("Location" -> "/noaccess") } } @@ -190,7 +197,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "render the zone view page when the user is logged in" in new WithApplication(app) { val result = underTest.viewAllZones()( - FakeRequest(GET, "/zones").withSession("username" -> "frodo").withCSRFToken) + FakeRequest(GET, "/zones").withSession("username" -> "frodo").withCSRFToken + ) status(result) must beEqualTo(OK) contentType(result) must beSome.which(_ == "text/html") contentAsString(result) must contain("Zones | VinylDNS") @@ -198,7 +206,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "redirect to the no access page when a user is locked out" in new WithApplication(app) { val result = lockedUserUnderTest.viewAllZones()( - FakeRequest(GET, "/zones").withSession("username" -> "lockedFbaggins").withCSRFToken) + FakeRequest(GET, "/zones").withSession("username" -> "lockedFbaggins").withCSRFToken + ) headers(result) must contain("Location" -> "/noaccess") } } @@ -212,7 +221,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "render the zones view page when the user is logged in" in new WithApplication(app) { val result = underTest.viewZone("some-id")( - FakeRequest(GET, "/zones/some-id").withSession("username" -> "frodo").withCSRFToken) + FakeRequest(GET, "/zones/some-id").withSession("username" -> "frodo").withCSRFToken + ) status(result) must beEqualTo(OK) contentType(result) must beSome.which(_ == "text/html") contentAsString(result) must contain("Zone | VinylDNS") @@ -222,7 +232,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica lockedUserUnderTest.viewZone("some-id")( FakeRequest(GET, "/zones/some-id") .withSession("username" -> "lockedFbaggins") - .withCSRFToken) + .withCSRFToken + ) headers(result) must contain("Location" -> "/noaccess") } } @@ -237,8 +248,10 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica } "redirect to the index page when the user is logged in" in new WithApplication(app) { val username = "LoggedInUser" - val result = underTest.loginPage()(FakeRequest(GET, "/login") - .withSession(("username", username))) + val result = underTest.loginPage()( + FakeRequest(GET, "/login") + .withSession(("username", username)) + ) status(result) must beEqualTo(SEE_OTHER) headers(result) must contain("Location" -> "/index") } @@ -246,7 +259,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica // redirects to the index page because the user is logged in, then locked status is checked there val result = lockedUserUnderTest.loginPage()( - FakeRequest(GET, "/login").withSession("username" -> "lockedFbaggins").withCSRFToken) + FakeRequest(GET, "/login").withSession("username" -> "lockedFbaggins").withCSRFToken + ) headers(result) must contain("Location" -> "/index") } } @@ -263,7 +277,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica oidcUnderTest.loginPage()( FakeRequest(GET, "/login") .withSession(VinylDNS.ID_TOKEN -> "test") - .withCSRFToken) + .withCSRFToken + ) status(result) must equalTo(SEE_OTHER) headers(result) must contain("Location" -> "/index") @@ -282,8 +297,10 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "clear the session cookie" in new WithApplication(app) { // TODO: cookie behavior is radically different in play 2.6, so we cannot look for a Set-Cookie header val username = "LoggedInUser" - val result = underTest.logout()(FakeRequest(GET, "/logout") - .withSession(("username", username))) + val result = underTest.logout()( + FakeRequest(GET, "/logout") + .withSession(("username", username)) + ) headers(result) must contain("Location" -> "/login") } } @@ -293,7 +310,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica oidcUnderTest.logout()( FakeRequest(GET, "/logout") .withSession(VinylDNS.ID_TOKEN -> "test") - .withCSRFToken) + .withCSRFToken + ) status(result) must equalTo(SEE_OTHER) headers(result) must contain("Location" -> "http://logout-test.com") @@ -305,7 +323,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "render the no access page when a user is locked out" in new WithApplication(app) { val result = lockedUserUnderTest.noAccess()( - FakeRequest(GET, "/noaccess").withSession("username" -> "lockedFbaggins").withCSRFToken) + FakeRequest(GET, "/noaccess").withSession("username" -> "lockedFbaggins").withCSRFToken + ) status(result) must beEqualTo(UNAUTHORIZED) contentType(result) must beSome.which(_ == "text/html") contentAsString(result) must contain("Account locked.") @@ -322,7 +341,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "render the batch changes view page when the user is logged in" in new WithApplication(app) { val result = underTest.viewAllBatchChanges()( - FakeRequest(GET, "/dnschanges").withSession("username" -> "frodo").withCSRFToken) + FakeRequest(GET, "/dnschanges").withSession("username" -> "frodo").withCSRFToken + ) status(result) must beEqualTo(OK) contentType(result) must beSome.which(_ == "text/html") contentAsString(result) must contain("DNS Changes | VinylDNS") @@ -332,7 +352,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica lockedUserUnderTest.viewAllBatchChanges()( FakeRequest(GET, "/dnschanges") .withSession("username" -> "lockedFbaggins") - .withCSRFToken) + .withCSRFToken + ) headers(result) must contain("Location" -> "/noaccess") } } @@ -348,7 +369,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica underTest.viewBatchChange("some-id")( FakeRequest(GET, "/dnschanges/some-id") .withSession("username" -> "frodo") - .withCSRFToken) + .withCSRFToken + ) status(result) must beEqualTo(OK) contentType(result) must beSome.which(_ == "text/html") contentAsString(result) must contain("DNS Change | VinylDNS") @@ -358,7 +380,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica lockedUserUnderTest.viewBatchChange("some-id")( FakeRequest(GET, "/dnschanges/some-id") .withSession("username" -> "lockedFbaggins") - .withCSRFToken) + .withCSRFToken + ) headers(result) must contain("Location" -> "/noaccess") } } @@ -372,7 +395,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "render the new batch change view page when the user is logged in" in new WithApplication(app) { val result = underTest.viewNewBatchChange()( - FakeRequest(GET, "/dnschanges/new").withSession("username" -> "frodo").withCSRFToken) + FakeRequest(GET, "/dnschanges/new").withSession("username" -> "frodo").withCSRFToken + ) status(result) must beEqualTo(OK) contentType(result) must beSome.which(_ == "text/html") contentAsString(result) must contain("New DNS Change | VinylDNS") @@ -382,7 +406,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica lockedUserUnderTest.viewNewBatchChange()( FakeRequest(GET, "/dnschanges/new") .withSession("username" -> "lockedFbaggins") - .withCSRFToken) + .withCSRFToken + ) headers(result) must contain("Location" -> "/noaccess") } } @@ -399,7 +424,8 @@ class FrontendControllerSpec extends Specification with Mockito with TestApplica "be displayed on the logged-in view if sidebar flag is true" in new WithApplication(app) { val result = underTest.viewAllZones()( - FakeRequest(GET, "/zones").withSession("username" -> "frodo").withCSRFToken) + FakeRequest(GET, "/zones").withSession("username" -> "frodo").withCSRFToken + ) status(result) must beEqualTo(OK) contentType(result) must beSome.which(_ == "text/html") contentAsString(result) must contain("test link sidebar") diff --git a/modules/portal/test/controllers/LdapAuthenticatorSpec.scala b/modules/portal/test/controllers/LdapAuthenticatorSpec.scala index 3bb800770..537511ea3 100644 --- a/modules/portal/test/controllers/LdapAuthenticatorSpec.scala +++ b/modules/portal/test/controllers/LdapAuthenticatorSpec.scala @@ -36,7 +36,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { searchResults: NamingEnumeration[SearchResult], searchNext: SearchResult, byDomainAuthenticator: LdapByDomainAuthenticator, - attributes: Attributes) + attributes: Attributes + ) /** * creates a container holding all mocks necessary to create @@ -70,14 +71,16 @@ class LdapAuthenticatorSpec extends Specification with Mockito { "apply method must create an LDAP Authenticator" in { val testConfig: Configuration = Configuration.load(Environment.simple()) ++ Configuration.from( - Map("portal.test_login" -> false)) + Map("portal.test_login" -> false) + ) val underTest = LdapAuthenticator.apply(new Settings(testConfig)) underTest must beAnInstanceOf[LdapAuthenticator] } "apply method must create a Test Authenticator if selected" in { val testConfig: Configuration = Configuration.load(Environment.simple()) ++ Configuration.from( - Map("portal.test_login" -> true)) + Map("portal.test_login" -> true) + ) val underTest = LdapAuthenticator.apply(new Settings(testConfig)) underTest must beAnInstanceOf[TestAuthenticator] } @@ -110,7 +113,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { val authenticator = new LdapAuthenticator( List(testDomain1, testDomain2), byDomainAuthenticator, - mock[ServiceAccount]) + mock[ServiceAccount] + ) val response = authenticator.authenticate("foo", "bar") @@ -133,7 +137,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { val authenticator = new LdapAuthenticator( List(testDomain1, testDomain2), byDomainAuthenticator, - mock[ServiceAccount]) + mock[ServiceAccount] + ) val response = authenticator.authenticate("foo", "bar") @@ -156,7 +161,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { val authenticator = new LdapAuthenticator( List(testDomain1, testDomain2), byDomainAuthenticator, - mock[ServiceAccount]) + mock[ServiceAccount] + ) val response = authenticator.authenticate("foo", "bar") @@ -186,7 +192,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { new LdapAuthenticator( List(testDomain1, testDomain2), byDomainAuthenticator, - serviceAccount) + serviceAccount + ) val response = authenticator.lookup("foo") @@ -218,7 +225,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { new LdapAuthenticator( List(testDomain1, testDomain2), byDomainAuthenticator, - serviceAccount) + serviceAccount + ) val response = authenticator.lookup("foo") @@ -243,7 +251,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { new LdapAuthenticator( List(testDomain1, testDomain2), byDomainAuthenticator, - serviceAccount) + serviceAccount + ) val response = authenticator.lookup("foo") @@ -268,7 +277,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { new LdapAuthenticator( List(testDomain1, testDomain2), byDomainAuthenticator, - serviceAccount) + serviceAccount + ) val response = authenticator.lookup("foo") @@ -291,7 +301,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { new LdapAuthenticator( List(testDomain1, testDomain2), byDomainAuthenticator, - serviceAccount) + serviceAccount + ) authenticator.healthCheck() val response = authenticator.healthCheck().unsafeRunSync() @@ -308,7 +319,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { new LdapAuthenticator( List(testDomain1, testDomain2), byDomainAuthenticator, - serviceAccount) + serviceAccount + ) authenticator.healthCheck() val response = authenticator.healthCheck().unsafeRunSync() @@ -325,7 +337,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { new LdapAuthenticator( List(testDomain1, testDomain2), byDomainAuthenticator, - serviceAccount) + serviceAccount + ) authenticator.healthCheck() val response = authenticator.healthCheck().unsafeRunSync() @@ -367,7 +380,9 @@ class LdapAuthenticatorSpec extends Specification with Mockito { List( nonexistentUser, nonexistentUser.copy(userName = "existing-user"), - nonexistentUser.copy(userName = "another-existing-user"))) + nonexistentUser.copy(userName = "another-existing-user") + ) + ) .unsafeRunSync() must beEqualTo(List(nonexistentUser)) } @@ -396,7 +411,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { // We first authenticate to the service account, and then to the user there.was( one(mocks.contextCreator).apply("test\\test", "test"), - one(mocks.contextCreator).apply("", "bar")) + one(mocks.contextCreator).apply("", "bar") + ) } "call the correct search on context" in { @@ -408,7 +424,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { val searchControlCapture = new ArgumentCapture[SearchControls] there.was( - one(mocks.context).search(baseNameCapture, usernameFilterCapture, searchControlCapture)) + one(mocks.context).search(baseNameCapture, usernameFilterCapture, searchControlCapture) + ) searchControlCapture.value.getSearchScope mustEqual 2 baseNameCapture.value mustEqual "DC=test,DC=test,DC=com" @@ -481,7 +498,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { val searchControlCapture = new ArgumentCapture[SearchControls] there.was( - one(mocks.context).search(baseNameCapture, usernameFilterCapture, searchControlCapture)) + one(mocks.context).search(baseNameCapture, usernameFilterCapture, searchControlCapture) + ) searchControlCapture.value.getSearchScope mustEqual 2 baseNameCapture.value mustEqual "DC=test,DC=test,DC=com" @@ -548,7 +566,9 @@ class LdapAuthenticatorSpec extends Specification with Mockito { "testuser", Some("test@test.test"), Some("Test"), - Some("User"))) + Some("User") + ) + ) val recordPagingUserLookup = underTest.lookup("recordPagingTestUser") @@ -558,7 +578,9 @@ class LdapAuthenticatorSpec extends Specification with Mockito { "recordPagingTestUser", Some("test@test.test"), Some("Test"), - Some("User"))) + Some("User") + ) + ) there.were(noCallsTo(mockLdapAuth)) } "authenticate the record paging test user" in { @@ -576,7 +598,9 @@ class LdapAuthenticatorSpec extends Specification with Mockito { "recordPagingTestUser", Some("test@test.test"), Some("Test"), - Some("User"))) + Some("User") + ) + ) there.were(noCallsTo(mockLdapAuth)) } "authenticate a user that is not the test user" in { @@ -606,7 +630,9 @@ class LdapAuthenticatorSpec extends Specification with Mockito { "testuser", Some("test@test.test"), Some("Test"), - Some("User"))) + Some("User") + ) + ) val recordPagingUserLookup = underTest.lookup("recordPagingTestUser") @@ -616,7 +642,9 @@ class LdapAuthenticatorSpec extends Specification with Mockito { "recordPagingTestUser", Some("test@test.test"), Some("Test"), - Some("User"))) + Some("User") + ) + ) there.were(noCallsTo(mockLdapAuth)) } @@ -635,7 +663,9 @@ class LdapAuthenticatorSpec extends Specification with Mockito { "recordPagingTestUser", Some("test@test.test"), Some("Test"), - Some("User"))) + Some("User") + ) + ) there.were(noCallsTo(mockLdapAuth)) } "lookup a user that is not the test user" in { @@ -658,7 +688,8 @@ class LdapAuthenticatorSpec extends Specification with Mockito { val underTest = new TestAuthenticator(mockLdapAuth) underTest.getUsersNotInLdap(List(nonexistentUser)).unsafeRunSync() must beEqualTo( - List(nonexistentUser)) + List(nonexistentUser) + ) } "perform a health check" in { val mockLdapAuth = mock[LdapAuthenticator] diff --git a/modules/portal/test/controllers/OidcAuthenticatorSpec.scala b/modules/portal/test/controllers/OidcAuthenticatorSpec.scala index 2ec3bf0e6..17be420f5 100644 --- a/modules/portal/test/controllers/OidcAuthenticatorSpec.scala +++ b/modules/portal/test/controllers/OidcAuthenticatorSpec.scala @@ -140,7 +140,8 @@ class OidcAuthenticatorSpec extends Specification with Mockito { val jwt = JWTClaimsSet.parse(tokenInfo) testOidcAuthenticator.getUserFromClaims(jwt) must beLeft( - ErrorResponse(500, "Username field not included in token from from OIDC provider")) + ErrorResponse(500, "Username field not included in token from from OIDC provider") + ) } } "getValidUsernameFromToken" should { @@ -222,7 +223,8 @@ class OidcAuthenticatorSpec extends Specification with Mockito { testResponse.setContent(body) testOidcAuthenticator.handleCallbackResponse(testResponse) must beLeft( - ErrorResponse(400, "Sign in token error: some error description")) + ErrorResponse(400, "Sign in token error: some error description") + ) } } } diff --git a/modules/portal/test/controllers/TestApplicationData.scala b/modules/portal/test/controllers/TestApplicationData.scala index 6c61f01df..6b94d4459 100644 --- a/modules/portal/test/controllers/TestApplicationData.scala +++ b/modules/portal/test/controllers/TestApplicationData.scala @@ -35,7 +35,8 @@ trait TestApplicationData { this: Mockito => "frodo", Some("fbaggins@hobbitmail.me"), Some("Frodo"), - Some("Baggins")) + Some("Baggins") + ) val frodoUser = User( "fbaggins", @@ -45,7 +46,8 @@ trait TestApplicationData { this: Mockito => Some("Baggins"), Some("fbaggins@hobbitmail.me"), DateTime.now, - "frodo-uuid") + "frodo-uuid" + ) val lockedFrodoUser = User( "lockedFbaggins", @@ -106,13 +108,15 @@ trait TestApplicationData { this: Mockito => Some("Gamgee"), Some("sgamgee@hobbitmail.me"), DateTime.now, - "sam-uuid") + "sam-uuid" + ) val samDetails = LdapUserDetails( "CN=sam,OU=hobbits,DC=middle,DC=earth", "sam", Some("sgamgee@hobbitmail.me"), Some("Sam"), - Some("Gamgee")) + Some("Gamgee") + ) val frodoJson: String = s"""{ @@ -239,7 +243,8 @@ trait TestApplicationData { this: Mockito => Configuration.load(Environment.simple()) ++ Configuration.from( Map( "portal.vinyldns.backend.url" -> s"http://localhost:$simulatedBackendPort", - "oidc.enabled" -> false) + "oidc.enabled" -> false + ) ) val mockAuth: Authenticator = mock[Authenticator] diff --git a/modules/portal/test/controllers/UserAccountAccessorSpec.scala b/modules/portal/test/controllers/UserAccountAccessorSpec.scala index ae9a64979..d150e1f27 100644 --- a/modules/portal/test/controllers/UserAccountAccessorSpec.scala +++ b/modules/portal/test/controllers/UserAccountAccessorSpec.scala @@ -33,7 +33,8 @@ class UserAccountAccessorSpec extends Specification with Mockito with BeforeEach Some("Baggins"), Some("fbaggins@hobbitmail.me"), DateTime.now, - "frodo-uuid") + "frodo-uuid" + ) private val userLog = UserChange( "frodo-uuid", @@ -102,7 +103,8 @@ class UserAccountAccessorSpec extends Specification with Mockito with BeforeEach user.copy(lockStatus = LockStatus.Locked), "system", DateTime.now, - user) + user + ) mockRepo.save(List(lockedUser)).returns(IO(List(lockedUser))) mockChangeRepo.save(any[UserChange]).returns(IO(lockedUserChange)) underTest.lockUsers(List(user)).unsafeRunSync() must beEqualTo(List(lockedUser)) diff --git a/modules/portal/test/controllers/VinylDNSSpec.scala b/modules/portal/test/controllers/VinylDNSSpec.scala index 587c0b4e2..c71ac36e9 100644 --- a/modules/portal/test/controllers/VinylDNSSpec.scala +++ b/modules/portal/test/controllers/VinylDNSSpec.scala @@ -75,7 +75,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w wsClient: WSClient = ws, components: ControllerComponents = components, crypto: CryptoAlgebra = crypto, - oidcAuthenticator: OidcAuthenticator = mockOidcAuth): VinylDNS = + oidcAuthenticator: OidcAuthenticator = mockOidcAuth + ): VinylDNS = new VinylDNS( configuration, authenticator, @@ -96,7 +97,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w mockUserAccessor, client, components, - crypto) + crypto + ) private def withLockedClient(client: WSClient) = TestVinylDNS( @@ -106,15 +108,16 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) "VinylDNS.Alerts" should { "return alertType and alertMessage are given" in { VinylDNS.Alerts.fromFlash( Flash( - Map( - "alertType" -> "danger", - "alertMessage" -> "Authentication failed, please try again"))) must + Map("alertType" -> "danger", "alertMessage" -> "Authentication failed, please try again") + ) + ) must beEqualTo(Some(Alert("danger", "Authentication failed, please try again"))) } @@ -158,7 +161,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w ws, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = vinyldnsPortal .getAuthenticatedUserData() .apply( @@ -204,8 +208,10 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = vinyldnsPortal .regenerateCreds() - .apply(FakeRequest(POST, "/regenerate-creds") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .apply( + FakeRequest(POST, "/regenerate-creds") + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(200) header("Pragma", result) must beSome("no-cache") @@ -225,8 +231,10 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = vinyldnsPortal .regenerateCreds() - .apply(FakeRequest(POST, "/regenerate-creds") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .apply( + FakeRequest(POST, "/regenerate-creds") + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(404) hasCacheHeaders(result) @@ -243,11 +251,14 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w FakeRequest(POST, "/regenerate-creds") .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) must beEqualTo(403) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) hasCacheHeaders(result) } "return unauthorized (401) if user account is locked" in new WithApplication(app) { @@ -280,7 +291,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w there.was(one(userAccessor).get("frodo")) } "call the new user account accessor and return the new style account" in new WithApplication( - app) { + app + ) { authenticator .authenticate(frodoDetails.username, "secondbreakfast") .returns(Right(frodoDetails)) @@ -291,13 +303,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .apply( FakeRequest().withFormUrlEncodedBody( "username" -> frodoDetails.username, - "password" -> "secondbreakfast") + "password" -> "secondbreakfast" + ) ) there.was(one(authenticator).authenticate("frodo", "secondbreakfast")) there.was(one(userAccessor).get("frodo")) } "call the user accessor to create the new user account if it is not found" in new WithApplication( - app) { + app + ) { authenticator.authenticate("frodo", "secondbreakfast").returns(Right(frodoDetails)) userAccessor.get(anyString).returns(IO.pure(None)) userAccessor.create(any[User]).returns(IO.pure(frodoUser)) @@ -312,7 +326,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w there.was(one(userAccessor).create(_: User)) } "call the user accessor to create the new style user account if it is not found" in new WithApplication( - app) { + app + ) { authenticator .authenticate(frodoDetails.username, "secondbreakfast") .returns(Right(frodoDetails)) @@ -324,14 +339,16 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .apply( FakeRequest().withFormUrlEncodedBody( "username" -> frodoDetails.username, - "password" -> "secondbreakfast") + "password" -> "secondbreakfast" + ) ) there.was(one(userAccessor).get(frodoDetails.username)) there.was(one(userAccessor).create(_: User)) } "do not call the user accessor to create the new user account if it is found" in new WithApplication( - app) { + app + ) { authenticator.authenticate("frodo", "secondbreakfast").returns(Right(frodoDetails)) userAccessor.get(any[String]).returns(IO.pure(Some(frodoUser))) @@ -356,7 +373,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .apply( FakeRequest().withFormUrlEncodedBody( "username" -> frodoDetails.username, - "password" -> "secondbreakfast") + "password" -> "secondbreakfast" + ) ) session(response).get("username") must beSome(frodoUser.userName) session(response).get("accessKey") must beSome(frodoUser.accessKey) @@ -374,7 +392,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .apply( FakeRequest().withFormUrlEncodedBody( "username" -> frodoDetails.username, - "password" -> "secondbreakfast") + "password" -> "secondbreakfast" + ) ) status(response) mustEqual 303 redirectLocation(response) must beSome("/index") @@ -548,7 +567,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w flash(response).get("alertType") must beSome("danger") flash(response).get("alertMessage") must beSome( "Authentication failed, please contact your VinylDNS " + - "administrators") + "administrators" + ) } } } @@ -579,7 +599,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.newGroup()( FakeRequest(POST, "/groups") .withJsonBody(hobbitGroupRequest) - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(OK) hasCacheHeaders(result) @@ -597,13 +618,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.newGroup()( FakeRequest(POST, "/groups") .withJsonBody(invalidHobbitGroup) - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(BAD_REQUEST) hasCacheHeaders(result) } "return authentication failed (401) when auth fails in the backend" in new WithApplication( - app) { + app + ) { val client = MockWS { case (POST, "http://localhost:9001/groups") => defaultActionBuilder { Results.Unauthorized("Invalid credentials") } @@ -616,7 +639,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.newGroup()( FakeRequest(POST, s"/groups") .withJsonBody(hobbitGroupRequest) - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(UNAUTHORIZED) hasCacheHeaders(result) @@ -633,7 +657,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.newGroup()( FakeRequest(POST, "/groups") .withJsonBody(hobbitGroupRequest) - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(CONFLICT) hasCacheHeaders(result) @@ -648,17 +673,21 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = underTest.newGroup()( FakeRequest(POST, "/groups") .withJsonBody(hobbitGroupRequest) .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) hasCacheHeaders(result) } "return unauthorized (401) if user is not logged in" in new WithApplication(app) { @@ -671,10 +700,12 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = underTest.newGroup()( FakeRequest(POST, "/groups") - .withJsonBody(hobbitGroupRequest)) + .withJsonBody(hobbitGroupRequest) + ) status(result) must beEqualTo(401) contentAsString(result) must beEqualTo("You are not logged in. Please login to continue.") @@ -697,14 +728,16 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.getGroup(hobbitGroupId)( FakeRequest(GET, s"/groups/$hobbitGroupId") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(OK) hasCacheHeaders(result) contentAsJson(result) must beEqualTo(hobbitGroup) } "return authentication failed (401) when auth fails in the backend" in new WithApplication( - app) { + app + ) { val client = MockWS { case (GET, u) if u == s"http://localhost:9001/groups/${hobbitGroupId}" => defaultActionBuilder { Results.Unauthorized("Invalid credentials") } @@ -716,7 +749,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.getGroup(hobbitGroupId)( FakeRequest(GET, s"/groups/$hobbitGroupId") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(UNAUTHORIZED) hasCacheHeaders(result) @@ -732,7 +766,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.getGroup("not-hobbits")( FakeRequest(GET, "/groups/not-hobbits") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(NOT_FOUND) hasCacheHeaders(result) @@ -747,18 +782,22 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = underTest.getGroup(hobbitGroupId)( FakeRequest(GET, s"/groups/$hobbitGroupId") .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } "return unauthorized (401) if user is not logged in" in new WithApplication(app) { val client = mock[WSClient] @@ -785,7 +824,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.deleteGroup(hobbitGroupId)( FakeRequest(DELETE, s"/groups/$hobbitGroupId") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(NO_CONTENT) hasCacheHeaders(result) @@ -810,21 +850,26 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = underTest.deleteGroup(hobbitGroupId)( FakeRequest(DELETE, s"/groups/$hobbitGroupId") .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } "return authentication failed (401) when authentication fails in the backend" in new WithApplication( - app) { + app + ) { val client = MockWS { case (DELETE, u) if u == s"http://localhost:9001/groups/$hobbitGroupId" => defaultActionBuilder { Results.Unauthorized("Invalid credentials") } @@ -836,7 +881,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.deleteGroup(hobbitGroupId)( FakeRequest(DELETE, s"/groups/$hobbitGroupId") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(UNAUTHORIZED) hasCacheHeaders(result) @@ -856,7 +902,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.deleteGroup(hobbitGroupId)( FakeRequest(DELETE, s"/groups/$hobbitGroupId") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(FORBIDDEN) hasCacheHeaders(result) @@ -873,7 +920,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.deleteGroup("not-hobbits")( FakeRequest(DELETE, "/groups/not-hobbits") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(NOT_FOUND) hasCacheHeaders(result) @@ -882,7 +930,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w ".updateGroup" should { "return the new group description if it is saved successfully - Ok (200)" in new WithApplication( - app) { + app + ) { val client = MockWS { case (PUT, u) if u == s"http://localhost:9001/groups/$hobbitGroupId" => defaultActionBuilder { Results.Ok(hobbitGroup) } @@ -894,7 +943,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.updateGroup(hobbitGroupId)( FakeRequest(PUT, s"/groups/$hobbitGroupId") .withJsonBody(hobbitGroup) - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(OK) contentAsJson(result) must beEqualTo(hobbitGroup) @@ -906,7 +956,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.updateGroup(hobbitGroupId)( FakeRequest(PUT, s"/groups/$hobbitGroupId") - .withJsonBody(hobbitGroup)) + .withJsonBody(hobbitGroup) + ) status(result) mustEqual 401 contentAsString(result) must beEqualTo("You are not logged in. Please login to continue.") @@ -922,21 +973,26 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = underTest.updateGroup(hobbitGroupId)( FakeRequest(PUT, s"/groups/$hobbitGroupId") .withJsonBody(hobbitGroup) .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) hasCacheHeaders(result) } "return bad request (400) when the request is rejected by the backend" in new WithApplication( - app) { + app + ) { val client = MockWS { case (PUT, u) if u == s"http://localhost:9001/groups/$hobbitGroupId" => defaultActionBuilder { Results.BadRequest("Unknown user") } @@ -948,7 +1004,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.updateGroup(hobbitGroupId)( FakeRequest(PUT, s"/groups/$hobbitGroupId") .withJsonBody(invalidHobbitGroup) - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(BAD_REQUEST) hasCacheHeaders(result) @@ -965,13 +1022,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.updateGroup(hobbitGroupId)( FakeRequest(PUT, s"/groups/$hobbitGroupId") .withJsonBody(hobbitGroup) - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(UNAUTHORIZED) hasCacheHeaders(result) } "return forbidden (403) when request fails permissions in the backend" in new WithApplication( - app) { + app + ) { val client = MockWS { case (PUT, u) if u == s"http://localhost:9001/groups/$hobbitGroupId" => defaultActionBuilder { Results.Forbidden("Authentication failed, bad signature") } @@ -983,13 +1042,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.updateGroup(hobbitGroupId)( FakeRequest(PUT, s"/groups/$hobbitGroupId") .withJsonBody(hobbitGroup) - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(FORBIDDEN) hasCacheHeaders(result) } "return not found (404) when the group is not found in the backend" in new WithApplication( - app) { + app + ) { val client = MockWS { case (PUT, u) if u == s"http://localhost:9001/groups/$hobbitGroupId" => defaultActionBuilder { Results.NotFound } @@ -1001,7 +1062,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.updateGroup("not-hobbits")( FakeRequest(PUT, "/groups/not-hobbits") .withJsonBody(hobbitGroup) - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(NOT_FOUND) hasCacheHeaders(result) @@ -1020,7 +1082,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.getMemberList(hobbitGroupId)( FakeRequest(GET, s"/data/groups/$hobbitGroupId/members") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(OK) hasCacheHeaders(result) @@ -1036,9 +1099,11 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = underTest.getMemberList(hobbitGroupId)( - FakeRequest(GET, s"/data/groups/$hobbitGroupId/members")) + FakeRequest(GET, s"/data/groups/$hobbitGroupId/members") + ) status(result) mustEqual 401 contentAsString(result) must beEqualTo("You are not logged in. Please login to continue.") @@ -1054,20 +1119,25 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = underTest.getMemberList(hobbitGroupId)( FakeRequest(GET, s"/data/groups/$hobbitGroupId/members") .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) must beEqualTo(FORBIDDEN) hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } "return bad request (400) when the request is rejected by the back end" in new WithApplication( - app) { + app + ) { val client = MockWS { case (GET, u) if u == s"http://localhost:9001/groups/$hobbitGroupId/members" => defaultActionBuilder { Results.BadRequest("Invalid maxItems") } @@ -1078,7 +1148,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.getMemberList(hobbitGroupId)( FakeRequest(GET, s"/groups/$hobbitGroupId/members?maxItems=0") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(BAD_REQUEST) hasCacheHeaders(result) @@ -1094,13 +1165,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.getMemberList(hobbitGroupId)( FakeRequest(GET, s"/groups/$hobbitGroupId/members") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(UNAUTHORIZED) hasCacheHeaders(result) } "return not found (404) when the group is not found in the backend" in new WithApplication( - app) { + app + ) { val client = MockWS { case (GET, u) if u == s"http://localhost:9001/groups/$hobbitGroupId/members" => defaultActionBuilder { Results.NotFound } @@ -1111,7 +1184,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.getMemberList(hobbitGroupId)( FakeRequest(GET, s"/groups/$hobbitGroupId/members") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(NOT_FOUND) hasCacheHeaders(result) @@ -1130,7 +1204,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.getGroups()( FakeRequest(GET, s"/api/groups") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(OK) hasCacheHeaders(result) @@ -1155,17 +1230,21 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = underTest.getGroups()( FakeRequest(GET, s"/api/groups") .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } "return unauthorized (401) when request fails authentication" in new WithApplication(app) { val client = MockWS { @@ -1182,10 +1261,12 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w mockUserAccessor, client, components, - crypto) + crypto + ) val result = underTest.getGroups()( FakeRequest(GET, s"/api/groups") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(UNAUTHORIZED) hasCacheHeaders(result) @@ -1201,7 +1282,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result: Future[Result] = underTest.serveCredsFile("credsfile.csv")( FakeRequest(GET, s"/download-creds-file/credsfile.csv") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) val content: String = contentAsString(result) content must contain("NT ID") content must contain(frodoUser.userName) @@ -1216,13 +1298,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w TestVinylDNS(config, mockLdapAuthenticator, mockUserAccessor, ws, components, crypto) val result: Future[Result] = underTest.serveCredsFile("credsfile.csv")( - FakeRequest(GET, s"/download-creds-file/credsfile.csv")) + FakeRequest(GET, s"/download-creds-file/credsfile.csv") + ) status(result) mustEqual 303 redirectLocation(result) must beSome("/login") flash(result).get("alertType") must beSome("danger") flash(result).get("alertMessage") must beSome( - "You are not logged in. Please login to continue.") + "You are not logged in. Please login to continue." + ) } "redirect to login if user account is locked" in new WithApplication(app) { import play.api.mvc.Result @@ -1235,13 +1319,16 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w ws, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result: Future[Result] = underTest.serveCredsFile("credsfile.csv")( FakeRequest(GET, s"/download-creds-file/credsfile.csv") .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 303 redirectLocation(result) must beSome("/noaccess") @@ -1257,17 +1344,20 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w ws, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result: Future[Result] = underTest.serveCredsFile("credsfile.csv")( FakeRequest(GET, s"/download-creds-file/credsfile.csv") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) mustEqual 303 redirectLocation(result) must beSome("/login") flash(result).get("alertType") must beSome("danger") flash(result).get("alertMessage") must beSome( - s"Unable to find user account for user name '${frodoUser.userName}'") + s"Unable to find user account for user name '${frodoUser.userName}'" + ) } } @@ -1305,7 +1395,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w ws, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = vinyldnsPortal .getUserDataByUsername(lookupValue) .apply(FakeRequest(GET, s"/api/users/lookupuser/$lookupValue")) @@ -1327,19 +1418,23 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w ws, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = vinyldnsPortal .getUserDataByUsername(lookupValue) .apply( FakeRequest(GET, s"/api/users/lookupuser/$lookupValue") .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) must beEqualTo(403) hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } "return a 404 if the account is not found" in new WithApplication(app) { userAccessor.get(any[String]).returns(IO.pure(None)) @@ -1377,12 +1472,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.getZones()( FakeRequest(GET, s"/api/zones").withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1403,12 +1501,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.getZone(hobbitZoneId)( FakeRequest(GET, s"/api/zones/$hobbitZoneId").withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1425,7 +1526,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.getZoneByName(hobbitZoneName)( FakeRequest(GET, s"/zones/name/$hobbitZoneName") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(OK) hasCacheHeaders(result) @@ -1443,7 +1545,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.getZoneByName("not-hobbits")( FakeRequest(GET, "/zones/name/not-hobbits") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(NOT_FOUND) hasCacheHeaders(result) @@ -1453,7 +1556,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.getZoneByName(hobbitZoneName)( - FakeRequest(GET, s"/api/zones/name/$hobbitZoneName")) + FakeRequest(GET, s"/api/zones/name/$hobbitZoneName") + ) status(result) mustEqual 401 hasCacheHeaders(result) @@ -1465,12 +1569,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.getZoneByName(hobbitZoneName)( FakeRequest(GET, s"/api/zones/name/$hobbitZoneName").withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1491,12 +1598,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.syncZone(hobbitZoneId)( FakeRequest(POST, s"/api/zones/$hobbitZoneId/sync").withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1507,7 +1617,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.getRecordSets(hobbitZoneId)( - FakeRequest(GET, s"/api/zones/$hobbitZoneId/recordsets")) + FakeRequest(GET, s"/api/zones/$hobbitZoneId/recordsets") + ) status(result) mustEqual 401 hasCacheHeaders(result) @@ -1519,12 +1630,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.getRecordSets(hobbitZoneId)( FakeRequest(GET, s"/api/zones/$hobbitZoneId/recordsets").withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1534,7 +1648,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.listRecordSetChanges(hobbitZoneId)( - FakeRequest(GET, s"/api/zones/$hobbitZoneId/recordsets")) + FakeRequest(GET, s"/api/zones/$hobbitZoneId/recordsets") + ) status(result) mustEqual 401 hasCacheHeaders(result) @@ -1546,12 +1661,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.listRecordSetChanges(hobbitZoneId)( FakeRequest(GET, s"/api/zones/$hobbitZoneId/recordsets").withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1574,12 +1692,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .withJsonBody(hobbitZoneRequest) .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1589,7 +1710,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.updateZone(hobbitZoneId)( - FakeRequest(PUT, s"/api/zones/$hobbitZoneId").withJsonBody(hobbitZoneRequest)) + FakeRequest(PUT, s"/api/zones/$hobbitZoneId").withJsonBody(hobbitZoneRequest) + ) status(result) mustEqual 401 hasCacheHeaders(result) @@ -1603,12 +1725,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .withJsonBody(hobbitZoneRequest) .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1619,7 +1744,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.addRecordSet(hobbitRecordSetId)( FakeRequest(POST, s"/api/zones/$hobbitZoneId/recordsets") - .withJsonBody(hobbitZoneRequest)) + .withJsonBody(hobbitZoneRequest) + ) status(result) mustEqual 401 hasCacheHeaders(result) @@ -1633,12 +1759,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .withJsonBody(hobbitZoneRequest) .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1648,7 +1777,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.deleteZone(hobbitZoneId)( - FakeRequest(DELETE, s"/api/zones/$hobbitZoneId").withJsonBody(hobbitZoneRequest)) + FakeRequest(DELETE, s"/api/zones/$hobbitZoneId").withJsonBody(hobbitZoneRequest) + ) status(result) mustEqual 401 hasCacheHeaders(result) @@ -1662,12 +1792,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .withJsonBody(hobbitZoneRequest) .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1678,7 +1811,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.updateRecordSet(hobbitZoneId, hobbitRecordSetId)( FakeRequest(PUT, s"/api/zones/$hobbitZoneId/recordsets/$hobbitRecordSetId") - .withJsonBody(hobbitZoneRequest)) + .withJsonBody(hobbitZoneRequest) + ) status(result) mustEqual 401 hasCacheHeaders(result) @@ -1692,12 +1826,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .withJsonBody(hobbitZoneRequest) .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1707,7 +1844,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.deleteRecordSet(hobbitZoneId, hobbitRecordSetId)( - FakeRequest(DELETE, s"/api/zones/$hobbitZoneId").withJsonBody(hobbitZoneRequest)) + FakeRequest(DELETE, s"/api/zones/$hobbitZoneId").withJsonBody(hobbitZoneRequest) + ) status(result) mustEqual 401 hasCacheHeaders(result) @@ -1721,12 +1859,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .withJsonBody(hobbitZoneRequest) .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1737,7 +1878,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.getBatchChange(hobbitZoneId)( FakeRequest(GET, s"/api/dnschanges/$hobbitZoneId") - .withJsonBody(hobbitZoneRequest)) + .withJsonBody(hobbitZoneRequest) + ) status(result) mustEqual 401 hasCacheHeaders(result) @@ -1751,12 +1893,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .withJsonBody(hobbitZoneRequest) .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1766,7 +1911,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.newBatchChange()( - FakeRequest(POST, s"/api/dnschanges").withJsonBody(hobbitZoneRequest)) + FakeRequest(POST, s"/api/dnschanges").withJsonBody(hobbitZoneRequest) + ) status(result) mustEqual 401 hasCacheHeaders(result) @@ -1780,12 +1926,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .withJsonBody(hobbitZoneRequest) .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1807,12 +1956,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w FakeRequest(POST, s"/api/dnschanges/123/cancel") .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1834,12 +1986,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w FakeRequest(POST, s"/api/dnschanges/123/approve") .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1861,12 +2016,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w FakeRequest(POST, s"/api/dnschanges/123/reject") .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1876,7 +2034,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val underTest = withClient(client) val result = underTest.listBatchChanges()( - FakeRequest(GET, s"/api/dnschanges").withJsonBody(hobbitZoneRequest)) + FakeRequest(GET, s"/api/dnschanges").withJsonBody(hobbitZoneRequest) + ) status(result) mustEqual 401 hasCacheHeaders(result) @@ -1890,12 +2049,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w .withJsonBody(hobbitZoneRequest) .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } @@ -1913,12 +2075,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = underTest.lockUser(frodoUser.id)( FakeRequest(PUT, s"/users/${frodoUser.id}/lock") .withSession( "username" -> superFrodoUser.userName, - "accessKey" -> superFrodoUser.accessKey)) + "accessKey" -> superFrodoUser.accessKey + ) + ) status(result) must beEqualTo(OK) contentAsJson(result) must beEqualTo(userJson) @@ -1934,7 +2099,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = underTest.lockUser(frodoUser.id)(FakeRequest(PUT, s"/users/${frodoUser.id}/lock")) @@ -1948,7 +2114,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.lockUser(frodoUser.id)( FakeRequest(PUT, s"/users/${frodoUser.id}/lock") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) must beEqualTo(403) contentAsString(result) must beEqualTo("Request restricted to super users only.") @@ -1970,12 +2137,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w client, components, crypto, - mockOidcAuth) + mockOidcAuth + ) val result = underTest.unlockUser(lockedFrodoUser.id)( FakeRequest(PUT, s"/users/${lockedFrodoUser.id}/unlock") .withSession( "username" -> superFrodoUser.userName, - "accessKey" -> superFrodoUser.accessKey)) + "accessKey" -> superFrodoUser.accessKey + ) + ) status(result) must beEqualTo(OK) contentAsJson(result) must beEqualTo(userJson) @@ -1998,7 +2168,8 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w val result = underTest.unlockUser(frodoUser.id)( FakeRequest(PUT, s"/users/${frodoUser.id}/unlock") - .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey)) + .withSession("username" -> frodoUser.userName, "accessKey" -> frodoUser.accessKey) + ) status(result) mustEqual 403 contentAsString(result) must beEqualTo("Request restricted to super users only.") @@ -2025,12 +2196,15 @@ class VinylDNSSpec extends Specification with Mockito with TestApplicationData w FakeRequest(GET, "/zones/backendids") .withSession( "username" -> lockedFrodoUser.userName, - "accessKey" -> lockedFrodoUser.accessKey)) + "accessKey" -> lockedFrodoUser.accessKey + ) + ) status(result) mustEqual 403 hasCacheHeaders(result) contentAsString(result) must beEqualTo( - s"User account for `${lockedFrodoUser.userName}` is locked.") + s"User account for `${lockedFrodoUser.userName}` is locked." + ) } } } diff --git a/modules/portal/test/models/CustomLinksSpec.scala b/modules/portal/test/models/CustomLinksSpec.scala index 3e1e598b5..59e1bc81f 100644 --- a/modules/portal/test/models/CustomLinksSpec.scala +++ b/modules/portal/test/models/CustomLinksSpec.scala @@ -57,7 +57,7 @@ class CustomLinksSpec extends Specification with Mockito { "title" -> linkTwo.title, "href" -> linkTwo.href, "icon" -> linkTwo.icon - ), + ) ) ) val customLinks = CustomLinks(Configuration.from(config)) diff --git a/modules/portal/test/models/VinylRequestSpec.scala b/modules/portal/test/models/VinylRequestSpec.scala index 81d35c33a..adc75e707 100644 --- a/modules/portal/test/models/VinylRequestSpec.scala +++ b/modules/portal/test/models/VinylRequestSpec.scala @@ -180,7 +180,8 @@ class VinylDNSRequestSpec extends Specification with Mockito { private def createMockVinylDNSRequest( url: String = "", method: String = "GET", - payload: Option[String] = None) = { + payload: Option[String] = None + ) = { val req = mock[VinylDNSRequest] val uri = new URI(url) req.url.returns(s"${uri.getScheme}://${uri.getHost}") diff --git a/modules/sqs/src/it/scala/vinyldns/sqs/queue/SqsMessageQueueIntegrationSpec.scala b/modules/sqs/src/it/scala/vinyldns/sqs/queue/SqsMessageQueueIntegrationSpec.scala index 937df2d58..ab112bd7d 100644 --- a/modules/sqs/src/it/scala/vinyldns/sqs/queue/SqsMessageQueueIntegrationSpec.scala +++ b/modules/sqs/src/it/scala/vinyldns/sqs/queue/SqsMessageQueueIntegrationSpec.scala @@ -33,9 +33,15 @@ import vinyldns.sqs.queue.SqsMessageQueue.InvalidMessageTimeout import scala.concurrent.duration.FiniteDuration -class SqsMessageQueueIntegrationSpec extends WordSpec - with MockitoSugar with BeforeAndAfterAll with BeforeAndAfterEach with Matchers with EitherMatchers with EitherValues - with ProtobufConversions { +class SqsMessageQueueIntegrationSpec + extends WordSpec + with MockitoSugar + with BeforeAndAfterAll + with BeforeAndAfterEach + with Matchers + with EitherMatchers + with EitherValues + with ProtobufConversions { private val sqsMessageQueueSettings: MessageQueueConfig = pureconfig.loadConfigOrThrow[MessageQueueConfig](ConfigFactory.load().getConfig("sqs")) @@ -51,9 +57,8 @@ class SqsMessageQueueIntegrationSpec extends WordSpec } // Delete queue after tests since stuff can potentially linger - override protected def afterAll(): Unit = { + override protected def afterAll(): Unit = queue.client.deleteQueue(queue.queueUrl) - } val rsAddChange: RecordSetChange = makeTestAddChange(rsOk) @@ -65,8 +70,10 @@ class SqsMessageQueueIntegrationSpec extends WordSpec val result = queue.receive(MessageCount(2).right.value).unsafeRunSync() result.map(_.command) should contain theSameElementsAs List(recordSetChange) - queue.requeue(SqsMessage(MessageId(result(0).id.value), recordSetChange)) - .attempt.unsafeRunSync() should beRight(()) + queue + .requeue(SqsMessage(MessageId(result(0).id.value), recordSetChange)) + .attempt + .unsafeRunSync() should beRight(()) val immediateReceive = queue.receive(MessageCount(2).right.value).unsafeRunSync() immediateReceive shouldBe Nil @@ -84,8 +91,13 @@ class SqsMessageQueueIntegrationSpec extends WordSpec result.map(_.command) shouldBe List(rsAddChange) // Set next visibility of timeout for message - queue.changeMessageTimeout(SqsMessage(MessageId(result(0).id.value), rsAddChange), - FiniteDuration(0, SECONDS)).attempt.unsafeRunSync() should beRight(()) + queue + .changeMessageTimeout( + SqsMessage(MessageId(result(0).id.value), rsAddChange), + FiniteDuration(0, SECONDS) + ) + .attempt + .unsafeRunSync() should beRight(()) // Test that we can immediately receive message after timeout adjustment val adjustedTimeoutResult = queue.receive(MessageCount(2).right.value).unsafeRunSync() @@ -112,8 +124,12 @@ class SqsMessageQueueIntegrationSpec extends WordSpec } val result = queue.receive(MessageCount(4).right.value).unsafeRunSync() - result.map(_.command) should contain theSameElementsAs List(rsAddChange, rsAddChange, zoneChangePending, - zoneChangePending) + result.map(_.command) should contain theSameElementsAs List( + rsAddChange, + rsAddChange, + zoneChangePending, + zoneChangePending + ) } "drop malformed message from the queue" in { @@ -121,15 +137,18 @@ class SqsMessageQueueIntegrationSpec extends WordSpec new SendMessageRequest() .withMessageBody("malformed data") .withQueueUrl(queue.queueUrl), - queue.client.sendMessageAsync) + queue.client.sendMessageAsync + ) val result = queue.receive(MessageCount(1).right.value).unsafeRunSync() result shouldBe empty } "succeed when attempting to remove item from empty queue" in { - queue.remove(SqsMessage(MessageId("does-not-exist"), rsAddChange)) - .attempt.unsafeRunSync() should beRight(()) + queue + .remove(SqsMessage(MessageId("does-not-exist"), rsAddChange)) + .attempt + .unsafeRunSync() should beRight(()) } "succeed when attempting to remove item from queue" in { @@ -137,15 +156,17 @@ class SqsMessageQueueIntegrationSpec extends WordSpec val result = queue.receive(MessageCount(1).right.value).unsafeRunSync() result.length shouldBe 1 - queue.remove(SqsMessage(MessageId(result(0).id.value), rsAddChange)) - .attempt.unsafeRunSync() should beRight(()) + queue + .remove(SqsMessage(MessageId(result(0).id.value), rsAddChange)) + .attempt + .unsafeRunSync() should beRight(()) } "send a single message request" in { queue.send(rsAddChange).attempt.unsafeRunSync() should beRight(()) val result = queue.receive(MessageCount(1).right.value).unsafeRunSync() - result should have length 1 + (result should have).length(1) result(0).command shouldBe a[RecordSetChange] } @@ -177,8 +198,11 @@ class SqsMessageQueueIntegrationSpec extends WordSpec "throw an InvalidMessageTimeout when attempting to set invalid visibility timeout" in { assertThrows[InvalidMessageTimeout] { - queue.changeMessageTimeout( - SqsMessage(MessageId("does-not-matter"), pendingCreateAAAA), new FiniteDuration(43201, SECONDS)) + queue + .changeMessageTimeout( + SqsMessage(MessageId("does-not-matter"), pendingCreateAAAA), + new FiniteDuration(43201, SECONDS) + ) .unsafeRunSync() } } diff --git a/modules/sqs/src/it/scala/vinyldns/sqs/queue/SqsMessageQueueProviderIntegrationSpec.scala b/modules/sqs/src/it/scala/vinyldns/sqs/queue/SqsMessageQueueProviderIntegrationSpec.scala index 20f4b360e..be83d5ad6 100644 --- a/modules/sqs/src/it/scala/vinyldns/sqs/queue/SqsMessageQueueProviderIntegrationSpec.scala +++ b/modules/sqs/src/it/scala/vinyldns/sqs/queue/SqsMessageQueueProviderIntegrationSpec.scala @@ -41,7 +41,8 @@ class SqsMessageQueueProviderIntegrationSpec extends WordSpec with Matchers { val badSettings = pureconfig.loadConfigOrThrow[MessageQueueConfig](badConfig) - a[pureconfig.error.ConfigReaderException[MessageQueueConfig]] should be thrownBy undertest.load(badSettings) + a[pureconfig.error.ConfigReaderException[MessageQueueConfig]] should be thrownBy undertest + .load(badSettings) .unsafeRunSync() } diff --git a/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueue.scala b/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueue.scala index c2e3c69f9..6d4347275 100644 --- a/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueue.scala +++ b/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueue.scala @@ -55,7 +55,8 @@ class SqsMessageQueue(val queueUrl: String, val client: AmazonSQSAsync) // Helper for handling SQS requests and responses def sqsAsync[A <: AmazonWebServiceRequest, B <: AmazonWebServiceResult[_]]( request: A, - f: (A, AsyncHandler[A, B]) => java.util.concurrent.Future[B]): IO[B] = + f: (A, AsyncHandler[A, B]) => java.util.concurrent.Future[B] + ): IO[B] = IO.async[B] { complete: (Either[Throwable, B] => Unit) => val asyncHandler = new AsyncHandler[A, B] { def onError(exception: Exception): Unit = complete(Left(exception)) @@ -114,7 +115,8 @@ class SqsMessageQueue(val queueUrl: String, val client: AmazonSQSAsync) logger.info(s"Deleting message with receipt handle: $receiptHandle.\n") sqsAsync[DeleteMessageRequest, DeleteMessageResult]( new DeleteMessageRequest(queueUrl, receiptHandle), - client.deleteMessageAsync).as(()) + client.deleteMessageAsync + ).as(()) } def remove(message: CommandMessage): IO[Unit] = @@ -132,7 +134,8 @@ class SqsMessageQueue(val queueUrl: String, val client: AmazonSQSAsync) sqsAsync[SendMessageRequest, SendMessageResult]( toSendMessageRequest(command) .withQueueUrl(queueUrl), - client.sendMessageAsync) + client.sendMessageAsync + ) }.as(()) def sendBatch[A <: ZoneCommand](cmds: NonEmptyList[A]): IO[SendBatchResult[A]] = @@ -142,7 +145,8 @@ class SqsMessageQueue(val queueUrl: String, val client: AmazonSQSAsync) sqsAsync[SendMessageBatchRequest, SendMessageBatchResult]( sendRequest .withQueueUrl(queueUrl), - client.sendMessageBatchAsync) + client.sendMessageBatchAsync + ) } .parSequence .map { sendResult => @@ -181,7 +185,8 @@ object SqsMessageQueue extends ProtobufConversions { final case class InvalidMessageTimeout(duration: Long) extends SqsMessageQueueError( s"Invalid duration: $duration seconds. Duration must be between " + - s"$MINIMUM_VISIBILITY_TIMEOUT-$MAXIMUM_VISIBILITY_TIMEOUT seconds.") + s"$MINIMUM_VISIBILITY_TIMEOUT-$MAXIMUM_VISIBILITY_TIMEOUT seconds." + ) // AWS limits as specified at: // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-limits.html @@ -197,7 +202,8 @@ object SqsMessageQueue extends ProtobufConversions { // $COVERAGE-ON$ def validateMessageTimeout( - duration: FiniteDuration): Either[InvalidMessageTimeout, FiniteDuration] = + duration: FiniteDuration + ): Either[InvalidMessageTimeout, FiniteDuration] = duration.toSeconds match { case valid if valid >= MINIMUM_VISIBILITY_TIMEOUT && valid <= MAXIMUM_VISIBILITY_TIMEOUT => Right(duration) @@ -227,7 +233,8 @@ object SqsMessageQueue extends ProtobufConversions { } def toSendMessageBatchRequest[A <: ZoneCommand]( - commands: NonEmptyList[A]): List[SendMessageBatchRequest] = { + commands: NonEmptyList[A] + ): List[SendMessageBatchRequest] = { // convert each message into an entry val entries = commands.map { cmd => new SendMessageBatchRequestEntry() @@ -253,7 +260,8 @@ object SqsMessageQueue extends ProtobufConversions { def toSendBatchResult[A <: ZoneCommand]( sendResultList: List[SendMessageBatchResult], - cmds: NonEmptyList[A]): SendBatchResult[A] = { + cmds: NonEmptyList[A] + ): SendBatchResult[A] = { val successfulIds = sendResultList.flatMap(_.getSuccessful.asScala.map(_.getId)) val successes = cmds.filter(cmd => successfulIds.contains(cmd.id)) diff --git a/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueueProvider.scala b/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueueProvider.scala index d2f442448..704eeae5d 100644 --- a/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueueProvider.scala +++ b/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueueProvider.scala @@ -60,18 +60,24 @@ class SqsMessageQueueProvider extends MessageQueueProvider { s"Setting up queue client with settings: " + s"service endpoint: ${sqsMessageQueueSettings.serviceEndpoint}; " + s"signing region: ${sqsMessageQueueSettings.serviceEndpoint}; " + - s"queue name: ${sqsMessageQueueSettings.queueName}") + s"queue name: ${sqsMessageQueueSettings.queueName}" + ) AmazonSQSAsyncClientBuilder .standard() .withEndpointConfiguration( new EndpointConfiguration( sqsMessageQueueSettings.serviceEndpoint, - sqsMessageQueueSettings.signingRegion)) + sqsMessageQueueSettings.signingRegion + ) + ) .withCredentials( new AWSStaticCredentialsProvider( new BasicAWSCredentials( sqsMessageQueueSettings.accessKey, - sqsMessageQueueSettings.secretKey))) + sqsMessageQueueSettings.secretKey + ) + ) + ) .build() } @@ -89,7 +95,8 @@ object SqsMessageQueueProvider { final case class InvalidQueueName(queueName: String) extends Throwable( s"Invalid queue name: $queueName. Must be 1-80 alphanumeric, hyphen or underscore characters. FIFO queues " + - "(queue names ending in \".fifo\") are not supported.") + "(queue names ending in \".fifo\") are not supported." + ) private val logger = LoggerFactory.getLogger(classOf[SqsMessageQueueProvider]) } diff --git a/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueueSettings.scala b/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueueSettings.scala index 301f6846c..e602fe2dd 100644 --- a/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueueSettings.scala +++ b/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageQueueSettings.scala @@ -21,4 +21,5 @@ case class SqsMessageQueueSettings( secretKey: String, serviceEndpoint: String, signingRegion: String, - queueName: String) + queueName: String +) diff --git a/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageType.scala b/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageType.scala index 70fd49efd..105b728a2 100644 --- a/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageType.scala +++ b/modules/sqs/src/main/scala/vinyldns/sqs/queue/SqsMessageType.scala @@ -59,9 +59,10 @@ object SqsMessageType { // the message-type could have a string value, but not a valid value for { messageTypeAttr <- Either.fromOption( - Option(sqsMessage.getMessageAttributes.get("message-type")).flatMap(mt => - Option(mt.getStringValue)), - MessageTypeNotFound) + Option(sqsMessage.getMessageAttributes.get("message-type")) + .flatMap(mt => Option(mt.getStringValue)), + MessageTypeNotFound + ) messageType <- fromString(messageTypeAttr) } yield messageType } diff --git a/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageQueueProviderSpec.scala b/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageQueueProviderSpec.scala index bd58c8f47..f776d6cb0 100644 --- a/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageQueueProviderSpec.scala +++ b/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageQueueProviderSpec.scala @@ -30,7 +30,8 @@ class SqsMessageQueueProviderSpec extends WordSpec with Matchers { "fail if queue name does not match regex" in { val invalidQueueName = "a" * 81 undertest.validateQueueName(invalidQueueName) shouldBe Left( - InvalidQueueName(invalidQueueName)) + InvalidQueueName(invalidQueueName) + ) } "fail if user species a fifo queue" in { diff --git a/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageQueueSpec.scala b/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageQueueSpec.scala index e50c80723..d6aeb875a 100644 --- a/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageQueueSpec.scala +++ b/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageQueueSpec.scala @@ -60,10 +60,11 @@ class SqsMessageQueueSpec "create a single batch request if total message payload is under 256KB" in { val messageSize = messageData(largeRsChange).getBytes().length val requestMaxChanges = MAXIMUM_BATCH_SIZE / messageSize - val recordSetChanges = for (_ <- 1 until requestMaxChanges) - yield - makeTestAddChange(rsOk, okZone).copy( - singleBatchChangeIds = largeRsChange.singleBatchChangeIds) + val recordSetChanges = + for (_ <- 1 until requestMaxChanges) + yield makeTestAddChange(rsOk, okZone).copy( + singleBatchChangeIds = largeRsChange.singleBatchChangeIds + ) val commands = NonEmptyList.fromListUnsafe(recordSetChanges.toList) toSendMessageBatchRequest(commands).length shouldBe 1 @@ -73,18 +74,20 @@ class SqsMessageQueueSpec val messageSize = messageData(largeRsChange).getBytes().length val requestMaxChanges = MAXIMUM_BATCH_SIZE / messageSize val requestTotalChanges = requestMaxChanges * 4 // Create four batches - val recordSetChanges = for (_ <- 1 until requestTotalChanges) - yield - makeTestAddChange(rsOk, okZone).copy( - singleBatchChangeIds = largeRsChange.singleBatchChangeIds) + val recordSetChanges = + for (_ <- 1 until requestTotalChanges) + yield makeTestAddChange(rsOk, okZone).copy( + singleBatchChangeIds = largeRsChange.singleBatchChangeIds + ) val commands = NonEmptyList.fromListUnsafe(recordSetChanges.toList) toSendMessageBatchRequest(commands).length shouldBe 4 } "send a single batch if batch contains fewer than ten items and total payload size is less than 256KB" in { val requestTotalChanges = 7 - val recordSetChanges = for (_ <- 1 to requestTotalChanges) - yield makeTestAddChange(rsOk, okZone) + val recordSetChanges = + for (_ <- 1 to requestTotalChanges) + yield makeTestAddChange(rsOk, okZone) val commands = NonEmptyList.fromListUnsafe(recordSetChanges.toList) val result = toSendMessageBatchRequest(commands) @@ -94,8 +97,9 @@ class SqsMessageQueueSpec } "partition batches with more than ten items into groups of ten" in { - val recordSetChanges = for (_ <- 1 to 100) - yield makeTestAddChange(rsOk, okZone) + val recordSetChanges = + for (_ <- 1 to 100) + yield makeTestAddChange(rsOk, okZone) val commands = NonEmptyList.fromListUnsafe(recordSetChanges.toList) val result = toSendMessageBatchRequest(commands) @@ -109,9 +113,11 @@ class SqsMessageQueueSpec val requestMaxChanges = MAXIMUM_BATCH_SIZE / messageSize val requestTotalChanges = requestMaxChanges * 2 - val recordSetChanges = for (_ <- 1 until requestTotalChanges) - yield - makeTestAddChange(rsOk, okZone).copy(singleBatchChangeIds = rsChange.singleBatchChangeIds) + val recordSetChanges = + for (_ <- 1 until requestTotalChanges) + yield makeTestAddChange(rsOk, okZone).copy( + singleBatchChangeIds = rsChange.singleBatchChangeIds + ) val commands = NonEmptyList.fromListUnsafe(recordSetChanges.toList) val result = toSendMessageBatchRequest(commands) diff --git a/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageSpec.scala b/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageSpec.scala index 85e5a15fb..3bee7537e 100644 --- a/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageSpec.scala +++ b/modules/sqs/src/test/scala/vinyldns/sqs/queue/SqsMessageSpec.scala @@ -45,7 +45,8 @@ class SqsMessageSpec extends WordSpec with Matchers with EitherValues with Proto "message-type" -> new MessageAttributeValue() .withStringValue(SqsZoneChangeMessage.name) .withDataType("String") - ).asJava) + ).asJava + ) parseSqsMessage(msg).right.value.command shouldBe zoneChangePending } @@ -60,7 +61,8 @@ class SqsMessageSpec extends WordSpec with Matchers with EitherValues with Proto "message-type" -> new MessageAttributeValue() .withStringValue(SqsRecordSetChangeMessage.name) .withDataType("String") - ).asJava) + ).asJava + ) parseSqsMessage(msg).right.value.command shouldBe pendingCreateAAAA } @@ -90,7 +92,8 @@ class SqsMessageSpec extends WordSpec with Matchers with EitherValues with Proto "message-type" -> new MessageAttributeValue() .withStringValue(SqsZoneChangeMessage.name) .withDataType("String") - ).asJava) + ).asJava + ) parseSqsMessage(message) shouldBe Left(EmptySqsMessageContents(message.getMessageId)) } diff --git a/project/plugins.sbt b/project/plugins.sbt index bcabbff53..61d60c05d 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -26,7 +26,7 @@ addSbtPlugin("de.heikoseeberger" % "sbt-header" % "5.0.0") addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.7.3") -addSbtPlugin("com.geirsson" % "sbt-scalafmt" % "1.5.1") +addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.2.1") addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")