export function parseAwsKmsKeyArn()

in modules/kms-keyring/src/arn_parsing.ts [36:109]


export function parseAwsKmsKeyArn(
  kmsKeyArn: string
): ParsedAwsKmsKeyArn | false {
  /* Precondition: A KMS Key Id must be a non-null string. */
  needs(
    kmsKeyArn && typeof kmsKeyArn === 'string',
    'KMS key arn must be a non-null string.'
  )

  const parts = kmsKeyArn.split(':')

  /* Check for early return (Postcondition): A valid ARN has 6 parts. */
  if (parts.length === 1) {
    /* Exceptional Postcondition: Only a valid AWS KMS resource.
     * This may result in this function being called twice.
     * However this is the most correct behavior.
     */
    parseAwsKmsResource(kmsKeyArn)
    return false
  }

  /* See: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-kms
   * arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012
   * arn:aws:kms:us-east-1:123456789012:alias/example-alias
   */
  const [
    arnLiteral,
    partition,
    service,
    region = '',
    account = '',
    resource = '',
  ] = parts

  const [resourceType, ...resourceSection] = resource.split('/')

  //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5
  //# The resource section MUST be non-empty and MUST be split by a
  //# single "/" any additional "/" are included in the resource id
  const resourceId = resourceSection.join('/')

  /* If this is a valid AWS KMS Key ARN, return the parsed ARN */
  needs(
    //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5
    //# MUST start with string "arn"
    arnLiteral === ARN_PREFIX &&
      //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5
      //# The partition MUST be a non-empty
      partition &&
      //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5
      //# The service MUST be the string "kms"
      service === KMS_SERVICE &&
      //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5
      //# The region MUST be a non-empty string
      region &&
      //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5
      //# The account MUST be a non-empty string
      account &&
      //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5
      //# The resource type MUST be either "alias" or "key"
      VALID_RESOURCE_TYPES.includes(resourceType) &&
      //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5
      //# The resource id MUST be a non-empty string
      resourceId,
    'Malformed arn.'
  )
  return {
    Partition: partition,
    Region: region,
    AccountId: account,
    ResourceType: resourceType,
    ResourceId: resourceId,
  }
}