Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

Secure Key Vault secret temporary files (#384)

Priyanshu Agrawal0f9515ea0931
diff --git a/plugins/power-pages/scripts/store-keyvault-secret.js b/plugins/power-pages/scripts/store-keyvault-secret.js
index 1b048b30e..1d76a05cb 100644
--- a/plugins/power-pages/scripts/store-keyvault-secret.js
+++ b/plugins/power-pages/scripts/store-keyvault-secret.js
@@ -8,8 +8,10 @@
// Usage (preferred — secret never in process args):
// printf '%s' '<value>' | node store-keyvault-secret.js --vaultName <name> --secretName <name>
//
-// Usage (convenience — secret is in the node process args but NOT in the az args):
+// Usage (convenience - secret is visible in the Node process args, not the az args):
// node store-keyvault-secret.js --vaultName <name> --secretName <name> --secretValue <value>
+// node store-keyvault-secret.js --vaultName <name> --secretName <name> --secretValue=<value>
+// Use the `=` form when the value begins with dashes.
//
// Output (JSON to stdout):
// { "secretUri": "https://myvault.vault.azure.net/secrets/mysecret/abc123..." }
@@ -23,105 +25,277 @@ const os = require('os');
const path = require('path');
const { spawnSync } = require('child_process');
-const args = process.argv.slice(2);
+function getArg(args, name) {
+ const flag = `--${name}`;
+ const idx = args.indexOf(flag);
+ const inlineArg = args.find((arg) => arg.startsWith(`${flag}=`));
-function getArg(name) {
- const idx = args.indexOf(`--${name}`);
- return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
-}
+ if (idx === -1) {
+ // Slice after the first `=` so values can contain leading dashes, spaces, and
+ // additional `=` characters without entering the spaced-form option grammar.
+ return inlineArg === undefined ? null : inlineArg.slice(flag.length + 1);
+ }
-const vaultName = getArg('vaultName');
-const secretName = getArg('secretName');
-const secretValueArg = getArg('secretValue');
-
-if (!vaultName || !secretName) {
- process.stderr.write(
- 'Usage:\n' +
- ' printf \'%s\' \'<value>\' | node store-keyvault-secret.js --vaultName <name> --secretName <name>\n' +
- ' node store-keyvault-secret.js --vaultName <name> --secretName <name> --secretValue <value>\n'
- );
- process.exit(1);
+ // Arguments use `--name value`. A bare flag or `--name --other` is present but
+ // empty, so callers can reject it without falling back to another input source.
+ const value = args[idx + 1];
+ return value === undefined || value.startsWith('--') ? '' : value;
}
-// Azure Key Vault name: 3-24 chars, starts with letter, alphanumerics and hyphens
-if (!/^[a-zA-Z][a-zA-Z0-9-]{1,22}[a-zA-Z0-9]$/.test(vaultName)) {
- process.stderr.write(
- 'Error: --vaultName must be 3-24 characters, starting with a letter, containing only alphanumerics and hyphens.\n'
- );
- process.exit(1);
+function parseArgs(args) {
+ return {
+ vaultName: getArg(args, 'vaultName'),
+ secretName: getArg(args, 'secretName'),
+ secretValue: getArg(args, 'secretValue'),
+ };
}
-// Key Vault secret name: 1-127 chars, alphanumerics and hyphens
-if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,125}[a-zA-Z0-9])?$/.test(secretName)) {
- process.stderr.write(
- 'Error: --secretName must be 1-127 characters, alphanumerics and hyphens only.\n'
- );
- process.exit(1);
-}
+function cleanupTemporarySecret(
+ fsImpl,
+ tempFileHandle,
+ tempFile,
+ tempFileCreated,
+ tempDir
+) {
+ const errors = [];
+
+ if (tempFileHandle !== null) {
+ try {
+ fsImpl.closeSync(tempFileHandle);
+ } catch (error) {
+ errors.push(error);
+ }
+ }
-// Resolve the secret value: prefer stdin, fall back to --secretValue
-let secretValue = secretValueArg;
+ if (tempFileCreated) {
+ try {
+ fsImpl.unlinkSync(tempFile);
+ } catch (error) {
+ if (error.code !== 'ENOENT') errors.push(error);
+ }
+ }
+
+ if (tempDir) {
+ try {
+ fsImpl.rmdirSync(tempDir);
+ } catch (error) {
+ if (error.code !== 'ENOENT') errors.push(error);
+ }
+ }
+
+ if (errors.length === 1) {
+ const error = new Error(`Failed to remove temporary secret artifacts: ${errors[0].message}`, {
+ cause: errors[0],
+ });
+ error.code = 'TEMP_CLEANUP_FAILED';
+ throw error;
+ }
-if (!secretValue) {
- // Read from stdin (non-TTY only — don't block waiting for interactive input)
- if (process.stdin.isTTY) {
- process.stderr.write(
- 'Error: No secret value provided. Pipe the value via stdin or pass --secretValue.\n'
+ if (errors.length > 1) {
+ const detail = errors.map((item) => item.message).join('; ');
+ const error = new AggregateError(
+ errors,
+ `Failed to remove temporary secret artifacts: ${detail}`
);
- process.exit(1);
+ error.code = 'TEMP_CLEANUP_FAILED';
+ throw error;
}
+}
+
+function storeKeyVaultSecret(
+ { vaultName, secretName, secretValue },
+ {
+ fsImpl = fs,
+ osImpl = os,
+ pathImpl = path,
+ spawnSyncImpl = spawnSync,
+ platform = process.platform,
+ } = {}
+) {
+ let tempDir = null;
+ let tempFile = null;
+ let tempFileHandle = null;
+ let tempFileCreated = false;
+ let output;
+ let operationError = null;
+ let cleanupError = null;
+
try {
- secretValue = fs.readFileSync(process.stdin.fd, 'utf8');
- } catch {
- process.stderr.write('Error: Failed to read secret value from stdin.\n');
- process.exit(1);
+ tempDir = fsImpl.mkdtempSync(pathImpl.join(osImpl.tmpdir(), 'kv-secret-'));
+
+ // Node's POSIX mode bits do not map to Windows ACLs. On Windows, the private
+ // directory inherits the current user's temp-directory DACL instead.
+ // See: https://nodejs.org/api/fs.html#file-modes
+ if (platform !== 'win32') {
+ fsImpl.chmodSync(tempDir, 0o700);
+ }
+
+ tempFile = pathImpl.join(tempDir, 'secret');
+ // `wx` maps to O_CREAT | O_EXCL, so an attacker-created file or symlink wins
+ // the race by making this write fail instead of redirecting the secret.
+ // See: https://nodejs.org/api/fs.html#file-system-flags
+ tempFileHandle = fsImpl.openSync(tempFile, 'wx', 0o600);
+ tempFileCreated = true;
+ fsImpl.writeFileSync(tempFileHandle, secretValue, 'utf8');
+ fsImpl.closeSync(tempFileHandle);
+ tempFileHandle = null;
+
+ const result = spawnSyncImpl('az', [
+ 'keyvault', 'secret', 'set',
+ '--vault-name', vaultName,
+ '--name', secretName,
+ '--file', tempFile,
+ '--encoding', 'utf-8',
+ '--query', '{secretUri:id}',
+ '-o', 'json',
+ ], { encoding: 'utf8', timeout: 30000 });
+
+ if (result.error) {
+ const error = new Error('Failed to run Azure CLI.');
+ error.code = 'AZ_SPAWN_FAILED';
+ error.cause = result.error;
+ throw error;
+ }
+
+ if (result.status !== 0) {
+ const error = new Error(`Failed to store secret in Key Vault "${vaultName}".`);
+ error.code = 'AZ_COMMAND_FAILED';
+ error.stderr = result.stderr;
+ throw error;
+ }
+
+ try {
+ output = JSON.parse(result.stdout);
+ } catch (cause) {
+ const error = new Error('Failed to parse Azure CLI output.');
+ error.code = 'AZ_OUTPUT_INVALID';
+ error.cause = cause;
+ throw error;
+ }
+ } catch (error) {
+ operationError = error;
+ } finally {
+ try {
+ cleanupTemporarySecret(
+ fsImpl,
+ tempFileHandle,
+ tempFile,
+ tempFileCreated,
+ tempDir
+ );
+ } catch (error) {
+ cleanupError = error;
+ }
}
-}
-if (!secretValue) {
- process.stderr.write('Error: Secret value is empty.\n');
- process.exit(1);
+ if (operationError) {
+ if (cleanupError) operationError.cleanupError = cleanupError;
+ throw operationError;
+ }
+ if (cleanupError) throw cleanupError;
+
+ return output;
}
-// Write the secret to a temp file with restrictive permissions (owner-only read/write).
-// This avoids passing the secret as a CLI argument to `az`, which would be visible
-// in process listings (ps, /proc) to other users on the same machine.
-const tmpFile = path.join(os.tmpdir(), `kv-secret-${process.pid}-${Date.now()}`);
-
-try {
- fs.writeFileSync(tmpFile, secretValue, { mode: 0o600 });
-
- const result = spawnSync('az', [
- 'keyvault', 'secret', 'set',
- '--vault-name', vaultName,
- '--name', secretName,
- '--file', tmpFile,
- '--encoding', 'utf-8',
- '--query', '{secretUri:id}',
- '-o', 'json',
- ], { encoding: 'utf8', timeout: 30000 });
-
- if (result.error) {
- process.stderr.write('Failed to run Azure CLI. Ensure `az` is installed and available on PATH.\n');
- process.exit(1);
+function runCli(
+ args = process.argv.slice(2),
+ {
+ stdin = process.stdin,
+ stdout = process.stdout,
+ stderr = process.stderr,
+ } = {},
+ dependencies
+) {
+ const { vaultName, secretName, secretValue: secretValueArg } = parseArgs(args);
+
+ if (!vaultName || !secretName) {
+ stderr.write(
+ 'Usage:\n' +
+ ' printf \'%s\' \'<value>\' | node store-keyvault-secret.js --vaultName <name> --secretName <name>\n' +
+ ' node store-keyvault-secret.js --vaultName <name> --secretName <name> --secretValue <value>\n' +
+ ' node store-keyvault-secret.js --vaultName <name> --secretName <name> --secretValue=<value>\n' +
+ 'Prefer stdin so the secret is not visible in process arguments. Use the `=` form for values that begin with dashes.\n'
+ );
+ return 1;
}
- if (result.status !== 0) {
- process.stderr.write(
- `Failed to store secret in Key Vault "${vaultName}". Ensure you have access and the vault exists.\n`
+ // Azure Key Vault name: 3-24 chars, starts with letter, alphanumerics and hyphens
+ if (!/^[a-zA-Z][a-zA-Z0-9-]{1,22}[a-zA-Z0-9]$/.test(vaultName)) {
+ stderr.write(
+ 'Error: --vaultName must be 3-24 characters, starting with a letter, containing only alphanumerics and hyphens.\n'
);
- if (result.stderr) process.stderr.write(result.stderr);
- process.exit(1);
+ return 1;
+ }
+
+ // Key Vault secret name: 1-127 chars, alphanumerics and hyphens
+ if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,125}[a-zA-Z0-9])?$/.test(secretName)) {
+ stderr.write(
+ 'Error: --secretName must be 1-127 characters, alphanumerics and hyphens only.\n'
+ );
+ return 1;
+ }
+
+ // Resolve the secret value: use --secretValue when present, otherwise read stdin.
+ let secretValue = secretValueArg;
+ if (secretValue === null) {
+ // Read from stdin (non-TTY only — don't block waiting for interactive input).
+ if (stdin.isTTY) {
+ stderr.write(
+ 'Error: No secret value provided. Pipe the value via stdin or pass --secretValue.\n'
+ );
+ return 1;
+ }
+
+ try {
+ secretValue = fs.readFileSync(stdin.fd, 'utf8');
+ } catch {
+ stderr.write('Error: Failed to read secret value from stdin.\n');
+ return 1;
+ }
+ }
+
+ if (!secretValue) {
+ stderr.write('Error: Secret value is empty.\n');
+ return 1;
}
try {
- const parsed = JSON.parse(result.stdout);
- process.stdout.write(JSON.stringify(parsed));
- } catch {
- process.stderr.write('Failed to parse Azure CLI output.\n');
- process.exit(1);
+ const result = storeKeyVaultSecret(
+ { vaultName, secretName, secretValue },
+ dependencies
+ );
+ stdout.write(JSON.stringify(result));
+ return 0;
+ } catch (error) {
+ if (error.code === 'AZ_SPAWN_FAILED') {
+ stderr.write('Failed to run Azure CLI. Ensure `az` is installed and available on PATH.\n');
+ } else if (error.code === 'AZ_COMMAND_FAILED') {
+ stderr.write(
+ `Failed to store secret in Key Vault "${vaultName}". Ensure you have access and the vault exists.\n`
+ );
+ if (error.stderr) stderr.write(error.stderr);
+ } else if (error.code === 'AZ_OUTPUT_INVALID') {
+ stderr.write('Failed to parse Azure CLI output.\n');
+ } else if (error.code === 'TEMP_CLEANUP_FAILED') {
+ stderr.write(`${error.message}\n`);
+ } else {
+ stderr.write(`Failed to prepare temporary secret file: ${error.message}\n`);
+ }
+
+ if (error.cleanupError) {
+ stderr.write(`${error.cleanupError.message}\n`);
+ }
+ return 1;
}
-} finally {
- // Always clean up the temp file
- try { fs.unlinkSync(tmpFile); } catch { /* ignore cleanup errors */ }
}
+
+if (require.main === module) {
+ process.exitCode = runCli();
+}
+
+module.exports = {
+ cleanupTemporarySecret,
+ parseArgs,
+ runCli,
+ storeKeyVaultSecret,
+};
diff --git a/plugins/power-pages/scripts/tests/store-keyvault-secret.test.js b/plugins/power-pages/scripts/tests/store-keyvault-secret.test.js
index 02c2e7f0c..d939c4ca0 100644
--- a/plugins/power-pages/scripts/tests/store-keyvault-secret.test.js
+++ b/plugins/power-pages/scripts/tests/store-keyvault-secret.test.js
@@ -1,9 +1,12 @@
const test = require('node:test');
const assert = require('node:assert/strict');
+const fs = require('fs');
+const os = require('os');
const path = require('path');
const { spawnSync } = require('child_process');
const cliPath = path.join(__dirname, '..', 'store-keyvault-secret.js');
+const { parseArgs, runCli, storeKeyVaultSecret } = require('../store-keyvault-secret');
function runStoreKeyvaultSecret(args, opts = {}) {
return spawnSync(process.execPath, [cliPath, ...args], {
@@ -13,10 +16,25 @@ function runStoreKeyvaultSecret(args, opts = {}) {
});
}
+function makeTempRoot(t) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'store-keyvault-secret-test-'));
+ const tempRoot = path.join(root, 'temporary files');
+ fs.mkdirSync(tempRoot);
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ return tempRoot;
+}
+
test('store-keyvault-secret fails with no arguments', () => {
const result = runStoreKeyvaultSecret([]);
assert.equal(result.status, 1);
- assert.match(result.stderr, /Usage:/);
+ assert.match(
+ result.stderr,
+ /printf '%s' '<value>' \| node store-keyvault-secret\.js --vaultName <name> --secretName <name>/
+ );
+ assert.match(result.stderr, /--secretValue <value>/);
+ assert.match(result.stderr, /--secretValue=<value>/);
+ assert.match(result.stderr, /Prefer stdin so the secret is not visible in process arguments/);
+ assert.match(result.stderr, /Use the `=` form for values that begin with dashes/);
});
test('store-keyvault-secret fails with missing --secretName', () => {
@@ -100,3 +118,391 @@ test('store-keyvault-secret rejects empty stdin', () => {
assert.equal(result.status, 1);
assert.match(result.stderr, /Secret value is empty/);
});
+
+test('store-keyvault-secret rejects explicit empty --secretValue without reading stdin', () => {
+ let stderr = '';
+ const status = runCli(
+ [
+ '--vaultName', 'my-vault',
+ '--secretName', 'my-secret',
+ '--secretValue', '',
+ ],
+ {
+ stdin: {
+ isTTY: false,
+ get fd() {
+ assert.fail('stdin must not be read when --secretValue is present');
+ },
+ },
+ stdout: { write: () => assert.fail('empty secrets must not produce output') },
+ stderr: { write: (value) => { stderr += value; } },
+ }
+ );
+
+ assert.equal(status, 1);
+ assert.equal(stderr, 'Error: Secret value is empty.\n');
+});
+
+for (const [name, args] of [
+ [
+ 'bare trailing --secretValue',
+ [
+ '--vaultName', 'my-vault',
+ '--secretName', 'my-secret',
+ '--secretValue',
+ ],
+ ],
+ [
+ '--secretValue followed by another option',
+ [
+ '--vaultName', 'my-vault',
+ '--secretName', 'my-secret',
+ '--secretValue', '--unused',
+ ],
+ ],
+]) {
+ test(`store-keyvault-secret rejects ${name} without reading stdin`, () => {
+ let stderr = '';
+ const status = runCli(
+ args,
+ {
+ stdin: {
+ isTTY: false,
+ get fd() {
+ assert.fail('stdin must not be read when --secretValue is present');
+ },
+ },
+ stdout: { write: () => assert.fail('missing values must not produce output') },
+ stderr: { write: (value) => { stderr += value; } },
+ },
+ {
+ spawnSyncImpl: () => assert.fail('az must not run for a missing secret value'),
+ }
+ );
+
+ assert.equal(status, 1);
+ assert.equal(stderr, 'Error: Secret value is empty.\n');
+ });
+}
+
+test('store-keyvault-secret parses unambiguous inline secret values verbatim', () => {
+ assert.equal(
+ parseArgs(['--secretValue=--foo']).secretValue,
+ '--foo'
+ );
+ assert.equal(
+ parseArgs(['--secretValue=value with spaces=and=equals']).secretValue,
+ 'value with spaces=and=equals'
+ );
+});
+
+test('store-keyvault-secret rejects empty inline --secretValue without reading stdin', () => {
+ let stderr = '';
+ const status = runCli(
+ [
+ '--vaultName', 'my-vault',
+ '--secretName', 'my-secret',
+ '--secretValue=',
+ ],
+ {
+ stdin: {
+ isTTY: false,
+ get fd() {
+ assert.fail('stdin must not be read when inline --secretValue is present');
+ },
+ },
+ stdout: { write: () => assert.fail('empty secrets must not produce output') },
+ stderr: { write: (value) => { stderr += value; } },
+ }
+ );
+
+ assert.equal(status, 1);
+ assert.equal(stderr, 'Error: Secret value is empty.\n');
+});
+
+test('store-keyvault-secret uses a private temp directory and keeps the secret out of az argv', (t) => {
+ const tempRoot = makeTempRoot(t);
+ const secretValue = 'secret value with spaces';
+ let report;
+
+ const result = storeKeyVaultSecret(
+ {
+ vaultName: 'my-vault',
+ secretName: 'my-secret',
+ secretValue,
+ },
+ {
+ osImpl: { tmpdir: () => tempRoot },
+ spawnSyncImpl(command, args, options) {
+ const fileIndex = args.indexOf('--file');
+ const secretPath = fileIndex === -1 ? null : args[fileIndex + 1];
+ report = {
+ command,
+ args,
+ options,
+ secret: fs.readFileSync(secretPath, 'utf8'),
+ secretPath,
+ fileMode: fs.statSync(secretPath).mode & 0o777,
+ directoryMode: fs.statSync(path.dirname(secretPath)).mode & 0o777,
+ };
+ return {
+ status: 0,
+ stdout: JSON.stringify({
+ secretUri: 'https://example.vault.azure.net/secrets/test/version',
+ }),
+ stderr: '',
+ };
+ },
+ }
+ );
+
+ assert.equal(result.secretUri, 'https://example.vault.azure.net/secrets/test/version');
+ assert.equal(report.command, 'az');
+ assert.deepEqual(report.options, { encoding: 'utf8', timeout: 30000 });
+ assert.equal(report.secret, secretValue);
+ assert.equal(report.args.includes(secretValue), false);
+ assert.notEqual(path.dirname(report.secretPath), tempRoot);
+ assert.equal(report.secretPath.startsWith(`${tempRoot}${path.sep}`), true);
+ assert.equal(fs.existsSync(report.secretPath), false);
+ assert.equal(fs.existsSync(path.dirname(report.secretPath)), false);
+ if (process.platform !== 'win32') {
+ assert.equal(report.fileMode, 0o600);
+ assert.equal(report.directoryMode, 0o700);
+ }
+});
+
+test('store-keyvault-secret cleans up the private temp directory when az fails', (t) => {
+ const tempRoot = makeTempRoot(t);
+ const secretValue = 'secret-on-failure';
+ let report;
+
+ assert.throws(
+ () => storeKeyVaultSecret(
+ {
+ vaultName: 'my-vault',
+ secretName: 'my-secret',
+ secretValue,
+ },
+ {
+ osImpl: { tmpdir: () => tempRoot },
+ spawnSyncImpl(command, args) {
+ const fileIndex = args.indexOf('--file');
+ const secretPath = fileIndex === -1 ? null : args[fileIndex + 1];
+ report = {
+ command,
+ args,
+ secret: fs.readFileSync(secretPath, 'utf8'),
+ secretPath,
+ };
+ return {
+ status: 7,
+ stdout: '',
+ stderr: 'fake Azure CLI failure\n',
+ };
+ },
+ }
+ ),
+ (error) => {
+ assert.equal(error.code, 'AZ_COMMAND_FAILED');
+ assert.equal(error.stderr, 'fake Azure CLI failure\n');
+ return true;
+ }
+ );
+
+ assert.equal(report.command, 'az');
+ assert.equal(report.secret, secretValue);
+ assert.equal(report.args.includes(secretValue), false);
+ assert.notEqual(path.dirname(report.secretPath), tempRoot);
+ assert.equal(report.secretPath.startsWith(`${tempRoot}${path.sep}`), true);
+ assert.equal(fs.existsSync(report.secretPath), false);
+ assert.equal(fs.existsSync(path.dirname(report.secretPath)), false);
+});
+
+test('store-keyvault-secret creates the secret file exclusively and cleans up partial creation', () => {
+ const calls = [];
+ const existingPathError = new Error('path already exists');
+ existingPathError.code = 'EEXIST';
+ const fsImpl = {
+ mkdtempSync(prefix) {
+ calls.push(['mkdtempSync', prefix]);
+ return '/tmp/kv-secret-private';
+ },
+ chmodSync(filePath, mode) {
+ calls.push(['chmodSync', filePath, mode]);
+ },
+ openSync(filePath, flag, mode) {
+ calls.push(['openSync', filePath, flag, mode]);
+ throw existingPathError;
+ },
+ writeFileSync() {
+ assert.fail('a pre-existing path must fail before writing');
+ },
+ closeSync() {
+ assert.fail('a file that was not opened must not be closed');
+ },
+ unlinkSync() {
+ assert.fail('a file that was not created must not be unlinked');
+ },
+ rmdirSync(filePath) {
+ calls.push(['rmdirSync', filePath]);
+ },
+ };
+
+ assert.throws(
+ () => storeKeyVaultSecret(
+ {
+ vaultName: 'my-vault',
+ secretName: 'my-secret',
+ secretValue: 'do-not-follow',
+ },
+ {
+ fsImpl,
+ osImpl: { tmpdir: () => '/tmp' },
+ pathImpl: path.posix,
+ platform: 'linux',
+ spawnSyncImpl: () => assert.fail('az must not run after exclusive creation fails'),
+ }
+ ),
+ (error) => error === existingPathError
+ );
+
+ assert.deepEqual(calls, [
+ ['mkdtempSync', '/tmp/kv-secret-'],
+ ['chmodSync', '/tmp/kv-secret-private', 0o700],
+ ['openSync', '/tmp/kv-secret-private/secret', 'wx', 0o600],
+ ['rmdirSync', '/tmp/kv-secret-private'],
+ ]);
+});
+
+test(
+ 'store-keyvault-secret does not follow a pre-existing symlink',
+ { skip: process.platform === 'win32' },
+ (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'store-keyvault-symlink-'));
+ const privateDir = path.join(root, 'private');
+ const targetPath = path.join(root, 'target');
+ fs.mkdirSync(privateDir, { mode: 0o700 });
+ fs.writeFileSync(targetPath, 'unchanged');
+ fs.symlinkSync(targetPath, path.join(privateDir, 'secret'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+
+ assert.throws(
+ () => storeKeyVaultSecret(
+ {
+ vaultName: 'my-vault',
+ secretName: 'my-secret',
+ secretValue: 'must-not-reach-target',
+ },
+ {
+ fsImpl: {
+ ...fs,
+ mkdtempSync: () => privateDir,
+ },
+ osImpl: { tmpdir: () => root },
+ pathImpl: path,
+ platform: process.platform,
+ spawnSyncImpl: () => assert.fail('az must not run when the secret path is a symlink'),
+ }
+ ),
+ (error) => {
+ assert.equal(error.code, 'EEXIST');
+ assert.equal(error.cleanupError.code, 'TEMP_CLEANUP_FAILED');
+ return true;
+ }
+ );
+
+ assert.equal(fs.readFileSync(targetPath, 'utf8'), 'unchanged');
+ }
+);
+
+test('store-keyvault-secret removes a partially written file when writing fails', () => {
+ const calls = [];
+ const writeError = new Error('disk is full');
+ writeError.code = 'ENOSPC';
+ const fsImpl = {
+ mkdtempSync: () => '/tmp/kv-secret-private',
+ chmodSync: () => {},
+ openSync: () => 42,
+ writeFileSync() {
+ calls.push('write');
+ throw writeError;
+ },
+ closeSync(handle) {
+ calls.push(['close', handle]);
+ },
+ unlinkSync(filePath) {
+ calls.push(['unlink', filePath]);
+ },
+ rmdirSync(filePath) {
+ calls.push(['rmdir', filePath]);
+ },
+ };
+
+ assert.throws(
+ () => storeKeyVaultSecret(
+ {
+ vaultName: 'my-vault',
+ secretName: 'my-secret',
+ secretValue: 'partial-write-test',
+ },
+ {
+ fsImpl,
+ osImpl: { tmpdir: () => '/tmp' },
+ pathImpl: path.posix,
+ platform: 'linux',
+ spawnSyncImpl: () => assert.fail('az must not run after a partial write'),
+ }
+ ),
+ (error) => error === writeError
+ );
+
+ assert.deepEqual(calls, [
+ 'write',
+ ['close', 42],
+ ['unlink', '/tmp/kv-secret-private/secret'],
+ ['rmdir', '/tmp/kv-secret-private'],
+ ]);
+});
+
+test('store-keyvault-secret preserves the az failure when cleanup also fails', () => {
+ const unlinkError = new Error('secret file is still busy');
+ unlinkError.code = 'EBUSY';
+ const directoryError = new Error('temporary directory is not empty');
+ directoryError.code = 'ENOTEMPTY';
+ const fsImpl = {
+ mkdtempSync: () => 'C:\\Temp\\kv-secret-private',
+ openSync: () => 42,
+ writeFileSync: () => {},
+ closeSync: () => {},
+ unlinkSync: () => { throw unlinkError; },
+ rmdirSync: () => { throw directoryError; },
+ };
+
+ assert.throws(
+ () => storeKeyVaultSecret(
+ {
+ vaultName: 'my-vault',
+ secretName: 'my-secret',
+ secretValue: 'cleanup-test',
+ },
+ {
+ fsImpl,
+ osImpl: { tmpdir: () => 'C:\\Temp' },
+ pathImpl: path.win32,
+ platform: 'win32',
+ spawnSyncImpl: () => ({
+ status: 1,
+ stderr: 'Azure denied the request',
+ }),
+ }
+ ),
+ (error) => {
+ assert.equal(error.code, 'AZ_COMMAND_FAILED');
+ assert.equal(error.stderr, 'Azure denied the request');
+ assert.equal(error.cleanupError.code, 'TEMP_CLEANUP_FAILED');
+ assert.match(error.cleanupError.message, /secret file is still busy/);
+ assert.match(error.cleanupError.message, /temporary directory is not empty/);
+ return true;
+ }
+ );
+});