Compare commits

...

21 Commits

Author SHA1 Message Date
Tom Proctor abba4a3980 Update to v2.4.1 (#317) 2022-04-28 16:20:56 +01:00
Tom Proctor e025870ee9 changelog++ 2022-04-28 11:29:22 +01:00
Tom Proctor 4f536680b6 Update default branch 2022-04-28 11:24:54 +01:00
dependabot[bot] fd9b31c94c chore(deps): bump jsonata from 1.8.4 to 1.8.6 (#312)
Bumps [jsonata](https://github.com/jsonata-js/jsonata) from 1.8.4 to 1.8.6.
- [Release notes](https://github.com/jsonata-js/jsonata/releases)
- [Changelog](https://github.com/jsonata-js/jsonata/blob/master/CHANGELOG.md)
- [Commits](https://github.com/jsonata-js/jsonata/compare/v1.8.4...v1.8.6)

---
updated-dependencies:
- dependency-name: jsonata
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

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

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-28 11:17:38 +01:00
Tom Proctor 8e9712e63b Fix tests from jest-when version bump (#311)
* Fix tests from jest-when version bump
* Delete unused test helpers
* Add workflow_dispatch for tests
2022-04-28 11:12:56 +01:00
dependabot[bot] 25737aea2b chore(deps-dev): bump jest-when from 2.7.2 to 3.5.1 (#294)
Bumps [jest-when](https://github.com/timkindberg/jest-when) from 2.7.2 to 3.5.1.
- [Release notes](https://github.com/timkindberg/jest-when/releases)
- [Commits](https://github.com/timkindberg/jest-when/compare/v2.7.2...v3.5.1)

---
updated-dependencies:
- dependency-name: jest-when
  dependency-type: direct:development
  update-type: version-update:semver-major
...

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

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-26 13:16:46 +01:00
dependabot[bot] c2b108a1cb chore(deps): bump node-fetch from 2.6.1 to 2.6.7 (#308)
Bumps [node-fetch](https://github.com/node-fetch/node-fetch) from 2.6.1 to 2.6.7.
- [Release notes](https://github.com/node-fetch/node-fetch/releases)
- [Commits](https://github.com/node-fetch/node-fetch/compare/v2.6.1...v2.6.7)

---
updated-dependencies:
- dependency-name: node-fetch
  dependency-type: indirect
...

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

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-26 13:14:45 +01:00
dependabot[bot] 7c940db65a chore(deps-dev): bump @types/jest from 26.0.23 to 27.4.1 (#297)
Bumps [@types/jest](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jest) from 26.0.23 to 27.4.1.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jest)

---
updated-dependencies:
- dependency-name: "@types/jest"
  dependency-type: direct:development
  update-type: version-update:semver-major
...

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

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-26 13:13:45 +01:00
dependabot[bot] d9ec4185f7 chore(deps): bump trim-off-newlines from 1.0.1 to 1.0.3 (#309)
Bumps [trim-off-newlines](https://github.com/stevemao/trim-off-newlines) from 1.0.1 to 1.0.3.
- [Release notes](https://github.com/stevemao/trim-off-newlines/releases)
- [Commits](https://github.com/stevemao/trim-off-newlines/compare/v1.0.1...v1.0.3)

---
updated-dependencies:
- dependency-name: trim-off-newlines
  dependency-type: indirect
...

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

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-26 13:12:57 +01:00
dependabot[bot] 203b1c7ae9 chore(deps): bump moment from 2.28.0 to 2.29.2 (#304)
Bumps [moment](https://github.com/moment/moment) from 2.28.0 to 2.29.2.
- [Release notes](https://github.com/moment/moment/releases)
- [Changelog](https://github.com/moment/moment/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/moment/moment/compare/2.28.0...2.29.2)

---
updated-dependencies:
- dependency-name: moment
  dependency-type: indirect
...

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

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-26 13:12:06 +01:00
dependabot[bot] 0580f85e79 chore(deps-dev): bump @types/got from 9.6.11 to 9.6.12 (#266)
Bumps [@types/got](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/got) from 9.6.11 to 9.6.12.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/got)

---
updated-dependencies:
- dependency-name: "@types/got"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

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

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-26 13:08:44 +01:00
Tom Proctor b222012f94 changelog++ 2022-04-26 13:08:02 +01:00
Christopher Swenson 40fb8d7236 Write a better error message when secret not found (follow-up) (#306)
* Write a better error message when key not found

* Address additional comments on #182

Co-authored-by: Simon Johansson <simon@simonjohansson.com>
2022-04-20 15:53:24 -07:00
Prakash Manglanathan 4aed62f922 Updated the version in Readme doc. (#303)
The Sample code provided in the readme doesn't work as expected unless the version has been updated to 2.4.0.
2022-04-07 16:42:18 -07:00
Tom Proctor 4679f8aa3c changelog++ 2022-04-07 15:35:48 +01:00
Kamil Domański 2f64a97498 make "role" input optional (#291)
* make "role" input optional

Per Vault documentation it doesn't have to be provided,
and the auth provider's "default_role" parameter is required
precisely for this case.
https://www.vaultproject.io/api/auth/jwt
2022-04-07 15:34:46 +01:00
Tom Proctor 25c4aec690 changelog++ 2022-04-07 14:11:27 +01:00
Kevin Schoonover c14a190aaa feat(): make secrets parameter optional (#299) 2022-04-07 14:10:23 +01:00
Joonas Venäläinen 843e7fa30a fix(docs): Fix bound_audience example url in Github OIDC Token section (#302) 2022-04-04 10:11:40 +01:00
Rosemary Wang 876cdcfdd3 Update docs with GitHub OIDC token configuration (#301) 2022-03-28 09:23:28 -07:00
Tom Proctor 67281159df Update jira action (#274)
* No longer check for Vault team membership
* Tweak jira states and search parameters
2021-11-08 11:16:29 +00:00
17 changed files with 583 additions and 988 deletions
+1 -1
View File
@@ -17,7 +17,7 @@ The yaml of the `vault-action` step, with any sensitive information masked or re
A clear and concise description of what you expected to happen.
**Log Output**
For the most verbose logs, [add a secret called `ACTIONS_STEP_DEBUG` with the value `true`](https://github.com/actions/toolkit/blob/master/docs/action-debugging.md). Then, re-run the workflow if possible and post the *raw logs* for the step here with any sensitive information masked or removed.
For the most verbose logs, [add a secret called `ACTIONS_STEP_DEBUG` with the value `true`](https://github.com/actions/toolkit/blob/main/docs/action-debugging.md). Then, re-run the workflow if possible and post the *raw logs* for the step here with any sensitive information masked or removed.
**Additional context**
Add any other context about the problem here.
+5 -4
View File
@@ -1,15 +1,16 @@
on:
push:
branches:
- master
- main
pull_request_target:
types: [opened, reopened, synchronize]
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
@@ -263,7 +264,7 @@ jobs:
# Removing publish step for now.
# publish:
# if: github.event_name == 'push' && contains(github.ref, 'master')
# if: github.event_name == 'push' && contains(github.ref, 'main')
# runs-on: ubuntu-latest
# needs: [build, integration, e2e]
# steps:
@@ -281,7 +282,7 @@ jobs:
# - name: npm install
# run: npm ci
# - name: release
# if: success() && endsWith(github.ref, 'master')
# if: success() && endsWith(github.ref, 'main')
# run: npx semantic-release
# env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+4 -19
View File
@@ -13,21 +13,6 @@ jobs:
runs-on: ubuntu-latest
name: Jira sync
steps:
- name: Check if community user
if: github.event.action == 'opened'
id: vault-team-role
run: |
TEAM=vault
ROLE="$(hub api orgs/hashicorp/teams/${TEAM}/memberships/${{ github.actor }} | jq -r '.role | select(.!=null)')"
if [[ -n ${ROLE} ]]; then
echo "Actor ${{ github.actor }} is a ${TEAM} team member, skipping ticket creation"
else
echo "Actor ${{ github.actor }} is not a ${TEAM} team member"
fi
echo "::set-output name=role::${ROLE}"
env:
GITHUB_TOKEN: ${{ secrets.JIRA_SYNC_GITHUB_TOKEN }}
- name: Login
uses: atlassian/gajira-login@v2.0.0
env:
@@ -46,7 +31,7 @@ jobs:
fi
- name: Create ticket
if: github.event.action == 'opened' && !steps.vault-team-role.outputs.role
if: github.event.action == 'opened'
uses: tomhjp/gh-action-jira-create@v0.2.0
with:
project: VAULT
@@ -63,7 +48,7 @@ jobs:
uses: tomhjp/gh-action-jira-search@v0.2.1
with:
# cf[10089] is Issue Link custom field
jql: 'project = "VAULT" and issuetype = "GH Issue" and cf[10089]="${{ github.event.issue.html_url || github.event.pull_request.html_url }}"'
jql: 'project = "VAULT" and cf[10089]="${{ github.event.issue.html_url || github.event.pull_request.html_url }}"'
- name: Sync comment
if: github.event.action == 'created' && steps.search.outputs.issue
@@ -77,11 +62,11 @@ jobs:
uses: atlassian/gajira-transition@v2.0.1
with:
issue: ${{ steps.search.outputs.issue }}
transition: Done
transition: Close
- name: Reopen ticket
if: github.event.action == 'reopened' && steps.search.outputs.issue
uses: atlassian/gajira-transition@v2.0.1
with:
issue: ${{ steps.search.outputs.issue }}
transition: "To Do"
transition: "Pending Triage"
+13
View File
@@ -1,5 +1,18 @@
## Unreleased
## 2.4.1 (April 28th, 2022)
Improvements:
* Make secrets parameter optional [GH-299](https://github.com/hashicorp/vault-action/pull/299)
* auth/jwt: make "role" input optional [GH-291](https://github.com/hashicorp/vault-action/pull/291)
* Write a better error message when secret not found [GH-306](https://github.com/hashicorp/vault-action/pull/306)
* bump jest-when from 2.7.2 to 3.5.1 [GH-294](https://github.com/hashicorp/vault-action/pull/294)
* bump node-fetch from 2.6.1 to 2.6.7 [GH-308](https://github.com/hashicorp/vault-action/pull/308)
* bump @types/jest from 26.0.23 to 27.4.1 [GH-297](https://github.com/hashicorp/vault-action/pull/297)
* bump trim-off-newlines from 1.0.1 to 1.0.3 [GH-309](https://github.com/hashicorp/vault-action/pull/309)
* bump moment from 2.28.0 to 2.29.2 [GH-304](https://github.com/hashicorp/vault-action/pull/304)
* bump @types/got from 9.6.11 to 9.6.12 [GH-266](https://github.com/hashicorp/vault-action/pull/266)
## 2.4.0 (October 21st, 2021)
Features:
+158 -58
View File
@@ -12,14 +12,21 @@ A helper action for easily pulling secrets from HashiCorp Vault™.
- [Vault GitHub Action](#vault-github-action)
- [Example Usage](#example-usage)
- [Authentication method](#authentication-method)
- [Authentication Methods](#authentication-methods)
- [JWT with GitHub OIDC Tokens](#jwt-with-github-oidc-tokens)
- [AppRole](#approle)
- [Token](#token)
- [GitHub](#github)
- [JWT with OIDC Provider](#jwt-with-oidc-provider)
- [Kubernetes](#kubernetes)
- [Other Auth Methods](#other-auth-methods)
- [Key Syntax](#key-syntax)
- [Simple Key](#simple-key)
- [Set Output Variable Name](#set-output-variable-name)
- [Multiple Secrets](#multiple-secrets)
- [Other Secret Engines](#other-secret-engines)
- [Adding Extra Headers](#adding-extra-headers)
- [Vault Enterprise Features](#vault-enterprise-features)
- [HashiCorp Cloud Platform or Vault Enterprise](#hashicorp-cloud-platform-or-vault-enterprise)
- [Namespace](#namespace)
- [Reference](#reference)
- [Masking - Hiding Secrets from Logs](#masking---hiding-secrets-from-logs)
@@ -36,11 +43,11 @@ jobs:
steps:
# ...
- name: Import Secrets
uses: hashicorp/vault-action@v2.3.1
uses: hashicorp/vault-action@v2.4.0
with:
url: https://vault.mycompany.com:8200
token: ${{ secrets.VaultToken }}
caCertificate: ${{ secrets.VAULTCA }}
token: ${{ secrets.VAULT_TOKEN }}
caCertificate: ${{ secrets.VAULT_CA_CERT }}
secrets: |
secret/data/ci/aws accessKey | AWS_ACCESS_KEY_ID ;
secret/data/ci/aws secretKey | AWS_SECRET_ACCESS_KEY ;
@@ -48,87 +55,176 @@ jobs:
# ...
```
## Authentication method
## Authentication Methods
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:
Consider using a [Vault authentication method](https://www.vaultproject.io/docs/auth) such as the JWT auth method with
[GitHub OIDC tokens](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect) or the AppRole auth method. You can configure which by using the `method` parameter.
### JWT with GitHub OIDC Tokens
You can configure trust between a GitHub Actions workflow
and Vault using the
[GitHub's OIDC provider](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect).
Each GitHub Actions workflow receives an auto-generated OIDC token with claims
to establish the identity of the workflow.
__Vault Configuration__
<details>
<summary>Click to toggle instructions for configuring Vault.</summary>
Set up Vault with the [JWT auth method](https://www.vaultproject.io/api/auth/jwt#configure).
Pass the following parameters to your auth method configuration:
- `oidc_discovery_url`: `https://token.actions.githubusercontent.com`
- `bound_issuer`: `https://token.actions.githubusercontent.com`
Configure a [Vault role](https://www.vaultproject.io/api/auth/jwt#create-role) for the auth method.
- `role_type`: `jwt`
- `bound_audiences`: `"https://github.com/<org>"`. Update this parameter if
you change the `aud` claim in the GitHub OIDC token via the
`jwtGithubAudience` parameter in the action config.
- `user_claim`: Set this to a claim name (e.g., `repository`) in the
[GitHub OIDC token](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect#understanding-the-oidc-token).
- `bound_claims` OR `bound_subject`: match on [GitHub subject claims](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect#example-subject-claims).
- For wildcard (non-exact) matches, use `bound_claims`.
- `bound_claims_type`: `glob`
- `bound_claims`: JSON object. Maps one or more claim names to corresponding wildcard values.
```json
{"sub": "repo:<orgName>/*"}
```
- For exact matches, use `bound_subject`.
- `bound_claims_type`: `string`
- `bound_subject`: Must exactly match the `sub` claim in the OIDC token.
```plaintext
repo:<orgName/repoName>:ref:refs/heads/branchName
```
</details>
__GitHub Actions Workflow__
In the GitHub Actions workflow, the workflow needs permissions to read contents
and write the ID token.
- **token**: (by default) you must provide a `token` parameter
```yaml
...
with:
url: https://vault.mycompany.com:8200
token: ${{ secrets.VaultToken }}
caCertificate: ${{ secrets.VAULTCA }}
jobs:
retrieve-secret:
permissions:
contents: read
id-token: write
```
- **approle**: you must provide a `roleId` & `secretId` parameter
In the action, provide the name of the Vault role you created to the `role` parameter.
You can optionally set the `jwtGithubAudience` parameter to change the `aud`
claim from its default.
```yaml
...
with:
url: https://vault.mycompany.com:8200
caCertificate: ${{ secrets.VAULT_CA_CERT }}
role: <Vault JWT Auth Role Name>
method: jwt
jwtGithubAudience: sigstore # set the GitHub token's aud claim
```
### AppRole
The [AppRole auth method](https://www.vaultproject.io/docs/auth/approle) allows
your GitHub Actions workflow to authenticate to Vault with a pre-defined role.
Set the role ID and secret ID as GitHub secrets and pass them to the
`roleId` and `secretId` parameters.
```yaml
with:
url: https://vault.mycompany.com:8200
caCertificate: ${{ secrets.VAULT_CA_CERT }}
method: approle
roleId: ${{ secrets.roleId }}
secretId: ${{ secrets.secretId }}
caCertificate: ${{ secrets.VAULTCA }}
roleId: ${{ secrets.VAULT_ROLE_ID }}
secretId: ${{ secrets.VAULT_SECRET_ID }}
```
- **github**: you must provide the github token as `githubToken`
**Notice: [Vault GitHub authentication](https://www.vaultproject.io/docs/auth/github)
### Token
For the default method of authenticating to Vault,
use a [Vault token](https://www.vaultproject.io/docs/concepts/tokens).
Set the Vault token as a GitHub secret and pass
it to the `token` parameter.
```yaml
with:
url: https://vault.mycompany.com:8200
caCertificate: ${{ secrets.VAULT_CA_CERT }}
token: ${{ secrets.VAULT_TOKEN }}
```
### GitHub
The [GitHub auth method](https://www.vaultproject.io/docs/auth/github)
requires `read:org` permissions for authentication. The auto-generated `GITHUB_TOKEN`
created for projects does not have these permissions and GitHub does not allow this
token's permissions to be modified. A new GitHub Token secret must be created with
`read:org` permissions to use this authentication method.**
`read:org` permissions to use this authentication method.
Pass the GitHub token as a GitHub secret into the `githubToken` parameter.
```yaml
...
with:
url: https://vault.mycompany.com:8200
caCertificate: ${{ secrets.VAULT_CA_CERT }}
method: github
githubToken: ${{ secrets.MY_GITHUB_TOKEN }}
caCertificate: ${{ secrets.VAULTCA }}
githubToken: ${{ secrets.GITHUB_TOKEN }}
```
- **jwt**: (Github OIDC) you must provide a `role` parameter, additionally you can pass `jwtGithubAudience` parameter.
### JWT with OIDC Provider
You can configure trust between your own OIDC Provider and Vault
with the JWT auth method. Provide a `role` & `jwtPrivateKey` parameters,
additionally you can pass `jwtKeyPassword` & `jwtTtl` parameters
```yaml
...
with:
url: https://vault.mycompany.com:8200
caCertificate: ${{ secrets.VAULT_CA_CERT }}
method: jwt
role: github-action
```
**Notice:** For Github provided OIDC token to work, the workflow should have `id-token: write` & `contents: read` specified in the `permissions` section of the workflow
```yaml
...
permissions:
id-token: write
contents: read
...
```
- **jwt**: you must provide a `role` & `jwtPrivateKey` parameters, additionally you can pass `jwtKeyPassword` & `jwtTtl` parameters
```yaml
...
with:
url: https://vault.mycompany.com:8200
method: jwt
role: github-action
role: <Vault JWT Auth Role Name>
jwtPrivateKey: ${{ secrets.JWT_PRIVATE_KEY }}
jwtKeyPassword: ${{ secrets.JWT_KEY_PASS }}
jwtTtl: 3600 # 1 hour, default value
```
- **kubernetes**: you must provide the `role` paramaters. You can optionally override the `kubernetesTokenPath` paramater for custom mounted serviceAccounts. Consider [kubernetes auth](https://www.vaultproject.io/docs/auth/kubernetes) when using self-hosted runners on Kubernetes:
### Kubernetes
Consider the [Kubernetes auth method](https://www.vaultproject.io/docs/auth/kubernetes)
when using self-hosted runners on Kubernetes. You must provide the `role` parameter
for the Vault role associated with the Kubernetes auth method.
You can optionally override the `kubernetesTokenPath` parameter for
custom-mounted serviceAccounts.
```yaml
...
with:
url: https://vault.mycompany.com:8200
caCertificate: ${{ secrets.VAULT_CA_CERT }}
method: kubernetes
role: ${{ secrets.KUBE_ROLE }}
role: <Vault Kubernetes Auth Role Name>
kubernetesTokenPath: /var/run/secrets/kubernetes.io/serviceaccount/token # default token path
```
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.
### Other Auth Methods
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
@@ -165,7 +261,6 @@ steps:
# 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`._
@@ -258,11 +353,16 @@ with:
This will automatically add the `x-secure-id` and `x-secure-secret` headers to every request to Vault.
## Vault Enterprise Features
## HashiCorp Cloud Platform or Vault Enterprise
If you are using [HCP Vault](https://cloud.hashicorp.com/products/vault)
or Vault Enterprise, you may need additional parameters in
your GitHub Actions workflow.
### Namespace
If you need to retrieve secrets from a specific Vault namespace, all that's required is an additional parameter specifying the namespace.
If you need to retrieve secrets from a specific Vault namespace, set the `namespace`
parameter specifying the namespace. In HCP Vault, the namespace defaults to `admin`.
```yaml
steps:
@@ -271,10 +371,10 @@ steps:
uses: hashicorp/vault-action
with:
url: https://vault-enterprise.mycompany.com:8200
caCertificate: ${{ secrets.VAULT_CA_CERT }}
method: token
caCertificate: ${{ secrets.VAULTCA }}
token: ${{ secrets.VaultToken }}
namespace: ns1
token: ${{ secrets.VAULT_TOKEN }}
namespace: admin
secrets: |
secret/ci/aws accessKey | AWS_ACCESS_KEY_ID ;
secret/ci/aws secretKey | AWS_SECRET_ACCESS_KEY ;
@@ -288,7 +388,7 @@ 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 | | |
| `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 | | |
| `method` | The method to use to authenticate with Vault. | `token` | |
| `role` | Vault role for specified auth method | | |
+1 -1
View File
@@ -6,7 +6,7 @@ inputs:
required: true
secrets:
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: false
namespace:
description: 'The Vault namespace from which to query secrets. Vault Enterprise only, unset by default'
required: false
+95 -48
View File
@@ -1245,7 +1245,7 @@ async function retrieveToken(method, client) {
case 'jwt': {
/** @type {string} */
let jwt;
const role = core.getInput('role', { required: true });
const role = core.getInput('role', { required: false });
const privateKeyRaw = core.getInput('jwtPrivateKey', { required: false });
const privateKey = Buffer.from(privateKeyRaw, 'base64').toString();
const keyPassword = core.getInput('jwtKeyPassword', { required: false });
@@ -3744,7 +3744,7 @@ const dateTime = (function () {
def.integerFormat.mandatoryDigits = def.width.min;
}
}
if (def.component === 'Y') {
if ('YMD'.indexOf(def.component) !== -1) {
// §9.8.4.4
def.n = -1;
if (def.width && def.width.max !== undefined) {
@@ -4115,6 +4115,7 @@ const dateTime = (function () {
return offsetHours * 60 + offsetMinutes;
};
} else if (part.integerFormat) {
part.integerFormat.n = part.n;
res = generateRegex(part.integerFormat);
} else {
// must be a month or day name
@@ -4159,6 +4160,17 @@ const dateTime = (function () {
} else { // type === 'integer'
matcher.type = 'integer';
const isUpper = formatSpec.case === tcase.UPPER;
let occurrences;
if(formatSpec.n && formatSpec.n > 0){
if(formatSpec.optionalDigits === 0){
occurrences = `{${formatSpec.n}}`;
} else {
occurrences = `{${formatSpec.n - formatSpec.optionalDigits},${formatSpec.n}}`;
}
} else {
occurrences = '+';
}
switch (formatSpec.primary) {
case formats.LETTERS:
matcher.regex = isUpper ? '[A-Z]+' : '[a-z]+';
@@ -4179,7 +4191,7 @@ const dateTime = (function () {
};
break;
case formats.DECIMAL:
matcher.regex = '[0-9]+';
matcher.regex = `[0-9]${occurrences}`;
if (formatSpec.ordinal) {
// ordinals
matcher.regex += '(?:th|st|nd|rd)';
@@ -5054,7 +5066,7 @@ const functions = (() => {
// Simply doing `new Buffer` at this point causes Browserify to pull
// in the entire Buffer browser library, which is large and unnecessary.
// Using `global.Buffer` defeats this.
return new global.Buffer(str, 'base64').toString('binary');
return new global.Buffer.from(str, 'base64').toString('binary'); // eslint-disable-line new-cap
};
return atob(str);
}
@@ -6763,7 +6775,8 @@ var jsonata = (function() {
}
if(expr.keepSingletonArray) {
if(!isSequence(resultSequence)) {
// if the array is explicitly constructed in the expression and marked to promote singleton sequences to array
if(Array.isArray(resultSequence) && resultSequence.cons && !resultSequence.sequence) {
resultSequence = createSequence(resultSequence);
}
resultSequence.keepSingleton = true;
@@ -7001,9 +7014,21 @@ var jsonata = (function() {
function * evaluateBinary(expr, input, environment) {
var result;
var lhs = yield * evaluate(expr.lhs, input, environment);
var rhs = yield * evaluate(expr.rhs, input, environment);
var op = expr.value;
//defer evaluation of RHS to allow short-circuiting
var evalrhs = function*(){return yield * evaluate(expr.rhs, input, environment);};
if (op === "and" || op === "or") {
try {
return yield * evaluateBooleanExpression(lhs, evalrhs, op);
} catch(err) {
err.position = expr.position;
err.token = op;
throw err;
}
}
var rhs = yield * evalrhs();
try {
switch (op) {
case '+':
@@ -7026,10 +7051,6 @@ var jsonata = (function() {
case '&':
result = evaluateStringConcat(lhs, rhs);
break;
case 'and':
case 'or':
result = evaluateBooleanExpression(lhs, rhs, op);
break;
case '..':
result = evaluateRangeExpression(lhs, rhs);
break;
@@ -7132,6 +7153,9 @@ var jsonata = (function() {
*/
function evaluateWildcard(expr, input) {
var results = createSequence();
if (Array.isArray(input) && input.outerWrapper && input.length > 0) {
input = input[0];
}
if (input !== null && typeof input === 'object') {
Object.keys(input).forEach(function (key) {
var value = input[key];
@@ -7380,35 +7404,31 @@ var jsonata = (function() {
/**
* Evaluate boolean expression against input data
* @param {Object} lhs - LHS value
* @param {Object} rhs - RHS value
* @param {Function} evalrhs - function to evaluate RHS value
* @param {Object} op - opcode
* @returns {*} Result
*/
function evaluateBooleanExpression(lhs, rhs, op) {
function * evaluateBooleanExpression(lhs, evalrhs, op) {
var result;
var lBool = fn.boolean(lhs);
var rBool = fn.boolean(rhs);
if (typeof lBool === 'undefined') {
lBool = false;
}
if (typeof rBool === 'undefined') {
rBool = false;
}
var lBool = boolize(lhs);
switch (op) {
case 'and':
result = lBool && rBool;
result = lBool && boolize(yield * evalrhs());
break;
case 'or':
result = lBool || rBool;
result = lBool || boolize(yield * evalrhs());
break;
}
return result;
}
function boolize(value) {
var booledValue = fn.boolean(value);
return typeof booledValue === 'undefined' ? false : booledValue;
}
/**
* Evaluate string concatenation against input data
* @param {Object} lhs - LHS value
@@ -7446,6 +7466,10 @@ var jsonata = (function() {
if (!Array.isArray(input)) {
input = createSequence(input);
}
// if the array is empty, add an undefined entry to enable literal JSON object to be generated
if (input.length === 0) {
input.push(undefined);
}
for(var itemIndex = 0; itemIndex < input.length; itemIndex++) {
var item = input[itemIndex];
@@ -7454,7 +7478,7 @@ var jsonata = (function() {
var pair = expr.lhs[pairIndex];
var key = yield * evaluate(pair[0], reduce ? item['@'] : item, env);
// key has to be a string
if (typeof key !== 'string') {
if (typeof key !== 'string' && key !== undefined) {
throw {
code: "T1003",
stack: (new Error()).stack,
@@ -7462,24 +7486,27 @@ var jsonata = (function() {
value: key
};
}
var entry = {data: item, exprIndex: pairIndex};
if (groups.hasOwnProperty(key)) {
// a value already exists in this slot
if(groups[key].exprIndex !== pairIndex) {
// this key has been generated by another expression in this group
// when multiple key expressions evaluate to the same key, then error D1009 must be thrown
throw {
code: "D1009",
stack: (new Error()).stack,
position: expr.position,
value: key
};
}
// append it as an array
groups[key].data = fn.append(groups[key].data, item);
} else {
groups[key] = entry;
if (key !== undefined) {
var entry = {data: item, exprIndex: pairIndex};
if (groups.hasOwnProperty(key)) {
// a value already exists in this slot
if(groups[key].exprIndex !== pairIndex) {
// this key has been generated by another expression in this group
// when multiple key expressions evaluate to the same key, then error D1009 must be thrown
throw {
code: "D1009",
stack: (new Error()).stack,
position: expr.position,
value: key
};
}
// append it as an array
groups[key].data = fn.append(groups[key].data, item);
} else {
groups[key] = entry;
}
}
}
}
@@ -7632,7 +7659,7 @@ var jsonata = (function() {
* @returns {Function} Higher order function representing prepared regex
*/
function evaluateRegex(expr) {
var re = new RegExp(expr.value);
var re = new jsonata.RegexEngine(expr.value);
var closure = function(str, fromIndex) {
var result;
re.lastIndex = fromIndex || 0;
@@ -8585,7 +8612,9 @@ var jsonata = (function() {
/**
* JSONata
* @param {Object} expr - JSONata expression
* @param {boolean} options - recover: attempt to recover on parse error
* @param {Object} options
* @param {boolean} options.recover: attempt to recover on parse error
* @param {Function} options.RegexEngine: RegEx class constructor to use
* @returns {{evaluate: evaluate, assign: assign}} Evaluated expression
*/
function jsonata(expr, options) {
@@ -8610,6 +8639,12 @@ var jsonata = (function() {
return timestamp.getTime();
}, '<:n>'));
if(options && options.RegexEngine) {
jsonata.RegexEngine = options.RegexEngine;
} else {
jsonata.RegexEngine = RegExp;
}
return {
evaluate: function (input, bindings, callback) {
// throw if the expression compiled with syntax errors
@@ -11230,9 +11265,17 @@ async function getSecrets(secretRequests, client) {
body = responseCache.get(requestPath);
cachedResponse = true;
} else {
const result = await client.get(requestPath);
body = result.body;
responseCache.set(requestPath, body);
try {
const result = await client.get(requestPath);
body = result.body;
responseCache.set(requestPath, body);
} catch (error) {
const {response} = error;
if (response.statusCode === 404) {
throw Error(`Unable to retrieve result for "${path}" because it was not found: ${response.body.trim()}`)
}
throw error
}
}
if (!selector.match(/.*[\.].*/)) {
selector = '"' + selector + '"'
@@ -15644,7 +15687,7 @@ async function exportSecrets() {
const exportEnv = core.getInput('exportEnv', { required: false }) != 'false';
const exportToken = (core.getInput('exportToken', { required: false }) || 'false').toLowerCase() != 'false';
const secretsInput = core.getInput('secrets', { required: true });
const secretsInput = core.getInput('secrets', { required: false });
const secretRequests = parseSecretsInput(secretsInput);
const vaultMethod = (core.getInput('method', { required: false }) || 'token').toLowerCase();
@@ -15733,6 +15776,10 @@ async function exportSecrets() {
* @param {string} secretsInput
*/
function parseSecretsInput(secretsInput) {
if (!secretsInput) {
return []
}
const secrets = secretsInput
.split(';')
.filter(key => !!key)
+11 -3
View File
@@ -109,20 +109,28 @@ describe('integration', () => {
jest.resetAllMocks();
when(core.getInput)
.calledWith('url')
.calledWith('url', expect.anything())
.mockReturnValueOnce(`${vaultUrl}`);
when(core.getInput)
.calledWith('token')
.calledWith('token', expect.anything())
.mockReturnValueOnce('testtoken');
});
function mockInput(secrets) {
when(core.getInput)
.calledWith('secrets')
.calledWith('secrets', expect.anything())
.mockReturnValueOnce(secrets);
}
it('prints a nice error message when secret not found', async () => {
mockInput(`secret/data/test secret ;
secret/data/test secret | NAMED_SECRET ;
secret/data/notFound kehe | NO_SIR ;`);
expect(exportSecrets()).rejects.toEqual(Error(`Unable to retrieve result for "secret/data/notFound" because it was not found: {"errors":[]}`));
})
it('get simple secret', async () => {
mockInput('secret/data/test secret');
+41 -24
View File
@@ -26,9 +26,9 @@ function mockGithubOIDCResponse(aud= "https://github.com/hashicorp/vault-action"
const now = rsasign.KJUR.jws.IntDate.getNow();
const payload = {
jti: "unique-id",
sub: "repo:hashicorp/vault-action:ref:refs/heads/master",
sub: "repo:hashicorp/vault-action:ref:refs/heads/main",
aud,
ref: "refs/heads/master",
ref: "refs/heads/main",
sha: "commit-sha",
repository: "hashicorp/vault-action",
repository_owner: "hashicorp",
@@ -41,7 +41,7 @@ function mockGithubOIDCResponse(aud= "https://github.com/hashicorp/vault-action"
base_ref: "",
event_name: "push",
ref_type: "branch",
job_workflow_ref: "hashicorp/vault-action/.github/workflows/workflow.yml@refs/heads/master",
job_workflow_ref: "hashicorp/vault-action/.github/workflows/workflow.yml@refs/heads/main",
iss: 'vault-action',
iat: now,
nbf: now,
@@ -51,6 +51,9 @@ function mockGithubOIDCResponse(aud= "https://github.com/hashicorp/vault-action"
return rsasign.KJUR.jws.JWS.sign(alg, JSON.stringify(header), JSON.stringify(payload), decryptedKey);
}
// The sign call inside this function takes a while to run, so cache the default JWT in a constant.
const defaultGithubJwt = mockGithubOIDCResponse();
describe('jwt auth', () => {
beforeAll(async () => {
// Verify Connection
@@ -99,7 +102,8 @@ describe('jwt auth', () => {
'X-Vault-Token': 'testtoken',
},
json: {
jwt_validation_pubkeys: publicRsaKey
jwt_validation_pubkeys: publicRsaKey,
default_role: "default"
}
});
@@ -137,23 +141,23 @@ describe('jwt auth', () => {
jest.resetAllMocks();
when(core.getInput)
.calledWith('url')
.calledWith('url', expect.anything())
.mockReturnValueOnce(`${vaultUrl}`);
when(core.getInput)
.calledWith('method')
.calledWith('method', expect.anything())
.mockReturnValueOnce('jwt');
when(core.getInput)
.calledWith('jwtPrivateKey')
.calledWith('jwtPrivateKey', expect.anything())
.mockReturnValueOnce(privateRsaKeyBase64);
when(core.getInput)
.calledWith('role')
.calledWith('role', expect.anything())
.mockReturnValueOnce('default');
when(core.getInput)
.calledWith('secrets')
.calledWith('secrets', expect.anything())
.mockReturnValueOnce('secret/data/test secret');
});
@@ -187,52 +191,65 @@ describe('jwt auth', () => {
jest.resetAllMocks();
when(core.getInput)
.calledWith('url')
.calledWith('url', expect.anything())
.mockReturnValueOnce(`${vaultUrl}`);
when(core.getInput)
.calledWith('method')
.calledWith('method', expect.anything())
.mockReturnValueOnce('jwt');
when(core.getInput)
.calledWith('jwtPrivateKey')
.calledWith('jwtPrivateKey', expect.anything())
.mockReturnValueOnce('');
when(core.getInput)
.calledWith('role')
.mockReturnValueOnce('default');
when(core.getInput)
.calledWith('secrets')
.calledWith('secrets', expect.anything())
.mockReturnValueOnce('secret/data/test secret');
when(core.getIDToken)
.calledWith()
.mockReturnValueOnce(mockGithubOIDCResponse());
});
it('successfully authenticates', async () => {
when(core.getInput)
.calledWith('role', expect.anything())
.mockReturnValueOnce('default');
when(core.getIDToken)
.calledWith(undefined)
.mockReturnValueOnce(defaultGithubJwt);
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('SECRET', 'SUPERSECRET');
});
it('successfully authenticates with `jwtGithubAudience` set to `sigstore`', async () => {
when(core.getInput)
.calledWith('role')
.calledWith('role', expect.anything())
.mockReturnValueOnce('default-sigstore');
when(core.getInput)
.calledWith('jwtGithubAudience')
.calledWith('jwtGithubAudience', expect.anything())
.mockReturnValueOnce('sigstore');
when(core.getIDToken)
.calledWith()
.calledWith(expect.anything())
.mockReturnValueOnce(mockGithubOIDCResponse('sigstore'));
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('SECRET', 'SUPERSECRET');
})
it('successfully authenticates as default role without specifying it', async () => {
when(core.getInput)
.calledWith('role', expect.anything())
.mockReturnValueOnce(null);
when(core.getIDToken)
.calledWith(undefined)
.mockReturnValueOnce(defaultGithubJwt);
await exportSecrets();
expect(core.exportVariable).toBeCalledWith('SECRET', 'SUPERSECRET');
})
});
});
+8 -20
View File
@@ -43,15 +43,15 @@ describe('integration', () => {
jest.resetAllMocks();
when(core.getInput)
.calledWith('url')
.calledWith('url', expect.anything())
.mockReturnValueOnce(`${vaultUrl}`);
when(core.getInput)
.calledWith('token')
.calledWith('token', expect.anything())
.mockReturnValueOnce('testtoken');
when(core.getInput)
.calledWith('namespace')
.calledWith('namespace', expect.anything())
.mockReturnValueOnce('ns1');
});
@@ -211,16 +211,16 @@ describe('authenticate with approle', () => {
.calledWith('method', expect.anything())
.mockReturnValueOnce('approle');
when(core.getInput)
.calledWith('roleId')
.calledWith('roleId', expect.anything())
.mockReturnValueOnce(roleId);
when(core.getInput)
.calledWith('secretId')
.calledWith('secretId', expect.anything())
.mockReturnValueOnce(secretId);
when(core.getInput)
.calledWith('url')
.calledWith('url', expect.anything())
.mockReturnValueOnce(`${vaultUrl}`);
when(core.getInput)
.calledWith('namespace')
.calledWith('namespace', expect.anything())
.mockReturnValueOnce('ns2');
});
@@ -286,18 +286,6 @@ async function writeSecret(engine, path, namespace, version, data) {
function mockInput(secrets) {
when(core.getInput)
.calledWith('secrets')
.calledWith('secrets', expect.anything())
.mockReturnValueOnce(secrets);
}
function mockEngineName(name) {
when(core.getInput)
.calledWith('path')
.mockReturnValueOnce(name);
}
function mockVersion(version) {
when(core.getInput)
.calledWith('kv-version')
.mockReturnValueOnce(version);
}
+205 -790
View File
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -16,7 +16,7 @@
"dist/**/*"
],
"release": {
"branch": "master",
"branch": "main",
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
@@ -45,7 +45,7 @@
"homepage": "https://github.com/hashicorp/vault-action#readme",
"dependencies": {
"got": "^11.5.1",
"jsonata": "^1.8.2",
"jsonata": "^1.8.6",
"jsrsasign": "^10.1.10"
},
"peerDependencies": {
@@ -54,10 +54,10 @@
"devDependencies": {
"@actions/core": "^1.6.0",
"@types/got": "^9.6.11",
"@types/jest": "^26.0.13",
"@types/jest": "^27.4.1",
"@zeit/ncc": "^0.22.3",
"jest": "^26.4.2",
"jest-when": "^2.7.2",
"jest-when": "^3.5.1",
"semantic-release": "^17.1.1"
}
}
+5 -1
View File
@@ -14,7 +14,7 @@ async function exportSecrets() {
const exportEnv = core.getInput('exportEnv', { required: false }) != 'false';
const exportToken = (core.getInput('exportToken', { required: false }) || 'false').toLowerCase() != 'false';
const secretsInput = core.getInput('secrets', { required: true });
const secretsInput = core.getInput('secrets', { required: false });
const secretRequests = parseSecretsInput(secretsInput);
const vaultMethod = (core.getInput('method', { required: false }) || 'token').toLowerCase();
@@ -103,6 +103,10 @@ async function exportSecrets() {
* @param {string} secretsInput
*/
function parseSecretsInput(secretsInput) {
if (!secretsInput) {
return []
}
const secrets = secretsInput
.split(';')
.filter(key => !!key)
+19 -10
View File
@@ -94,7 +94,7 @@ describe('parseSecretsInput', () => {
describe('parseHeaders', () => {
it('parses simple header', () => {
when(core.getInput)
.calledWith('extraHeaders')
.calledWith('extraHeaders', undefined)
.mockReturnValueOnce('TEST: 1');
const result = parseHeadersInput('extraHeaders');
expect(Array.from(result)).toContainEqual(['test', '1']);
@@ -102,7 +102,7 @@ describe('parseHeaders', () => {
it('parses simple header with whitespace', () => {
when(core.getInput)
.calledWith('extraHeaders')
.calledWith('extraHeaders', undefined)
.mockReturnValueOnce(`
TEST: 1
`);
@@ -112,7 +112,7 @@ describe('parseHeaders', () => {
it('parses multiple headers', () => {
when(core.getInput)
.calledWith('extraHeaders')
.calledWith('extraHeaders', undefined)
.mockReturnValueOnce(`
TEST: 1
FOO: bAr
@@ -124,7 +124,7 @@ describe('parseHeaders', () => {
it('parses null response', () => {
when(core.getInput)
.calledWith('extraHeaders')
.calledWith('extraHeaders', undefined)
.mockReturnValueOnce(null);
const result = parseHeadersInput('extraHeaders');
expect(Array.from(result)).toHaveLength(0);
@@ -136,29 +136,29 @@ describe('exportSecrets', () => {
jest.resetAllMocks();
when(core.getInput)
.calledWith('url')
.calledWith('url', expect.anything())
.mockReturnValueOnce('http://vault:8200');
when(core.getInput)
.calledWith('token')
.calledWith('token', expect.anything())
.mockReturnValueOnce('EXAMPLE');
});
function mockInput(key) {
when(core.getInput)
.calledWith('secrets')
.calledWith('secrets', expect.anything())
.mockReturnValueOnce(key);
}
function mockVersion(version) {
when(core.getInput)
.calledWith('kv-version')
.calledWith('kv-version', expect.anything())
.mockReturnValueOnce(version);
}
function mockExtraHeaders(headerString) {
when(core.getInput)
.calledWith('extraHeaders')
.calledWith('extraHeaders', expect.anything())
.mockReturnValueOnce(headerString);
}
@@ -181,7 +181,7 @@ describe('exportSecrets', () => {
function mockExportToken(doExport) {
when(core.getInput)
.calledWith('exportToken')
.calledWith('exportToken', expect.anything())
.mockReturnValueOnce(doExport);
}
@@ -331,4 +331,13 @@ with blank lines
expect(command.issue).toBeCalledWith('add-mask', 'with blank lines');
expect(core.setOutput).toBeCalledWith('key', multiLineString);
})
it('export only Vault token, no secrets', async () => {
mockExportToken("true")
await exportSecrets();
expect(core.exportVariable).toBeCalledTimes(1);
expect(core.exportVariable).toBeCalledWith('VAULT_TOKEN', 'EXAMPLE');
})
});
+1 -1
View File
@@ -25,7 +25,7 @@ async function retrieveToken(method, client) {
case 'jwt': {
/** @type {string} */
let jwt;
const role = core.getInput('role', { required: true });
const role = core.getInput('role', { required: false });
const privateKeyRaw = core.getInput('jwtPrivateKey', { required: false });
const privateKey = Buffer.from(privateKeyRaw, 'base64').toString();
const keyPassword = core.getInput('jwtKeyPassword', { required: false });
+1 -1
View File
@@ -16,7 +16,7 @@ const {
function mockInput(name, key) {
when(core.getInput)
.calledWith(name)
.calledWith(name, expect.anything())
.mockReturnValueOnce(key);
}
+11 -3
View File
@@ -34,9 +34,17 @@ async function getSecrets(secretRequests, client) {
body = responseCache.get(requestPath);
cachedResponse = true;
} else {
const result = await client.get(requestPath);
body = result.body;
responseCache.set(requestPath, body);
try {
const result = await client.get(requestPath);
body = result.body;
responseCache.set(requestPath, body);
} catch (error) {
const {response} = error;
if (response.statusCode === 404) {
throw Error(`Unable to retrieve result for "${path}" because it was not found: ${response.body.trim()}`)
}
throw error
}
}
if (!selector.match(/.*[\.].*/)) {
selector = '"' + selector + '"'