All files / src keyvault-secrets.ts

97.4% Statements 75/77
85% Branches 51/60
96.77% Functions 30/31
97.4% Lines 75/77

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350                                3x                                                                                                                                                   19x 19x                           1x 1x 1x           1x       3x 3x               1x 1x 1x         1x             1x 1x             3x 3x             1x             1x 1x           1x 2x             1x 1x               3x                   5x 5x 6x 4x 4x 4x 6x   3x                   14x 14x 12x   2x       5x         6x 6x 1x     5x 1x     4x                 15x 15x 13x     15x 15x 15x 2x     15x             15x 2x 2x 2x       13x                 2x 2x       2x       4x       54x 54x                 11x 11x   11x   40x 29x 11x   11x                                       8x 8x               5x         5x 5x    
import { AzureClient } from './client'
import type { AzureRequestInit, AzureRequestOverrides } from './client'
import {
  jsonProperty,
  readBoolean,
  readNumber,
  readString,
  readStringRecord,
} from './internal/json'
import { pagedItems, paginate } from './internal/paging'
import type { PagedAsyncIterableIterator, PageSettings } from './internal/paging'
import { keyVaultOAuthScope } from './internal/request-core'
import type { AzureRequestCredential } from './internal/request-core'
import { jsonRequestError } from './internal/request-error'
import { encodeResourceSegment, normalizeServiceUrl } from './internal/url'
 
const keyVaultApiVersion = '7.6'
 
export interface KeyVaultClientOptions extends Omit<AzureRequestOverrides, 'credential'> {
  fetch?: typeof globalThis.fetch
}
 
export type KeyVaultRequestOptions = Omit<AzureRequestInit, 'method' | 'body'>
 
export interface SecretAttributesOptions extends KeyVaultRequestOptions {
  contentType?: string
  enabled?: boolean
  notBefore?: Date
  expiresOn?: Date
  tags?: Record<string, string>
}
 
export interface GetSecretOptions extends KeyVaultRequestOptions {
  version?: string
}
 
export interface SecretProperties {
  vaultUrl: string
  name: string
  version?: string
  id?: string
  contentType?: string
  enabled?: boolean
  notBefore?: Date
  expiresOn?: Date
  tags?: Record<string, string>
  certificateKeyId?: string
  managed?: boolean
  createdOn?: Date
  updatedOn?: Date
  recoveryLevel?: string
  recoverableDays?: number
  recoveryId?: string
  scheduledPurgeDate?: Date
  deletedOn?: Date
}
 
export interface KeyVaultSecret {
  name: string
  value?: string
  properties: SecretProperties
}
 
export interface DeletedSecret extends KeyVaultSecret {
  recoveryId?: string
  scheduledPurgeDate?: Date
  deletedOn?: Date
}
 
export interface SecretPage<T> {
  value: T[]
  continuationToken?: string
}
 
interface SecretRequestBody {
  value?: string
  contentType: string | undefined
  tags: Record<string, string> | undefined
  attributes: ReturnType<typeof serializeAttributes>
}
 
export class KeyVaultSecretClient {
  public readonly url: string
  private readonly client: AzureClient
 
  public constructor(
    vaultUrl: string,
    credential?: AzureRequestCredential,
    options: KeyVaultClientOptions = {},
  ) {
    this.url = normalizeServiceUrl(vaultUrl, 'vaultUrl')
    this.client = new AzureClient({
      credential,
      fetch: options.fetch,
      retryOptions: options.retryOptions,
      scope: options.scope ?? keyVaultOAuthScope,
      authorityHost: options.authorityHost,
    })
  }
 
  public async setSecret(
    name: string,
    value: string,
    options: SecretAttributesOptions = {},
  ): Promise<KeyVaultSecret> {
    const { contentType, tags, enabled, notBefore, expiresOn, ...init } = options
    const attributes = serializeAttributes({ enabled, notBefore, expiresOn })
    const payload = await this.send('PUT', this.secretUrl(name), init, {
      value,
      contentType,
      tags,
      attributes,
    })
    return parseSecret(payload, this.url, name)
  }
 
  public async getSecret(name: string, options: GetSecretOptions = {}): Promise<KeyVaultSecret> {
    const { version, ...init } = options
    return parseSecret(await this.send('GET', this.secretUrl(name, version), init), this.url, name)
  }
 
  public async updateSecretProperties(
    name: string,
    version = '',
    options: SecretAttributesOptions = {},
  ): Promise<SecretProperties> {
    const { contentType, tags, enabled, notBefore, expiresOn, ...init } = options
    const attributes = serializeAttributes({ enabled, notBefore, expiresOn })
    const payload = await this.send('PATCH', this.secretUrl(name, version), init, {
      contentType,
      tags,
      attributes,
    })
    return parseSecretProperties(payload, this.url, name)
  }
 
  public async deleteSecret(
    name: string,
    options: KeyVaultRequestOptions = {},
  ): Promise<DeletedSecret> {
    const payload = await this.send('DELETE', this.secretUrl(name), options)
    return parseDeletedSecret(payload, this.url, name)
  }
 
  public async getDeletedSecret(
    name: string,
    options: KeyVaultRequestOptions = {},
  ): Promise<DeletedSecret> {
    const payload = await this.send('GET', this.deletedSecretUrl(name), options)
    return parseDeletedSecret(payload, this.url, name)
  }
 
  public async purgeDeletedSecret(
    name: string,
    options: KeyVaultRequestOptions = {},
  ): Promise<void> {
    await this.send('DELETE', this.deletedSecretUrl(name), options)
  }
 
  public async recoverDeletedSecret(
    name: string,
    options: KeyVaultRequestOptions = {},
  ): Promise<KeyVaultSecret> {
    const payload = await this.send('POST', `${this.deletedSecretUrl(name)}/recover`, options)
    return parseSecret(payload, this.url, name)
  }
 
  public listPropertiesOfSecrets(
    options: KeyVaultRequestOptions = {},
  ): PagedAsyncIterableIterator<SecretProperties, SecretPage<SecretProperties>> {
    return this.list(`${this.url}/secrets`, options, (item) =>
      parseSecretProperties(item, this.url),
    )
  }
 
  public listDeletedSecrets(
    options: KeyVaultRequestOptions = {},
  ): PagedAsyncIterableIterator<DeletedSecret, SecretPage<DeletedSecret>> {
    return this.list(`${this.url}/deletedsecrets`, options, (item) =>
      parseDeletedSecret(item, this.url),
    )
  }
 
  public listPropertiesOfSecretVersions(
    name: string,
    options: KeyVaultRequestOptions = {},
  ): PagedAsyncIterableIterator<SecretProperties, SecretPage<SecretProperties>> {
    return this.list(`${this.secretUrl(name)}/versions`, options, (item) =>
      parseSecretProperties(item, this.url, name),
    )
  }
 
  private list<T>(
    url: string,
    options: KeyVaultRequestOptions,
    parse: (item: unknown) => T,
  ): PagedAsyncIterableIterator<T, SecretPage<T>> {
    return pagedItems((settings: PageSettings = {}) =>
      paginate(async (link) => {
        const payload = await this.send('GET', this.pageUrl(link ?? url, url), options)
        const items = jsonProperty(payload, 'value')
        const nextLink = readString(payload, 'nextLink')
        const continuationToken = nextLink === '' ? undefined : nextLink
        return {
          page: {
            value: Array.isArray(items) ? items.map((item) => parse(item)) : [],
            continuationToken,
          },
          continuationToken,
        }
      }, settings.continuationToken),
    )
  }
 
  private secretUrl(name: string, version?: string, collection = 'secrets'): string {
    const url = `${this.url}/${collection}/${encodeResourceSegment(name, 'Secret name')}`
    if (version === undefined) {
      return url
    }
    return version === '' ? `${url}/` : `${url}/${encodeResourceSegment(version, 'Secret version')}`
  }
 
  private deletedSecretUrl(name: string): string {
    return this.secretUrl(name, undefined, 'deletedsecrets')
  }
 
  /** Continuation links must stay on the configured vault and continue the same listing. */
  private pageUrl(link: string, listUrl: string): string {
    const url = new URL(link, `${this.url}/`)
    if (url.origin !== new URL(this.url).origin) {
      throw new TypeError('Key Vault continuation URL must match the configured vault origin')
    }
 
    if (url.pathname !== new URL(listUrl).pathname) {
      throw new TypeError('Key Vault continuation URL must continue the same listing')
    }
 
    return url.toString()
  }
 
  private async send(
    method: string,
    target: string,
    options: KeyVaultRequestOptions,
    body?: SecretRequestBody,
  ): Promise<unknown> {
    const url = new URL(target)
    if (!url.searchParams.has('api-version')) {
      url.searchParams.set('api-version', keyVaultApiVersion)
    }
 
    const headers = new Headers(options.headers)
    headers.set('Accept', 'application/json')
    if (body !== undefined) {
      headers.set('Content-Type', 'application/json')
    }
 
    const response = await this.client.fetch(url, {
      ...options,
      redirect: options.redirect ?? 'manual',
      method,
      headers,
      body: body === undefined ? undefined : JSON.stringify(body),
    })
    if (!response.ok) {
      throw await jsonRequestError(`${method} ${url.toString()}`, response, (payload) => {
        const error = jsonProperty(payload, 'error')
        return { code: jsonProperty(error, 'code'), message: jsonProperty(error, 'message') }
      })
    }
 
    return response.status === 204 ? undefined : await response.json()
  }
}
 
function serializeAttributes(attributes: {
  enabled: boolean | undefined
  notBefore: Date | undefined
  expiresOn: Date | undefined
}): { enabled?: boolean; nbf?: number; exp?: number } | undefined {
  const { enabled, notBefore, expiresOn } = attributes
  Iif (enabled === undefined && notBefore === undefined && expiresOn === undefined) {
    return undefined
  }
 
  return { enabled, nbf: toEpochSeconds(notBefore), exp: toEpochSeconds(expiresOn) }
}
 
function toEpochSeconds(date: Date | undefined): number | undefined {
  return date === undefined ? undefined : Math.floor(date.getTime() / 1000)
}
 
function epochSecondsDate(value: unknown, key: string): Date | undefined {
  const seconds = readNumber(value, key)
  return seconds === undefined ? undefined : new Date(seconds * 1000)
}
 
/** Secret identifiers look like `https://vault/secrets/{name}/{version}`. */
function parseSecretProperties(
  payload: unknown,
  vaultUrl: string,
  fallbackName = '',
): SecretProperties {
  const id = readString(payload, 'id')
  const identifier = id === undefined ? undefined : new URL(id)
  const [, name, version] =
    identifier?.pathname
      .split('/')
      .filter((segment) => segment !== '')
      .map((segment) => decodeURIComponent(segment)) ?? []
  const attributes = jsonProperty(payload, 'attributes')
 
  return {
    vaultUrl: identifier?.origin ?? vaultUrl,
    name: name ?? fallbackName,
    version,
    id,
    contentType: readString(payload, 'contentType'),
    enabled: readBoolean(attributes, 'enabled'),
    notBefore: epochSecondsDate(attributes, 'nbf'),
    expiresOn: epochSecondsDate(attributes, 'exp'),
    tags: readStringRecord(payload, 'tags'),
    certificateKeyId: readString(payload, 'kid'),
    managed: readBoolean(payload, 'managed'),
    createdOn: epochSecondsDate(attributes, 'created'),
    updatedOn: epochSecondsDate(attributes, 'updated'),
    recoveryLevel: readString(attributes, 'recoveryLevel'),
    recoverableDays: readNumber(attributes, 'recoverableDays'),
  }
}
 
function parseSecret(payload: unknown, vaultUrl: string, fallbackName?: string): KeyVaultSecret {
  const properties = parseSecretProperties(payload, vaultUrl, fallbackName)
  return { name: properties.name, value: readString(payload, 'value'), properties }
}
 
function parseDeletedSecret(
  payload: unknown,
  vaultUrl: string,
  fallbackName?: string,
): DeletedSecret {
  const deletion = {
    recoveryId: readString(payload, 'recoveryId'),
    deletedOn: epochSecondsDate(payload, 'deletedDate'),
    scheduledPurgeDate: epochSecondsDate(payload, 'scheduledPurgeDate'),
  }
  const secret = parseSecret(payload, vaultUrl, fallbackName)
  return { ...secret, ...deletion, properties: { ...secret.properties, ...deletion } }
}