import { SecretClient } from "@azure/keyvault-secrets" ; import { logger } from "../../logger" ; import { AzureAccessOpts } from "../../types" ; import { build as buildError } from "../errorBuilder" ; import { errorStatusCode } from "../errorStatusCode" ; import { getCredentials } from "./azurecredentials" ; export const validateValues = ( keyVaultName , secretName , secretValue ? ) : void => { if ( ! keyVaultName ) { throw buildError ( errorStatusCode . VALIDATION_ERR , "azure-key-vault-missing-name" ) ; } if ( ! secretName ) { throw buildError ( errorStatusCode . VALIDATION_ERR , "azure-key-vault-missing-secret-name" ) ; } if ( secretValue !== undefined && ! secretValue ) { throw buildError ( errorStatusCode . VALIDATION_ERR , "azure-key-vault-missing-secret-value" ) ; } } ; export const getClient = async ( keyVaultName , opts ) : Promise < SecretClient > => { try { const url = `https://${ keyVaultName }.vault.azure.net` ; const credentials = await getCredentials ( opts ) ; return new SecretClient ( url , credentials ! ) ; } catch ( err ) { throw buildError ( errorStatusCode . AZURE_KEY_VAULT_ERR , "azure-key-vault-client-err" , err ) ; } } ; param keyVaultName param secretName param secretValue param opts export const setSecret = async ( keyVaultName , secretName , secretValue , opts = { } ) : Promise < void > => { try { validateValues ( keyVaultName , secretName , secretValue ) ; const messageWithNoValue = `secret ${ secretName } in key vault ${ keyVaultName }` ; const client = await getClient ( keyVaultName , opts ) ; logger . debug ( `Setting ${ messageWithNoValue }` ) ; await client . setSecret ( secretName , secretValue ) ; logger . debug ( `Setting ${ messageWithNoValue } is complete` ) ; } catch ( err ) { throw buildError ( errorStatusCode . AZURE_KEY_VAULT_ERR , "azure-key-vault-set-secret-err" , err ) ; } } ; param keyVaultName param secretName param opts export const getSecret = async ( keyVaultName , secretName , opts = { } ) : Promise < string | undefined > => { try { validateValues ( keyVaultName , secretName ) ; const message = `secret ${ secretName } from key vault ${ keyVaultName }` ; const client = await getClient ( keyVaultName , opts ) ; logger . debug ( `Getting ${ message }` ) ; const latestSecret = await client . getSecret ( secretName ) ; logger . debug ( `Got ${ message }` ) ; return latestSecret . value ; } catch ( err ) { if ( err . code === "SecretNotFound" && err . statusCode === 404 ) { return undefined ; } throw buildError ( errorStatusCode . AZURE_KEY_VAULT_ERR , "azure-key-vault-get-secret-err" , err ) ; } } ;