|
| 1 | +// Copyright 2019 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | +import fetch from 'node-fetch'; |
| 15 | +import { awsInstanceProfileCredentials } from './aws-helper'; |
| 16 | + |
| 17 | +jest.mock('node-fetch'); |
| 18 | + |
| 19 | +function sleep(ms) { |
| 20 | + return new Promise(resolve => { |
| 21 | + setTimeout(resolve, ms); |
| 22 | + }); |
| 23 | +} |
| 24 | + |
| 25 | +it('getIAMInstanceProfile', async () => { |
| 26 | + let count = 0; |
| 27 | + const expectedCredentials = [ |
| 28 | + { |
| 29 | + Code: 'Success', |
| 30 | + LastUpdated: '2019-12-17T10:55:38Z', |
| 31 | + Type: 'AWS-HMAC', |
| 32 | + AccessKeyId: 'AccessKeyId', |
| 33 | + SecretAccessKey: 'SecretAccessKey', |
| 34 | + Token: 'SessionToken', |
| 35 | + Expiration: new Date(Date.now() + 1000).toISOString(), // expires 1 sec later |
| 36 | + }, |
| 37 | + { |
| 38 | + Code: 'Success', |
| 39 | + LastUpdated: '2019-12-17T10:55:38Z', |
| 40 | + Type: 'AWS-HMAC', |
| 41 | + AccessKeyId: 'AccessKeyId2', |
| 42 | + SecretAccessKey: 'SecretAccessKey2', |
| 43 | + Token: 'SessionToken2', |
| 44 | + Expiration: new Date(Date.now() + 10000).toISOString(), // expires 10 sec later |
| 45 | + }, |
| 46 | + ]; |
| 47 | + const mockFetch = (url: string) => { |
| 48 | + if (url === 'http://169.254.169.254/latest/meta-data/iam/security-credentials/') { |
| 49 | + return Promise.resolve({ text: () => Promise.resolve('some_iam_role') }); |
| 50 | + } |
| 51 | + return Promise.resolve({ |
| 52 | + json: () => Promise.resolve(expectedCredentials[count++]), |
| 53 | + }); |
| 54 | + }; |
| 55 | + fetch.mockImplementation(mockFetch); |
| 56 | + sleep; |
| 57 | + expect(await awsInstanceProfileCredentials.getCredentials()).toBe(expectedCredentials[0]); |
| 58 | + expect(await awsInstanceProfileCredentials.getCredentials()).toBe(expectedCredentials[0]); |
| 59 | + await sleep(1500) |
| 60 | + expect(await awsInstanceProfileCredentials.getCredentials()).toBe(expectedCredentials[1]); |
| 61 | + expect(await awsInstanceProfileCredentials.getCredentials()).toBe(expectedCredentials[1]); |
| 62 | +}); |
0 commit comments