CSLFE automatic encryption with Node Js

Hello.
I’m consistently facing MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27020 errors when implementing MongoDB’s automatic encryption, despite using a MongoDB Atlas mongodb+srv:// connection string. Notably, manual encryption works without issues.
For example I have used this boiler code to make automation encryption to work:

and

Environment: Node.js with MongoDB driver. I’ve tried both local and Atlas KMS providers, creating local master and data encryption keys as per MongoDB’s guide. My JSONSchemaCreator is set up for field-level encryption. Network and firewall settings appear correct, and MongoDB versions are compatible.

Seeking insights or suggestions as to why automatic encryption consistently fails, while manual encryption operates as expected.

Hey @815cc7c74da0ae10eaac9a793bc9c35,

Welcome to the MongoDB Community forums :sparkles:

Could you kindly confirm whether you’re using a local MongoDB server or MongoDB Atlas? I noticed the default MongoDB port is typically 27017, yet I see an initiation of connection on port 27020. Is this intentional? Are you running it on a different port?

Furthermore, to gain better insights, could you share the error stack trace encountered while attempting to connect to the MongoDB cluster?

Additionally, it would be helpful to know the version of MongoDB you’re using, the MongoDB driver version, the Nodejs version, and the documentation link you’re referencing.

Look forward to hearing from you.

Regards,
Kushagra

Thank you for your reply!
I am connecting to a mongodb atlas cluster.
I have a dedicated cluster using M10.
example:
mongodb+srv://admin:@cluster0.somecluster.mongodb.net/?retryWrites=true&w=majority
If I understand correctly port 27020 is for running mongocryptd. But I don’t have a MongoDB Enterprise Server. But connecting to Atlas locally shouldn’t be a problem?
I am using this demo for example that gives me the error:

Nodejs version: v18.17.0
mongodb version: v7.0.2
mongodb driver version ^6.0.0

and this is the error stack trace:

MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27020
    at EventTarget.<anonymous> (/Users/pinchashodadad/Downloads/docs-in-use-encryption-examples-main/csfle/node/local/reader/node_modules/mongodb/lib/sdam/topology.js:276:34)
    at [nodejs.internal.kHybridDispatch] (node:internal/event_target:741:20)
    at EventTarget.dispatchEvent (node:internal/event_target:683:26)
    at abortSignal (node:internal/abort_controller:368:10)
    at TimeoutController.abort (node:internal/abort_controller:402:5)
    at Timeout.<anonymous> (/Users/pinchashodadad/Downloads/docs-in-use-encryption-examples-main/csfle/node/local/reader/node_modules/mongodb/lib/utils.js:1011:92)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27020' => ServerDescription {
        address: 'localhost:27020',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 1822125,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27020
            at connectionFailureError (/Users/pinchashodadad/Downloads/docs-in-use-encryption-examples-main/csfle/node/local/reader/node_modules/mongodb/lib/cmap/connect.js:379:20)
            at Socket.<anonymous> (/Users/pinchashodadad/Downloads/docs-in-use-encryption-examples-main/csfle/node/local/reader/node_modules/mongodb/lib/cmap/connect.js:285:22)
            at Object.onceWrapper (node:events:629:26)
            at Socket.emit (node:events:514:28)
            at emitErrorNT (node:internal/streams/destroy:151:8)
            at emitErrorCloseNT (node:internal/streams/destroy:116:3)
            at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
          [Symbol(errorLabels)]: Set(1) { 'ResetPool' },
          [cause]: Error: connect ECONNREFUSED 127.0.0.1:27020
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) {
            errno: -61,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '127.0.0.1',
            port: 27020
          }
        },
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {},
  [cause]: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27020
      at connectionFailureError (/Users/pinchashodadad/Downloads/docs-in-use-encryption-examples-main/csfle/node/local/reader/node_modules/mongodb/lib/cmap/connect.js:379:20)
      at Socket.<anonymous> (/Users/pinchashodadad/Downloads/docs-in-use-encryption-examples-main/csfle/node/local/reader/node_modules/mongodb/lib/cmap/connect.js:285:22)
      at Object.onceWrapper (node:events:629:26)
      at Socket.emit (node:events:514:28)
      at emitErrorNT (node:internal/streams/destroy:151:8)
      at emitErrorCloseNT (node:internal/streams/destroy:116:3)
      at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
    [Symbol(errorLabels)]: Set(1) { 'ResetPool' },
    [cause]: Error: connect ECONNREFUSED 127.0.0.1:27020
        at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) {
      errno: -61,
      code: 'ECONNREFUSED',
      syscall: 'connect',
      address: '127.0.0.1',
      port: 27020
    }
  }
}```

thank you in advance!

@Kushagra_Kesav would you need any additional information?

@Kushagra_Kesav I figured it out locally. That I need to install and run mongocryptd. But I don’t understand why? If my URI is towards a atlas cluster. How can I make sure in production this will work?

Hi @815cc7c74da0ae10eaac9a793bc9c35,

This usually happens when mongocryptd is either not present or not running. Make sure it is on the current path and matches your hardware platform (e.g., ARM vs x86).

Alternatively, consider migrating to crypt_shared library for several benefits one being that it does not require you to spawn another process to perform automatic encryption. The Automatic Encryption Shared Library is a preferred alternative to mongocryptd. You can place this file and point the driver to use it. Please refer to the linked documentation to learn more about it.

Note that by design, mongocryptd cannot bind to any external network interface (Ref); it strictly listens to localhost or a Unix domain socket, and so must be running on the same machine as the driver/client code.

Best regards,
Kushagra

1 Like

@Kushagra_Kesav thank you so much for the response. Helped me a lot. Would you have any experience on pointing me out on how to do this for a production application, particularly a lambda function in aws?

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.