From f20e646603bfe11d0444529774be5afce31a3089 Mon Sep 17 00:00:00 2001 From: Scott Motte Date: Fri, 16 Jun 2023 10:00:27 -0700 Subject: [PATCH] Add options.DOTENV_KEY --- lib/main.js | 13 ++++++++++--- tests/test-config-vault.js | 28 ++++++++++++++-------------- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/lib/main.js b/lib/main.js index 69cb939f..84f81a1e 100644 --- a/lib/main.js +++ b/lib/main.js @@ -58,7 +58,7 @@ function _parseVault (options) { // handle scenario for comma separated keys - for use with key rotation // example: DOTENV_KEY="dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenv.org/vault/.env.vault?environment=prod" - const keys = _dotenvKey().split(',') + const keys = _dotenvKey(options).split(',') const length = keys.length let decrypted @@ -99,11 +99,18 @@ function _debug (message) { console.log(`[dotenv@${version}][DEBUG] ${message}`) } -function _dotenvKey () { +function _dotenvKey (options) { + // prioritize developer directly setting options.DOTENV_KEY + if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { + return options.DOTENV_KEY + } + + // secondary infra already contains a DOTENV_KEY environment variable if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { return process.env.DOTENV_KEY } + // fallback to empty string return '' } @@ -212,7 +219,7 @@ function config (options) { const vaultPath = _vaultPath(options) // fallback to original dotenv if DOTENV_KEY is not set - if (_dotenvKey().length === 0) { + if (_dotenvKey(options).length === 0) { return DotenvModule.configDotenv(options) } diff --git a/tests/test-config-vault.js b/tests/test-config-vault.js index 8500f517..160ffa58 100644 --- a/tests/test-config-vault.js +++ b/tests/test-config-vault.js @@ -170,20 +170,6 @@ t.test('when DOTENV_KEY is empty string falls back to .env file', ct => { ct.end() }) -t.test('when DOTENV_KEY is passed as an option it successfully decrypts and injects', ct => { - envStub.restore() - envStub = sinon.stub(process.env, 'DOTENV_KEY').value('') - - ct.plan(1) - - const result = dotenv.config({ path: testPath, DOTENV_KEY: dotenvKey }) - - ct.equal(result.parsed.ALPHA, 'zeta') - ct.equal(process.env.ALPHA, 'bar') - - ct.end() -}) - t.test('does not write over keys already in process.env by default', ct => { ct.plan(2) @@ -208,6 +194,20 @@ t.test('does write over keys already in process.env if override turned on', ct = ct.equal(process.env.ALPHA, 'zeta') }) +t.test('when DOTENV_KEY is passed as an option it successfully decrypts and injects', ct => { + envStub.restore() + envStub = sinon.stub(process.env, 'DOTENV_KEY').value('') + + ct.plan(2) + + const result = dotenv.config({ path: testPath, DOTENV_KEY: dotenvKey }) + + ct.equal(result.parsed.ALPHA, 'zeta') + ct.equal(process.env.ALPHA, 'zeta') + + ct.end() +}) + t.test('can write to a different object rather than process.env', ct => { ct.plan(3)