diff --git a/.github/workflows/local-test.yaml b/.github/workflows/local-test.yaml index 4bb0613..efbfd14 100644 --- a/.github/workflows/local-test.yaml +++ b/.github/workflows/local-test.yaml @@ -59,3 +59,36 @@ jobs: echo cat secrets.json jq -c . < secrets.json + revoke-token: + name: revoke-token + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2 + + - uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3.6.0 + with: + node-version: '16.14.0' + + - name: NPM Install + run: npm ci + + - name: NPM Build + run: npm run build + + - name: Setup Vault + run: node ./integrationTests/e2e/setup.js + env: + VAULT_HOST: localhost + VAULT_PORT: 8200 + + - name: Import Secrets + id: import-secrets + # use the local changes + uses: ./ + # run against a specific version of vault-action + # uses: hashicorp/vault-action@v2.1.2 + with: + url: http://localhost:8200 + method: token + token: testtoken + revokeToken: true diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d50d06..91dcf35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,8 @@ ## Unreleased -* Add changes here +Features: + +* Add `revokeToken` input to revoke the generated token after the workflow run is complete [GH-501](https://github.com/hashicorp/vault-action/pull/501) ## 2.7.4 (October 26, 2023) diff --git a/action.yml b/action.yml index 84d314d..9f56c29 100644 --- a/action.yml +++ b/action.yml @@ -89,9 +89,14 @@ inputs: secretEncodingType: description: 'The encoding type of the secret to decode. If not specified, the secret will not be decoded. Supported values: base64, hex, utf8' required: false + revokeToken: + description: 'When set to true, automatically revokes the vault token after the run is complete.' + default: "false" + required: false runs: using: 'node16' main: 'dist/index.js' + post: "dist/revoke/index.js" branding: icon: 'unlock' color: 'gray-dark' diff --git a/integrationTests/basic/revoke.test.js b/integrationTests/basic/revoke.test.js new file mode 100644 index 0000000..1a83013 --- /dev/null +++ b/integrationTests/basic/revoke.test.js @@ -0,0 +1,118 @@ +jest.mock('@actions/core'); +jest.mock('@actions/core/lib/command'); +const core = require('@actions/core'); + +const got = require('got'); +const { when } = require('jest-when'); + +const { revokeToken, getDefaultOptions, VAULT_TOKEN_STATE } = require('../../src/action'); +const { retrieveToken } = require('../../src/auth'); + +const vaultUrl = `http://${process.env.VAULT_HOST || 'localhost'}:${process.env.VAULT_PORT || '8200'}`; +const vaultToken = `${process.env.VAULT_TOKEN || 'testtoken'}` + +describe('authenticate with userpass', () => { + const username = `testUsername`; + const password = `testPassword`; + beforeAll(async () => { + try { + // Verify Connection + await got(`${vaultUrl}/v1/secret/config`, { + headers: { + 'X-Vault-Token': vaultToken, + }, + }); + + await got(`${vaultUrl}/v1/secret/data/userpass-test`, { + method: 'POST', + headers: { + 'X-Vault-Token': vaultToken, + }, + json: { + data: { + secret: 'SUPERSECRET_WITH_USERPASS', + }, + }, + }); + + // Enable userpass + try { + await got(`${vaultUrl}/v1/sys/auth/userpass`, { + method: 'POST', + headers: { + 'X-Vault-Token': vaultToken + }, + json: { + type: 'userpass' + }, + }); + } catch (error) { + const { response } = error; + if (response.statusCode === 400 && response.body.includes("path is already in use")) { + // Userpass might already be enabled from previous test runs + } else { + throw error; + } + } + + // Create policies + await got(`${vaultUrl}/v1/sys/policies/acl/userpass-test`, { + method: 'POST', + headers: { + 'X-Vault-Token': vaultToken + }, + json: { + "name": "userpass-test", + "policy": `path \"auth/userpass/*\" {\n capabilities = [\"read\", \"list\"]\n}\npath \"auth/userpass/users/${username}\"\n{\n capabilities = [\"create\", \"read\", \"update\", \"delete\", \"list\"]\n}\n\npath \"secret/data/*\" {\n capabilities = [\"list\"]\n}\npath \"secret/metadata/*\" {\n capabilities = [\"list\"]\n}\n\npath \"secret/data/userpass-test\" {\n capabilities = [\"read\", \"list\"]\n}\npath \"secret/metadata/userpass-test\" {\n capabilities = [\"read\", \"list\"]\n}\n` + }, + }); + + // Create user + await got(`${vaultUrl}/v1/auth/userpass/users/${username}`, { + method: 'POST', + headers: { + 'X-Vault-Token': vaultToken + }, + json: { + password: `${password}`, + policies: 'userpass-test' + }, + }); + } catch (err) { + console.warn('Create user in userpass', err.response.body); + throw err; + } + }); + + beforeEach(() => { + jest.resetAllMocks(); + + when(core.getInput) + .calledWith('method', expect.anything()) + .mockReturnValueOnce('userpass'); + when(core.getInput) + .calledWith('username', expect.anything()) + .mockReturnValueOnce(username); + when(core.getInput) + .calledWith('password', expect.anything()) + .mockReturnValueOnce(password); + // also queried by revokeToken + when(core.getInput) + .calledWith('url', expect.anything()) + .mockReturnValue(`${vaultUrl}`); + when(core.getInput) + .calledWith('revokeToken', expect.anything()) + .mockReturnValueOnce('true'); + }); + + it('revoke token', async () => { + const defaultOptions = getDefaultOptions(); + const vaultToken = await retrieveToken("userpass", got.extend(defaultOptions)); + when(core.getState).calledWith(VAULT_TOKEN_STATE).mockReturnValue(vaultToken); + await revokeToken() + // token is now revoked so we can't revoke again + await expect(revokeToken()) + .rejects + .toThrow('failed to revoke vault token. code: ERR_NON_2XX_3XX_RESPONSE, message: Response code 403 (Forbidden), vaultResponse: {"errors":["permission denied"]}'); + }) +}); diff --git a/package.json b/package.json index 4d106f8..afc3720 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "A Github Action that allows you to consume vault secrets as secure environment variables.", "main": "dist/index.js", "scripts": { - "build": "ncc build src/entry.js -o dist", + "build": "ncc build src/entry.js -o dist && ncc build src/revoke.js -o dist/revoke", "test": "jest", "test:integration:basic": "jest -c integrationTests/basic/jest.config.js", "test:integration:enterprise": "jest -c integrationTests/enterprise/jest.config.js", diff --git a/src/action.js b/src/action.js index 94c8f8e..eb1f887 100644 --- a/src/action.js +++ b/src/action.js @@ -8,27 +8,13 @@ const { WILDCARD } = require('./constants'); const { auth: { retrieveToken }, secrets: { getSecrets } } = require('./index'); +const VAULT_TOKEN_STATE = "VAULT_TOKEN"; const AUTH_METHODS = ['approle', 'token', 'github', 'jwt', 'kubernetes', 'ldap', 'userpass']; const ENCODING_TYPES = ['base64', 'hex', 'utf8']; -async function exportSecrets() { + +function getDefaultOptions() { const vaultUrl = core.getInput('url', { required: true }); - const vaultNamespace = core.getInput('namespace', { required: false }); - const extraHeaders = parseHeadersInput('extraHeaders', { required: false }); - const exportEnv = core.getInput('exportEnv', { required: false }) != 'false'; - const outputToken = (core.getInput('outputToken', { required: false }) || 'false').toLowerCase() != 'false'; - const exportToken = (core.getInput('exportToken', { required: false }) || 'false').toLowerCase() != 'false'; - - const secretsInput = core.getInput('secrets', { required: false }); - const secretRequests = parseSecretsInput(secretsInput); - - const secretEncodingType = core.getInput('secretEncodingType', { required: false }); - - const vaultMethod = (core.getInput('method', { required: false }) || 'token').toLowerCase(); - const authPayload = core.getInput('authPayload', { required: false }); - if (!AUTH_METHODS.includes(vaultMethod) && !authPayload) { - throw Error(`Sorry, the provided authentication method ${vaultMethod} is not currently supported and no custom authPayload was provided.`); - } const defaultOptions = { prefixUrl: vaultUrl, @@ -44,6 +30,8 @@ async function exportSecrets() { } } + const extraHeaders = parseHeadersInput('extraHeaders', { required: false }); + const vaultNamespace = core.getInput('namespace', { required: false }); const tlsSkipVerify = (core.getInput('tlsSkipVerify', { required: false }) || 'false').toLowerCase() != 'false'; if (tlsSkipVerify === true) { defaultOptions.https.rejectUnauthorized = false; @@ -56,12 +44,12 @@ async function exportSecrets() { const clientCertificateRaw = core.getInput('clientCertificate', { required: false }); if (clientCertificateRaw != null) { - defaultOptions.https.certificate = Buffer.from(clientCertificateRaw, 'base64').toString(); + defaultOptions.https.certificate = Buffer.from(clientCertificateRaw, 'base64').toString(); } const clientKeyRaw = core.getInput('clientKey', { required: false }); if (clientKeyRaw != null) { - defaultOptions.https.key = Buffer.from(clientKeyRaw, 'base64').toString(); + defaultOptions.https.key = Buffer.from(clientKeyRaw, 'base64').toString(); } for (const [headerName, headerValue] of extraHeaders) { @@ -72,13 +60,37 @@ async function exportSecrets() { defaultOptions.headers["X-Vault-Namespace"] = vaultNamespace; } + return defaultOptions +} + +async function exportSecrets() { + const exportEnv = core.getInput('exportEnv', { required: false }) != 'false'; + const revokeToken = core.getInput("revokeToken", { required: false }) !== 'false' + const outputToken = (core.getInput('outputToken', { required: false }) || 'false').toLowerCase() != 'false'; + const exportToken = (core.getInput('exportToken', { required: false }) || 'false').toLowerCase() != 'false'; + + const secretsInput = core.getInput('secrets', { required: false }); + const secretRequests = parseSecretsInput(secretsInput); + + const secretEncodingType = core.getInput('secretEncodingType', { required: false }); + + const vaultMethod = (core.getInput('method', { required: false }) || 'token').toLowerCase(); + const authPayload = core.getInput('authPayload', { required: false }); + if (!AUTH_METHODS.includes(vaultMethod) && !authPayload) { + throw Error(`Sorry, the provided authentication method ${vaultMethod} is not currently supported and no custom authPayload was provided.`); + } + + const defaultOptions = getDefaultOptions(); const vaultToken = await retrieveToken(vaultMethod, got.extend(defaultOptions)); core.setSecret(vaultToken) + if (revokeToken) { + core.saveState(VAULT_TOKEN_STATE, vaultToken) + } defaultOptions.headers['X-Vault-Token'] = vaultToken; const client = got.extend(defaultOptions); if (outputToken === true) { - core.setOutput('vault_token', `${vaultToken}`); + core.setOutput('vault_token', `${vaultToken}`); } if (exportToken === true) { core.exportVariable('VAULT_TOKEN', `${vaultToken}`); @@ -134,7 +146,7 @@ async function exportSecrets() { */ function parseSecretsInput(secretsInput) { if (!secretsInput) { - return [] + return [] } const secrets = secretsInput @@ -219,9 +231,56 @@ function parseHeadersInput(inputKey, inputOptions) { }, new Map()); } +async function revokeToken() { + const token = core.getState(VAULT_TOKEN_STATE) + if (!token || token === "") { + core.debug(`provided token in state (${VAULT_TOKEN_STATE}) is empty. skipping...`) + return + } + core.setSecret(token) + + const defaultOptions = getDefaultOptions(); + defaultOptions.headers['X-Vault-Token'] = token; + const client = got.extend(defaultOptions); + try { + await revokeClientToken(client) + } catch (err) { + throw err + } +} + +/** + * @param {import('got').Got} client + */ +async function revokeClientToken(client) { + const path = "v1/auth/token/revoke-self" + /** @type {'json'} */ + const responseType = 'json'; + var options = { + responseType, + }; + + core.debug(`Revoking Vault Token from ${path} endpoint`); + + let response; + try { + response = await client.post(path, options); + } catch (err) { + if (err instanceof got.HTTPError) { + throw Error(`failed to revoke vault token. code: ${err.code}, message: ${err.message}, vaultResponse: ${JSON.stringify(err.response.body)}`) + } else { + throw err + } + } + core.debug('✔ Vault Token successfully revoked'); +} + module.exports = { exportSecrets, parseSecretsInput, parseHeadersInput, + getDefaultOptions, + revokeToken, + VAULT_TOKEN_STATE }; diff --git a/src/revoke.js b/src/revoke.js new file mode 100644 index 0000000..0c54a42 --- /dev/null +++ b/src/revoke.js @@ -0,0 +1,11 @@ +const core = require('@actions/core'); +const { revokeToken } = require('./action'); + +(async () => { + try { + await revokeToken() + } catch (error) { + core.setOutput("errorMessage", error.message); + core.setFailed(error.message); + } +})();