Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to export Vault Token #127

Merged
merged 4 commits into from
Oct 1, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ Here are all the inputs available through `with`:
| `authPayload` | The JSON payload to be sent to Vault when using a custom authentication method. | | |
| `extraHeaders` | A string of newline separated extra headers to include on every request. | | |
| `exportEnv` | Whether or not export secrets as environment variables. | `true` | |
| `exportToken` | Whether or not export Vault token as environment variables (i.e VAULT_TOKEN). | `false` | |
| `caCertificate` | Base64 encoded CA certificate the server certificate was signed with. | | |
| `clientCertificate` | Base64 encoded client certificate the action uses to authenticate with Vault when mTLS is enabled. | | |
| `clientKey` | Base64 encoded client key the action uses to authenticate with Vault when mTLS is enabled. | | |
Expand Down
4 changes: 4 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ inputs:
description: 'Whether or not export secrets as environment variables.'
default: 'true'
required: false
exportToken:
description: 'Whether or not export Vault token as environment variables.'
default: 'false'
required: false
caCertificate:
description: 'Base64 encoded CA certificate to verify the Vault server certificate.'
required: false
Expand Down
21 changes: 15 additions & 6 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10688,7 +10688,9 @@ async function getSecrets(secretRequests, client) {
body = result.body;
responseCache.set(requestPath, body);
}

if (!selector.match(/.*[\.].*/)) {
selector = '"' + selector + '"'
}
selector = "data." + selector
body = JSON.parse(body)
if (body.data["data"] != undefined) {
Expand All @@ -10714,7 +10716,7 @@ function selectData(data, selector) {
const ata = jsonata(selector);
let result = JSON.stringify(ata.evaluate(data));
// Compat for custom engines
if (!result && ata.ast().type === "path" && ata.ast()['steps'].length === 1 && selector !== 'data' && 'data' in data) {
if (!result && ((ata.ast().type === "path" && ata.ast()['steps'].length === 1) || ata.ast().type === "string") && selector !== 'data' && 'data' in data) {
result = JSON.stringify(jsonata(`data.${selector}`).evaluate(data));
} else if (!result) {
throw Error(`Unable to retrieve result for ${selector}. No match data was found. Double check your Key or Selector.`);
Expand Down Expand Up @@ -14022,6 +14024,7 @@ async function exportSecrets() {
const vaultNamespace = core.getInput('namespace', { required: false });
const extraHeaders = parseHeadersInput('extraHeaders', { required: false });
const exportEnv = core.getInput('exportEnv', { required: false }) != 'false';
const exportToken = (core.getInput('exportToken', { required: false }) || 'false').toLowerCase() != 'false';

const secretsInput = core.getInput('secrets', { required: true });
const secretRequests = parseSecretsInput(secretsInput);
Expand Down Expand Up @@ -14070,6 +14073,11 @@ async function exportSecrets() {
defaultOptions.headers['X-Vault-Token'] = vaultToken;
const client = got.extend(defaultOptions);

if (exportToken === true) {
command.issue('add-mask', vaultToken);
core.exportVariable('VAULT_TOKEN', `${vaultToken}`);
}

const requests = secretRequests.map(request => {
const { path, selector } = request;
return request;
Expand Down Expand Up @@ -14134,12 +14142,13 @@ function parseSecretsInput(secretsInput) {
throw Error(`You must provide a valid path and key. Input: "${secret}"`);
}

const [path, selector] = pathParts;
const [path, selectorQuoted] = pathParts;

/** @type {any} */
const selectorAst = jsonata(selector).ast();
const selectorAst = jsonata(selectorQuoted).ast();
const selector = selectorQuoted.replace(new RegExp('"', 'g'), '');

if ((selectorAst.type !== "path" || selectorAst.steps[0].stages) && !outputVarName) {
if ((selectorAst.type !== "path" || selectorAst.steps[0].stages) && selectorAst.type !== "string" && !outputVarName) {
throw Error(`You must provide a name for the output key when using json selectors. Input: "${secret}"`);
}

Expand All @@ -14166,7 +14175,7 @@ function parseSecretsInput(secretsInput) {
*/
function normalizeOutputKey(dataKey, isEnvVar = false) {
let outputKey = dataKey
.replace('.', '__').replace(/[^\p{L}\p{N}_-]/gu, '');
.replace('.', '__').replace(new RegExp('-', 'g'), '').replace(/[^\p{L}\p{N}_-]/gu, '');
if (isEnvVar) {
outputKey = outputKey.toUpperCase();
}
Expand Down
16 changes: 8 additions & 8 deletions integrationTests/basic/integration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ describe('integration', () => {
},
json: {
data: {
otherSecret: 'OTHERSUPERSECRET',
"other-Secret-dash": 'OTHERSUPERSECRET',
},
}
});
Expand Down Expand Up @@ -100,7 +100,7 @@ describe('integration', () => {
'X-Vault-Token': 'testtoken',
},
json: {
otherSecret: 'OTHERCUSTOMSECRET',
"other-Secret-dash": 'OTHERCUSTOMSECRET',
},
});
});
Expand Down Expand Up @@ -140,26 +140,26 @@ describe('integration', () => {
});

it('get nested secret', async () => {
mockInput('secret/data/nested/test otherSecret');
mockInput(`secret/data/nested/test "other-Secret-dash"`);

await exportSecrets();

expect(core.exportVariable).toBeCalledWith('OTHERSECRET', 'OTHERSUPERSECRET');
expect(core.exportVariable).toBeCalledWith('OTHERSECRETDASH', 'OTHERSUPERSECRET');
});

it('get multiple secrets', async () => {
mockInput(`
secret/data/test secret ;
secret/data/test secret | NAMED_SECRET ;
secret/data/nested/test otherSecret ;`);
secret/data/nested/test "other-Secret-dash" ;`);

await exportSecrets();

expect(core.exportVariable).toBeCalledTimes(3);

expect(core.exportVariable).toBeCalledWith('SECRET', 'SUPERSECRET');
expect(core.exportVariable).toBeCalledWith('NAMED_SECRET', 'SUPERSECRET');
expect(core.exportVariable).toBeCalledWith('OTHERSECRET', 'OTHERSUPERSECRET');
expect(core.exportVariable).toBeCalledWith('OTHERSECRETDASH', 'OTHERSUPERSECRET');
});

it('leading slash kvv2', async () => {
Expand All @@ -179,11 +179,11 @@ describe('integration', () => {
});

it('get nested secret from K/V v1', async () => {
mockInput('secret-kv1/nested/test otherSecret');
mockInput('secret-kv1/nested/test "other-Secret-dash"');

await exportSecrets();

expect(core.exportVariable).toBeCalledWith('OTHERSECRET', 'OTHERCUSTOMSECRET');
expect(core.exportVariable).toBeCalledWith('OTHERSECRETDASH', 'OTHERCUSTOMSECRET');
});

it('leading slash kvv1', async () => {
Expand Down
15 changes: 11 additions & 4 deletions src/action.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ async function exportSecrets() {
const vaultNamespace = core.getInput('namespace', { required: false });
const extraHeaders = parseHeadersInput('extraHeaders', { required: false });
const exportEnv = core.getInput('exportEnv', { required: false }) != 'false';
const exportToken = (core.getInput('exportToken', { required: false }) || 'false').toLowerCase() != 'false';

const secretsInput = core.getInput('secrets', { required: true });
const secretRequests = parseSecretsInput(secretsInput);
Expand Down Expand Up @@ -60,6 +61,11 @@ async function exportSecrets() {
defaultOptions.headers['X-Vault-Token'] = vaultToken;
const client = got.extend(defaultOptions);

if (exportToken === true) {
command.issue('add-mask', vaultToken);
core.exportVariable('VAULT_TOKEN', `${vaultToken}`);
}

const requests = secretRequests.map(request => {
const { path, selector } = request;
return request;
Expand Down Expand Up @@ -124,12 +130,13 @@ function parseSecretsInput(secretsInput) {
throw Error(`You must provide a valid path and key. Input: "${secret}"`);
}

const [path, selector] = pathParts;
const [path, selectorQuoted] = pathParts;

/** @type {any} */
const selectorAst = jsonata(selector).ast();
const selectorAst = jsonata(selectorQuoted).ast();
const selector = selectorQuoted.replace(new RegExp('"', 'g'), '');

if ((selectorAst.type !== "path" || selectorAst.steps[0].stages) && !outputVarName) {
if ((selectorAst.type !== "path" || selectorAst.steps[0].stages) && selectorAst.type !== "string" && !outputVarName) {
throw Error(`You must provide a name for the output key when using json selectors. Input: "${secret}"`);
}

Expand All @@ -156,7 +163,7 @@ function parseSecretsInput(secretsInput) {
*/
function normalizeOutputKey(dataKey, isEnvVar = false) {
let outputKey = dataKey
.replace('.', '__').replace(/[^\p{L}\p{N}_-]/gu, '');
.replace('.', '__').replace(new RegExp('-', 'g'), '').replace(/[^\p{L}\p{N}_-]/gu, '');
if (isEnvVar) {
outputKey = outputKey.toUpperCase();
}
Expand Down
37 changes: 37 additions & 0 deletions src/action.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,12 @@ describe('exportSecrets', () => {
}
}

function mockExportToken(doExport) {
when(core.getInput)
.calledWith('exportToken')
.mockReturnValueOnce(doExport);
}

it('simple secret retrieval', async () => {
mockInput('test key');
mockVaultData({
Expand Down Expand Up @@ -257,4 +263,35 @@ describe('exportSecrets', () => {
expect(core.exportVariable).toBeCalledWith('KEY__VALUE', '1');
expect(core.setOutput).toBeCalledWith('key__value', '1');
});

it('export Vault token', async () => {
mockInput('test key');
mockVaultData({
key: 1
});
mockExportToken("true")

await exportSecrets();

expect(core.exportVariable).toBeCalledTimes(2);

expect(core.exportVariable).toBeCalledWith('VAULT_TOKEN', 'EXAMPLE');
expect(core.exportVariable).toBeCalledWith('KEY', '1');
expect(core.setOutput).toBeCalledWith('key', '1');
});

it('not export Vault token', async () => {
mockInput('test key');
mockVaultData({
key: 1
});
mockExportToken("false")

await exportSecrets();

expect(core.exportVariable).toBeCalledTimes(1);

expect(core.exportVariable).toBeCalledWith('KEY', '1');
expect(core.setOutput).toBeCalledWith('key', '1');
});
});
6 changes: 4 additions & 2 deletions src/secrets.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ async function getSecrets(secretRequests, client) {
body = result.body;
responseCache.set(requestPath, body);
}

if (!selector.match(/.*[\.].*/)) {
selector = '"' + selector + '"'
}
selector = "data." + selector
body = JSON.parse(body)
if (body.data["data"] != undefined) {
Expand All @@ -64,7 +66,7 @@ function selectData(data, selector) {
const ata = jsonata(selector);
let result = JSON.stringify(ata.evaluate(data));
// Compat for custom engines
if (!result && ata.ast().type === "path" && ata.ast()['steps'].length === 1 && selector !== 'data' && 'data' in data) {
if (!result && ((ata.ast().type === "path" && ata.ast()['steps'].length === 1) || ata.ast().type === "string") && selector !== 'data' && 'data' in data) {
result = JSON.stringify(jsonata(`data.${selector}`).evaluate(data));
} else if (!result) {
throw Error(`Unable to retrieve result for ${selector}. No match data was found. Double check your Key or Selector.`);
Expand Down