-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecret-key.ts
77 lines (61 loc) · 1.91 KB
/
secret-key.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { SSMClientConfig } from '@aws-sdk/client-ssm';
import {
ssmParameter,
secretsManagerSecret,
Parameter,
Secret,
} from "aws-parameter-cache";
import { KeyType } from "./key-type";
export interface SecretKeyOptions {
/** The maximum amount of time in milliseconds a parameter will be considered fresh */
readonly maxAge?: number;
/** The service configuration options */
readonly configuration?: SSMClientConfig;
}
export class SecretKey {
private param?: Parameter | Secret;
constructor(
private readonly secretKeyString: string,
private readonly options?: SecretKeyOptions
) {}
public async getValue(): Promise<string> {
const { secretKeyType, ...props } = JSON.parse(this.secretKeyString);
switch (secretKeyType) {
case KeyType.PLAIN_TEXT:
return props.value;
case KeyType.SSM_PARAMETER: {
if (!this.param) {
this.param = ssmParameter({
ssmClientConfig: this.options?.configuration,
maxAge: this.options?.maxAge,
name: props.parameterName,
withDecryption: true,
});
}
const value = await (this.param as Parameter).value;
if (Array.isArray(value)) {
throw new Error("StringList is not supported!");
}
return value;
}
case KeyType.SECRETS_MANAGER: {
if (!this.param) {
this.param = secretsManagerSecret({
secretsManagerClientConfig: this.options?.configuration,
maxAge: this.options?.maxAge,
secretId: props.secretId,
});
}
const value = await (this.param as Secret).secretString;
return props.fieldName ? JSON.parse(value)[props.fieldName] : value;
}
default:
throw new Error(`Unsupported secret key type ${secretKeyType}`);
}
}
public refresh(): void {
if (this.param) {
this.param.refresh();
}
}
}