< Summary - Envilder Node.js SDK

Information
Class: src/sdks/nodejs/src/infrastructure/aws/aws-ssm-secret-provider.ts
Assembly: Default
File(s): src/sdks/nodejs/src/infrastructure/aws/aws-ssm-secret-provider.ts
Tag: 605_44106794472
Line coverage
100%
Covered lines: 55
Uncovered lines: 0
Coverable lines: 55
Total lines: 175
Line coverage: 100%
Branch coverage
91%
Covered branches: 33
Total branches: 36
Branch coverage: 91.6%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

File(s)

src/sdks/nodejs/src/infrastructure/aws/aws-ssm-secret-provider.ts

#LineLine coverage
 1import { GetParametersCommand, type SSMClient } from '@aws-sdk/client-ssm';
 2import type { SecretExistence } from '../../domain/contract-validation-result.js';
 3import {
 4  ExpiredCredentialsError,
 5  isExpiredCredentialsError,
 6} from '../../domain/expired-credentials-error.js';
 7import type { ISecretExistenceChecker } from '../../domain/ports/secret-existence-checker.js';
 8import type { ISecretProvider } from '../../domain/ports/secret-provider.js';
 9import {
 10  isSsoSessionExpiredError,
 11  SsoSessionExpiredError,
 12} from '../../domain/sso-session-expired-error.js';
 13import { describeError } from '../describe-error.js';
 14
 515const SSM_BATCH_SIZE = 10;
 16
 517const AUTHENTICATION_ERROR_NAMES = new Set([
 18  'CredentialsProviderError',
 19  'UnrecognizedClientException',
 20  'InvalidClientTokenId',
 21  'InvalidSignatureException',
 22  'IncompleteSignatureException',
 23]);
 24
 25/**
 26 * Errors that fail a whole `GetParameters` call because of one of its names,
 27 * so each name is checked on its own to tell which one.
 28 */
 529const PER_NAME_ERROR_NAMES = new Set([
 30  'AccessDeniedException',
 31  'ValidationException',
 32]);
 33
 34/**
 35 * {@link ISecretProvider} backed by AWS SSM Parameter Store.
 36 *
 37 * Parameters are retrieved with decryption enabled so that
 38 * SecureString values are returned in plain text.
 39 *
 40 * SSM supports fetching up to 10 parameters per request,
 41 * so names are chunked into batches automatically.
 42 */
 43export class AwsSsmSecretProvider
 44  implements ISecretProvider, ISecretExistenceChecker
 45{
 46  private readonly ssmClient: SSMClient;
 47  private readonly profile?: string;
 48
 49  constructor(ssmClient: SSMClient, profile?: string) {
 2450    if (!ssmClient) {
 151      throw new Error('ssmClient cannot be null');
 52    }
 2353    this.ssmClient = ssmClient;
 2354    this.profile = profile;
 55  }
 56
 57  async getSecrets(names: string[]): Promise<Map<string, string>> {
 1558    const result = new Map<string, string>();
 1559    if (names.length === 0) {
 160      return result;
 61    }
 62
 1463    for (const name of names) {
 2864      if (!name?.trim()) {
 165        throw new Error('Secret name cannot be null or whitespace');
 66      }
 67    }
 68
 1369    for (let i = 0; i < names.length; i += SSM_BATCH_SIZE) {
 1470      const batch = names.slice(i, i + SSM_BATCH_SIZE);
 1471      try {
 1472        const response = await this.ssmClient.send(
 73          new GetParametersCommand({
 74            Names: batch,
 75            WithDecryption: true,
 76          }),
 77        );
 78
 879        for (const param of response.Parameters ?? []) {
 680          if (param.Name && param.Value != null) {
 681            result.set(param.Name, param.Value);
 82          }
 83        }
 84      } catch (error) {
 685        if (isSsoSessionExpiredError(error)) {
 186          throw new SsoSessionExpiredError(this.profile, error);
 87        }
 588        if (isExpiredCredentialsError(error)) {
 189          throw new ExpiredCredentialsError(error);
 90        }
 491        throw error;
 92      }
 93    }
 94
 795    return result;
 96  }
 97
 98  /**
 99   * Uses `GetParameters` in batches of 10 with `WithDecryption: false`: the
 100   * names it cannot find come back in `InvalidParameters`, and the values it
 101   * returns are never read. Needs `ssm:GetParameters` on the parameters.
 102   */
 103  async checkSecretsExist(
 104    names: readonly string[],
 105  ): Promise<ReadonlyMap<string, SecretExistence>> {
 12106    const results = new Map<string, SecretExistence>();
 12107    const distinct = [...new Set(names)];
 12108    for (let i = 0; i < distinct.length; i += SSM_BATCH_SIZE) {
 14109      const batch = distinct.slice(i, i + SSM_BATCH_SIZE);
 14110      for (const [name, existence] of await this.checkBatch(batch)) {
 41111        results.set(name, existence);
 112      }
 113    }
 12114    return results;
 115  }
 116
 117  private async checkBatch(
 118    batch: readonly string[],
 119  ): Promise<Array<[string, SecretExistence]>> {
 16120    try {
 16121      const { InvalidParameters = [] } = await this.ssmClient.send(
 122        new GetParametersCommand({
 123          Names: [...batch],
 124          WithDecryption: false,
 125        }),
 126      );
 8127      const missing = new Set(InvalidParameters);
 30128      return batch.map((name) => [
 129        name,
 130        { status: missing.has(name) ? 'missing' : 'exists' },
 131      ]);
 132    } catch (error) {
 8133      if (batch.length > 1 && PER_NAME_ERROR_NAMES.has(errorName(error))) {
 1134        const perName = await Promise.all(
 2135          batch.map((name) => this.checkBatch([name])),
 136        );
 1137        return perName.flat();
 138      }
 7139      const existence = this.toExistence(error);
 11140      return batch.map((name) => [name, existence]);
 141    }
 142  }
 143
 144  private toExistence(error: unknown): SecretExistence {
 145    // Expired credentials are a credentials problem: reported, not thrown,
 146    // with the same remediation a load gives.
 7147    if (isSsoSessionExpiredError(error)) {
 1148      return {
 149        status: 'authentication_failed',
 150        reason: new SsoSessionExpiredError(this.profile, error).message,
 151      };
 152    }
 6153    if (isExpiredCredentialsError(error)) {
 1154      return {
 155        status: 'authentication_failed',
 156        reason: new ExpiredCredentialsError(error).message,
 157      };
 158    }
 5159    const name = errorName(error);
 5160    const reason = describeError(error);
 5161    if (name === 'AccessDeniedException') {
 1162      return { status: 'access_denied', reason };
 163    }
 4164    if (AUTHENTICATION_ERROR_NAMES.has(name)) {
 3165      return { status: 'authentication_failed', reason };
 166    }
 1167    return { status: 'provider_error', reason };
 168  }
 169}
 170
 171function errorName(error: unknown): string {
 10172  return typeof error === 'object' && error !== null && 'name' in error
 173    ? String(error.name)
 174    : '';
 175}