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

optionally revoke token at the end of workflow run #501

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
33 changes: 33 additions & 0 deletions .github/workflows/local-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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/[email protected]
with:
url: http://localhost:8200
method: token
token: testtoken
revokeToken: true
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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)

Expand Down
5 changes: 5 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
118 changes: 118 additions & 0 deletions integrationTests/basic/revoke.test.js
Original file line number Diff line number Diff line change
@@ -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"]}');
})
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
101 changes: 80 additions & 21 deletions src/action.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
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.`);
}
function getDefaultOptions() {
const vaultUrl = core.getInput('url', { required: true });

const defaultOptions = {
prefixUrl: vaultUrl,
Expand All @@ -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;
Expand All @@ -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) {
Expand All @@ -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}`);
Expand Down Expand Up @@ -134,7 +146,7 @@ async function exportSecrets() {
*/
function parseSecretsInput(secretsInput) {
if (!secretsInput) {
return []
return []
}

const secrets = secretsInput
Expand Down Expand Up @@ -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
}
Comment on lines +269 to +273
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would like to know whether fail on revoke can also be switched off with some flag, something like ignoreFailureRevokeToken.

}
core.debug('✔ Vault Token successfully revoked');
}

module.exports = {
exportSecrets,
parseSecretsInput,
parseHeadersInput,
getDefaultOptions,
revokeToken,
VAULT_TOKEN_STATE
};

11 changes: 11 additions & 0 deletions src/revoke.js
Original file line number Diff line number Diff line change
@@ -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);
}
})();