{"record":{"id":"78f1d195b52a8640","repo":"mongodb/node-mongodb-native","slug":"host-host-is-not-valid-for-oidc-authenticatio","errorCode":null,"errorMessage":"Host '${host}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${allowedHosts.join(',')}'","messagePattern":"Host '(.+?)' is not valid for OIDC authentication with ALLOWED_HOSTS of '(.+?)'","errorType":"exception","errorClass":"MongoInvalidArgumentError","httpStatus":null,"severity":"error","filePath":"src/mongo_client.ts","lineNumber":662,"sourceCode":"    }\n    if (typeof options.srvHost === 'string') {\n      const hosts = await resolveSRVRecord(options);\n\n      for (const [index, host] of hosts.entries()) {\n        options.hosts[index] = host;\n      }\n    }\n\n    // It is important to perform validation of hosts AFTER SRV resolution, to check the real hostname,\n    // but BEFORE we even attempt connecting with a potentially not allowed hostname\n    if (options.credentials?.mechanism === AuthMechanism.MONGODB_OIDC) {\n      const allowedHosts =\n        options.credentials?.mechanismProperties?.ALLOWED_HOSTS || DEFAULT_ALLOWED_HOSTS;\n      const isServiceAuth = !!options.credentials?.mechanismProperties?.ENVIRONMENT;\n      if (!isServiceAuth) {\n        for (const host of options.hosts) {\n          if (!hostMatchesWildcards(host.toHostPort().host, allowedHosts)) {\n            throw new MongoInvalidArgumentError(\n              `Host '${host}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${allowedHosts.join(\n                ','\n              )}'`\n            );\n          }\n        }\n      }\n    }\n\n    this.topology = new Topology(this, options.hosts, options);\n    // Events can be emitted before initialization is complete so we have to\n    // save the reference to the topology on the client ASAP if the event handlers need to access it\n\n    this.topology.once(Topology.OPEN, () => this.emit('open', this));\n\n    for (const event of MONGO_CLIENT_EVENTS) {\n      this.topology.on(event, (...args: any[]) => this.emit(event, ...(args as any)));\n    }","sourceCodeStart":644,"sourceCodeEnd":680,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/dce7939f86fb283e167ad709955abedb7bf23124/src/mongo_client.ts#L644-L680","documentation":"During connect (src/mongo_client.ts:655), when OIDC authentication is configured and the environment is NOT a service environment (no ENVIRONMENT set), the driver validates every host in the connection (including SRV-resolved hosts) against ALLOWED_HOSTS. If any host's hostname does not match the allowed list (or the default allowed hosts), it throws MongoInvalidArgumentError. This is a security control preventing OIDC token exchange with untrusted hosts.","triggerScenarios":"Connecting with mechanism 'MONGODB-OIDC' to a host whose domain is not in ALLOWED_HOSTS. Using mongodb+srv:// where SRV resolution yields a host outside the allowed set. Setting a custom ALLOWED_HOSTS that omits the deployment's domain.","commonSituations":"Misconfigured ALLOWED_HOSTS (typo, missing domain, overly restrictive wildcard). Connecting to a new cluster region/shard not added to the allowed list. SRV records expanding to hosts the caller did not anticipate.","solutions":["Add the deployment's host(s) to ALLOWED_HOSTS in mechanismProperties, e.g. ALLOWED_HOSTS: ['cluster.example.com', '*.mongodb.net'].","If using a trusted service environment, set ENVIRONMENT in mechanismProperties to bypass host validation (only for managed environments like Azure/GCP).","Verify the connection string host and any SRV-resolved hosts against the ALLOWED_HOSTS list before connecting."],"exampleFix":"// before\nconst client = new MongoClient(uri, {\n  authMechanismProperties: { ALLOWED_HOSTS: ['trusted.example.com'] },\n  auth: { mechanism: 'MONGODB-OIDC', ... }\n});\n// after\nconst client = new MongoClient(uri, {\n  authMechanismProperties: { ALLOWED_HOSTS: ['trusted.example.com', 'cluster.mongodb.net'] },\n  auth: { mechanism: 'MONGODB-OIDC', ... }\n});","handlingStrategy":"validation","validationCode":"function validateOidcHosts(hosts, allowedHosts) {\n  const { hostMatchesWildcards } = require('mongodb'); // or implement locally\n  for (const h of hosts) {\n    if (!hostMatchesWildcards(h, allowedHosts)) {\n      throw new Error(`Host ${h} not in ALLOWED_HOSTS`);\n    }\n  }\n}","typeGuard":"function isOidcMechanismProperties(v: unknown): v is { ALLOWED_HOSTS: string[]; ENVIRONMENT?: string } {\n  return v != null && Array.isArray((v as any).ALLOWED_HOSTS);\n}","tryCatchPattern":"try {\n  await client.connect();\n} catch (e) {\n  if (e instanceof MongoInvalidArgumentError && /ALLOWED_HOSTS/.test(e.message)) {\n    // add the host to ALLOWED_HOSTS and retry\n  } else throw e;\n}","preventionTips":["Pre-populate ALLOWED_HOSTS with all domains the deployment may resolve to (including SRV-expanded shards).","Use a service ENVIRONMENT when running in a managed OIDC provider to bypass host checks safely.","Validate connection-string hosts against ALLOWED_HOSTS during config bootstrap."],"tags":["oidc","auth","security","configuration"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}