Compare commits

..

58 Commits

Author SHA1 Message Date
Richard Simpson 22e3f3e09e fix: mark actions dep as option 2020-04-12 00:10:54 -05:00
Richard Simpson 727494f451 feat: add npm publish and JSONata parsing
BREAKING CHANGE: Switches Key retrieval to use JSONata for parsing.
This allows for more powerful key retrieval and output, but resulted
in a number of related changes to how both key retrieval is done and
how "automatic" output & env keys are generated.

Adds an NPM lib publish to allow consuming parts for other actions that
may want to interact with Vault using vault-action's syntax or parts
without being forced to use the action itself.
2020-04-12 00:00:18 -05:00
Richard Simpson fa68886b06 chore(ci): use standard nodejs shipped with vms 2020-04-11 23:58:16 -05:00
Richard Simpson a7527a3e8a chore: make vault action consumable (#43)
* chore: make vault action consumable

* fix prefixless queries to default to data

* fix the right build entrypoint

* make output more forgiving and shore up selectors

* clarify doc language

* add npmtoken
2020-04-11 23:54:04 -05:00
Richard Simpson 9878eba70a chore: rebuild action 2020-04-07 12:16:27 -05:00
Richard Simpson 83d944ba1a fix: actually allow custom methods 2020-04-07 12:14:02 -05:00
Richard Simpson 567ec72c33 fix: document custom authentication method 2020-04-07 12:09:06 -05:00
Richard Simpson 5c464962be feat: add generic auth (#39)
* feat: add generic auth

Adds the ability to authenticate against any normal Vault endpoint by added the `authPayload` input.

When an unrecognized method is provided, the action will attempt to hit `v1/auth/<method>/login` with the provided `authPayload and parse out the token in the response
2020-04-04 13:19:48 -05:00
dependabot-preview[bot] ea29244204 chore(deps): [security] bump minimist from 1.2.0 to 1.2.5 (#38)
Bumps [minimist](https://github.com/substack/minimist) from 1.2.0 to 1.2.5. **This update includes security fixes.**
- [Release notes](https://github.com/substack/minimist/releases)
- [Commits](https://github.com/substack/minimist/compare/1.2.0...1.2.5)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-04-03 20:49:29 -05:00
Richard Simpson 5de02d5a14 docs: fix type 2020-04-03 12:34:34 -05:00
Richard Simpson 8845b5c724 docs: Actually mark required as required 2020-04-03 12:33:08 -05:00
Richard Simpson c80d0b130c docs: Clean up output a bit 2020-04-03 12:30:03 -05:00
Richard Simpson 01bb0f9bc9 docs: add reference 2020-04-03 12:24:42 -05:00
dependabot-preview[bot] 5a70924133 chore(deps-dev): bump semantic-release from 15.13.24 to 17.0.4 (#18)
Bumps [semantic-release](https://github.com/semantic-release/semantic-release) from 15.13.24 to 17.0.4.
- [Release notes](https://github.com/semantic-release/semantic-release/releases)
- [Commits](https://github.com/semantic-release/semantic-release/compare/v15.13.24...v17.0.4)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-04-03 11:00:18 -05:00
dependabot-preview[bot] b5fdbf352b chore(deps-dev): bump jest-when from 2.7.0 to 2.7.1 (#34)
Bumps [jest-when](https://github.com/timkindberg/jest-when) from 2.7.0 to 2.7.1.
- [Release notes](https://github.com/timkindberg/jest-when/releases)
- [Commits](https://github.com/timkindberg/jest-when/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-04-03 10:53:49 -05:00
dependabot-preview[bot] 268a32f886 chore(deps-dev): bump @types/jest from 25.1.4 to 25.1.5 (#36)
Bumps [@types/jest](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jest) from 25.1.4 to 25.1.5.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jest)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-04-03 10:53:43 -05:00
dependabot-preview[bot] f2b4d0b645 chore(deps-dev): bump jest from 25.2.1 to 25.2.7 (#37)
Bumps [jest](https://github.com/facebook/jest) from 25.2.1 to 25.2.7.
- [Release notes](https://github.com/facebook/jest/releases)
- [Changelog](https://github.com/facebook/jest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/facebook/jest/compare/v25.2.1...v25.2.7)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-04-03 10:53:38 -05:00
Richard Simpson 675d33e3da docs: add note about exportEnv option 2020-04-03 10:52:40 -05:00
Richard Simpson 50ece41861 chore: I really should PR changes 2020-03-31 12:20:05 -05:00
Richard Simpson ed8303ca53 fix: fix got not being use correctly and path prefix 2020-03-31 12:15:30 -05:00
Richard Simpson 0e719ef42a chore: compile release 2020-03-31 12:01:15 -05:00
Richard Simpson 795c9eddca feat: add github auth and cleanup docs a little
Adds the GitHub Authentication method
2020-03-31 11:56:54 -05:00
dependabot-preview[bot] 9e8c0bad27 chore(deps): bump got from 10.6.0 to 10.7.0 (#30)
Bumps [got](https://github.com/sindresorhus/got) from 10.6.0 to 10.7.0.
- [Release notes](https://github.com/sindresorhus/got/releases)
- [Commits](https://github.com/sindresorhus/got/compare/v10.6.0...v10.7.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-03-26 14:47:12 -05:00
dependabot-preview[bot] 751a3d19ad chore(deps-dev): bump jest from 25.1.0 to 25.2.1 (#31)
Bumps [jest](https://github.com/facebook/jest) from 25.1.0 to 25.2.1.
- [Release notes](https://github.com/facebook/jest/releases)
- [Changelog](https://github.com/facebook/jest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/facebook/jest/compare/v25.1.0...v25.2.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-03-26 14:47:05 -05:00
dependabot-preview[bot] cc7ceeef06 chore(deps-dev): bump @zeit/ncc from 0.21.1 to 0.22.0 (#29)
Bumps [@zeit/ncc](https://github.com/zeit/ncc) from 0.21.1 to 0.22.0.
- [Release notes](https://github.com/zeit/ncc/releases)
- [Commits](https://github.com/zeit/ncc/compare/0.21.1...0.22.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-03-24 10:52:12 -05:00
dependabot-preview[bot] fa23030c10 chore(deps): [security] bump acorn from 6.4.0 to 6.4.1 (#28)
Bumps [acorn](https://github.com/acornjs/acorn) from 6.4.0 to 6.4.1. **This update includes a security fix.**
- [Release notes](https://github.com/acornjs/acorn/releases)
- [Commits](https://github.com/acornjs/acorn/compare/6.4.0...6.4.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-03-13 20:07:36 -05:00
Richard Simpson 4561f9e26e docs: fix typo and clarify masking 2020-03-11 14:16:21 -05:00
Richard Simpson cb2908ac94 docs: promote non-key syntax sections 2020-03-11 14:12:53 -05:00
Richard Simpson 198a7ed7d2 docs: add headers docs and toc 2020-03-11 14:11:13 -05:00
Richard Simpson 4ab6f6070f fix: release new action bundle 2020-03-11 14:02:39 -05:00
Richard Simpson bef2eb0b90 feat: add the ability to set extra headers (#27)
* feat: add the ability to set extra headers

* switch to more generic map solution for headers
2020-03-11 14:02:13 -05:00
dependabot-preview[bot] 0ece1da433 chore(deps-dev): bump @types/jest from 25.1.3 to 25.1.4 (#26)
Bumps [@types/jest](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jest) from 25.1.3 to 25.1.4.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jest)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-03-10 16:25:50 -05:00
dependabot-preview[bot] 7fb0d673d1 chore(deps): bump @actions/core from 1.2.2 to 1.2.3 (#25)
Bumps [@actions/core](https://github.com/actions/toolkit/tree/HEAD/packages/core) from 1.2.2 to 1.2.3.
- [Release notes](https://github.com/actions/toolkit/releases)
- [Changelog](https://github.com/actions/toolkit/blob/master/packages/core/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/core)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-04 10:20:55 -06:00
Richard Simpson 4edbc9a77a chore: fix step output syntax 2020-02-20 11:38:11 -06:00
Richard Simpson 5357098084 fix(tests): fix unit tests and improve e2e 2020-02-20 11:24:04 -06:00
dependabot-preview[bot] 3dfe7ff808 chore(deps): bump got from 10.5.7 to 10.6.0
Bumps [got](https://github.com/sindresorhus/got) from 10.5.7 to 10.6.0.
- [Release notes](https://github.com/sindresorhus/got/releases)
- [Commits](https://github.com/sindresorhus/got/compare/v10.5.7...v10.6.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-20 17:14:12 +00:00
dependabot-preview[bot] 1049321b7a chore(deps-dev): bump @types/jest from 24.0.18 to 25.1.3
Bumps [@types/jest](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jest) from 24.0.18 to 25.1.3.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jest)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-20 17:14:05 +00:00
Richard Simpson ec10b5e257 feat: add ability to retrieve secrets via ouputs 2020-02-20 11:13:47 -06:00
Richard Simpson 7d1d7d26ad fix(build): bump build file 2020-02-20 01:48:49 -06:00
dependabot-preview[bot] f9753d75ef chore(deps-dev): bump jest from 24.9.0 to 25.1.0
Bumps [jest](https://github.com/facebook/jest) from 24.9.0 to 25.1.0.
- [Release notes](https://github.com/facebook/jest/releases)
- [Changelog](https://github.com/facebook/jest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/facebook/jest/compare/v24.9.0...v25.1.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-20 07:45:21 +00:00
Richard Simpson 11b4c03a67 fix(deps): fix comma issue in export variables 2020-02-20 01:43:53 -06:00
dependabot-preview[bot] bd26be00ff chore(deps): bump @actions/core from 1.1.1 to 1.2.2
Bumps [@actions/core](https://github.com/actions/toolkit/tree/HEAD/packages/core) from 1.1.1 to 1.2.2.
- [Release notes](https://github.com/actions/toolkit/releases)
- [Changelog](https://github.com/actions/toolkit/blob/master/packages/core/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/core)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-20 07:42:55 +00:00
dependabot-preview[bot] 452a071f5c chore(deps): bump got from 10.2.2 to 10.5.7
Bumps [got](https://github.com/sindresorhus/got) from 10.2.2 to 10.5.7.
- [Release notes](https://github.com/sindresorhus/got/releases)
- [Commits](https://github.com/sindresorhus/got/compare/v10.2.2...v10.5.7)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-20 07:41:41 +00:00
dependabot-preview[bot] a11e5a2e84 chore(deps-dev): bump @zeit/ncc from 0.20.5 to 0.21.1
Bumps [@zeit/ncc](https://github.com/zeit/ncc) from 0.20.5 to 0.21.1.
- [Release notes](https://github.com/zeit/ncc/releases)
- [Commits](https://github.com/zeit/ncc/compare/0.20.5...0.21.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-20 07:41:00 +00:00
dependabot-preview[bot] 7f552b0d14 chore(deps): [security] bump https-proxy-agent from 2.2.2 to 2.2.4
Bumps [https-proxy-agent](https://github.com/TooTallNate/node-https-proxy-agent) from 2.2.2 to 2.2.4. **This update includes security fixes.**
- [Release notes](https://github.com/TooTallNate/node-https-proxy-agent/releases)
- [Commits](https://github.com/TooTallNate/node-https-proxy-agent/compare/2.2.2...2.2.4)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-20 07:39:46 +00:00
Richard Simpson 20f954e024 chore: add place to buy me a coffee 2020-02-06 09:19:22 -06:00
Richard Simpson a884aa8e59 docs: clarify other engine support. 2020-02-05 16:37:16 -06:00
Richard Simpson 0188d9d223 feat: add support for (nearly) any engine (#15)
* feat: add support for (nearly) any engine

* cache response and fixup data depth logic

* use starting slash as non-kv sentinel value

* add tests for custom engines

* improve docs and add descriptor of generic support

* update dist
2020-02-05 16:33:12 -06:00
Giancarlo França f229481670 feat: support for KV version 1 and custom-named engines (#12)
* feat: kv v1 and engine path

* doc: add custom version and engine path usage docs

Co-authored-by: Richard Simpson <richardsimpson@outlook.com>
2020-02-04 09:40:55 -06:00
Antoine Méausoone 3b9239de79 feat(authenticate): add approle auth method (#10)
* feat(authenticate): add approle auth method

* docs(readme): update readme

* fix: update index.js

* fix: update got to 10.2.2 to fix ncc

* chore: clean up code slightly

* chore: update tests to use got correctly

* chore(test): fix integration tests

* chore: streamline method logic

* chore: make role and secret required in approle

Co-authored-by: Sébastien FAUVART <sebastien.fauvart@gmail.com>
Co-authored-by: Richard Simpson <richardsimpson@outlook.com>
2020-01-28 19:10:19 -06:00
Richard Simpson 7a9634236c chore(build): re-enable builds on PR and restrict publish to master 2020-01-09 10:45:52 -06:00
Richard Simpson ab4dc55b2e fix: actually build namespace changes 2020-01-09 10:31:15 -06:00
dependabot[bot] e394527e23 chore(deps): bump handlebars from 4.2.1 to 4.5.3 (#9)
Bumps [handlebars](https://github.com/wycats/handlebars.js) from 4.2.1 to 4.5.3.
- [Release notes](https://github.com/wycats/handlebars.js/releases)
- [Changelog](https://github.com/wycats/handlebars.js/blob/master/release-notes.md)
- [Commits](https://github.com/wycats/handlebars.js/compare/v4.2.1...v4.5.3)

Signed-off-by: dependabot[bot] <support@github.com>
2019-12-29 21:04:07 -06:00
dependabot[bot] 29150a8fd2 chore(deps): bump npm from 6.11.3 to 6.13.4 (#8)
Bumps [npm](https://github.com/npm/cli) from 6.11.3 to 6.13.4.
- [Release notes](https://github.com/npm/cli/releases)
- [Changelog](https://github.com/npm/cli/blob/latest/CHANGELOG.md)
- [Commits](https://github.com/npm/cli/compare/v6.11.3...v6.13.4)

Signed-off-by: dependabot[bot] <support@github.com>
2019-12-13 13:56:22 -06:00
Richard Simpson 38c189f087 chore(test): organize tests a bit better (#7)
* chore(test): organize tests a bit better

* add caching
2019-11-24 16:00:31 -06:00
Antoine Méausoone 3747195c5f feat(namespace): handle request on vault namespace (#5)
* feat(namespace): handle request on vault namespace
2019-11-24 15:21:11 -06:00
Richard Simpson 0104a02854 doc: fix old docs 2019-10-16 10:23:36 -05:00
Richard Simpson c81d6f1774 doc: add small clarification comment 2019-10-16 10:17:12 -05:00
31 changed files with 18843 additions and 5001 deletions
+1
View File
@@ -0,0 +1 @@
ko_fi: richicoder
+109 -33
View File
@@ -1,45 +1,85 @@
on: [push] on:
push:
branches:
- master
pull_request:
jobs: jobs:
test: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
services:
vault:
image: vault:1.2.3
ports:
- 8200/tcp
env:
VAULT_DEV_ROOT_TOKEN_ID: testtoken
options: --cap-add=IPC_LOCK
steps: steps:
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: Use Node.js 10.x - uses: actions/setup-node@v1
uses: actions/setup-node@v1
with: with:
node-version: 10.x node-version: ''
- name: setup npm cache
uses: actions/cache@v1
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: npm install - name: npm install
run: npm ci run: npm ci
- name: npm build - name: npm build
run: npm run build run: npm run build
- name: npm run test - name: npm run test
run: npm run test run: npm run test
env:
CI: true integration:
- name: npm run test:integration runs-on: ubuntu-latest
run: npm run test:integration
env: services:
VAULT_HOST: localhost vaultBasic:
VAULT_PORT: ${{ job.services.vault.ports[8200] }} image: vault:1.2.3
CI: true ports:
- 8200/tcp
env:
VAULT_DEV_ROOT_TOKEN_ID: testtoken
options: --cap-add=IPC_LOCK
vaultEnterprise:
image: hashicorp/vault-enterprise:1.3.0_ent
ports:
- 8200/tcp
env:
VAULT_DEV_ROOT_TOKEN_ID: testtoken
options: --cap-add=IPC_LOCK
steps:
- uses: actions/checkout@v1
- uses: actions/setup-node@v1
with:
node-version: ''
- name: setup npm cache
uses: actions/cache@v1
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: npm install
run: npm ci
- name: npm build
run: npm run build
- name: npm run test:integration:basic
run: npm run test:integration:basic
env:
VAULT_HOST: localhost
VAULT_PORT: ${{ job.services.vaultBasic.ports[8200] }}
CI: true
- name: npm run test:integration:enterprise
run: npm run test:integration:enterprise
env:
VAULT_HOST: localhost
VAULT_PORT: ${{ job.services.vaultEnterprise.ports[8200] }}
CI: true
e2e: e2e:
runs-on: ubuntu-latest runs-on: ubuntu-latest
services: services:
vault: vault:
image: vault:1.2.3 image: vault:1.3.0
ports: ports:
- 8200/tcp - 8200/tcp
env: env:
@@ -48,21 +88,28 @@ jobs:
steps: steps:
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: Use Node.js 10.x - uses: actions/setup-node@v1
uses: actions/setup-node@v1
with: with:
node-version: 10.x node-version: ''
- name: setup npm cache
uses: actions/cache@v1
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: npm install - name: npm install
run: npm ci run: npm ci
- name: npm build - name: npm build
run: npm run build run: npm run build
- name: setup vault - name: setup vault
run: node ./e2e/setup.js run: node ./integrationTests/e2e/setup.js
env: env:
VAULT_HOST: localhost VAULT_HOST: localhost
VAULT_PORT: ${{ job.services.vault.ports[8200] }} VAULT_PORT: ${{ job.services.vault.ports[8200] }}
- name: use vault action - name: use vault action (default K/V version 2)
uses: ./ uses: ./
id: kv-secrets
with: with:
url: http://localhost:${{ job.services.vault.ports[8200] }} url: http://localhost:${{ job.services.vault.ports[8200] }}
token: testtoken token: testtoken
@@ -70,18 +117,46 @@ jobs:
test secret ; test secret ;
test secret | NAMED_SECRET ; test secret | NAMED_SECRET ;
nested/test otherSecret ; nested/test otherSecret ;
- name: use vault action (custom K/V version 1)
uses: ./
with:
url: http://localhost:${{ job.services.vault.ports[8200] }}
token: testtoken
path: my-secret
kv-version: 1
secrets: |
test altSecret ;
test altSecret | NAMED_ALTSECRET ;
nested/test otherAltSecret ;
- name: use vault action (using cubbyhole engine)
uses: ./
with:
url: http://localhost:${{ job.services.vault.ports[8200] }}
token: testtoken
secrets: |
/cubbyhole/test foo ;
/cubbyhole/test zip | NAMED_CUBBYSECRET ;
- name: verify - name: verify
run: npm run test:e2e run: npm run test:e2e
env:
OTHER_SECRET_OUTPUT: ${{ steps.kv-secrets.outputs.otherSecret }}
publish: publish:
if: github.event_name == 'push' && contains(github.ref, 'master')
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: [test, e2e] needs: [build, integration, e2e]
steps: steps:
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: Use Node.js 10.x - uses: actions/setup-node@v1
uses: actions/setup-node@v1
with: with:
node-version: 10.x node-version: ''
- name: setup npm cache
uses: actions/cache@v1
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: npm install - name: npm install
run: npm ci run: npm ci
- name: release - name: release
@@ -89,4 +164,5 @@ jobs:
run: npx semantic-release run: npx semantic-release
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+35
View File
@@ -0,0 +1,35 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"name": "vscode-jest-tests",
"request": "launch",
"args": [
"--runInBand"
],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"program": "${workspaceFolder}/node_modules/jest/bin/jest"
},
{
"type": "node",
"name": "vscode-integration-tests",
"request": "launch",
"args": [
"--runInBand",
"--config=${workspaceFolder}/integrationTests/basic/jest.config.js"
],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"program": "${workspaceFolder}/node_modules/jest/bin/jest"
}
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"markdown-toc.depthFrom": 2
}
+248 -8
View File
@@ -1,6 +1,29 @@
# vault-action # vault-action
A helper action for easily pulling secrets from the v2 K/V backend of vault. A helper action for easily pulling secrets from HashiCorp Vault.
By default, this action pulls from [Version 2](https://www.vaultproject.io/docs/secrets/kv/kv-v2/) of the K/V Engine. See examples below for how to [use v1](#using-kv-version-1) as well as [other non-K/V engines](#other-secret-engines).
<!-- TOC -->
- [Example Usage](#example-usage)
- [Authentication method](#authentication-method)
- [Key Syntax](#key-syntax)
- [Simple Key](#simple-key)
- [Set Output Variable Name](#set-output-variable-name)
- [Multiple Secrets](#multiple-secrets)
- [Nested Secrets](#nested-secrets)
- [Using K/V version 1](#using-kv-version-1)
- [Custom K/V Engine Path](#custom-kv-engine-path)
- [Other Secret Engines](#other-secret-engines)
- [Adding Extra Headers](#adding-extra-headers)
- [Vault Enterprise Features](#vault-enterprise-features)
- [Namespace](#namespace)
- [Reference](#reference)
- [Masking - Hiding Secrets from Logs](#masking---hiding-secrets-from-logs)
- [Normalization](#normalization)
<!-- /TOC -->
## Example Usage ## Example Usage
@@ -22,6 +45,37 @@ jobs:
# ... # ...
``` ```
## Authentication method
While most workflows will likely use a vault token, you can also use an `approle` to authenticate with Vault. You can configure which by using the `method` parameter:
- **token**: (by default) you must provide a `token` parameter
```yaml
...
with:
url: https://vault.mycompany.com:8200
token: ${{ secrets.VaultToken }}
```
- **approle**: you must provide a `roleId` & `secretId` parameter
```yaml
...
with:
url: https://vault.mycompany.com:8200
method: approle
roleId: ${{ secrets.roleId }}
secretId: ${{ secrets.secretId }}
```
- **github**: you must provide the github token as `githubToken`
```yaml
...
with:
url: https://vault.mycompany.com:8200
method: github
githubToken: ${{ secrets.GITHUB_TOKEN }}
```
If any other method is specified and you provide an `authPayload`, the action will attempt to `POST` to `auth/${method}/login` with the provided payload and parse out the client token.
## Key Syntax ## Key Syntax
The `secrets` parameter is a set of multiple secret requests separated by the `;` character. The `secrets` parameter is a set of multiple secret requests separated by the `;` character.
@@ -29,7 +83,7 @@ The `secrets` parameter is a set of multiple secret requests separated by the `;
Each secret request is comprised of the `path` and the `key` of the desired secret, and optionally the desired Env Var output name. Each secret request is comprised of the `path` and the `key` of the desired secret, and optionally the desired Env Var output name.
```raw ```raw
{{ Secret Path }} {{ Secret Key }} | {{ Output Environment Variable Name }} {{ Secret Path }} {{ Secret Key or Selector }} | {{ Env/Output Variable Name }}
``` ```
### Simple Key ### Simple Key
@@ -41,15 +95,30 @@ with:
secrets: ci npmToken secrets: ci npmToken
``` ```
`vault-action` will automatically normalize the given data key, and output: `vault-action` will automatically normalize the given secret selector key, and set the follow as environment variables for the following steps in the current job:
```bash ```bash
NPMTOKEN=somelongtoken NPMTOKEN=somelongtoken
``` ```
### Set Environment Variable Name You can also access the secret via outputs:
However, if you want to set it to a specific environmental variable, say `NPM_TOKEN`, you could do this instead: ```yaml
steps:
# ...
- name: Import Secrets
id: secrets
# Import config...
- name: Sensitive Operation
run: "my-cli --token '${{ steps.secrets.outputs.npmToken }}'"
```
_**Note:** If you'd like to only use outputs and disable automatic environment variables, you can set the `exportEnv` option to `false`._
### Set Output Variable Name
However, if you want to set it to a specific name, say `NPM_TOKEN`, you could do this instead:
```yaml ```yaml
with: with:
@@ -62,17 +131,188 @@ With that, `vault-action` will now use your requested name and output:
NPM_TOKEN=somelongtoken NPM_TOKEN=somelongtoken
``` ```
```yaml
steps:
# ...
- name: Import Secrets
id: secrets
# Import config...
- name: Sensitive Operation
run: "my-cli --token '${{ steps.secrets.outputs.NPM_TOKEN }}'"
```
### Multiple Secrets ### Multiple Secrets
This action can take multi-line input, so say you had your AWS keys stored in a path and wanted to retrieve both of them. You can do: This action can take multi-line input, so say you had your AWS keys stored in a path and wanted to retrieve both of them. You can do:
```yaml ```yaml
with: with:
keys: | secrets: |
ci/aws accessKey | AWS_ACCESS_KEY_ID ; ci/aws accessKey | AWS_ACCESS_KEY_ID ;
ci/aws secretKey | AWS_SECRET_ACCESS_KEY ci/aws secretKey | AWS_SECRET_ACCESS_KEY
``` ```
## Masking ### Nested Secrets
This action uses Github Action's built in masking, so all variables will automatically be masked if printed to the console or to logs. By default, `vault-action` will read the key from `data.data` in the response for the K/V v2 engine (default), or `data` for K/V v1 and other Secret Engines (see below for more info).
If you need to retrieve a sub-key from a JSON document, or are interested in some other component of the Vault response, you can specify a different key as the path to the desired out.
_**Important**_: You must specify an [Output Variable Name](#set-output-variable-name) when using this method.
```yaml
with:
secrets: |
my/path pair.key | NESTED_SECRET ;
```
Under the covers, we're using [JSONata](https://jsonata.org/) to provide the querying functionality. Any valid JSONata syntax is valid here, and will be outputed as a `JSON.stringify`-ied result.
### Using K/V version 1
By default, `vault-action` expects a K/V engine using [version 2](https://www.vaultproject.io/docs/secrets/kv/kv-v2.html).
In order to work with a [v1 engine](https://www.vaultproject.io/docs/secrets/kv/kv-v1/), the `kv-version` parameter may be passed:
```yaml
with:
kv-version: 1
```
## Custom K/V Engine Path
When you enable the K/V Engine, by default it's placed at the path `secret`, so a secret named `ci` will be accessed from `secret/ci`. However, [if you enabled the secrets engine using a custom `path`](https://www.vaultproject.io/docs/commands/secrets/enable/#inlinecode--path-4), you
can pass it as follows:
```yaml
with:
path: my-secrets
secrets: ci npmToken
```
This way, the `ci` secret in the example above will be retrieved from `my-secrets/ci`.
## Other Secret Engines
While this action primarily supports the K/V engine, it is possible to request secrets from other engines in Vault.
To do so when specifying the `Secret Path`, just append a leading forward slash (`/`) and specify the path as described in the Vault API documentation.
For example, to retrieve a stored secret from the [`cubbyhole` engine](https://www.vaultproject.io/api-docs/secret/cubbyhole/), assuming you have a stored secret at the path `foo` with the contents:
```json
{
"foo": "bar",
"zip": "zap"
}
```
You could request the contents like so:
```yaml
with:
secrets: |
/cubbyhole/foo foo ;
/cubbyhole/foo zip | MY_KEY ;
```
Resulting in:
```bash
FOO=bar
MY_KEY=zap
```
```yaml
steps:
# ...
- name: Import Secrets
id: secrets
# Import config...
- name: Sensitive Operation
run: "my-cli --token '${{ steps.secrets.outputs.foo }}'"
- name: Another Sensitive Operation
run: "my-cli --token '${{ steps.secrets.outputs.MY_KEY }}'"
```
Secrets pulled from the same `Secret Path` are cached by default. So if you, for example, are using the `aws` engine and retrieve a key, only a single key for a given path is returned.
e.g.:
```yaml
with:
secrets: |
/aws/creds/ci access_key | AWS_ACCESS_KEY_ID ;
/aws/creds/ci secret_key | AWS_SECRET_ACCESS_KEY
```
would work fine.
*NOTE: Per [Nested Secrets](#nested-secrets), the `Key` is pulled from the `data` property of the response.*
## Adding Extra Headers
If you ever need to add extra headers to the vault request, say if you need to authenticate with a firewall, all you need to do is set `extraHeaders`:
```yaml
with:
secrets: |
ci/aws accessKey | AWS_ACCESS_KEY_ID ;
ci/aws secretKey | AWS_SECRET_ACCESS_KEY
extraHeaders: |
X-Secure-Id: ${{ secrets.SECURE_ID }}
X-Secure-Secret: ${{ secrets.SECURE_SECRET }}
```
This will automatically add the `x-secure-id` and `x-secure-secret` headers to every request to Vault.
## Vault Enterprise Features
### Namespace
If you need to retrieve secrets from a specific Vault namespace, all that's required is an additional parameter specifying the namespace.
```yaml
steps:
# ...
- name: Import Secrets
uses: RichiCoder1/vault-action
with:
url: https://vault-enterprise.mycompany.com:8200
method: token
token: ${{ secrets.VaultToken }}
namespace: ns1
secrets: |
ci/aws accessKey | AWS_ACCESS_KEY_ID ;
ci/aws secretKey | AWS_SECRET_ACCESS_KEY ;
ci npm_token
```
## Reference
Here are all the inputs available through `with`:
| Input | Description | Default | Required |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | -------- |
| `url` | The URL for the vault endpoint | | ✔ |
| `secrets` | A semicolon-separated list of secrets to retrieve. These will automatically be converted to environmental variable keys. See README for more details | | ✔ |
| `namespace` | The Vault namespace from which to query secrets. Vault Enterprise only, unset by default | | |
| `path` | The path of a non-default K/V engine | | |
| `kv-version` | The version of the K/V engine to use. | `2` | |
| `method` | The method to use to authenticate with Vault. | `token` | |
| `token` | The Vault Token to be used to authenticate with Vault | | |
| `roleId` | The Role Id for App Role authentication | | |
| `secretId` | The Secret Id for App Role authentication | | |
| `githubToken` | The Github Token to be used to authenticate with Vault | | |
| `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` | |
## Masking - Hiding Secrets from Logs
This action uses GitHub Action's built-in masking, so all variables will automatically be masked (aka hidden) if printed to the console or to logs.
**This only obscures secrets from output logs.** If someone has the ability to edit your workflows, then they are able to read and therefore write secrets to somewhere else just like normal GitHub Secrets.
## Normalization
To make it simpler to consume certain secrets as env vars, if no Env/Output Var Name is specified `vault-action` will replace and `.` chars with `__`, remove any other non-letter or number characters. If you're concerned about the result, it's recommended to provider an explicit Output Var Key.
-94
View File
@@ -1,94 +0,0 @@
const core = require('@actions/core');
const command = require('@actions/core/lib/command');
const got = require('got');
async function exportSecrets() {
const vaultUrl = core.getInput('url', { required: true });
const vaultToken = core.getInput('token', { required: true });
const secretsInput = core.getInput('secrets', { required: true });
const secrets = parseSecretsInput(secretsInput);
for (const secret of secrets) {
const { secretPath, outputName, secretKey } = secret;
const result = await got(`${vaultUrl}/v1/secret/data/${secretPath}`, {
headers: {
'X-Vault-Token': vaultToken
}
});
const parsedResponse = JSON.parse(result.body);
const vaultKeyData = parsedResponse.data;
const versionData = vaultKeyData.data;
const value = versionData[secretKey];
command.issue('add-mask', value);
core.exportVariable(outputName, `${value}`);
core.debug(`${secretPath} => ${outputName}`);
}
};
/**
* Parses a secrets input string into key paths and their resulting environment variable name.
* @param {string} secretsInput
*/
function parseSecretsInput(secretsInput) {
const secrets = secretsInput
.split(';')
.filter(key => !!key)
.map(key => key.trim())
.filter(key => key.length !== 0);
/** @type {{ secretPath: string; outputName: string; dataKey: string; }[]} */
const output = [];
for (const secret of secrets) {
let path = secret;
let outputName = null;
const renameSigilIndex = secret.lastIndexOf('|');
if (renameSigilIndex > -1) {
path = secret.substring(0, renameSigilIndex).trim();
outputName = secret.substring(renameSigilIndex + 1).trim();
if (outputName.length < 1) {
throw Error(`You must provide a value when mapping a secret to a name. Input: "${secret}"`);
}
}
const pathParts = path
.split(/\s+/)
.map(part => part.trim())
.filter(part => part.length !== 0);
if (pathParts.length !== 2) {
throw Error(`You must provide a valid path and key. Input: "${secret}"`)
}
const [secretPath, secretKey] = pathParts;
// If we're not using a mapped name, normalize the key path into a variable name.
if (!outputName) {
outputName = normalizeOutputKey(secretKey);
}
output.push({
secretPath,
outputName,
secretKey
});
}
return output;
}
/**
* Replaces any forward-slash characters to
* @param {string} dataKey
*/
function normalizeOutputKey(dataKey) {
return dataKey.replace('/', '__').replace(/[^\w-]/, '').toUpperCase();
}
module.exports = {
exportSecrets,
parseSecretsInput,
normalizeOutputKey
};
-136
View File
@@ -1,136 +0,0 @@
jest.mock('got');
jest.mock('@actions/core');
jest.mock('@actions/core/lib/command');
const core = require('@actions/core');
const got = require('got');
const {
exportSecrets,
parseSecretsInput,
} = require('./action');
const { when } = require('jest-when');
describe('parseSecretsInput', () => {
it('parses simple secret', () => {
const output = parseSecretsInput('test key');
expect(output).toContainEqual({
secretPath: 'test',
secretKey: 'key',
outputName: 'KEY',
});
});
it('parses mapped secret', () => {
const output = parseSecretsInput('test key|testName');
expect(output).toHaveLength(1);
expect(output[0]).toMatchObject({
outputName: 'testName',
});
});
it('fails on invalid mapped name', () => {
expect(() => parseSecretsInput('test key|'))
.toThrowError(`You must provide a value when mapping a secret to a name. Input: "test key|"`)
});
it('fails on invalid path for mapped', () => {
expect(() => parseSecretsInput('|testName'))
.toThrowError(`You must provide a valid path and key. Input: "|testName"`)
});
it('parses multiple secrets', () => {
const output = parseSecretsInput('first a;second b;');
expect(output).toHaveLength(2);
expect(output[0]).toMatchObject({
secretPath: 'first',
});
expect(output[1]).toMatchObject({
secretPath: 'second',
});
});
it('parses multiple complex secret input', () => {
const output = parseSecretsInput('first a;second b|secondName');
expect(output).toHaveLength(2);
expect(output[0]).toMatchObject({
outputName: 'A',
});
expect(output[1]).toMatchObject({
outputName: 'secondName',
});
});
it('parses multiline input', () => {
const output = parseSecretsInput(`
first a;
second b;
third c | SOME_C;`);
expect(output).toHaveLength(3);
expect(output[0]).toMatchObject({
secretPath: 'first',
});
expect(output[1]).toMatchObject({
outputName: 'B',
});
expect(output[2]).toMatchObject({
outputName: 'SOME_C',
});
})
});
describe('exportSecrets', () => {
beforeEach(() => {
jest.resetAllMocks();
when(core.getInput)
.calledWith('url')
.mockReturnValue('http://vault:8200');
when(core.getInput)
.calledWith('token')
.mockReturnValue('EXAMPLE');
});
function mockInput(key) {
when(core.getInput)
.calledWith('secrets')
.mockReturnValue(key);
}
function mockVaultData(data) {
got.mockResolvedValue({
body: JSON.stringify({
data: {
data
}
})
});
}
it('simple secret retrieval', async () => {
mockInput('test key');
mockVaultData({
key: 1
});
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('KEY', '1');
});
it('mapped secret retrieval', async () => {
mockInput('test key|TEST_NAME');
mockVaultData({
key: 1
});
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('TEST_NAME', '1');
});
});
+38 -5
View File
@@ -1,18 +1,51 @@
name: 'Vault Secrets' name: 'Vault Secrets'
description: 'A Github Action that allows you to consume the v2 K/V backend of HashiCorp Vault as secure environment variables' description: 'A Github Action that allows you to consume the v2 K/V backend of HashiCorp Vault as secure environment variables'
inputs: inputs:
url: url:
description: 'The URL for the vault endpoint' description: 'The URL for the vault endpoint'
required: true required: true
token:
description: 'The Vault Token to be used to authenticate with Vault'
required: true
secrets: secrets:
description: 'A semicolon-separated list of secrets to retrieve. These will automatically be converted to environmental variable keys. See README for more details' description: 'A semicolon-separated list of secrets to retrieve. These will automatically be converted to environmental variable keys. See README for more details'
required: true required: true
namespace:
description: 'The Vault namespace from which to query secrets. Vault Enterprise only, unset by default'
required: false
path:
description: 'The path of a non-default K/V engine'
required: false
kv-version:
description: 'The version of the K/V engine to use.'
default: '2'
required: false
method:
description: 'The method to use to authenticate with Vault.'
default: 'token'
required: false
token:
description: 'The Vault Token to be used to authenticate with Vault'
required: false
roleId:
description: 'The Role Id for App Role authentication'
required: false
secretId:
description: 'The Secret Id for App Role authentication'
required: false
githubToken:
description: 'The Github Token to be used to authenticate with Vault'
required: false
authPayload:
description: 'The JSON payload to be sent to Vault when using a custom authentication method.'
required: false
extraHeaders:
description: 'A string of newline separated extra headers to include on every request.'
required: false
exportEnv:
description: 'Whether or not export secrets as environment variables.'
default: 'true'
required: false
runs: runs:
using: 'node12' using: 'node12'
main: 'dist/index.js' main: 'dist/index.js'
branding: branding:
icon: 'unlock' icon: 'unlock'
color: 'gray-dark' color: 'gray-dark'
+11144 -2128
View File
File diff suppressed because it is too large Load Diff
+17
View File
@@ -0,0 +1,17 @@
# Start vault server locally for the purposes of integration tests.
version: "3.0"
services:
vault:
image: vault:1.3.0
environment:
VAULT_DEV_ROOT_TOKEN_ID: testtoken
ports:
- 8200:8200
privileged: true
vault-enterprise:
image: hashicorp/vault-enterprise:1.3.0_ent
environment:
VAULT_DEV_ROOT_TOKEN_ID: testtoken
ports:
- 8201:8200
privileged: true
-7
View File
@@ -1,7 +0,0 @@
describe('e2e', () => {
it('verify', () => {
expect(process.env.SECRET).toBe("SUPERSECRET");
expect(process.env.NAMED_SECRET).toBe("SUPERSECRET");
expect(process.env.OTHERSECRET).toBe("OTHERSUPERSECRET");
});
});
-41
View File
@@ -1,41 +0,0 @@
const got = require('got');
(async () => {
try {
// Verify Connection
await got(`http://${process.env.VAULT_HOST}:${process.env.VAULT_PORT}/v1/secret/config`, {
headers: {
'X-Vault-Token': 'testtoken',
},
});
await got(`http://${process.env.VAULT_HOST}:${process.env.VAULT_PORT}/v1/secret/data/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
body: {
data: {
secret: "SUPERSECRET",
},
},
json: true,
});
await got(`http://${process.env.VAULT_HOST}:${process.env.VAULT_PORT}/v1/secret/data/nested/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
body: {
data: {
otherSecret: "OTHERSUPERSECRET",
},
},
json: true,
});
} catch (error) {
console.log(error);
process.exit(1);
}
})();
-103
View File
@@ -1,103 +0,0 @@
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 { exportSecrets } = require('../action');
describe('integration', () => {
beforeAll(async () => {
// Verify Connection
await got(`http://${process.env.VAULT_HOST}:${process.env.VAULT_PORT}/v1/secret/config`, {
headers: {
'X-Vault-Token': 'testtoken',
},
});
await got(`http://${process.env.VAULT_HOST}:${process.env.VAULT_PORT}/v1/secret/data/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
body: {
data: {
secret: "SUPERSECRET",
},
},
json: true,
});
await got(`http://${process.env.VAULT_HOST}:${process.env.VAULT_PORT}/v1/secret/data/nested/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
body: {
data: {
otherSecret: "OTHERSUPERSECRET",
},
},
json: true,
});
})
beforeEach(() => {
jest.resetAllMocks();
when(core.getInput)
.calledWith('url')
.mockReturnValue(`http://${process.env.VAULT_HOST}:${process.env.VAULT_PORT}`);
when(core.getInput)
.calledWith('token')
.mockReturnValue('testtoken');
});
function mockInput(secrets) {
when(core.getInput)
.calledWith('secrets')
.mockReturnValue(secrets);
}
it('get simple secret', async () => {
mockInput('test secret')
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('SECRET', 'SUPERSECRET');
});
it('re-map secret', async () => {
mockInput('test secret | TEST_KEY')
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('TEST_KEY', 'SUPERSECRET');
});
it('get nested secret', async () => {
mockInput('nested/test otherSecret')
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('OTHERSECRET', 'OTHERSUPERSECRET');
});
it('get multiple secrets', async () => {
mockInput(`
test secret ;
test secret | NAMED_SECRET ;
nested/test otherSecret ;`);
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');
});
});
+210
View File
@@ -0,0 +1,210 @@
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 { exportSecrets } = require('../../src/action');
const vaultUrl = `http://${process.env.VAULT_HOST || 'localhost'}:${process.env.VAULT_PORT || '8200'}`;
describe('integration', () => {
beforeAll(async () => {
// Verify Connection
await got(`${vaultUrl}/v1/secret/config`, {
headers: {
'X-Vault-Token': 'testtoken',
},
});
await got(`${vaultUrl}/v1/secret/data/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
data: {
secret: 'SUPERSECRET',
},
},
});
await got(`${vaultUrl}/v1/secret/data/nested/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
data: {
otherSecret: 'OTHERSUPERSECRET',
},
}
});
// Enable custom secret engine
try {
await got(`${vaultUrl}/v1/sys/mounts/my-secret`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
type: 'kv'
}
});
} catch (error) {
const {response} = error;
if (response.statusCode === 400 && response.body.includes("path is already in use")) {
// Engine might already be enabled from previous test runs
} else {
throw error;
}
}
await got(`${vaultUrl}/v1/my-secret/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
secret: 'CUSTOMSECRET',
}
});
await got(`${vaultUrl}/v1/my-secret/nested/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
otherSecret: 'OTHERCUSTOMSECRET',
},
});
});
beforeEach(() => {
jest.resetAllMocks();
when(core.getInput)
.calledWith('url')
.mockReturnValueOnce(`${vaultUrl}`);
when(core.getInput)
.calledWith('token')
.mockReturnValueOnce('testtoken');
});
function mockInput(secrets) {
when(core.getInput)
.calledWith('secrets')
.mockReturnValueOnce(secrets);
}
function mockEngineName(name) {
when(core.getInput)
.calledWith('path')
.mockReturnValueOnce(name);
}
function mockVersion(version) {
when(core.getInput)
.calledWith('kv-version')
.mockReturnValueOnce(version);
}
it('get simple secret', async () => {
mockInput('test secret');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('SECRET', 'SUPERSECRET');
});
it('re-map secret', async () => {
mockInput('test secret | TEST_KEY');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('TEST_KEY', 'SUPERSECRET');
});
it('get nested secret', async () => {
mockInput('nested/test otherSecret');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('OTHERSECRET', 'OTHERSUPERSECRET');
});
it('get multiple secrets', async () => {
mockInput(`
test secret ;
test secret | NAMED_SECRET ;
nested/test otherSecret ;`);
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');
});
it('get secret from K/V v1', async () => {
mockInput('test secret');
mockEngineName('my-secret');
mockVersion('1');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('SECRET', 'CUSTOMSECRET');
});
it('get nested secret from K/V v1', async () => {
mockInput('nested/test otherSecret');
mockEngineName('my-secret');
mockVersion('1');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('OTHERSECRET', 'OTHERCUSTOMSECRET');
});
describe('generic engines', () => {
beforeAll(async () => {
await got(`${vaultUrl}/v1/cubbyhole/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
foo: "bar",
zip: "zap"
},
});
});
it('supports cubbyhole', async () => {
mockInput('/cubbyhole/test foo');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('FOO', 'bar');
});
it('caches responses', async () => {
mockInput(`
/cubbyhole/test foo ;
/cubbyhole/test zip`);
await exportSecrets();
expect(core.debug).toBeCalledWith(' using cached response');
expect(core.exportVariable).toBeCalledWith('FOO', 'bar');
expect(core.exportVariable).toBeCalledWith('ZIP', 'zap');
});
})
});
+4
View File
@@ -0,0 +1,4 @@
# e2e tests
This test suite runs `vault-action` as a GitHub Action in the context of a live build, and then verifies that the appropriate environmental variables are set.
These tests are intended to mostly be very simple smoke tests to verify that the action is being compiled and run correctly in context.
+13
View File
@@ -0,0 +1,13 @@
describe('e2e', () => {
it('verify', () => {
expect(process.env.SECRET).toBe("SUPERSECRET");
expect(process.env.NAMED_SECRET).toBe("SUPERSECRET");
expect(process.env.OTHERSECRET).toBe("OTHERSUPERSECRET");
expect(process.env.OTHER_SECRET_OUTPUT).toBe("OTHERSUPERSECRET");
expect(process.env.ALTSECRET).toBe("CUSTOMSECRET");
expect(process.env.NAMED_ALTSECRET).toBe("CUSTOMSECRET");
expect(process.env.OTHERALTSECRET).toBe("OTHERCUSTOMSECRET");
expect(process.env.FOO).toBe("bar");
expect(process.env.NAMED_CUBBYSECRET).toBe("zap");
});
});
+82
View File
@@ -0,0 +1,82 @@
const got = require('got');
const vaultUrl = `${process.env.VAULT_HOST}:${process.env.VAULT_PORT}`;
(async () => {
try {
// Verify Connection
await got(`http://${vaultUrl}/v1/secret/config`, {
headers: {
'X-Vault-Token': 'testtoken',
},
});
await got(`http://${vaultUrl}/v1/secret/data/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
data: {
secret: 'SUPERSECRET',
},
},
});
await got(`http://${vaultUrl}/v1/secret/data/nested/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
data: {
otherSecret: 'OTHERSUPERSECRET',
},
}
});
await got(`http://${vaultUrl}/v1/sys/mounts/my-secret`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
type: 'kv'
}
});
await got(`http://${vaultUrl}/v1/my-secret/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
altSecret: 'CUSTOMSECRET',
}
});
await got(`http://${vaultUrl}/v1/my-secret/nested/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
otherAltSecret: 'OTHERCUSTOMSECRET',
},
});
await got(`http://${vaultUrl}/v1/cubbyhole/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
},
json: {
foo: 'bar',
zip: 'zap',
},
});
} catch (error) {
console.log(error);
process.exit(1);
}
})();
@@ -0,0 +1,307 @@
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 { exportSecrets } = require('../../src/action');
const vaultUrl = `http://${process.env.VAULT_HOST || 'localhost'}:${process.env.VAULT_PORT || '8201'}`;
describe('integration', () => {
beforeAll(async () => {
try {
// Verify Connection
await got(`${vaultUrl}/v1/secret/config`, {
headers: {
'X-Vault-Token': 'testtoken',
},
});
// Create namespace
await enableNamespace('ns1');
// Enable K/V v2 secret engine at 'secret/'
await enableEngine('secret', 'ns1', 2);
await writeSecret('secret', 'test', 'ns1', 2, {secret: 'SUPERSECRET_IN_NAMESPACE'})
await writeSecret('secret', 'nested/test', 'ns1', 2, {otherSecret: 'OTHERSUPERSECRET_IN_NAMESPACE'})
// Enable K/V v1 secret engine at 'my-secret/'
await enableEngine('my-secret', 'ns1', 1);
await writeSecret('my-secret', 'test', 'ns1', 1, {secret: 'CUSTOMSECRET_IN_NAMESPACE'})
await writeSecret('my-secret', 'nested/test', 'ns1', 1, {otherSecret: 'OTHERCUSTOMSECRET_IN_NAMESPACE'})
} catch (e) {
console.error('Failed to setup test', e);
throw e;
}
});
beforeEach(() => {
jest.resetAllMocks();
when(core.getInput)
.calledWith('url')
.mockReturnValueOnce(`${vaultUrl}`);
when(core.getInput)
.calledWith('token')
.mockReturnValueOnce('testtoken');
when(core.getInput)
.calledWith('namespace')
.mockReturnValueOnce('ns1');
});
it('get simple secret', async () => {
mockInput('test secret');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('SECRET', 'SUPERSECRET_IN_NAMESPACE');
});
it('re-map secret', async () => {
mockInput('test secret | TEST_KEY');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('TEST_KEY', 'SUPERSECRET_IN_NAMESPACE');
});
it('get nested secret', async () => {
mockInput('nested/test otherSecret');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('OTHERSECRET', 'OTHERSUPERSECRET_IN_NAMESPACE');
});
it('get multiple secrets', async () => {
mockInput(`
test secret ;
test secret | NAMED_SECRET ;
nested/test otherSecret ;`);
await exportSecrets();
expect(core.exportVariable).toBeCalledTimes(3);
expect(core.exportVariable).toBeCalledWith('SECRET', 'SUPERSECRET_IN_NAMESPACE');
expect(core.exportVariable).toBeCalledWith('NAMED_SECRET', 'SUPERSECRET_IN_NAMESPACE');
expect(core.exportVariable).toBeCalledWith('OTHERSECRET', 'OTHERSUPERSECRET_IN_NAMESPACE');
});
it('get secret from K/V v1', async () => {
mockInput('test secret');
mockEngineName('my-secret');
mockVersion('1');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('SECRET', 'CUSTOMSECRET_IN_NAMESPACE');
});
it('get nested secret from K/V v1', async () => {
mockInput('nested/test otherSecret');
mockEngineName('my-secret');
mockVersion('1');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('OTHERSECRET', 'OTHERCUSTOMSECRET_IN_NAMESPACE');
});
});
describe('authenticate with approle', () => {
let roleId;
let secretId;
beforeAll(async () => {
try {
// Verify Connection
await got(`${vaultUrl}/v1/secret/config`, {
headers: {
'X-Vault-Token': 'testtoken',
},
});
// Create namespace
await enableNamespace("ns2");
// Enable K/V v2 secret engine at 'secret/'
await enableEngine("secret", "ns2", 2);
// Add secret
await writeSecret('secret', 'test', 'ns2', 2, {secret: 'SUPERSECRET_WITH_APPROLE'})
// Enable approle
try {
await got(`${vaultUrl}/v1/sys/auth/approle`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
'X-Vault-Namespace': 'ns2',
},
json: {
type: 'approle'
},
});
} catch (error) {
const {response} = error;
if (response.statusCode === 400 && response.body.includes("path is already in use")) {
// Approle might already be enabled from previous test runs
} else {
throw error;
}
}
// Create policies
await got(`${vaultUrl}/v1/sys/policies/acl/test`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
'X-Vault-Namespace': 'ns2',
},
json: {
"name":"test",
"policy":"path \"auth/approle/*\" {\n capabilities = [\"read\", \"list\"]\n}\npath \"auth/approle/role/my-role/role-id\"\n{\n capabilities = [\"create\", \"read\", \"update\", \"delete\", \"list\"]\n}\npath \"auth/approle/role/my-role/secret-id\"\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/test\" {\n capabilities = [\"read\", \"list\"]\n}\npath \"secret/metadata/test\" {\n capabilities = [\"read\", \"list\"]\n}\npath \"secret/data/test/*\" {\n capabilities = [\"read\", \"list\"]\n}\npath \"secret/metadata/test/*\" {\n capabilities = [\"read\", \"list\"]\n}\n"
},
});
// Create approle
await got(`${vaultUrl}/v1/auth/approle/role/my-role`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
'X-Vault-Namespace': 'ns2',
},
json: {
policies: 'test'
},
});
// Get role-id
const roldIdResponse = await got(`${vaultUrl}/v1/auth/approle/role/my-role/role-id`, {
headers: {
'X-Vault-Token': 'testtoken',
'X-Vault-Namespace': 'ns2',
},
responseType: 'json',
});
roleId = roldIdResponse.body.data.role_id;
// Get secret-id
const secretIdResponse = await got(`${vaultUrl}/v1/auth/approle/role/my-role/secret-id`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
'X-Vault-Namespace': 'ns2',
},
responseType: 'json',
});
secretId = secretIdResponse.body.data.secret_id;
} catch(err) {
console.warn('Create approle', err.response.body);
throw err;
}
});
beforeEach(() => {
jest.resetAllMocks();
when(core.getInput)
.calledWith('method', expect.anything())
.mockReturnValueOnce('approle');
when(core.getInput)
.calledWith('roleId')
.mockReturnValueOnce(roleId);
when(core.getInput)
.calledWith('secretId')
.mockReturnValueOnce(secretId);
when(core.getInput)
.calledWith('url')
.mockReturnValueOnce(`${vaultUrl}`);
when(core.getInput)
.calledWith('namespace')
.mockReturnValueOnce('ns2');
});
it('authenticate with approle', async() => {
mockInput('test secret');
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('SECRET', 'SUPERSECRET_WITH_APPROLE');
})
});
async function enableNamespace(name) {
try {
await got(`${vaultUrl}/v1/sys/namespaces/${name}`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
}
});
} catch (error) {
const {response} = error;
if (response.statusCode === 400 && response.body.includes("already exists")) {
// Namespace might already be enabled from previous test runs
} else {
throw error;
}
}
}
async function enableEngine(path, namespace, version) {
try {
await got(`${vaultUrl}/v1/sys/mounts/${path}`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
'X-Vault-Namespace': namespace,
},
json: { type: 'kv', config: {}, options: { version }, generate_signing_key: true },
});
} catch (error) {
const {response} = error;
if (response.statusCode === 400 && response.body.includes("path is already in use")) {
// Engine might already be enabled from previous test runs
} else {
throw error;
}
}
}
async function writeSecret(engine, path, namespace, version, data) {
const secretPath = (version == 1) ? (`${engine}/${path}`) : (`${engine}/data/${path}`);
const secretPayload = (version == 1) ? (data) : ({data});
await got(`${vaultUrl}/v1/${secretPath}`, {
method: 'POST',
headers: {
'X-Vault-Token': 'testtoken',
'X-Vault-Namespace': namespace,
},
json: secretPayload
});
}
function mockInput(secrets) {
when(core.getInput)
.calledWith('secrets')
.mockReturnValueOnce(secrets);
}
function mockEngineName(name) {
when(core.getInput)
.calledWith('path')
.mockReturnValueOnce(name);
}
function mockVersion(version) {
when(core.getInput)
.calledWith('kv-version')
.mockReturnValueOnce(version);
}
@@ -0,0 +1,3 @@
module.exports = {
verbose: true
};
+1 -1
View File
@@ -1,3 +1,3 @@
module.exports = { module.exports = {
testPathIgnorePatterns: ['/node_modules/', '<rootDir>/integration/', '<rootDir>/e2e/'], testPathIgnorePatterns: ['/node_modules/', '<rootDir>/integrationTests/'],
}; };
+5968 -2435
View File
File diff suppressed because it is too large Load Diff
+21 -10
View File
@@ -4,17 +4,23 @@
"description": "A Github Action that allows you to consume vault secrets as secure environment variables.", "description": "A Github Action that allows you to consume vault secrets as secure environment variables.",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
"build": "ncc build index.js -o dist", "build": "ncc build src/entry.js -o dist",
"test": "jest", "test": "jest",
"test:integration": "jest -c integration/jest.config.js", "test:integration:basic": "jest -c integrationTests/basic/jest.config.js",
"test:e2e": "jest -c e2e/jest.config.js" "test:integration:enterprise": "jest -c integrationTests/enterprise/jest.config.js",
"test:e2e": "jest -c integrationTests/e2e/jest.config.js"
}, },
"files": [
"src/**/*",
"dist/**/*"
],
"release": { "release": {
"branch": "master", "branch": "master",
"plugins": [ "plugins": [
"@semantic-release/commit-analyzer", "@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator", "@semantic-release/release-notes-generator",
"@semantic-release/github" "@semantic-release/github",
"@semantic-release/npm"
], ],
"ci": false "ci": false
}, },
@@ -37,14 +43,19 @@
}, },
"homepage": "https://github.com/RichiCoder1/vault-action#readme", "homepage": "https://github.com/RichiCoder1/vault-action#readme",
"dependencies": { "dependencies": {
"@actions/core": "^1.1.1", "got": "^10.2.2",
"got": "^9.6.0" "jsonata": "^1.8.2"
},
"peerDependencies": {
"@actions/core": ">=1 <2"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "^24.0.18", "@actions/core": "^1.2.3",
"@zeit/ncc": "^0.20.5", "@types/got": "^9.6.9",
"jest": "^24.9.0", "@types/jest": "^25.1.3",
"@zeit/ncc": "^0.22.0",
"jest": "^25.1.0",
"jest-when": "^2.7.0", "jest-when": "^2.7.0",
"semantic-release": "^15.13.24" "semantic-release": "^17.0.4"
} }
} }
+203
View File
@@ -0,0 +1,203 @@
// @ts-check
const core = require('@actions/core');
const command = require('@actions/core/lib/command');
const got = require('got').default;
const jsonata = require('jsonata');
const { auth: { retrieveToken }, secrets: { getSecrets } } = require('./index');
const AUTH_METHODS = ['approle', 'token', 'github'];
const VALID_KV_VERSION = [-1, 1, 2];
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';
let enginePath = core.getInput('path', { required: false });
/** @type {number | string} */
let kvVersion = core.getInput('kv-version', { required: false });
const secretsInput = core.getInput('secrets', { required: true });
const secretRequests = parseSecretsInput(secretsInput);
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,
headers: {}
}
for (const [headerName, headerValue] of extraHeaders) {
defaultOptions.headers[headerName] = headerValue;
}
if (vaultNamespace != null) {
defaultOptions.headers["X-Vault-Namespace"] = vaultNamespace;
}
const vaultToken = await retrieveToken(vaultMethod, got.extend(defaultOptions));
defaultOptions.headers['X-Vault-Token'] = vaultToken;
const client = got.extend(defaultOptions);
if (!enginePath) {
enginePath = 'secret';
}
if (!kvVersion) {
kvVersion = 2;
}
kvVersion = +kvVersion;
if (Number.isNaN(kvVersion) || !VALID_KV_VERSION.includes(kvVersion)) {
throw Error(`You must provide a valid K/V version (${VALID_KV_VERSION.slice(1).join(', ')}). Input: "${kvVersion}"`);
}
const requests = secretRequests.map(request => {
const { path, selector } = request;
if (path.startsWith('/')) {
return request;
}
const kvPath = (kvVersion === 2)
? `/${enginePath}/data/${path}`
: `/${enginePath}/${path}`;
const kvSelector = (kvVersion === 2)
? `data.data.${selector}`
: `data.${selector}`;
return { ...request, path: kvPath, selector: kvSelector };
});
const results = await getSecrets(requests, client);
for (const result of results) {
const { value, request, cachedResponse } = result;
if (cachedResponse) {
core.debug(' using cached response');
}
command.issue('add-mask', value);
if (exportEnv) {
core.exportVariable(request.envVarName, `${value}`);
}
core.setOutput(request.outputVarName, `${value}`);
core.debug(`${request.path} => outputs.${request.outputVarName}${exportEnv ? ` | env.${request.envVarName}` : ''}`);
}
};
/** @typedef {Object} SecretRequest
* @property {string} path
* @property {string} envVarName
* @property {string} outputVarName
* @property {string} selector
*/
/**
* Parses a secrets input string into key paths and their resulting environment variable name.
* @param {string} secretsInput
*/
function parseSecretsInput(secretsInput) {
const secrets = secretsInput
.split(';')
.filter(key => !!key)
.map(key => key.trim())
.filter(key => key.length !== 0);
/** @type {SecretRequest[]} */
const output = [];
for (const secret of secrets) {
let pathSpec = secret;
let outputVarName = null;
const renameSigilIndex = secret.lastIndexOf('|');
if (renameSigilIndex > -1) {
pathSpec = secret.substring(0, renameSigilIndex).trim();
outputVarName = secret.substring(renameSigilIndex + 1).trim();
if (outputVarName.length < 1) {
throw Error(`You must provide a value when mapping a secret to a name. Input: "${secret}"`);
}
}
const pathParts = pathSpec
.split(/\s+/)
.map(part => part.trim())
.filter(part => part.length !== 0);
if (pathParts.length !== 2) {
throw Error(`You must provide a valid path and key. Input: "${secret}"`);
}
const [path, selector] = pathParts;
/** @type {any} */
const selectorAst = jsonata(selector).ast();
if ((selectorAst.type !== "path" || selectorAst.steps[0].stages) && !outputVarName) {
throw Error(`You must provide a name for the output key when using json selectors. Input: "${secret}"`);
}
let envVarName = outputVarName;
if (!outputVarName) {
outputVarName = normalizeOutputKey(selector);
envVarName = normalizeOutputKey(selector, true);
}
output.push({
path,
envVarName,
outputVarName,
selector
});
}
return output;
}
/**
* Replaces any dot chars to __ and removes non-ascii charts
* @param {string} dataKey
* @param {boolean=} isEnvVar
*/
function normalizeOutputKey(dataKey, isEnvVar = false) {
let outputKey = dataKey
.replace('.', '__').replace(/[^\p{L}\p{N}_-]/gu, '');
if (isEnvVar) {
outputKey = outputKey.toUpperCase();
}
return outputKey;
}
/**
* @param {string} inputKey
* @param {any} inputOptions
*/
function parseHeadersInput(inputKey, inputOptions) {
/** @type {string}*/
const rawHeadersString = core.getInput(inputKey, inputOptions) || '';
const headerStrings = rawHeadersString
.split('\n')
.map(line => line.trim())
.filter(line => line !== '');
return headerStrings
.reduce((map, line) => {
const seperator = line.indexOf(':');
const key = line.substring(0, seperator).trim().toLowerCase();
const value = line.substring(seperator + 1).trim();
if (map.has(key)) {
map.set(key, [map.get(key), value].join(', '));
} else {
map.set(key, value);
}
return map;
}, new Map());
}
module.exports = {
exportSecrets,
parseSecretsInput,
normalizeOutputKey,
parseHeadersInput
};
+260
View File
@@ -0,0 +1,260 @@
jest.mock('got');
jest.mock('@actions/core');
jest.mock('@actions/core/lib/command');
const core = require('@actions/core');
const got = require('got');
const {
exportSecrets,
parseSecretsInput,
parseResponse,
parseHeadersInput
} = require('./action');
const { when } = require('jest-when');
describe('parseSecretsInput', () => {
it('parses simple secret', () => {
const output = parseSecretsInput('test key');
expect(output).toContainEqual({
path: 'test',
selector: 'key',
outputVarName: 'key',
envVarName: 'KEY'
});
});
it('parses mapped secret', () => {
const output = parseSecretsInput('test key|testName');
expect(output).toHaveLength(1);
expect(output[0]).toMatchObject({
outputVarName: 'testName',
envVarName: 'testName',
});
});
it('fails on invalid mapped name', () => {
expect(() => parseSecretsInput('test key|'))
.toThrowError(`You must provide a value when mapping a secret to a name. Input: "test key|"`)
});
it('fails on invalid path for mapped', () => {
expect(() => parseSecretsInput('|testName'))
.toThrowError(`You must provide a valid path and key. Input: "|testName"`)
});
it('parses multiple secrets', () => {
const output = parseSecretsInput('first a;second b;');
expect(output).toHaveLength(2);
expect(output[0]).toMatchObject({
path: 'first',
});
expect(output[1]).toMatchObject({
path: 'second',
});
});
it('parses multiple complex secret input', () => {
const output = parseSecretsInput('first a;second b|secondName');
expect(output).toHaveLength(2);
expect(output[0]).toMatchObject({
outputVarName: 'a',
envVarName: 'A',
});
expect(output[1]).toMatchObject({
outputVarName: 'secondName',
envVarName: 'secondName'
});
});
it('parses multiline input', () => {
const output = parseSecretsInput(`
first a;
second b;
third c | SOME_C;`);
expect(output).toHaveLength(3);
expect(output[0]).toMatchObject({
path: 'first',
});
expect(output[1]).toMatchObject({
outputVarName: 'b',
envVarName: 'B'
});
expect(output[2]).toMatchObject({
outputVarName: 'SOME_C',
envVarName: 'SOME_C',
});
});
});
describe('parseHeaders', () => {
it('parses simple header', () => {
when(core.getInput)
.calledWith('extraHeaders')
.mockReturnValueOnce('TEST: 1');
const result = parseHeadersInput('extraHeaders');
expect(Array.from(result)).toContainEqual(['test', '1']);
});
it('parses simple header with whitespace', () => {
when(core.getInput)
.calledWith('extraHeaders')
.mockReturnValueOnce(`
TEST: 1
`);
const result = parseHeadersInput('extraHeaders');
expect(Array.from(result)).toContainEqual(['test', '1']);
});
it('parses multiple headers', () => {
when(core.getInput)
.calledWith('extraHeaders')
.mockReturnValueOnce(`
TEST: 1
FOO: bAr
`);
const result = parseHeadersInput('extraHeaders');
expect(Array.from(result)).toContainEqual(['test', '1']);
expect(Array.from(result)).toContainEqual(['foo', 'bAr']);
});
it('parses null response', () => {
when(core.getInput)
.calledWith('extraHeaders')
.mockReturnValueOnce(null);
const result = parseHeadersInput('extraHeaders');
expect(Array.from(result)).toHaveLength(0);
});
});
describe('exportSecrets', () => {
beforeEach(() => {
jest.resetAllMocks();
when(core.getInput)
.calledWith('url')
.mockReturnValueOnce('http://vault:8200');
when(core.getInput)
.calledWith('token')
.mockReturnValueOnce('EXAMPLE');
});
function mockInput(key) {
when(core.getInput)
.calledWith('secrets')
.mockReturnValueOnce(key);
}
function mockVersion(version) {
when(core.getInput)
.calledWith('kv-version')
.mockReturnValueOnce(version);
}
function mockExtraHeaders(headerString) {
when(core.getInput)
.calledWith('extraHeaders')
.mockReturnValueOnce(headerString);
}
function mockVaultData(data, version='2') {
switch(version) {
case '1':
got.extend.mockReturnValue({
get: async () => ({ body: JSON.stringify({ data }) })
});
break;
case '2':
got.extend.mockReturnValue({
get: async () => ({ body: JSON.stringify({ data: {
data
} }) })
});
break;
}
}
it('simple secret retrieval', async () => {
mockInput('test key');
mockVaultData({
key: 1
});
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('KEY', '1');
expect(core.setOutput).toBeCalledWith('key', '1');
});
it('intl secret retrieval', async () => {
mockInput('测试 测试');
mockVaultData({
测试: 1
});
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('测试', '1');
expect(core.setOutput).toBeCalledWith('测试', '1');
});
it('mapped secret retrieval', async () => {
mockInput('test key|TEST_NAME');
mockVaultData({
key: 1
});
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('TEST_NAME', '1');
expect(core.setOutput).toBeCalledWith('TEST_NAME', '1');
});
it('simple secret retrieval from K/V v1', async () => {
const version = '1';
mockInput('test key');
mockExtraHeaders(`
TEST: 1
`);
mockVaultData({
key: 1
});
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('KEY', '1');
expect(core.setOutput).toBeCalledWith('key', '1');
});
it('simple secret retrieval with extra headers', async () => {
const version = '1';
mockInput('test key');
mockVersion(version);
mockVaultData({
key: 1
}, version);
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('KEY', '1');
expect(core.setOutput).toBeCalledWith('key', '1');
});
it('nested secret retrieval', async () => {
mockInput('test key.value');
mockVaultData({
key: { value: 1 }
});
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('KEY__VALUE', '1');
expect(core.setOutput).toBeCalledWith('key__value', '1');
});
});
+81
View File
@@ -0,0 +1,81 @@
// @ts-check
const core = require('@actions/core');
/***
* Authenticate with Vault and retrieve a Vault token that can be used for requests.
* @param {string} method
* @param {import('got').Got} client
*/
async function retrieveToken(method, client) {
switch (method) {
case 'approle': {
const vaultRoleId = core.getInput('roleId', { required: true });
const vaultSecretId = core.getInput('secretId', { required: true });
return await getClientToken(client, method, { role_id: vaultRoleId, secret_id: vaultSecretId });
}
case 'github': {
const githubToken = core.getInput('githubToken', { required: true });
return await getClientToken(client, method, { token: githubToken });
}
default: {
if (!method || method === 'token') {
return core.getInput('token', { required: true });
} else {
/** @type {string} */
const payload = core.getInput('authPayload', { required: true });
if (!payload) {
throw Error('When using a custom authentication method, you must provide the payload');
}
return await getClientToken(client, method, JSON.parse(payload.trim()));
}
}
}
}
/***
* Call the appropriate login endpoint and parse out the token in the response.
* @param {import('got').Got} client
* @param {string} method
* @param {any} payload
*/
async function getClientToken(client, method, payload) {
/** @type {'json'} */
const responseType = 'json';
var options = {
json: payload,
responseType,
};
core.debug(`Retrieving Vault Token from v1/auth/${method}/login endpoint`);
/** @type {import('got').Response<VaultLoginResponse>} */
const response = await client.post(`v1/auth/${method}/login`, options);
if (response && response.body && response.body.auth && response.body.auth.client_token) {
core.debug('✔ Vault Token successfully retrieved');
core.startGroup('Token Info');
core.debug(`Operating under policies: ${JSON.stringify(response.body.auth.policies)}`);
core.debug(`Token Metadata: ${JSON.stringify(response.body.auth.metadata)}`);
core.endGroup();
return response.body.auth.client_token;
} else {
throw Error(`Unable to retrieve token from ${method}'s login endpoint.`);
}
}
/***
* @typedef {Object} VaultLoginResponse
* @property {{
* client_token: string;
* accessor: string;
* policies: string[];
* metadata: unknown;
* lease_duration: number;
* renewable: boolean;
* }} auth
*/
module.exports = {
retrieveToken,
};
View File
+7
View File
@@ -0,0 +1,7 @@
const auth = require('./auth');
const secrets = require('./secrets');
module.exports = {
auth,
secrets
};
+76
View File
@@ -0,0 +1,76 @@
const jsonata = require("jsonata");
/**
* @typedef {Object} SecretRequest
* @property {string} path
* @property {string} selector
*/
/**
* @template {SecretRequest} TRequest
* @typedef {Object} SecretResponse
* @property {TRequest} request
* @property {string} value
* @property {boolean} cachedResponse
*/
/**
* @template TRequest
* @param {Array<TRequest>} secretRequests
* @param {import('got').Got} client
* @return {Promise<SecretResponse<TRequest>[]>}
*/
async function getSecrets(secretRequests, client) {
const responseCache = new Map();
const results = [];
for (const secretRequest of secretRequests) {
const { path, selector } = secretRequest;
const requestPath = `v1${path}`;
let body;
let cachedResponse = false;
if (responseCache.has(requestPath)) {
body = responseCache.get(requestPath);
cachedResponse = true;
} else {
const result = await client.get(requestPath);
body = result.body;
responseCache.set(requestPath, body);
}
const value = selectData(JSON.parse(body), selector);
results.push({
request: secretRequest,
value,
cachedResponse
});
}
return results;
}
/**
* Uses a Jsonata selector retrieve a bit of data from the result
* @param {object} data
* @param {string} selector
*/
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) {
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.`);
}
if (result.startsWith(`"`)) {
result = result.substring(1, result.length - 1);
}
return result;
}
module.exports = {
getSecrets,
selectData
}
+12
View File
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2019",
"moduleResolution": "node",
"allowJs": true,
"noEmit": true
},
"exclude": [
"node_modules"
]
}