| | | 1 | | import { |
| | | 2 | | GetParameterCommand, |
| | | 3 | | PutParameterCommand, |
| | | 4 | | type SSM, |
| | | 5 | | } from '@aws-sdk/client-ssm'; |
| | | 6 | | import { injectable } from 'inversify'; |
| | | 7 | | import { EnvironmentVariable } from '../../domain/EnvironmentVariable.js'; |
| | | 8 | | import { SecretOperationError } from '../../domain/errors/DomainErrors.js'; |
| | | 9 | | import type { ISecretProvider } from '../../domain/ports/ISecretProvider.js'; |
| | | 10 | | |
| | 9 | 11 | | @injectable() |
| | 9 | 12 | | export class AwsSsmSecretProvider implements ISecretProvider { |
| | | 13 | | private ssm: SSM; |
| | | 14 | | |
| | | 15 | | constructor(ssm: SSM) { |
| | 34 | 16 | | this.ssm = ssm; |
| | | 17 | | } |
| | | 18 | | |
| | | 19 | | async getSecret(name: string): Promise<string | undefined> { |
| | 6 | 20 | | try { |
| | 6 | 21 | | const command = new GetParameterCommand({ |
| | | 22 | | Name: name, |
| | | 23 | | WithDecryption: true, |
| | | 24 | | }); |
| | 6 | 25 | | const { Parameter } = await this.ssm.send(command); |
| | 2 | 26 | | return Parameter?.Value; |
| | | 27 | | } catch (error) { |
| | 4 | 28 | | if ( |
| | | 29 | | typeof error === 'object' && |
| | | 30 | | error !== null && |
| | | 31 | | 'name' in error && |
| | | 32 | | error.name === 'ParameterNotFound' |
| | | 33 | | ) { |
| | 2 | 34 | | return undefined; |
| | | 35 | | } |
| | | 36 | | const errorMessage = |
| | 2 | 37 | | error instanceof Error ? error.message : String(error); |
| | 4 | 38 | | throw new SecretOperationError( |
| | | 39 | | `Failed to get secret ${EnvironmentVariable.maskSecretPath(name)}: ${errorMessage}`, |
| | | 40 | | ); |
| | | 41 | | } |
| | | 42 | | } |
| | | 43 | | |
| | | 44 | | async setSecret(name: string, value: string): Promise<void> { |
| | 4 | 45 | | const command = new PutParameterCommand({ |
| | | 46 | | Name: name, |
| | | 47 | | Value: value, |
| | | 48 | | Type: 'SecureString', |
| | | 49 | | Overwrite: true, |
| | | 50 | | }); |
| | 4 | 51 | | await this.ssm.send(command); |
| | | 52 | | } |
| | | 53 | | } |