mongodbaggregation-frameworkmongodb-csfle

NodeJS MongoDB CSFLE Aggregation replaceroot error


I get this error on the following query: Note: punches collection is NOT encrypted nor has any encrypted CSLFE, I have another collection with CSLFE Query encryption fields. Just for your info, if I add the stages manually in Compass, it is working

query:

punches.aggregate([ { '$match': { '$and': [ { profileId: { '$in': [ new ObjectId('65a824c94528792470c0edf6'), new ObjectId('65a824cb4528792470c0ee5a'), new ObjectId('65a824d24528792470c0f01d'), new ObjectId('65a824d34528792470c0f053'), new ObjectId('65a824d44528792470c0f073'), new ObjectId('65a824d54528792470c0f0a2') ] } } ] } }, { '$match': { organizationId: new ObjectId('6507ae62881ea4139434fe9c'), punchDateTime: { '$gte': 2023-01-30T00:00:00.000Z, '$lte': 2024-01-30T00:00:00.000Z } } }, { '$skip': 0 }, { '$limit': 4000 }, { '$group': { _id: '$deviceCode', latestDocument: { '$first': '$$ROOT' } } }, { '$replaceRoot': { newRoot: '$latestDocument' } }, { '$sort': { deviceCode: 1, 'name.text': 1 } }], { allowDiskUse: true })

error:

MongoCryptError: csfle "analyze_query" failed: Access to variable ROOT disallowed [Error 2, code 31127]
    at StateMachine.execute (D:\backend\node_modules\mongodb\src\client-side-encryption\state_machine.ts:271:13)
    at processTicksAndRejections (node:internal/process/task_queues:95:5) {stack: 'MongoCryptError: csfle "analyze_query" failed…ions (node:internal/process/task_queues:95:5)', message: 'csfle "analyze_query" failed: Access to variable ROOT disallowed [Error 2, code 31127]', Symbol(errorLabels): Set(0)}

for a simpler look at the query, this is the pipeline:

pipelines [
  {
    '$match': {
      organizationId: new ObjectId('6507ae62881ea4139434fe9c'),
      punchDateTime: {
        '$gte': 2023-01-30T00:00:00.000Z,
        '$lte': 2024-01-30T00:00:00.000Z
      }
    }
  },
  { '$skip': 0 },
  { '$limit': 4000 },
  {
    '$group': { _id: '$deviceCode', latestDocument: { '$first': '$$ROOT' } }
  },
  { '$replaceRoot': { newRoot: '$latestDocument' } },
  { '$sort': { deviceCode: 1, 'name.text': 1 } }
] 

Solution

  • The csfle "analyze_query" failed error is occurring on the client side, while the local encryption process is analyzing the query to determine if any keys need to be fetched. Using "$ROOT" complicates which fields are being accessed, making that determination harder. Rather than add logic to determine whether or not that could possibly matter, the developers apparently took the "safe" route and simply refused to entertain aggregation pipelines using $ROOT when CSFLE is enabled in the client.

    One possible solution is to instantiate 2 MongoClients in your code, one with the autoEncryption option, and one without. When you have a need to run aggregation with $ROOT, use the non-encrypting client.