diff --git a/src/cmap/auth/mongodb_oidc/machine_workflow.ts b/src/cmap/auth/mongodb_oidc/machine_workflow.ts index 7a0fd96aefc..b666335ec0c 100644 --- a/src/cmap/auth/mongodb_oidc/machine_workflow.ts +++ b/src/cmap/auth/mongodb_oidc/machine_workflow.ts @@ -94,7 +94,12 @@ export abstract class MachineWorkflow implements Workflow { credentials: MongoCredentials ): Promise { if (this.cache.hasAccessToken) { - return this.cache.getAccessToken(); + const token = this.cache.getAccessToken(); + // New connections won't have an access token so ensure we set here. + if (!connection.accessToken) { + connection.accessToken = token; + } + return token; } else { const token = await this.callback(credentials); this.cache.put({ accessToken: token.access_token, expiresInSeconds: token.expires_in }); diff --git a/test/unit/cmap/auth/mongodb_oidc/gcp_machine_workflow.test.ts b/test/unit/cmap/auth/mongodb_oidc/gcp_machine_workflow.test.ts index 4cdd2bb4b2e..48d66f49d82 100644 --- a/test/unit/cmap/auth/mongodb_oidc/gcp_machine_workflow.test.ts +++ b/test/unit/cmap/auth/mongodb_oidc/gcp_machine_workflow.test.ts @@ -19,4 +19,28 @@ describe('GCPMachineFlow', function () { }); }); }); + + describe('#getTokenFromCacheOrEnv', function () { + context('when the cache has a token', function () { + const connection = sinon.createStubInstance(Connection); + const credentials = sinon.createStubInstance(MongoCredentials); + + context('when the connection has no token', function () { + let cache; + let workflow; + + this.beforeEach(function () { + cache = new TokenCache(); + cache.put({ accessToken: 'test', expiresInSeconds: 7200 }); + workflow = new GCPMachineWorkflow(cache); + }); + + it('sets the token on the connection', async function () { + const token = await workflow.getTokenFromCacheOrEnv(connection, credentials); + expect(token).to.equal('test'); + expect(connection.accessToken).to.equal('test'); + }); + }); + }); + }); });