@@ -7,8 +7,10 @@ import type {
77} from '@mongodb-js/devtools-connect' ;
88import type SSHTunnel from '@mongodb-js/ssh-tunnel' ;
99import EventEmitter from 'events' ;
10- import { redactConnectionOptions , redactConnectionString } from './redact ' ;
10+ import ConnectionString from 'mongodb-connection-string-url ' ;
1111import _ from 'lodash' ;
12+
13+ import { redactConnectionOptions , redactConnectionString } from './redact' ;
1214import type { ConnectionOptions } from './connection-options' ;
1315import {
1416 forceCloseTunnel ,
@@ -28,6 +30,36 @@ export type CloneableMongoClient = MongoClient & {
2830
2931export type ReauthenticationHandler = ( ) => PromiseLike < void > | void ;
3032
33+ // Return an ALLOWED_HOSTS value that matches the hosts listed in the connection
34+ // string, including possible SRV "sibling" domains.
35+ function matchingAllowedHosts (
36+ connectionOptions : Readonly < ConnectionOptions >
37+ ) : string [ ] {
38+ const connectionString = new ConnectionString (
39+ connectionOptions . connectionString ,
40+ { looseValidation : true }
41+ ) ;
42+ const suffixes = connectionString . hosts . map ( ( hostStr ) => {
43+ // eslint-disable-next-line
44+ const { host } = hostStr . match ( / ^ (?< host > .+ ?) (?< port > : [ ^ : \] \[ ] + ) ? $ / )
45+ ?. groups ! ;
46+ if ( host . startsWith ( '[' ) && host . endsWith ( ']' ) ) {
47+ return host . slice ( 1 , - 1 ) ; // IPv6
48+ }
49+ if ( host . match ( / ^ [ 0 - 9 . ] + $ / ) ) {
50+ return host ; // IPv4
51+ }
52+ if ( ! host . includes ( '.' ) || ! connectionString . isSRV ) {
53+ return host ;
54+ }
55+ // An SRV record for foo.bar.net can resolve to any hosts that match `*.bar.net`
56+ const parts = host . split ( '.' ) ;
57+ parts [ 0 ] = '*' ;
58+ return parts . join ( '.' ) ;
59+ } ) ;
60+ return [ ...new Set ( suffixes ) ] ;
61+ }
62+
3163export function prepareOIDCOptions (
3264 connectionOptions : Readonly < ConnectionOptions > ,
3365 signal ?: AbortSignal ,
@@ -51,10 +83,11 @@ export function prepareOIDCOptions(
5183 return allowedFlows ;
5284 } ;
5385
54- // Set the driver's `authMechanismProperties` (non-url)
55- // `ALLOWED_HOSTS` value to `*`.
5686 if ( connectionOptions . oidc ?. enableUntrustedEndpoints ) {
57- options . authMechanismProperties . ALLOWED_HOSTS = [ '*' ] ;
87+ // Set the driver's `authMechanismProperties` (non-url) `ALLOWED_HOSTS` value
88+ // to match the connection string hosts, including possible SRV "sibling" domains.
89+ options . authMechanismProperties . ALLOWED_HOSTS =
90+ matchingAllowedHosts ( connectionOptions ) ;
5891 }
5992
6093 // @ts -expect-error Will go away on @types/node update
0 commit comments