Skip to content

Commit

Permalink
mongodb-core: fix serialization of BigInt values in query (#3575)
Browse files Browse the repository at this point in the history
* fixing the BigInt mongo sanitization issue
* mongodb-core: adding a test for the BigInt fix

---------

Co-authored-by: Amjad Mahfoud <amjad.mahfoud@neofinancial.com>
  • Loading branch information
tlhunter and amjad-mahfoud-neo committed Aug 25, 2023
1 parent 9cbd635 commit 68c46af
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
8 changes: 6 additions & 2 deletions packages/datadog-plugin-mongodb-core/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,14 @@ class MongodbCorePlugin extends DatabasePlugin {
}
}

function sanitizeBigInt (data) {
return JSON.stringify(data, (_key, value) => typeof value === 'bigint' ? value.toString() : value)
}

function getQuery (cmd) {
if (!cmd || typeof cmd !== 'object' || Array.isArray(cmd)) return
if (cmd.query) return JSON.stringify(limitDepth(cmd.query))
if (cmd.filter) return JSON.stringify(limitDepth(cmd.filter))
if (cmd.query) return sanitizeBigInt(limitDepth(cmd.query))
if (cmd.filter) return sanitizeBigInt(limitDepth(cmd.filter))
}

function getResource (plugin, ns, query, operationName) {
Expand Down
33 changes: 33 additions & 0 deletions packages/datadog-plugin-mongodb-core/test/core.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,39 @@ describe('Plugin', () => {
}, () => {})
})

it('should serialize BigInt without erroring', done => {
agent
.use(traces => {
const span = traces[0][0]
const resource = `find test.${collection}`
const query = `{"_id":"9999999999999999999999"}`

expect(span).to.have.property('resource', resource)
expect(span.meta).to.have.property('mongodb.query', query)
})
.then(done)
.catch(done)

try {
server.command(`test.${collection}`, {
find: `test.${collection}`,
query: {
_id: 9999999999999999999999n
}
}, () => {})
} catch (err) {
// It appears that most versions of MongodDB are happy to use a BigInt instance.
// For example, 2.0.0, 3.2.0, 3.1.10, etc.
// However, version 3.1.9 throws a synchronous error that it wants a Decimal128 instead.
if (err.message.includes('Decimal128')) {
// eslint-disable-next-line no-console
console.log('This version of mongodb-core does not accept BigInt instances')
return done()
}
done(err)
}
})

it('should stringify BSON objects', done => {
const BSON = require(`../../../versions/bson@4.0.0`).get()
const id = '123456781234567812345678'
Expand Down

0 comments on commit 68c46af

Please sign in to comment.