Skip to content

Commit 245bfdc

Browse files
committed
Add environment variable credential provider
1 parent e6bef42 commit 245bfdc

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import {
2+
ENV_KEY,
3+
ENV_SECRET,
4+
ENV_SESSION,
5+
fromEnv,
6+
} from "../lib/fromEnv";
7+
8+
const akid = process.env[ENV_KEY];
9+
const secret = process.env[ENV_SECRET];
10+
const token = process.env[ENV_SESSION];
11+
12+
beforeEach(() => {
13+
delete process.env[ENV_KEY];
14+
delete process.env[ENV_SECRET];
15+
delete process.env[ENV_SESSION];
16+
});
17+
18+
afterAll(() => {
19+
process.env[ENV_KEY] = akid;
20+
process.env[ENV_SECRET] = secret;
21+
process.env[ENV_SESSION] = token;
22+
});
23+
24+
describe('fromEnv', () => {
25+
it('should read credentials from known environment variables', async () => {
26+
process.env[ENV_KEY] = 'foo';
27+
process.env[ENV_SECRET] = 'bar';
28+
process.env[ENV_SESSION] = 'baz';
29+
30+
expect(await fromEnv()()).toEqual({
31+
accessKeyId: 'foo',
32+
secretKey: 'bar',
33+
sessionToken: 'baz',
34+
});
35+
});
36+
37+
it('can create credentials without a session token', async () => {
38+
process.env[ENV_KEY] = 'foo';
39+
process.env[ENV_SECRET] = 'bar';
40+
41+
expect(await fromEnv()()).toEqual({
42+
accessKeyId: 'foo',
43+
secretKey: 'bar',
44+
sessionToken: void 0,
45+
});
46+
});
47+
48+
it(
49+
'should reject the promise if no environmental credentials can be found',
50+
async () => {
51+
try {
52+
await fromEnv()();
53+
fail('The promise should have been rejected.');
54+
} catch (e) {}
55+
}
56+
);
57+
});

packages/credential-provider/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export * from './lib/chain';
22
export * from './lib/fromCredentials';
3+
export * from './lib/fromEnv';
34
export * from './lib/isCredentials';
45
export * from './lib/memoize';
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import {CredentialProvider} from "./CredentialProvider";
2+
import {Credentials} from "./Credentials";
3+
4+
export const ENV_KEY = 'AWS_ACCESS_KEY_ID';
5+
export const ENV_SECRET = 'AWS_SECRET_ACCESS_KEY';
6+
export const ENV_SESSION = 'AWS_SESSION_TOKEN';
7+
8+
export function fromEnv(): CredentialProvider {
9+
return () => {
10+
const accessKeyId: string = process.env[ENV_KEY];
11+
const secretKey: string = process.env[ENV_SECRET];
12+
if (accessKeyId && secretKey) {
13+
return Promise.resolve<Credentials>({
14+
accessKeyId,
15+
secretKey,
16+
sessionToken: process.env[ENV_SESSION],
17+
});
18+
}
19+
20+
return Promise.reject<Credentials>('Unable to find environment variable credentials.');
21+
};
22+
}

0 commit comments

Comments
 (0)