From 728f8240e4cbb51220bf958cbb9d4597af7a82e4 Mon Sep 17 00:00:00 2001 From: Alessio Gallitano <25105748+galales@users.noreply.github.com> Date: Tue, 13 Feb 2024 16:08:27 +0100 Subject: [PATCH] PIN-4557: Safer mongodb regex filters --- .../tenantprocess/common/readmodel/ReadModelQuery.scala | 7 +++++++ .../common/readmodel/ReadModelTenantQueries.scala | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/scala/it/pagopa/interop/tenantprocess/common/readmodel/ReadModelQuery.scala b/src/main/scala/it/pagopa/interop/tenantprocess/common/readmodel/ReadModelQuery.scala index fe36d40..879e51a 100644 --- a/src/main/scala/it/pagopa/interop/tenantprocess/common/readmodel/ReadModelQuery.scala +++ b/src/main/scala/it/pagopa/interop/tenantprocess/common/readmodel/ReadModelQuery.scala @@ -1,5 +1,12 @@ package it.pagopa.interop.tenantprocess.common.readmodel +import org.mongodb.scala.bson.conversions.Bson +import org.mongodb.scala.model.Filters + trait ReadModelQuery { def mapToVarArgs[A, B](l: Seq[A])(f: Seq[A] => B): Option[B] = Option.when(l.nonEmpty)(f(l)) + + def escape(str: String): String = str.replaceAll("([.*+?^${}()|\\[\\]\\\\])", "\\\\$1") + def safeRegex(fieldName: String, pattern: String, options: String): Bson = + Filters.regex(fieldName, escape(pattern), options) } diff --git a/src/main/scala/it/pagopa/interop/tenantprocess/common/readmodel/ReadModelTenantQueries.scala b/src/main/scala/it/pagopa/interop/tenantprocess/common/readmodel/ReadModelTenantQueries.scala index 1dfaeba..7f95b99 100644 --- a/src/main/scala/it/pagopa/interop/tenantprocess/common/readmodel/ReadModelTenantQueries.scala +++ b/src/main/scala/it/pagopa/interop/tenantprocess/common/readmodel/ReadModelTenantQueries.scala @@ -222,7 +222,7 @@ object ReadModelTenantQueries extends ReadModelQuery { private def listTenantsFilters(name: Option[String]): Bson = { val nameFilter = name match { - case Some(n) if n.nonEmpty => List(Filters.regex("data.name", n, "i")) + case Some(n) if n.nonEmpty => List(safeRegex("data.name", n, "i")) case _ => Nil } val withSelfcareIdFilter = Filters.exists("data.selfcareId", true)