diff --git a/ScalliGraph b/ScalliGraph index 985e5e8a7f..8a7900ffdb 160000 --- a/ScalliGraph +++ b/ScalliGraph @@ -1 +1 @@ -Subproject commit 985e5e8a7f488b1797d6bae478ddf07ed0f4c874 +Subproject commit 8a7900ffdbf11ed6e29e0dfa450e3e1ca776af35 diff --git a/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/ActionSrvTest.scala b/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/ActionSrvTest.scala index 6edb69076b..66980decaa 100644 --- a/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/ActionSrvTest.scala +++ b/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/ActionSrvTest.scala @@ -2,10 +2,10 @@ package org.thp.thehive.connector.cortex.services import org.thp.cortex.client.{CortexClient, TestCortexClientProvider} import org.thp.cortex.dto.v0.OutputJob -import org.thp.scalligraph.AppBuilder import org.thp.scalligraph.auth.AuthContext import org.thp.scalligraph.models._ import org.thp.scalligraph.traversal.TraversalOps._ +import org.thp.scalligraph.{AppBuilder, EntityName} import org.thp.thehive.connector.cortex.controllers.v0.ActionCtrl import org.thp.thehive.connector.cortex.models.{JobStatus, TheHiveCortexSchemaProvider} import org.thp.thehive.models._ @@ -35,23 +35,24 @@ class ActionSrvTest extends PlaySpecification with TestAppBuilder { ) .bindNamedToProvider[Database, BasicDatabaseProvider]("with-thehive-cortex-schema") - def testAppBuilder[A](body: AppBuilder => A): A = testApp { app => - body( - app - .`override`( - _.bindActor[CortexActor]("cortex-actor") - .bindToProvider[CortexClient, TestCortexClientProvider] - .bind[Connector, TestConnector] - .bindToProvider[Schema, TheHiveCortexSchemaProvider] - ) - ) - } + def testAppBuilder[A](body: AppBuilder => A): A = + testApp { app => + body( + app + .`override`( + _.bindActor[CortexActor]("cortex-actor") + .bindToProvider[CortexClient, TestCortexClientProvider] + .bind[Connector, TestConnector] + .bindToProvider[Schema, TheHiveCortexSchemaProvider] + ) + ) + } "action service" should { "execute, create and handle finished action operations" in testApp { app => app[Database].roTransaction { implicit graph => implicit val entityWrites: OWrites[Entity] = app[ActionCtrl].entityWrites - val task1: Task with Entity = app[TaskSrv].startTraversal.has("title", "case 1 task 1").head + val task1: Task with Entity = app[TaskSrv].startTraversal.has(_.title, "case 1 task 1").head val richAction = await(app[ActionSrv].execute(task1, None, "respTest1", JsObject.empty)) richAction.workerId shouldEqual "respTest1" @@ -77,7 +78,7 @@ class ActionSrvTest extends PlaySpecification with TestAppBuilder { "handle action related to Task and Log" in testApp { app => app[Database].roTransaction { implicit graph => implicit val entityWrites: OWrites[Entity] = app[ActionCtrl].entityWrites - val log1 = app[LogSrv].startTraversal.has("message", "log for action test").head + val log1 = app[LogSrv].startTraversal.has(_.message, "log for action test").head val richAction = await(app[ActionSrv].execute(log1, None, "respTest1", JsObject.empty)) richAction.workerId shouldEqual "respTest1" @@ -101,15 +102,15 @@ class ActionSrvTest extends PlaySpecification with TestAppBuilder { } app[Database].roTransaction { implicit graph => - app[TaskSrv].startTraversal.has("title", "case 2 task 2").has("status", "Completed").exists must beTrue - app[TaskSrv].startTraversal.has("title", "case 2 task 2").logs.has("message", "test log from action").exists must beTrue + app[TaskSrv].startTraversal.has(_.title, "case 2 task 2").has(_.status, TaskStatus.Completed).exists must beTrue + app[TaskSrv].startTraversal.has(_.title, "case 2 task 2").logs.has(_.message, "test log from action").exists must beTrue } } "handle action related to an Alert" in testApp { app => implicit val entityWrites: OWrites[Entity] = app[ActionCtrl].entityWrites val alert = app[Database].roTransaction { implicit graph => - app[AlertSrv].get("testType;testSource;ref2").visible.head + app[AlertSrv].get(EntityName("testType;testSource;ref2")).visible.head } alert.read must beFalse val richAction = await(app[ActionSrv].execute(alert, None, "respTest1", JsObject.empty)) @@ -122,7 +123,7 @@ class ActionSrvTest extends PlaySpecification with TestAppBuilder { updatedActionTry must beSuccessfulTry app[Database].roTransaction { implicit graph => - val updatedAlert = app[AlertSrv].get("testType;testSource;ref2").visible.richAlert.head // FIXME + val updatedAlert = app[AlertSrv].get(EntityName("testType;testSource;ref2")).visible.richAlert.head // FIXME updatedAlert.read must beTrue updatedAlert.tags.map(_.toString) must contain("test tag from action") // TODO } diff --git a/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/EntityHelperTest.scala b/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/EntityHelperTest.scala index 5c78531e68..0aa8bef360 100644 --- a/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/EntityHelperTest.scala +++ b/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/EntityHelperTest.scala @@ -1,5 +1,6 @@ package org.thp.thehive.connector.cortex.services +import org.thp.scalligraph.EntityName import org.thp.scalligraph.auth.AuthContext import org.thp.scalligraph.models.{Database, DummyUserSrv} import org.thp.scalligraph.traversal.TraversalOps._ @@ -17,7 +18,7 @@ class EntityHelperTest extends PlaySpecification with TestAppBuilder { "return task info" in testApp { app => app[Database].roTransaction { implicit graph => for { - task <- app[TaskSrv].startTraversal.has("title", "case 1 task 1").getOrFail("Task") + task <- app[TaskSrv].startTraversal.has(_.title, "case 1 task 1").getOrFail("Task") (title, tlp, pap) <- app[EntityHelper].entityInfo(task) } yield (title, tlp, pap) } must beASuccessfulTry.which { @@ -31,7 +32,7 @@ class EntityHelperTest extends PlaySpecification with TestAppBuilder { "return observable info" in testApp { app => app[Database].roTransaction { implicit graph => for { - observable <- app[ObservableSrv].startTraversal.has("message", "Some weird domain").getOrFail("Observable") + observable <- app[ObservableSrv].startTraversal.has(_.message, "Some weird domain").getOrFail("Observable") (title, tlp, pap) <- app[EntityHelper].entityInfo(observable) } yield (title, tlp, pap) } must beASuccessfulTry.which { @@ -45,7 +46,7 @@ class EntityHelperTest extends PlaySpecification with TestAppBuilder { "find a manageable entity only (task)" in testApp { app => app[Database].roTransaction { implicit graph => for { - task <- app[TaskSrv].startTraversal.has("title", "case 1 task 1").getOrFail("Task") + task <- app[TaskSrv].startTraversal.has(_.title, "case 1 task 1").getOrFail("Task") t <- app[EntityHelper].get("Task", task._id, Permissions.manageAction) } yield t } must beSuccessfulTry @@ -54,7 +55,7 @@ class EntityHelperTest extends PlaySpecification with TestAppBuilder { "find a manageable entity only (alert)" in testApp { app => app[Database].roTransaction { implicit graph => for { - alert <- app[AlertSrv].get("testType;testSource;ref2").visible.getOrFail("Alert") + alert <- app[AlertSrv].get(EntityName("testType;testSource;ref2")).visible.getOrFail("Alert") t <- app[EntityHelper].get("Alert", alert._id, Permissions.manageAction) } yield t } must beSuccessfulTry diff --git a/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/JobSrvTest.scala b/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/JobSrvTest.scala index 45e886592f..c6aba2221d 100644 --- a/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/JobSrvTest.scala +++ b/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/JobSrvTest.scala @@ -57,7 +57,7 @@ class JobSrvTest extends PlaySpecification with TestAppBuilder { val createdJobTry = app[Database].tryTransaction { implicit graph => for { - observable <- app[ObservableSrv].startTraversal.has("message", "hello world").getOrFail("Observable") + observable <- app[ObservableSrv].startTraversal.has(_.message, "hello world").getOrFail("Observable") createdJob <- app[JobSrv].create(job, observable) } yield createdJob } @@ -69,14 +69,14 @@ class JobSrvTest extends PlaySpecification with TestAppBuilder { (updatedJob.report.get \ "data").as[String] shouldEqual "imageedit_2_3904987689.jpg" app[Database].roTransaction { implicit graph => - app[JobSrv].get(updatedJob).observable.has("message", "hello world").exists must beTrue + app[JobSrv].get(updatedJob).observable.has(_.message, "hello world").exists must beTrue app[JobSrv].get(updatedJob).reportObservables.toList.length must equalTo(2).updateMessage { s => s"$s\nreport observables are : ${app[JobSrv].get(updatedJob).reportObservables.richObservable.toList.mkString("\n")}" } for { - audit <- app[AuditSrv].startTraversal.has("objectId", updatedJob._id).getOrFail("Audit") - organisation <- app[OrganisationSrv].get("cert").getOrFail("Organisation") + audit <- app[AuditSrv].startTraversal.has(_.objectId, updatedJob._id.toString).getOrFail("Audit") + organisation <- app[OrganisationSrv].getByName("cert").getOrFail("Organisation") user <- app[UserSrv].startTraversal.getByName("certuser@thehive.local").getOrFail("User") } yield new JobFinished().filter(audit, Some(updatedJob), organisation, Some(user)) } must beASuccessfulTry(true) diff --git a/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/ResponderSrvTest.scala b/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/ResponderSrvTest.scala index e2f280cca5..528b0c8b2c 100644 --- a/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/ResponderSrvTest.scala +++ b/cortex/connector/src/test/scala/org/thp/thehive/connector/cortex/services/ResponderSrvTest.scala @@ -32,7 +32,7 @@ class ResponderSrvTest extends PlaySpecification with TestAppBuilder { "responder service" should { "fetch responders by type" in testApp { app => val task = app[Database].roTransaction { implicit graph => - app[TaskSrv].startTraversal.has("title", "case 1 task 1").head + app[TaskSrv].startTraversal.has(_.title, "case 1 task 1").head } val r = await(app[ResponderSrv].getRespondersByType("case_task", task._id)) diff --git a/misp/connector/src/main/scala/org/thp/thehive/connector/misp/services/MispImportSrv.scala b/misp/connector/src/main/scala/org/thp/thehive/connector/misp/services/MispImportSrv.scala index 8e0f6d77e6..216272bfb9 100644 --- a/misp/connector/src/main/scala/org/thp/thehive/connector/misp/services/MispImportSrv.scala +++ b/misp/connector/src/main/scala/org/thp/thehive/connector/misp/services/MispImportSrv.scala @@ -308,22 +308,21 @@ class MispImportSrv @Inject() ( Future.fromTry { logger.info("Removing old observables") db.tryTransaction { implicit graph => - alertSrv - .get(alert) - .observables - .filter( - _.or( - _.has("_updatedAt", P.lt(startSyncDate)), - _.and(_.hasNot("_updatedAt"), _.has("_createdAt", P.lt(startSyncDate))) - ) + alertSrv + .get(alert) + .observables + .filter( + _.or( + _.has(_._updatedAt, P.lt(startSyncDate)), + _.and(_.hasNot(_._updatedAt), _.has(_._createdAt, P.lt(startSyncDate))) ) - .toIterator - .toTry { obs => - logger.info(s"Remove $obs") - observableSrv.remove(obs) - } - } - .map(_ => ()) + ) + .toIterator + .toTry { obs => + logger.info(s"Remove $obs") + observableSrv.remove(obs) + } + }.map(_ => ()) } } } diff --git a/misp/connector/src/main/scala/org/thp/thehive/connector/misp/services/TheHiveMispClient.scala b/misp/connector/src/main/scala/org/thp/thehive/connector/misp/services/TheHiveMispClient.scala index 690098fc46..4841cda933 100644 --- a/misp/connector/src/main/scala/org/thp/thehive/connector/misp/services/TheHiveMispClient.scala +++ b/misp/connector/src/main/scala/org/thp/thehive/connector/misp/services/TheHiveMispClient.scala @@ -114,22 +114,23 @@ class TheHiveMispClient( whitelistTags ) { - @Inject() def this(config: TheHiveMispClientConfig, mat: Materializer) = this( - config.name, - config.url, - config.auth, - new ProxyWS(config.wsConfig, mat), - config.maxAge, - config.excludedOrganisations, - config.excludedTags, - config.whitelistTags, - config.purpose, - config.caseTemplate, - config.artifactTags, - config.exportCaseTags, - config.includedTheHiveOrganisations, - config.excludedTheHiveOrganisations - ) + @Inject() def this(config: TheHiveMispClientConfig, mat: Materializer) = + this( + config.name, + config.url, + config.auth, + new ProxyWS(config.wsConfig, mat), + config.maxAge, + config.excludedOrganisations, + config.excludedTags, + config.whitelistTags, + config.purpose, + config.caseTemplate, + config.artifactTags, + config.exportCaseTags, + config.includedTheHiveOrganisations, + config.excludedTheHiveOrganisations + ) val (canImport, canExport) = purpose match { case MispPurpose.ImportAndExport => (true, true) @@ -140,9 +141,9 @@ class TheHiveMispClient( def organisationFilter(organisationSteps: Traversal.V[Organisation]): Traversal.V[Organisation] = { val includedOrgs = if (includedTheHiveOrganisations.contains("*") || includedTheHiveOrganisations.isEmpty) organisationSteps - else organisationSteps.has("name", P.within(includedTheHiveOrganisations)) + else organisationSteps.has(_.name, P.within(includedTheHiveOrganisations: _*)) if (excludedTheHiveOrganisations.isEmpty) includedOrgs - else includedOrgs.has("name", P.without(excludedTheHiveOrganisations)) + else includedOrgs.has(_.name, P.without(excludedTheHiveOrganisations: _*)) } override def getStatus(implicit ec: ExecutionContext): Future[JsObject] = diff --git a/thehive/app/org/thp/thehive/controllers/dav/VFS.scala b/thehive/app/org/thp/thehive/controllers/dav/VFS.scala index d13b2606b6..ac2c7b8c16 100644 --- a/thehive/app/org/thp/thehive/controllers/dav/VFS.scala +++ b/thehive/app/org/thp/thehive/controllers/dav/VFS.scala @@ -13,55 +13,57 @@ import org.thp.thehive.services.TaskOps._ @Singleton class VFS @Inject() (caseSrv: CaseSrv) { - def get(path: List[String])(implicit graph: Graph, authContext: AuthContext): Seq[Resource] = path match { - case Nil | "" :: Nil => List(StaticResource("")) - case "cases" :: Nil => List(StaticResource("")) - case "cases" :: cid :: Nil => caseSrv.startTraversal.getByNumber(cid.toInt).toSeq.map(EntityResource(_, "")) - case "cases" :: cid :: "observables" :: Nil => List(StaticResource("")) - case "cases" :: cid :: "tasks" :: Nil => List(StaticResource("")) - case "cases" :: cid :: "observables" :: aid :: Nil => - caseSrv - .startTraversal - .getByNumber(cid.toInt) - .observables - .attachments - .has("attachmentId", aid) - .toSeq - .map(AttachmentResource(_, emptyId = true)) - case "cases" :: cid :: "tasks" :: aid :: Nil => - caseSrv - .startTraversal - .getByNumber(cid.toInt) - .tasks - .logs - .attachments - .has("attachmentId", aid) - .toSeq - .map(AttachmentResource(_, emptyId = true)) - case _ => Nil - } + def get(path: List[String])(implicit graph: Graph, authContext: AuthContext): Seq[Resource] = + path match { + case Nil | "" :: Nil => List(StaticResource("")) + case "cases" :: Nil => List(StaticResource("")) + case "cases" :: cid :: Nil => caseSrv.startTraversal.getByNumber(cid.toInt).toSeq.map(EntityResource(_, "")) + case "cases" :: cid :: "observables" :: Nil => List(StaticResource("")) + case "cases" :: cid :: "tasks" :: Nil => List(StaticResource("")) + case "cases" :: cid :: "observables" :: aid :: Nil => + caseSrv + .startTraversal + .getByNumber(cid.toInt) + .observables + .attachments + .has(_.attachmentId, aid) + .toSeq + .map(AttachmentResource(_, emptyId = true)) + case "cases" :: cid :: "tasks" :: aid :: Nil => + caseSrv + .startTraversal + .getByNumber(cid.toInt) + .tasks + .logs + .attachments + .has(_.attachmentId, aid) + .toSeq + .map(AttachmentResource(_, emptyId = true)) + case _ => Nil + } - def list(path: List[String])(implicit graph: Graph, authContext: AuthContext): Seq[Resource] = path match { - case Nil | "" :: Nil => List(StaticResource("cases")) - case "cases" :: Nil => caseSrv.startTraversal.visible.toSeq.map(c => EntityResource(c, c.number.toString)) - case "cases" :: cid :: Nil => List(StaticResource("observables"), StaticResource("tasks")) - case "cases" :: cid :: "observables" :: Nil => - caseSrv - .startTraversal - .getByNumber(cid.toInt) - .observables - .attachments - .domainMap(AttachmentResource(_, emptyId = false)) - .toSeq - case "cases" :: cid :: "tasks" :: Nil => - caseSrv - .startTraversal - .getByNumber(cid.toInt) - .tasks - .logs - .attachments - .domainMap(AttachmentResource(_, emptyId = false)) - .toSeq - case _ => Nil - } + def list(path: List[String])(implicit graph: Graph, authContext: AuthContext): Seq[Resource] = + path match { + case Nil | "" :: Nil => List(StaticResource("cases")) + case "cases" :: Nil => caseSrv.startTraversal.visible.toSeq.map(c => EntityResource(c, c.number.toString)) + case "cases" :: cid :: Nil => List(StaticResource("observables"), StaticResource("tasks")) + case "cases" :: cid :: "observables" :: Nil => + caseSrv + .startTraversal + .getByNumber(cid.toInt) + .observables + .attachments + .domainMap(AttachmentResource(_, emptyId = false)) + .toSeq + case "cases" :: cid :: "tasks" :: Nil => + caseSrv + .startTraversal + .getByNumber(cid.toInt) + .tasks + .logs + .attachments + .domainMap(AttachmentResource(_, emptyId = false)) + .toSeq + case _ => Nil + } } diff --git a/thehive/app/org/thp/thehive/controllers/v0/AuditRenderer.scala b/thehive/app/org/thp/thehive/controllers/v0/AuditRenderer.scala index 218047efbc..4b93313587 100644 --- a/thehive/app/org/thp/thehive/controllers/v0/AuditRenderer.scala +++ b/thehive/app/org/thp/thehive/controllers/v0/AuditRenderer.scala @@ -98,8 +98,8 @@ trait AuditRenderer { def jsonSummary(auditSrv: AuditSrv, requestId: String)(implicit graph: Graph): JsObject = auditSrv .startTraversal - .has("requestId", requestId) - .has("mainAction", false) + .has(_.requestId, requestId) + .has(_.mainAction, false) .group( _.byValue(_.objectType), _.by(_.groupCount(_.byValue(_.action))) diff --git a/thehive/app/org/thp/thehive/controllers/v0/CaseCtrl.scala b/thehive/app/org/thp/thehive/controllers/v0/CaseCtrl.scala index dcd27bd6ba..e8f7d3cb4b 100644 --- a/thehive/app/org/thp/thehive/controllers/v0/CaseCtrl.scala +++ b/thehive/app/org/thp/thehive/controllers/v0/CaseCtrl.scala @@ -337,7 +337,7 @@ class PublicCase @Inject() ( .property("computed.handlingDurationInHours", UMapping.long)( _.select( _.coalesce( - _.has("endDate") + _.has(_.endDate) .sack( (_: JLong, endDate: JLong) => endDate, _.by(_.value(_.endDate).graphMap[Long, JLong, Converter[Long, JLong]](_.getTime, Converter.long)) diff --git a/thehive/app/org/thp/thehive/models/TheHiveSchemaDefinition.scala b/thehive/app/org/thp/thehive/models/TheHiveSchemaDefinition.scala index 926fe35def..41b8efcaf6 100644 --- a/thehive/app/org/thp/thehive/models/TheHiveSchemaDefinition.scala +++ b/thehive/app/org/thp/thehive/models/TheHiveSchemaDefinition.scala @@ -14,14 +14,13 @@ import org.thp.scalligraph.janus.JanusDatabase import org.thp.scalligraph.models._ import org.thp.scalligraph.traversal.TraversalOps._ import play.api.Logger -import play.api.inject.Injector import scala.collection.JavaConverters._ import scala.reflect.runtime.{universe => ru} import scala.util.{Success, Try} @Singleton -class TheHiveSchemaDefinition @Inject() (injector: Injector) extends Schema with UpdatableSchema { +class TheHiveSchemaDefinition @Inject() extends Schema with UpdatableSchema { // Make sure TypeDefinitionCategory has been initialised before ModifierType to prevent ExceptionInInitializerError TypeDefinitionCategory.BACKING_INDEX @@ -30,7 +29,7 @@ class TheHiveSchemaDefinition @Inject() (injector: Injector) extends Schema with val operations: Operations = Operations(name) .addProperty[Option[Boolean]]("Observable", "seen") .updateGraph("Add manageConfig permission to org-admin profile", "Profile") { traversal => - Try(traversal.has("name", "org-admin").raw.property("permissions", "manageConfig").iterate()) + Try(traversal.unsafeHas("name", "org-admin").raw.property("permissions", "manageConfig").iterate()) Success(()) } .updateGraph("Remove duplicate custom fields", "CustomField") { traversal => diff --git a/thehive/app/org/thp/thehive/services/AlertSrv.scala b/thehive/app/org/thp/thehive/services/AlertSrv.scala index c35ae92c49..2a330e7e86 100644 --- a/thehive/app/org/thp/thehive/services/AlertSrv.scala +++ b/thehive/app/org/thp/thehive/services/AlertSrv.scala @@ -150,7 +150,7 @@ class AlertSrv @Inject() ( ): Try[Unit] = { val maybeExistingObservable = richObservable.dataOrAttachment match { case Left(data) => get(alert).observables.filterOnData(data.data) - case Right(attachment) => get(alert).observables.has("attachmentId", attachment.attachmentId) + case Right(attachment) => get(alert).observables.filterOnAttachmentId(attachment.attachmentId) } maybeExistingObservable .richObservable @@ -334,9 +334,13 @@ object AlertOps { def getBySourceId(`type`: String, source: String, sourceRef: String): Traversal.V[Alert] = traversal - .has("type", `type`) - .has("source", source) - .has("sourceRef", sourceRef) + .has(_.`type`, `type`) + .has(_.source, source) + .has(_.sourceRef, sourceRef) + + def filterByType(`type`: String): Traversal.V[Alert] = traversal.has(_.`type`, `type`) + + def filterBySource(source: String): Traversal.V[Alert] = traversal.has(_.source, source) def organisation: Traversal.V[Organisation] = traversal.out[AlertOrganisation].v[Organisation] @@ -454,7 +458,7 @@ object AlertOps { } def customFields(name: String): Traversal.E[AlertCustomField] = - traversal.outE[AlertCustomField].filter(_.inV.has("name", name)).e[AlertCustomField] + traversal.outE[AlertCustomField].filter(_.inV.v[CustomField].has(_.name, name)) def customFields: Traversal.E[AlertCustomField] = traversal.outE[AlertCustomField].e[AlertCustomField] diff --git a/thehive/app/org/thp/thehive/services/AuditSrv.scala b/thehive/app/org/thp/thehive/services/AuditSrv.scala index ba3256f75e..ae4a9d8765 100644 --- a/thehive/app/org/thp/thehive/services/AuditSrv.scala +++ b/thehive/app/org/thp/thehive/services/AuditSrv.scala @@ -65,7 +65,7 @@ class AuditSrv @Inject() ( */ def getMainByIds(order: Order, ids: String*)(implicit graph: Graph): Traversal.V[Audit] = getByIds(ids: _*) - .has("mainAction", true) + .has(_.mainAction, true) .sort(_.by("_createdAt", order)) def mergeAudits[R](body: => Try[R])(auditCreator: R => Try[Unit])(implicit graph: Graph): Try[R] = { diff --git a/thehive/app/org/thp/thehive/services/ConfigSrv.scala b/thehive/app/org/thp/thehive/services/ConfigSrv.scala index cbbb3372f0..7a9a394d64 100644 --- a/thehive/app/org/thp/thehive/services/ConfigSrv.scala +++ b/thehive/app/org/thp/thehive/services/ConfigSrv.scala @@ -68,7 +68,7 @@ class ConfigSrv @Inject() ( userSrv .get(userName) .config - .has("name", name) + .has(_.name, name) .headOption } } @@ -82,7 +82,7 @@ object ConfigOps { def notificationRaw: Traversal[Config with Entity, Vertex, Converter[Config with Entity, Vertex]] = traversal .clone() - .has("name", P.eq[String]("notification")) + .has(_.name, "notification") // Retrieve triggers configured for each organisation val organisationTriggers: Iterator[(String, Trigger, Option[String])] = { @@ -137,6 +137,6 @@ object ConfigOps { } } - def getValue[A: Reads](name: String): Traversal[JsValue, String, Converter[JsValue, String]] = traversal.has("name", name).value(_.value) + def getValue[A: Reads](name: String): Traversal[JsValue, String, Converter[JsValue, String]] = traversal.has(_.name, name).value(_.value) } } diff --git a/thehive/app/org/thp/thehive/services/DatabaseWrapper.scala b/thehive/app/org/thp/thehive/services/DatabaseWrapper.scala deleted file mode 100644 index ae762f23ba..0000000000 --- a/thehive/app/org/thp/thehive/services/DatabaseWrapper.scala +++ /dev/null @@ -1,107 +0,0 @@ -//package org.thp.thehive.services -// -//import java.util.Date -//import java.util.function.Consumer -// -//import akka.NotUsed -//import akka.stream.scaladsl.Source -// -//import javax.inject.Provider -//import org.apache.tinkerpop.gremlin.structure.{Graph, Transaction} -//import org.thp.scalligraph.auth.AuthContext -//import org.thp.scalligraph.models.Model.Base -//import org.thp.scalligraph.models._ -// -//import scala.reflect.runtime.{universe => ru} -//import scala.util.Try -// -//class DatabaseWrapper(dbProvider: Provider[Database]) extends Database { -// lazy val db: Database = dbProvider.get() -// override lazy val createdAtMapping: SingleMapping[Date, _] = db.createdAtMapping -// override lazy val createdByMapping: SingleMapping[String, String] = db.createdByMapping -// override lazy val updatedAtMapping: OptionMapping[Date, _] = db.updatedAtMapping -// override lazy val updatedByMapping: OptionMapping[String, String] = db.updatedByMapping -// override lazy val binaryMapping: SingleMapping[Array[Byte], String] = db.binaryMapping -// -// override def close(): Unit = db.close() -// -// override def isValidId(id: String): Boolean = db.isValidId(id) -// -// override def createVertex[V <: Product](graph: Graph, authContext: AuthContext, model: Model.Vertex[V], v: V): V with Entity = -// db.createVertex(graph, authContext, model, v) -// -// override def createEdge[E <: Product, FROM <: Product, TO <: Product]( -// graph: Graph, -// authContext: AuthContext, -// model: Model.Edge[E], -// e: E, -// from: FROM with Entity, -// to: TO with Entity -// ): E with Entity = db.createEdge(graph, authContext, model, e, from, to) -// -//// override def update[E <: Product]( -//// elementTraversal: GremlinScala[_ <: Element], -//// fields: Seq[(String, Any)], -//// model: Base[E], -//// graph: Graph, -//// authContext: AuthContext -//// ): Try[Seq[E with Entity]] = db.update(elementTraversal, fields, model, graph, authContext) -// -// override def roTransaction[A](body: Graph => A): A = db.roTransaction(body) -// override def transaction[A](body: Graph => A): A = db.transaction(body) -// override def tryTransaction[A](body: Graph => Try[A]): Try[A] = db.tryTransaction(body) -// override def source[A](query: Graph => Iterator[A]): Source[A, NotUsed] = db.source(query) -// override def source[A, B](body: Graph => (Iterator[A], B)): (Source[A, NotUsed], B) = db.source(body) -// override def currentTransactionId(graph: Graph): AnyRef = db.currentTransactionId(graph) -// override def addCallback(callback: () => Try[Unit])(implicit graph: Graph): Unit = db.addCallback(callback) -// override def takeCallbacks(graph: Graph): List[() => Try[Unit]] = db.takeCallbacks(graph) -// override def version(module: String): Int = db.version(module) -// override def setVersion(module: String, v: Int): Try[Unit] = db.setVersion(module, v) -// override def getModel[E <: Product: ru.TypeTag]: Base[E] = db.getModel[E] -// override def getVertexModel[E <: Product: ru.TypeTag]: Model.Vertex[E] = db.getVertexModel[E] -// override def getEdgeModel[E <: Product: ru.TypeTag, FROM <: Product, TO <: Product]: Model.Edge[E, FROM, TO] = db.getEdgeModel[E, FROM, TO] -// override def createSchemaFrom(schemaObject: Schema)(implicit authContext: AuthContext): Try[Unit] = db.createSchemaFrom(schemaObject)(authContext) -// override def createSchema(model: Model, models: Model*): Try[Unit] = db.createSchema(model, models: _*) -// override def createSchema(models: Seq[Model]): Try[Unit] = db.createSchema(models) -// override def addSchemaIndexes(schemaObject: Schema): Try[Unit] = db.addSchemaIndexes(schemaObject) -// override def addSchemaIndexes(model: Model, models: Model*): Try[Unit] = db.addSchemaIndexes(model, models: _*) -// override def addSchemaIndexes(models: Seq[Model]): Try[Unit] = db.addSchemaIndexes(models) -// override def enableIndexes(): Try[Unit] = db.enableIndexes() -// override def removeAllIndexes(): Unit = db.removeAllIndexes() -// override def addProperty[T](model: String, propertyName: String, mapping: Mapping[_, _, _]): Try[Unit] = -// db.addProperty(model, propertyName, mapping) -// override def removeProperty(model: String, propertyName: String, usedOnlyByThisModel: Boolean): Try[Unit] = -// db.removeProperty(model, propertyName, usedOnlyByThisModel) -// override def addIndex(model: String, indexType: IndexType.Value, properties: Seq[String]): Try[Unit] = db.addIndex(model, indexType, properties) -// override def drop(): Unit = db.drop() -// -// override def getSingleProperty[D, G](element: Element, key: String, mapping: SingleMapping[D, G]): D = db.getSingleProperty(element, key, mapping) -// -// override def getOptionProperty[D, G](element: Element, key: String, mapping: OptionMapping[D, G]): Option[D] = -// db.getOptionProperty(element, key, mapping) -// override def getListProperty[D, G](element: Element, key: String, mapping: ListMapping[D, G]): Seq[D] = db.getListProperty(element, key, mapping) -// override def getSetProperty[D, G](element: Element, key: String, mapping: SetMapping[D, G]): Set[D] = db.getSetProperty(element, key, mapping) -// override def getProperty[D](element: Element, key: String, mapping: Mapping[D, _, _]): D = db.getProperty(element, key, mapping) -// -// override def setSingleProperty[D, G](element: Element, key: String, value: D, mapping: SingleMapping[D, _]): Unit = -// db.setSingleProperty[D, G](element, key, value, mapping) -// -// override def setOptionProperty[D, G](element: Element, key: String, value: Option[D], mapping: OptionMapping[D, _]): Unit = -// db.setOptionProperty[D, G](element, key, value, mapping) -// -// override def setListProperty[D, G](element: Element, key: String, values: Seq[D], mapping: ListMapping[D, _]): Unit = -// db.setListProperty[D, G](element, key, values, mapping) -// -// override def setSetProperty[D, G](element: Element, key: String, values: Set[D], mapping: SetMapping[D, _]): Unit = -// db.setSetProperty[D, G](element, key, values, mapping) -// override def setProperty[D](element: Element, key: String, value: D, mapping: Mapping[D, _, _]): Unit = db.setProperty(element, key, value, mapping) -// override def labelFilter[E <: Element](model: Model): GremlinScala[E] => GremlinScala[E] = db.labelFilter(model) -// override def labelFilter[E <: Element](label: String): GremlinScala[E] => GremlinScala[E] = db.labelFilter(label) -// override lazy val extraModels: Seq[Model] = db.extraModels -// override def addTransactionListener(listener: Consumer[Transaction.Status])(implicit graph: Graph): Unit = db.addTransactionListener(listener) -// override def mapPredicate[T](predicate: P[T]): P[T] = db.mapPredicate(predicate) -// override def toId(id: Any): Any = db.toId(id) -// -// override val binaryLinkModel: Model.Edge[BinaryLink, Binary, Binary] = db.binaryLinkModel -// override val binaryModel: Model.Vertex[Binary] = db.binaryModel -//} diff --git a/thehive/app/org/thp/thehive/services/ReportTagSrv.scala b/thehive/app/org/thp/thehive/services/ReportTagSrv.scala index c22e009eaf..a22d578e3a 100644 --- a/thehive/app/org/thp/thehive/services/ReportTagSrv.scala +++ b/thehive/app/org/thp/thehive/services/ReportTagSrv.scala @@ -18,8 +18,8 @@ import scala.util.Try class ReportTagSrv @Inject() (observableSrv: ObservableSrv)(implicit @Named("with-thehive-schema") db: Database) extends VertexSrv[ReportTag] { val observableReportTagSrv = new EdgeSrv[ObservableReportTag, Observable, ReportTag] - def updateTags(observable: Observable with Entity, origin: String, reportTags: Seq[ReportTag])( - implicit graph: Graph, + def updateTags(observable: Observable with Entity, origin: String, reportTags: Seq[ReportTag])(implicit + graph: Graph, authContext: AuthContext ): Try[Unit] = { observableSrv.get(observable).reportTags.fromOrigin(origin).remove() @@ -35,6 +35,6 @@ object ReportTagOps { implicit class ReportTagOpsDefs(traversal: Traversal.V[ReportTag]) { def observable: Traversal.V[Observable] = traversal.in[ObservableReportTag].v[Observable] - def fromOrigin(origin: String): Traversal.V[ReportTag] = traversal.has("origin", origin) + def fromOrigin(origin: String): Traversal.V[ReportTag] = traversal.has(_.origin, origin) } } diff --git a/thehive/app/org/thp/thehive/services/notification/NotificationActor.scala b/thehive/app/org/thp/thehive/services/notification/NotificationActor.scala index 382b3b8e61..dead9d9464 100644 --- a/thehive/app/org/thp/thehive/services/notification/NotificationActor.scala +++ b/thehive/app/org/thp/thehive/services/notification/NotificationActor.scala @@ -180,7 +180,7 @@ class NotificationActor @Inject() ( organisationSrv .get(organisation) .config - .has("name", "notification") + .has(_.name, "notification") .value(_.value) .toIterator .foreach { notificationConfig: JsValue => @@ -191,7 +191,7 @@ class NotificationActor @Inject() ( organisationSrv .get(organisation) .users - .filter(_.config.hasNot("name", "notification")) + .filter(_.config.hasNot(_.name, "notification")) .toIterator .foreach { user => executeNotification(Some(user), userConfig, audit, context, obj, organisation) diff --git a/thehive/test/org/thp/thehive/controllers/v0/LogCtrlTest.scala b/thehive/test/org/thp/thehive/controllers/v0/LogCtrlTest.scala index 24d2fe9dea..899c0747cb 100644 --- a/thehive/test/org/thp/thehive/controllers/v0/LogCtrlTest.scala +++ b/thehive/test/org/thp/thehive/controllers/v0/LogCtrlTest.scala @@ -14,7 +14,7 @@ class LogCtrlTest extends PlaySpecification with TestAppBuilder { "be able to create a log" in testApp { app => val task = app[Database].roTransaction { implicit graph => - app[TaskSrv].startTraversal.has("title", "case 1 task 1").headOption.get + app[TaskSrv].startTraversal.has(_.title, "case 1 task 1").getOrFail("Task").get } val request = FakeRequest("POST", s"/api/case/task/${task._id}/log") @@ -22,27 +22,27 @@ class LogCtrlTest extends PlaySpecification with TestAppBuilder { .withJsonBody(Json.parse(""" {"message":"log 1\n\n### yeahyeahyeahs", "deleted":false} """.stripMargin)) - val result = app[LogCtrl].create(task._id)(request) + val result = app[LogCtrl].create(task._id.toString)(request) status(result) shouldEqual 201 app[Database].roTransaction { implicit graph => - app[TaskSrv].get(task).logs.has("message", "log 1\n\n### yeahyeahyeahs").exists + app[TaskSrv].get(task).logs.has(_.message, "log 1\n\n### yeahyeahyeahs").exists } must beTrue } "be able to create and remove a log" in testApp { app => val log = app[Database].roTransaction { implicit graph => - app[LogSrv].startTraversal.has("message", "log for action test").getOrFail("Log").get + app[LogSrv].startTraversal.has(_.message, "log for action test").getOrFail("Log").get } val requestDelete = FakeRequest("DELETE", s"/api/case/task/log/${log._id}").withHeaders("user" -> "certuser@thehive.local") - val resultDelete = app[LogCtrl].delete(log._id)(requestDelete) + val resultDelete = app[LogCtrl].delete(log._id.toString)(requestDelete) status(resultDelete) shouldEqual 204 val deletedLog = app[Database].roTransaction { implicit graph => - app[LogSrv].startTraversal.has("message", "log for action test").headOption + app[LogSrv].startTraversal.has(_.message, "log for action test").headOption } deletedLog should beNone } diff --git a/thehive/test/org/thp/thehive/controllers/v0/TaskCtrlTest.scala b/thehive/test/org/thp/thehive/controllers/v0/TaskCtrlTest.scala index f5ce1c4dcc..42e78d7cdb 100644 --- a/thehive/test/org/thp/thehive/controllers/v0/TaskCtrlTest.scala +++ b/thehive/test/org/thp/thehive/controllers/v0/TaskCtrlTest.scala @@ -39,10 +39,10 @@ class TaskCtrlTest extends PlaySpecification with TestAppBuilder { "task controller" should { "list available tasks and get one task" in testApp { app => val taskId = app[Database].roTransaction { implicit graph => - app[TaskSrv].startTraversal.has("title", "case 1 task 1")._id.getOrFail("Task").get + app[TaskSrv].startTraversal.has(_.title, "case 1 task 1")._id.getOrFail("Task").get } val request = FakeRequest("GET", s"/api/case/task/$taskId").withHeaders("user" -> "certuser@thehive.local") - val result = app[TaskCtrl].get(taskId)(request) + val result = app[TaskCtrl].get(taskId.toString)(request) val resultTask = contentAsJson(result) status(result) shouldEqual 200 @@ -63,12 +63,12 @@ class TaskCtrlTest extends PlaySpecification with TestAppBuilder { "patch a task" in testApp { app => val taskId = app[Database].roTransaction { implicit graph => - app[TaskSrv].startTraversal.has("title", "case 1 task 1")._id.getOrFail("Task").get + app[TaskSrv].startTraversal.has(_.title, "case 1 task 1")._id.getOrFail("Task").get } val request = FakeRequest("PATCH", s"/api/case/task/$taskId") .withHeaders("user" -> "certuser@thehive.local") .withJsonBody(Json.parse("""{"title": "new title task 1", "owner": "certuser@thehive.local", "status": "InProgress"}""")) - val result = app[TaskCtrl].update(taskId)(request) + val result = app[TaskCtrl].update(taskId.toString)(request) status(result) shouldEqual 200 @@ -85,7 +85,7 @@ class TaskCtrlTest extends PlaySpecification with TestAppBuilder { val newTask = app[Database] .roTransaction { implicit graph => - app[TaskSrv].startTraversal.has("title", "new title task 1").richTask.getOrFail("Task") + app[TaskSrv].startTraversal.has(_.title, "new title task 1").richTask.getOrFail("Task") } .map(TestTask.apply) .map(_.copy(startDate = None)) @@ -93,7 +93,7 @@ class TaskCtrlTest extends PlaySpecification with TestAppBuilder { } "create a new task for an existing case" in testApp { app => - val request = FakeRequest("POST", "/api/case/#1/task?flag=true") + val request = FakeRequest("POST", "/api/case/1/task?flag=true") .withJsonBody( Json .parse( @@ -107,7 +107,7 @@ class TaskCtrlTest extends PlaySpecification with TestAppBuilder { ) .withHeaders("user" -> "certuser@thehive.local") - val result = app[TaskCtrl].create("#1")(request) + val result = app[TaskCtrl].create("1")(request) val resultTask = contentAsJson(result) status(result) must beEqualTo(201).updateMessage(s => s"$s\n${contentAsString(result)}") @@ -134,18 +134,18 @@ class TaskCtrlTest extends PlaySpecification with TestAppBuilder { "unset task owner" in testApp { app => val taskId = app[Database].roTransaction { implicit graph => - app[TaskSrv].startTraversal.has("title", "case 1 task 1")._id.getOrFail("Task").get + app[TaskSrv].startTraversal.has(_.title, "case 1 task 1")._id.getOrFail("Task").get } val request = FakeRequest("PATCH", s"/api/case/task/$taskId") .withHeaders("user" -> "certuser@thehive.local") .withJsonBody(Json.parse("""{"owner": null}""")) - val result = app[TaskCtrl].update(taskId)(request) + val result = app[TaskCtrl].update(taskId.toString)(request) status(result) shouldEqual 200 val newTask = app[Database] .roTransaction { implicit graph => - app[TaskSrv].startTraversal.has("title", "case 1 task 1").richTask.getOrFail("Task") + app[TaskSrv].startTraversal.has(_.title, "case 1 task 1").richTask.getOrFail("Task") } .map(TestTask.apply) @@ -186,7 +186,7 @@ class TaskCtrlTest extends PlaySpecification with TestAppBuilder { } "get tasks stats" in testApp { app => - val case1 = app[Database].roTransaction(graph => app[CaseSrv].startTraversal(graph).has("title", "case#1").getOrFail("Case")) + val case1 = app[Database].roTransaction(graph => app[CaseSrv].startTraversal(graph).has(_.title, "case#1").getOrFail("Case")) case1 must beSuccessfulTry diff --git a/thehive/test/org/thp/thehive/controllers/v1/AlertCtrlTest.scala b/thehive/test/org/thp/thehive/controllers/v1/AlertCtrlTest.scala index f1c1217d82..d0f65a2559 100644 --- a/thehive/test/org/thp/thehive/controllers/v1/AlertCtrlTest.scala +++ b/thehive/test/org/thp/thehive/controllers/v1/AlertCtrlTest.scala @@ -136,7 +136,7 @@ class AlertCtrlTest extends PlaySpecification with TestAppBuilder { "get an alert" in testApp { app => val alertSrv = app.apply[AlertSrv] app.apply[Database].roTransaction { implicit graph => - alertSrv.startTraversal.has("sourceRef", "ref1").getOrFail("Alert") + alertSrv.startTraversal.has(_.sourceRef, "ref1").getOrFail("Alert") } must beSuccessfulTry.which { alert: Alert with Entity => val request = FakeRequest("GET", s"/api/v1/alert/${alert._id}").withHeaders("user" -> "socuser@thehive.local") val result = app[AlertCtrl].get(alert._id)(request) diff --git a/thehive/test/org/thp/thehive/services/notification/notifiers/NotificationTemplateTest.scala b/thehive/test/org/thp/thehive/services/notification/notifiers/NotificationTemplateTest.scala index 6113ad6d5f..790b847308 100644 --- a/thehive/test/org/thp/thehive/services/notification/notifiers/NotificationTemplateTest.scala +++ b/thehive/test/org/thp/thehive/services/notification/notifiers/NotificationTemplateTest.scala @@ -80,8 +80,8 @@ class NotificationTemplateTest extends PlaySpecification with TestAppBuilder { case4 <- app[CaseSrv].get("#1").getOrFail("Case") _ <- app[CaseSrv].addTags(case4, Set("emailer test")) _ <- app[CaseSrv].addTags(case4, Set("emailer test")) // this is needed to make AuditSrv write Audit in DB - audit <- app[AuditSrv].startTraversal.has("objectId", case4._id).getOrFail("Audit") - user <- app[UserSrv].get("certuser@thehive.local").getOrFail("User") + audit <- app[AuditSrv].startTraversal.has(_.objectId, case4._id.toString).getOrFail("Audit") + user <- app[UserSrv].get(EntityName("certuser@thehive.local")).getOrFail("User") msg <- templateEngine(app[Schema]).buildMessage(template, audit, Some(case4), Some(case4), Some(user), "http://localhost/") } yield msg } diff --git a/thehive/test/org/thp/thehive/services/notification/triggers/AlertCreatedTest.scala b/thehive/test/org/thp/thehive/services/notification/triggers/AlertCreatedTest.scala index c51877b37a..84eb7a9611 100644 --- a/thehive/test/org/thp/thehive/services/notification/triggers/AlertCreatedTest.scala +++ b/thehive/test/org/thp/thehive/services/notification/triggers/AlertCreatedTest.scala @@ -48,7 +48,7 @@ class AlertCreatedTest extends PlaySpecification with TestAppBuilder { alert must beSuccessfulTry - val audit = app[AuditSrv].startTraversal.has("objectId", alert.get._id).getOrFail("Audit") + val audit = app[AuditSrv].startTraversal.has(_.objectId, alert.get._id.toString).getOrFail("Audit") audit must beSuccessfulTry