Skip to content

Commit

Permalink
PIN-4557: Safer mongodb regex filters
Browse files Browse the repository at this point in the history
  • Loading branch information
galales committed Feb 13, 2024
1 parent ef2615d commit f97e5cf
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ object ReadModelAgreementQueries extends ReadModelQuery {
)(Filters.or)

private def listTenantFilters(name: Option[String]): Bson = {
val nameFilter = name.map(Filters.regex("tenants.data.name", _, "i"))
val nameFilter = name.map(safeRegex("tenants.data.name", _, "i"))

mapToVarArgs(nameFilter.toList)(Filters.and).getOrElse(Filters.empty())
}
Expand Down Expand Up @@ -303,7 +303,7 @@ object ReadModelAgreementQueries extends ReadModelQuery {
consumersIds: List[String],
producersIds: List[String]
): Bson = {
val nameFilter = name.map(Filters.regex("eservices.data.name", _, "i"))
val nameFilter = name.map(safeRegex("eservices.data.name", _, "i"))
val consumersIdsFilter = mapToVarArgs(consumersIds.map(Filters.eq("data.consumerId", _)))(Filters.or)
val producersIdsFilter = mapToVarArgs(producersIds.map(Filters.eq("data.producerId", _)))(Filters.or)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package it.pagopa.interop.agreementprocess.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)
}

0 comments on commit f97e5cf

Please sign in to comment.