mirror of
https://github.com/hashicorp/vault-action.git
synced 2026-07-28 17:33:15 +03:00
Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9878eba70a | |||
| 83d944ba1a | |||
| 567ec72c33 | |||
| 5c464962be | |||
| ea29244204 | |||
| 5de02d5a14 | |||
| 8845b5c724 | |||
| c80d0b130c | |||
| 01bb0f9bc9 | |||
| 5a70924133 | |||
| b5fdbf352b | |||
| 268a32f886 | |||
| f2b4d0b645 | |||
| 675d33e3da | |||
| 50ece41861 | |||
| ed8303ca53 | |||
| 0e719ef42a | |||
| 795c9eddca | |||
| 9e8c0bad27 | |||
| 751a3d19ad | |||
| cc7ceeef06 | |||
| fa23030c10 | |||
| 4561f9e26e | |||
| cb2908ac94 | |||
| 198a7ed7d2 | |||
| 4ab6f6070f | |||
| bef2eb0b90 | |||
| 0ece1da433 | |||
| 7fb0d673d1 | |||
| 4edbc9a77a | |||
| 5357098084 | |||
| 3dfe7ff808 | |||
| 1049321b7a | |||
| ec10b5e257 |
@@ -112,6 +112,7 @@ jobs:
|
|||||||
VAULT_PORT: ${{ job.services.vault.ports[8200] }}
|
VAULT_PORT: ${{ job.services.vault.ports[8200] }}
|
||||||
- name: use vault action (default K/V version 2)
|
- 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
|
||||||
@@ -140,6 +141,8 @@ jobs:
|
|||||||
/cubbyhole/test zip | NAMED_CUBBYSECRET ;
|
/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')
|
if: github.event_name == 'push' && contains(github.ref, 'master')
|
||||||
|
|||||||
Vendored
+3
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"markdown-toc.depthFrom": 2
|
||||||
|
}
|
||||||
@@ -4,6 +4,25 @@ 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).
|
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)
|
||||||
|
- [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)
|
||||||
|
|
||||||
|
<!-- /TOC -->
|
||||||
|
|
||||||
## Example Usage
|
## Example Usage
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
@@ -26,16 +45,16 @@ jobs:
|
|||||||
|
|
||||||
## Authentication method
|
## Authentication method
|
||||||
|
|
||||||
While most workflows will likely use a vault token, you can also use an `approle` to authenticate with vaule. You can configure which by using the `method` parameter:
|
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
|
- **token**: (by default) you must provide a `token` parameter
|
||||||
```yaml
|
```yaml
|
||||||
...
|
...
|
||||||
with:
|
with:
|
||||||
url: https://vault.mycompany.com:8200
|
url: https://vault.mycompany.com:8200
|
||||||
token: ${{ secrets.VaultToken }}
|
token: ${{ secrets.VaultToken }}
|
||||||
```
|
```
|
||||||
- **approle**: you must provide a roleId & secretId parameter
|
- **approle**: you must provide a `roleId` & `secretId` parameter
|
||||||
```yaml
|
```yaml
|
||||||
...
|
...
|
||||||
with:
|
with:
|
||||||
@@ -44,6 +63,16 @@ with:
|
|||||||
roleId: ${{ secrets.roleId }}
|
roleId: ${{ secrets.roleId }}
|
||||||
secretId: ${{ secrets.secretId }}
|
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
|
||||||
|
|
||||||
@@ -52,7 +81,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 }} | {{ Output Variable Name }}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Simple Key
|
### Simple Key
|
||||||
@@ -64,15 +93,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:
|
||||||
@@ -85,6 +129,17 @@ 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:
|
||||||
@@ -107,7 +162,7 @@ with:
|
|||||||
kv-version: 1
|
kv-version: 1
|
||||||
```
|
```
|
||||||
|
|
||||||
### Custom K/V Engine Path
|
## 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
|
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:
|
can pass it as follows:
|
||||||
@@ -120,7 +175,7 @@ with:
|
|||||||
|
|
||||||
This way, the `ci` secret in the example above will be retrieved from `my-secrets/ci`.
|
This way, the `ci` secret in the example above will be retrieved from `my-secrets/ci`.
|
||||||
|
|
||||||
### Other Secret Engines
|
## Other Secret Engines
|
||||||
|
|
||||||
While this action primarily supports the K/V engine, it is possible to request secrets from other engines in Vault.
|
While this action primarily supports the K/V engine, it is possible to request secrets from other engines in Vault.
|
||||||
|
|
||||||
@@ -147,7 +202,20 @@ with:
|
|||||||
Resulting in:
|
Resulting in:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
FOO=bar MY_KEY=zap
|
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.
|
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.
|
||||||
@@ -165,6 +233,22 @@ would work fine.
|
|||||||
|
|
||||||
NOTE: The `Secret Key` is pulled from the `data` property of the response.
|
NOTE: The `Secret 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
|
## Vault Enterprise Features
|
||||||
|
|
||||||
### Namespace
|
### Namespace
|
||||||
@@ -187,6 +271,27 @@ steps:
|
|||||||
ci npm_token
|
ci npm_token
|
||||||
```
|
```
|
||||||
|
|
||||||
## Masking
|
## Reference
|
||||||
|
|
||||||
This action uses Github Action's built in masking, so all variables will automatically be masked if printed to the console or to logs.
|
Here is 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.
|
||||||
|
|||||||
+34
-4
@@ -1,18 +1,48 @@
|
|||||||
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:
|
namespace:
|
||||||
description: 'The Vault namespace from which to query secrets. Vault Enterprise only, unset by default'
|
description: 'The Vault namespace from which to query secrets. Vault Enterprise only, unset by default'
|
||||||
required: false
|
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'
|
||||||
|
|||||||
Vendored
+433
-272
@@ -34,7 +34,7 @@ module.exports =
|
|||||||
/******/ // the startup function
|
/******/ // the startup function
|
||||||
/******/ function startup() {
|
/******/ function startup() {
|
||||||
/******/ // Load entry module and return exports
|
/******/ // Load entry module and return exports
|
||||||
/******/ return __webpack_require__(104);
|
/******/ return __webpack_require__(676);
|
||||||
/******/ };
|
/******/ };
|
||||||
/******/ // initialize runtime
|
/******/ // initialize runtime
|
||||||
/******/ runtime(__webpack_require__);
|
/******/ runtime(__webpack_require__);
|
||||||
@@ -648,10 +648,14 @@ const defaults = {
|
|||||||
maxRedirects: 10,
|
maxRedirects: 10,
|
||||||
prefixUrl: '',
|
prefixUrl: '',
|
||||||
methodRewriting: true,
|
methodRewriting: true,
|
||||||
|
allowGetBody: false,
|
||||||
ignoreInvalidCookies: false,
|
ignoreInvalidCookies: false,
|
||||||
context: {},
|
context: {},
|
||||||
_pagination: {
|
_pagination: {
|
||||||
transform: (response) => {
|
transform: (response) => {
|
||||||
|
if (response.request.options.responseType === 'json') {
|
||||||
|
return response.body;
|
||||||
|
}
|
||||||
return JSON.parse(response.body);
|
return JSON.parse(response.body);
|
||||||
},
|
},
|
||||||
paginate: response => {
|
paginate: response => {
|
||||||
@@ -801,22 +805,6 @@ class Response extends Readable {
|
|||||||
module.exports = Response;
|
module.exports = Response;
|
||||||
|
|
||||||
|
|
||||||
/***/ }),
|
|
||||||
|
|
||||||
/***/ 104:
|
|
||||||
/***/ (function(__unusedmodule, __unusedexports, __webpack_require__) {
|
|
||||||
|
|
||||||
const core = __webpack_require__(470);
|
|
||||||
const { exportSecrets } = __webpack_require__(751);
|
|
||||||
|
|
||||||
(async () => {
|
|
||||||
try {
|
|
||||||
await core.group('Get Vault Secrets', exportSecrets);
|
|
||||||
} catch (error) {
|
|
||||||
core.setFailed(error.message);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
|
|
||||||
/***/ }),
|
/***/ }),
|
||||||
|
|
||||||
/***/ 110:
|
/***/ 110:
|
||||||
@@ -1019,6 +1007,7 @@ exports.preNormalizeArguments = (options, defaults) => {
|
|||||||
options.dnsCache = (_e = options.dnsCache, (_e !== null && _e !== void 0 ? _e : false));
|
options.dnsCache = (_e = options.dnsCache, (_e !== null && _e !== void 0 ? _e : false));
|
||||||
options.useElectronNet = Boolean(options.useElectronNet);
|
options.useElectronNet = Boolean(options.useElectronNet);
|
||||||
options.methodRewriting = Boolean(options.methodRewriting);
|
options.methodRewriting = Boolean(options.methodRewriting);
|
||||||
|
options.allowGetBody = Boolean(options.allowGetBody);
|
||||||
options.context = (_f = options.context, (_f !== null && _f !== void 0 ? _f : {}));
|
options.context = (_f = options.context, (_f !== null && _f !== void 0 ? _f : {}));
|
||||||
return options;
|
return options;
|
||||||
};
|
};
|
||||||
@@ -1131,7 +1120,8 @@ exports.normalizeArguments = (url, options, defaults) => {
|
|||||||
}
|
}
|
||||||
return normalizedOptions;
|
return normalizedOptions;
|
||||||
};
|
};
|
||||||
const withoutBody = new Set(['GET', 'HEAD']);
|
const withoutBody = new Set(['HEAD']);
|
||||||
|
const withoutBodyUnlessSpecified = 'GET';
|
||||||
exports.normalizeRequestArguments = async (options) => {
|
exports.normalizeRequestArguments = async (options) => {
|
||||||
var _a, _b, _c;
|
var _a, _b, _c;
|
||||||
options = exports.mergeOptions(options);
|
options = exports.mergeOptions(options);
|
||||||
@@ -1146,6 +1136,9 @@ exports.normalizeRequestArguments = async (options) => {
|
|||||||
if ((isBody || isForm || isJson) && withoutBody.has(options.method)) {
|
if ((isBody || isForm || isJson) && withoutBody.has(options.method)) {
|
||||||
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
|
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
|
||||||
}
|
}
|
||||||
|
if (!options.allowGetBody && (isBody || isForm || isJson) && withoutBodyUnlessSpecified === options.method) {
|
||||||
|
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
|
||||||
|
}
|
||||||
if ([isBody, isForm, isJson].filter(isTrue => isTrue).length > 1) {
|
if ([isBody, isForm, isJson].filter(isTrue => isTrue).length > 1) {
|
||||||
throw new TypeError('The `body`, `json` and `form` options are mutually exclusive');
|
throw new TypeError('The `body`, `json` and `form` options are mutually exclusive');
|
||||||
}
|
}
|
||||||
@@ -1192,7 +1185,7 @@ exports.normalizeRequestArguments = async (options) => {
|
|||||||
// a payload body and the method semantics do not anticipate such a
|
// a payload body and the method semantics do not anticipate such a
|
||||||
// body.
|
// body.
|
||||||
if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) {
|
if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) {
|
||||||
if ((options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH' || options.method === 'DELETE') &&
|
if ((options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH' || options.method === 'DELETE' || (options.allowGetBody && options.method === 'GET')) &&
|
||||||
!is_1.default.undefined(uploadBodySize)) {
|
!is_1.default.undefined(uploadBodySize)) {
|
||||||
// @ts-ignore We assign if it is undefined, so this IS correct
|
// @ts-ignore We assign if it is undefined, so this IS correct
|
||||||
headers['content-length'] = String(uploadBodySize);
|
headers['content-length'] = String(uploadBodySize);
|
||||||
@@ -1559,6 +1552,94 @@ module.exports.iterator = (emitter, event, options) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/***/ }),
|
||||||
|
|
||||||
|
/***/ 151:
|
||||||
|
/***/ (function(module, __unusedexports, __webpack_require__) {
|
||||||
|
|
||||||
|
// @ts-check
|
||||||
|
const core = __webpack_require__(470);
|
||||||
|
|
||||||
|
/***
|
||||||
|
* 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,
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
/***/ }),
|
/***/ }),
|
||||||
|
|
||||||
/***/ 154:
|
/***/ 154:
|
||||||
@@ -1567,7 +1648,7 @@ module.exports.iterator = (emitter, event, options) => {
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
// rfc7231 6.1
|
// rfc7231 6.1
|
||||||
const statusCodeCacheableByDefault = [
|
const statusCodeCacheableByDefault = new Set([
|
||||||
200,
|
200,
|
||||||
203,
|
203,
|
||||||
204,
|
204,
|
||||||
@@ -1579,10 +1660,10 @@ const statusCodeCacheableByDefault = [
|
|||||||
410,
|
410,
|
||||||
414,
|
414,
|
||||||
501,
|
501,
|
||||||
];
|
]);
|
||||||
|
|
||||||
// This implementation does not understand partial responses (206)
|
// This implementation does not understand partial responses (206)
|
||||||
const understoodStatuses = [
|
const understoodStatuses = new Set([
|
||||||
200,
|
200,
|
||||||
203,
|
203,
|
||||||
204,
|
204,
|
||||||
@@ -1597,7 +1678,14 @@ const understoodStatuses = [
|
|||||||
410,
|
410,
|
||||||
414,
|
414,
|
||||||
501,
|
501,
|
||||||
];
|
]);
|
||||||
|
|
||||||
|
const errorStatusCodes = new Set([
|
||||||
|
500,
|
||||||
|
502,
|
||||||
|
503,
|
||||||
|
504,
|
||||||
|
]);
|
||||||
|
|
||||||
const hopByHopHeaders = {
|
const hopByHopHeaders = {
|
||||||
date: true, // included, because we add Age update Date
|
date: true, // included, because we add Age update Date
|
||||||
@@ -1610,6 +1698,7 @@ const hopByHopHeaders = {
|
|||||||
'transfer-encoding': true,
|
'transfer-encoding': true,
|
||||||
upgrade: true,
|
upgrade: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
const excludedFromRevalidationUpdate = {
|
const excludedFromRevalidationUpdate = {
|
||||||
// Since the old body is reused, it doesn't make sense to change properties of the body
|
// Since the old body is reused, it doesn't make sense to change properties of the body
|
||||||
'content-length': true,
|
'content-length': true,
|
||||||
@@ -1618,6 +1707,20 @@ const excludedFromRevalidationUpdate = {
|
|||||||
'content-range': true,
|
'content-range': true,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function toNumberOrZero(s) {
|
||||||
|
const n = parseInt(s, 10);
|
||||||
|
return isFinite(n) ? n : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 5861
|
||||||
|
function isErrorResponse(response) {
|
||||||
|
// consider undefined response as faulty
|
||||||
|
if(!response) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return errorStatusCodes.has(response.status);
|
||||||
|
}
|
||||||
|
|
||||||
function parseCacheControl(header) {
|
function parseCacheControl(header) {
|
||||||
const cc = {};
|
const cc = {};
|
||||||
if (!header) return cc;
|
if (!header) return cc;
|
||||||
@@ -1654,7 +1757,6 @@ module.exports = class CachePolicy {
|
|||||||
cacheHeuristic,
|
cacheHeuristic,
|
||||||
immutableMinTimeToLive,
|
immutableMinTimeToLive,
|
||||||
ignoreCargoCult,
|
ignoreCargoCult,
|
||||||
trustServerDate,
|
|
||||||
_fromObject,
|
_fromObject,
|
||||||
} = {}
|
} = {}
|
||||||
) {
|
) {
|
||||||
@@ -1670,8 +1772,6 @@ module.exports = class CachePolicy {
|
|||||||
|
|
||||||
this._responseTime = this.now();
|
this._responseTime = this.now();
|
||||||
this._isShared = shared !== false;
|
this._isShared = shared !== false;
|
||||||
this._trustServerDate =
|
|
||||||
undefined !== trustServerDate ? trustServerDate : true;
|
|
||||||
this._cacheHeuristic =
|
this._cacheHeuristic =
|
||||||
undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE
|
undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE
|
||||||
this._immutableMinTtl =
|
this._immutableMinTtl =
|
||||||
@@ -1732,7 +1832,7 @@ module.exports = class CachePolicy {
|
|||||||
'HEAD' === this._method ||
|
'HEAD' === this._method ||
|
||||||
('POST' === this._method && this._hasExplicitExpiration())) &&
|
('POST' === this._method && this._hasExplicitExpiration())) &&
|
||||||
// the response status code is understood by the cache, and
|
// the response status code is understood by the cache, and
|
||||||
understoodStatuses.indexOf(this._status) !== -1 &&
|
understoodStatuses.has(this._status) &&
|
||||||
// the "no-store" cache directive does not appear in request or response header fields, and
|
// the "no-store" cache directive does not appear in request or response header fields, and
|
||||||
!this._rescc['no-store'] &&
|
!this._rescc['no-store'] &&
|
||||||
// the "private" response directive does not appear in the response, if the cache is shared, and
|
// the "private" response directive does not appear in the response, if the cache is shared, and
|
||||||
@@ -1751,7 +1851,7 @@ module.exports = class CachePolicy {
|
|||||||
(this._isShared && this._rescc['s-maxage']) ||
|
(this._isShared && this._rescc['s-maxage']) ||
|
||||||
this._rescc.public ||
|
this._rescc.public ||
|
||||||
// has a status code that is defined as cacheable by default
|
// has a status code that is defined as cacheable by default
|
||||||
statusCodeCacheableByDefault.indexOf(this._status) !== -1)
|
statusCodeCacheableByDefault.has(this._status))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1898,24 +1998,13 @@ module.exports = class CachePolicy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Value of the Date response header or current time if Date was demed invalid
|
* Value of the Date response header or current time if Date was invalid
|
||||||
* @return timestamp
|
* @return timestamp
|
||||||
*/
|
*/
|
||||||
date() {
|
date() {
|
||||||
if (this._trustServerDate) {
|
|
||||||
return this._serverDate();
|
|
||||||
}
|
|
||||||
return this._responseTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
_serverDate() {
|
|
||||||
const serverDate = Date.parse(this._resHeaders.date);
|
const serverDate = Date.parse(this._resHeaders.date);
|
||||||
if (isFinite(serverDate)) {
|
if (isFinite(serverDate)) {
|
||||||
const maxClockDrift = 8 * 3600 * 1000;
|
return serverDate;
|
||||||
const clockDrift = Math.abs(this._responseTime - serverDate);
|
|
||||||
if (clockDrift < maxClockDrift) {
|
|
||||||
return serverDate;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return this._responseTime;
|
return this._responseTime;
|
||||||
}
|
}
|
||||||
@@ -1927,19 +2016,14 @@ module.exports = class CachePolicy {
|
|||||||
* @return Number
|
* @return Number
|
||||||
*/
|
*/
|
||||||
age() {
|
age() {
|
||||||
let age = Math.max(0, (this._responseTime - this.date()) / 1000);
|
let age = this._ageValue();
|
||||||
if (this._resHeaders.age) {
|
|
||||||
let ageValue = this._ageValue();
|
|
||||||
if (ageValue > age) age = ageValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const residentTime = (this.now() - this._responseTime) / 1000;
|
const residentTime = (this.now() - this._responseTime) / 1000;
|
||||||
return age + residentTime;
|
return age + residentTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
_ageValue() {
|
_ageValue() {
|
||||||
const ageValue = parseInt(this._resHeaders.age);
|
return toNumberOrZero(this._resHeaders.age);
|
||||||
return isFinite(ageValue) ? ageValue : 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1975,18 +2059,18 @@ module.exports = class CachePolicy {
|
|||||||
}
|
}
|
||||||
// if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field.
|
// if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field.
|
||||||
if (this._rescc['s-maxage']) {
|
if (this._rescc['s-maxage']) {
|
||||||
return parseInt(this._rescc['s-maxage'], 10);
|
return toNumberOrZero(this._rescc['s-maxage']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.
|
// If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.
|
||||||
if (this._rescc['max-age']) {
|
if (this._rescc['max-age']) {
|
||||||
return parseInt(this._rescc['max-age'], 10);
|
return toNumberOrZero(this._rescc['max-age']);
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;
|
const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;
|
||||||
|
|
||||||
const serverDate = this._serverDate();
|
const serverDate = this.date();
|
||||||
if (this._resHeaders.expires) {
|
if (this._resHeaders.expires) {
|
||||||
const expires = Date.parse(this._resHeaders.expires);
|
const expires = Date.parse(this._resHeaders.expires);
|
||||||
// A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired").
|
// A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired").
|
||||||
@@ -2010,13 +2094,24 @@ module.exports = class CachePolicy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
timeToLive() {
|
timeToLive() {
|
||||||
return Math.max(0, this.maxAge() - this.age()) * 1000;
|
const age = this.maxAge() - this.age();
|
||||||
|
const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']);
|
||||||
|
const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']);
|
||||||
|
return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
stale() {
|
stale() {
|
||||||
return this.maxAge() <= this.age();
|
return this.maxAge() <= this.age();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_useStaleIfError() {
|
||||||
|
return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age();
|
||||||
|
}
|
||||||
|
|
||||||
|
useStaleWhileRevalidate() {
|
||||||
|
return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age();
|
||||||
|
}
|
||||||
|
|
||||||
static fromObject(obj) {
|
static fromObject(obj) {
|
||||||
return new this(undefined, undefined, { _fromObject: obj });
|
return new this(undefined, undefined, { _fromObject: obj });
|
||||||
}
|
}
|
||||||
@@ -2134,6 +2229,13 @@ module.exports = class CachePolicy {
|
|||||||
*/
|
*/
|
||||||
revalidatedPolicy(request, response) {
|
revalidatedPolicy(request, response) {
|
||||||
this._assertRequestHasHeaders(request);
|
this._assertRequestHasHeaders(request);
|
||||||
|
if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful
|
||||||
|
return {
|
||||||
|
modified: false,
|
||||||
|
matches: false,
|
||||||
|
policy: this,
|
||||||
|
};
|
||||||
|
}
|
||||||
if (!response || !response.headers) {
|
if (!response || !response.headers) {
|
||||||
throw Error('Response headers missing');
|
throw Error('Response headers missing');
|
||||||
}
|
}
|
||||||
@@ -2211,7 +2313,6 @@ module.exports = class CachePolicy {
|
|||||||
shared: this._isShared,
|
shared: this._isShared,
|
||||||
cacheHeuristic: this._cacheHeuristic,
|
cacheHeuristic: this._cacheHeuristic,
|
||||||
immutableMinTimeToLive: this._immutableMinTtl,
|
immutableMinTimeToLive: this._immutableMinTtl,
|
||||||
trustServerDate: this._trustServerDate,
|
|
||||||
}),
|
}),
|
||||||
modified: false,
|
modified: false,
|
||||||
matches: true,
|
matches: true,
|
||||||
@@ -2881,19 +2982,21 @@ const create = (defaults) => {
|
|||||||
const result = await got(normalizedOptions);
|
const result = await got(normalizedOptions);
|
||||||
// eslint-disable-next-line no-await-in-loop
|
// eslint-disable-next-line no-await-in-loop
|
||||||
const parsed = await pagination.transform(result);
|
const parsed = await pagination.transform(result);
|
||||||
|
const current = [];
|
||||||
for (const item of parsed) {
|
for (const item of parsed) {
|
||||||
if (pagination.filter(item, all)) {
|
if (pagination.filter(item, all, current)) {
|
||||||
if (!pagination.shouldContinue(item, all)) {
|
if (!pagination.shouldContinue(item, all, current)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
yield item;
|
yield item;
|
||||||
all.push(item);
|
all.push(item);
|
||||||
|
current.push(item);
|
||||||
if (all.length === pagination.countLimit) {
|
if (all.length === pagination.countLimit) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const optionsToMerge = pagination.paginate(result);
|
const optionsToMerge = pagination.paginate(result, all, current);
|
||||||
if (optionsToMerge === false) {
|
if (optionsToMerge === false) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -3146,7 +3249,7 @@ function asStream(options) {
|
|||||||
throw new Error('Got\'s stream is not writable when the `body`, `json` or `form` option is used');
|
throw new Error('Got\'s stream is not writable when the `body`, `json` or `form` option is used');
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
else if (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH') {
|
else if (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH' || (options.allowGetBody && options.method === 'GET')) {
|
||||||
options.body = input;
|
options.body = input;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -3551,6 +3654,13 @@ exports.setFailed = setFailed;
|
|||||||
//-----------------------------------------------------------------------
|
//-----------------------------------------------------------------------
|
||||||
// Logging Commands
|
// Logging Commands
|
||||||
//-----------------------------------------------------------------------
|
//-----------------------------------------------------------------------
|
||||||
|
/**
|
||||||
|
* Gets whether Actions Step Debug is on or not
|
||||||
|
*/
|
||||||
|
function isDebug() {
|
||||||
|
return process.env['RUNNER_DEBUG'] === '1';
|
||||||
|
}
|
||||||
|
exports.isDebug = isDebug;
|
||||||
/**
|
/**
|
||||||
* Writes debug message to user log
|
* Writes debug message to user log
|
||||||
* @param message debug message
|
* @param message debug message
|
||||||
@@ -4609,6 +4719,22 @@ module.exports = require("util");
|
|||||||
|
|
||||||
/***/ }),
|
/***/ }),
|
||||||
|
|
||||||
|
/***/ 676:
|
||||||
|
/***/ (function(__unusedmodule, __unusedexports, __webpack_require__) {
|
||||||
|
|
||||||
|
const core = __webpack_require__(470);
|
||||||
|
const { exportSecrets } = __webpack_require__(928);
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
await core.group('Get Vault Secrets', exportSecrets);
|
||||||
|
} catch (error) {
|
||||||
|
core.setFailed(error.message);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
/***/ }),
|
||||||
|
|
||||||
/***/ 678:
|
/***/ 678:
|
||||||
/***/ (function(__unusedmodule, exports, __webpack_require__) {
|
/***/ (function(__unusedmodule, exports, __webpack_require__) {
|
||||||
|
|
||||||
@@ -4834,221 +4960,6 @@ module.exports.DuplexWrapper = DuplexWrapper;
|
|||||||
|
|
||||||
module.exports = require("fs");
|
module.exports = require("fs");
|
||||||
|
|
||||||
/***/ }),
|
|
||||||
|
|
||||||
/***/ 751:
|
|
||||||
/***/ (function(module, __unusedexports, __webpack_require__) {
|
|
||||||
|
|
||||||
const core = __webpack_require__(470);
|
|
||||||
const command = __webpack_require__(431);
|
|
||||||
const got = __webpack_require__(77);
|
|
||||||
|
|
||||||
const AUTH_METHODS = ['approle', 'token'];
|
|
||||||
const VALID_KV_VERSION = [-1, 1, 2];
|
|
||||||
|
|
||||||
async function exportSecrets() {
|
|
||||||
const vaultUrl = core.getInput('url', { required: true });
|
|
||||||
const vaultNamespace = core.getInput('namespace', { required: false });
|
|
||||||
|
|
||||||
let enginePath = core.getInput('path', { required: false });
|
|
||||||
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';
|
|
||||||
if (!AUTH_METHODS.includes(vaultMethod)) {
|
|
||||||
throw Error(`Sorry, the authentication method ${vaultMethod} is not currently supported.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
let vaultToken = null;
|
|
||||||
switch (vaultMethod) {
|
|
||||||
case 'approle':
|
|
||||||
const vaultRoleId = core.getInput('roleId', { required: true });
|
|
||||||
const vaultSecretId = core.getInput('secretId', { required: true });
|
|
||||||
core.debug('Try to retrieve Vault Token from approle');
|
|
||||||
var options = {
|
|
||||||
headers: {},
|
|
||||||
json: { role_id: vaultRoleId, secret_id: vaultSecretId },
|
|
||||||
responseType: 'json'
|
|
||||||
};
|
|
||||||
|
|
||||||
if (vaultNamespace != null) {
|
|
||||||
options.headers["X-Vault-Namespace"] = vaultNamespace;
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await got.post(`${vaultUrl}/v1/auth/approle/login`, options);
|
|
||||||
if (result && result.body && result.body.auth && result.body.auth.client_token) {
|
|
||||||
vaultToken = result.body.auth.client_token;
|
|
||||||
core.debug('✔ Vault Token has retrieved from approle');
|
|
||||||
} else {
|
|
||||||
throw Error(`No token was retrieved with the role_id and secret_id provided.`);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
vaultToken = core.getInput('token', { required: true });
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
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 responseCache = new Map();
|
|
||||||
for (const secretRequest of secretRequests) {
|
|
||||||
const { secretPath, outputName, secretSelector, isJSONPath } = secretRequest;
|
|
||||||
const requestOptions = {
|
|
||||||
headers: {
|
|
||||||
'X-Vault-Token': vaultToken
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
if (vaultNamespace != null) {
|
|
||||||
requestOptions.headers["X-Vault-Namespace"] = vaultNamespace;
|
|
||||||
}
|
|
||||||
|
|
||||||
let requestPath = `${vaultUrl}/v1`;
|
|
||||||
const kvRequest = !secretPath.startsWith('/')
|
|
||||||
if (!kvRequest) {
|
|
||||||
requestPath += secretPath;
|
|
||||||
} else {
|
|
||||||
requestPath += (kvVersion === 2)
|
|
||||||
? `/${enginePath}/data/${secretPath}`
|
|
||||||
: `/${enginePath}/${secretPath}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
let body;
|
|
||||||
if (responseCache.has(requestPath)) {
|
|
||||||
body = responseCache.get(requestPath);
|
|
||||||
core.debug('ℹ using cached response');
|
|
||||||
} else {
|
|
||||||
const result = await got(requestPath, requestOptions);
|
|
||||||
body = result.body;
|
|
||||||
responseCache.set(requestPath, body);
|
|
||||||
}
|
|
||||||
|
|
||||||
let dataDepth = isJSONPath === true ? 0 : kvRequest === false ? 1 : kvVersion;
|
|
||||||
|
|
||||||
const secretData = getResponseData(body, dataDepth);
|
|
||||||
const value = selectData(secretData, secretSelector);
|
|
||||||
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, secretSelector] = pathParts;
|
|
||||||
|
|
||||||
// If we're not using a mapped name, normalize the key path into a variable name.
|
|
||||||
if (!outputName) {
|
|
||||||
outputName = normalizeOutputKey(secretSelector);
|
|
||||||
}
|
|
||||||
|
|
||||||
output.push({
|
|
||||||
secretPath,
|
|
||||||
outputName,
|
|
||||||
secretSelector,
|
|
||||||
isJSONPath: secretSelector.startsWith('$')
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return output;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parses a JSON response and returns the secret data
|
|
||||||
* @param {string} responseBody
|
|
||||||
* @param {number} kvVersion
|
|
||||||
*/
|
|
||||||
function getResponseData(responseBody, dataLevel) {
|
|
||||||
let secretData = JSON.parse(responseBody);
|
|
||||||
|
|
||||||
for (let i = 0; i < dataLevel; i++) {
|
|
||||||
secretData = secretData['data'];
|
|
||||||
}
|
|
||||||
return secretData;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parses a JSON response and returns the secret data
|
|
||||||
* @param {Object} data
|
|
||||||
* @param {string} selector
|
|
||||||
*/
|
|
||||||
function selectData(data, selector, isJSONPath) {
|
|
||||||
if (!isJSONPath) {
|
|
||||||
return data[selector];
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: JSONPath
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Replaces any forward-slash characters to
|
|
||||||
* @param {string} dataKey
|
|
||||||
*/
|
|
||||||
function normalizeOutputKey(dataKey) {
|
|
||||||
return dataKey.replace('/', '__').replace(/[^\w-]/, '').toUpperCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseBoolInput(input) {
|
|
||||||
if (input === null || input === undefined || input.trim() === '') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return Boolean(input);
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
exportSecrets,
|
|
||||||
parseSecretsInput,
|
|
||||||
parseResponse: getResponseData,
|
|
||||||
normalizeOutputKey
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
/***/ }),
|
/***/ }),
|
||||||
|
|
||||||
/***/ 753:
|
/***/ 753:
|
||||||
@@ -5816,6 +5727,256 @@ exports.proxyEvents = (proxy, emitter) => {
|
|||||||
|
|
||||||
module.exports = require("dns");
|
module.exports = require("dns");
|
||||||
|
|
||||||
|
/***/ }),
|
||||||
|
|
||||||
|
/***/ 928:
|
||||||
|
/***/ (function(module, __unusedexports, __webpack_require__) {
|
||||||
|
|
||||||
|
// @ts-check
|
||||||
|
const core = __webpack_require__(470);
|
||||||
|
const command = __webpack_require__(431);
|
||||||
|
const got = __webpack_require__(77).default;
|
||||||
|
const { retrieveToken } = __webpack_require__(151);
|
||||||
|
|
||||||
|
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 client = got.extend(defaultOptions);
|
||||||
|
const vaultToken = await retrieveToken(vaultMethod, client);
|
||||||
|
|
||||||
|
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 responseCache = new Map();
|
||||||
|
for (const secretRequest of secretRequests) {
|
||||||
|
const { secretPath, outputVarName, envVarName, secretSelector, isJSONPath } = secretRequest;
|
||||||
|
const requestOptions = {
|
||||||
|
headers: {
|
||||||
|
'X-Vault-Token': vaultToken
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const [headerName, headerValue] of extraHeaders) {
|
||||||
|
requestOptions.headers[headerName] = headerValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vaultNamespace != null) {
|
||||||
|
requestOptions.headers["X-Vault-Namespace"] = vaultNamespace;
|
||||||
|
}
|
||||||
|
|
||||||
|
let requestPath = `v1`;
|
||||||
|
const kvRequest = !secretPath.startsWith('/')
|
||||||
|
if (!kvRequest) {
|
||||||
|
requestPath += secretPath;
|
||||||
|
} else {
|
||||||
|
requestPath += (kvVersion === 2)
|
||||||
|
? `/${enginePath}/data/${secretPath}`
|
||||||
|
: `/${enginePath}/${secretPath}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
let body;
|
||||||
|
if (responseCache.has(requestPath)) {
|
||||||
|
body = responseCache.get(requestPath);
|
||||||
|
core.debug('ℹ using cached response');
|
||||||
|
} else {
|
||||||
|
const result = await client.get(requestPath, requestOptions);
|
||||||
|
body = result.body;
|
||||||
|
responseCache.set(requestPath, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
let dataDepth = isJSONPath === true ? 0 : kvRequest === false ? 1 : kvVersion;
|
||||||
|
|
||||||
|
const secretData = getResponseData(body, dataDepth);
|
||||||
|
const value = selectData(secretData, secretSelector, isJSONPath);
|
||||||
|
command.issue('add-mask', value);
|
||||||
|
if (exportEnv) {
|
||||||
|
core.exportVariable(envVarName, `${value}`);
|
||||||
|
}
|
||||||
|
core.setOutput(outputVarName, `${value}`);
|
||||||
|
core.debug(`✔ ${secretPath} => outputs.${outputVarName}${exportEnv ? ` | env.${envVarName}` : ''}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** @typedef {Object} SecretRequest
|
||||||
|
* @property {string} secretPath
|
||||||
|
* @property {string} envVarName
|
||||||
|
* @property {string} outputVarName
|
||||||
|
* @property {string} secretSelector
|
||||||
|
* @property {boolean} isJSONPath
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 path = secret;
|
||||||
|
let outputVarName = null;
|
||||||
|
|
||||||
|
const renameSigilIndex = secret.lastIndexOf('|');
|
||||||
|
if (renameSigilIndex > -1) {
|
||||||
|
path = 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 = 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, secretSelector] = pathParts;
|
||||||
|
|
||||||
|
const isJSONPath = secretSelector.includes('.');
|
||||||
|
|
||||||
|
if (isJSONPath && !outputVarName) {
|
||||||
|
throw Error(`You must provide a name for the output key when using json selectors. Input: "${secret}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
let envVarName = outputVarName;
|
||||||
|
if (!outputVarName) {
|
||||||
|
outputVarName = secretSelector;
|
||||||
|
envVarName = normalizeOutputKey(outputVarName);
|
||||||
|
}
|
||||||
|
|
||||||
|
output.push({
|
||||||
|
secretPath,
|
||||||
|
envVarName,
|
||||||
|
outputVarName,
|
||||||
|
secretSelector,
|
||||||
|
isJSONPath
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a JSON response and returns the secret data
|
||||||
|
* @param {string} responseBody
|
||||||
|
* @param {number} dataLevel
|
||||||
|
*/
|
||||||
|
function getResponseData(responseBody, dataLevel) {
|
||||||
|
let secretData = JSON.parse(responseBody);
|
||||||
|
|
||||||
|
for (let i = 0; i < dataLevel; i++) {
|
||||||
|
secretData = secretData['data'];
|
||||||
|
}
|
||||||
|
return secretData;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a JSON response and returns the secret data
|
||||||
|
* @param {Object} data
|
||||||
|
* @param {string} selector
|
||||||
|
*/
|
||||||
|
function selectData(data, selector, isJSONPath) {
|
||||||
|
if (!isJSONPath) {
|
||||||
|
return data[selector];
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: JSONPath
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces any forward-slash characters to
|
||||||
|
* @param {string} dataKey
|
||||||
|
*/
|
||||||
|
function normalizeOutputKey(dataKey) {
|
||||||
|
return dataKey.replace('/', '__').replace(/[^\w-]/, '').toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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,
|
||||||
|
parseResponse: getResponseData,
|
||||||
|
normalizeOutputKey,
|
||||||
|
parseHeadersInput
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
/***/ }),
|
/***/ }),
|
||||||
|
|
||||||
/***/ 946:
|
/***/ 946:
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ const core = require('@actions/core');
|
|||||||
const got = require('got');
|
const got = require('got');
|
||||||
const { when } = require('jest-when');
|
const { when } = require('jest-when');
|
||||||
|
|
||||||
const { exportSecrets } = require('../../action');
|
const { exportSecrets } = require('../../src/action');
|
||||||
|
|
||||||
const vaultUrl = `http://${process.env.VAULT_HOST || 'localhost'}:${process.env.VAULT_PORT || '8200'}`;
|
const vaultUrl = `http://${process.env.VAULT_HOST || 'localhost'}:${process.env.VAULT_PORT || '8200'}`;
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ describe('e2e', () => {
|
|||||||
expect(process.env.SECRET).toBe("SUPERSECRET");
|
expect(process.env.SECRET).toBe("SUPERSECRET");
|
||||||
expect(process.env.NAMED_SECRET).toBe("SUPERSECRET");
|
expect(process.env.NAMED_SECRET).toBe("SUPERSECRET");
|
||||||
expect(process.env.OTHERSECRET).toBe("OTHERSUPERSECRET");
|
expect(process.env.OTHERSECRET).toBe("OTHERSUPERSECRET");
|
||||||
|
expect(process.env.OTHER_SECRET_OUTPUT).toBe("OTHERSUPERSECRET");
|
||||||
expect(process.env.ALTSECRET).toBe("CUSTOMSECRET");
|
expect(process.env.ALTSECRET).toBe("CUSTOMSECRET");
|
||||||
expect(process.env.NAMED_ALTSECRET).toBe("CUSTOMSECRET");
|
expect(process.env.NAMED_ALTSECRET).toBe("CUSTOMSECRET");
|
||||||
expect(process.env.OTHERALTSECRET).toBe("OTHERCUSTOMSECRET");
|
expect(process.env.OTHERALTSECRET).toBe("OTHERCUSTOMSECRET");
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ const core = require('@actions/core');
|
|||||||
const got = require('got');
|
const got = require('got');
|
||||||
const { when } = require('jest-when');
|
const { when } = require('jest-when');
|
||||||
|
|
||||||
const { exportSecrets } = require('../../action');
|
const { exportSecrets } = require('../../src/action');
|
||||||
|
|
||||||
const vaultUrl = `http://${process.env.VAULT_HOST || 'localhost'}:${process.env.VAULT_PORT || '8201'}`;
|
const vaultUrl = `http://${process.env.VAULT_HOST || 'localhost'}:${process.env.VAULT_PORT || '8201'}`;
|
||||||
|
|
||||||
@@ -212,7 +212,7 @@ describe('authenticate with approle', () => {
|
|||||||
jest.resetAllMocks();
|
jest.resetAllMocks();
|
||||||
|
|
||||||
when(core.getInput)
|
when(core.getInput)
|
||||||
.calledWith('method')
|
.calledWith('method', expect.anything())
|
||||||
.mockReturnValueOnce('approle');
|
.mockReturnValueOnce('approle');
|
||||||
when(core.getInput)
|
when(core.getInput)
|
||||||
.calledWith('roleId')
|
.calledWith('roleId')
|
||||||
@@ -228,7 +228,7 @@ describe('authenticate with approle', () => {
|
|||||||
.mockReturnValueOnce('ns2');
|
.mockReturnValueOnce('ns2');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('authenticate with approle', async()=> {
|
it('authenticate with approle', async() => {
|
||||||
mockInput('test secret');
|
mockInput('test secret');
|
||||||
|
|
||||||
await exportSecrets();
|
await exportSecrets();
|
||||||
|
|||||||
Generated
+2275
-1885
File diff suppressed because it is too large
Load Diff
+7
-6
@@ -4,7 +4,7 @@
|
|||||||
"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/index.js -o dist",
|
||||||
"test": "jest",
|
"test": "jest",
|
||||||
"test:integration:basic": "jest -c integrationTests/basic/jest.config.js",
|
"test:integration:basic": "jest -c integrationTests/basic/jest.config.js",
|
||||||
"test:integration:enterprise": "jest -c integrationTests/enterprise/jest.config.js",
|
"test:integration:enterprise": "jest -c integrationTests/enterprise/jest.config.js",
|
||||||
@@ -38,14 +38,15 @@
|
|||||||
},
|
},
|
||||||
"homepage": "https://github.com/RichiCoder1/vault-action#readme",
|
"homepage": "https://github.com/RichiCoder1/vault-action#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@actions/core": "^1.2.2",
|
"got": "^10.2.2",
|
||||||
"got": "^10.2.2"
|
"@actions/core": "^1.2.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/jest": "^24.0.18",
|
"@types/got": "^9.6.9",
|
||||||
"@zeit/ncc": "^0.21.1",
|
"@types/jest": "^25.1.3",
|
||||||
|
"@zeit/ncc": "^0.22.0",
|
||||||
"jest": "^25.1.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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+90
-55
@@ -1,54 +1,47 @@
|
|||||||
|
// @ts-check
|
||||||
const core = require('@actions/core');
|
const core = require('@actions/core');
|
||||||
const command = require('@actions/core/lib/command');
|
const command = require('@actions/core/lib/command');
|
||||||
const got = require('got');
|
const got = require('got').default;
|
||||||
|
const { retrieveToken } = require('./auth');
|
||||||
|
|
||||||
const AUTH_METHODS = ['approle', 'token'];
|
const AUTH_METHODS = ['approle', 'token', 'github'];
|
||||||
const VALID_KV_VERSION = [-1, 1, 2];
|
const VALID_KV_VERSION = [-1, 1, 2];
|
||||||
|
|
||||||
async function exportSecrets() {
|
async function exportSecrets() {
|
||||||
const vaultUrl = core.getInput('url', { required: true });
|
const vaultUrl = core.getInput('url', { required: true });
|
||||||
const vaultNamespace = core.getInput('namespace', { required: false });
|
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 });
|
let enginePath = core.getInput('path', { required: false });
|
||||||
|
/** @type {number | string} */
|
||||||
let kvVersion = core.getInput('kv-version', { required: false });
|
let kvVersion = core.getInput('kv-version', { required: false });
|
||||||
|
|
||||||
const secretsInput = core.getInput('secrets', { required: true });
|
const secretsInput = core.getInput('secrets', { required: true });
|
||||||
const secretRequests = parseSecretsInput(secretsInput);
|
const secretRequests = parseSecretsInput(secretsInput);
|
||||||
|
|
||||||
const vaultMethod = core.getInput('method', { required: false }) || 'token';
|
const vaultMethod = (core.getInput('method', { required: false }) || 'token').toLowerCase();
|
||||||
if (!AUTH_METHODS.includes(vaultMethod)) {
|
const authPayload = core.getInput('authPayload', { required: false });
|
||||||
throw Error(`Sorry, the authentication method ${vaultMethod} is not currently supported.`);
|
if (!AUTH_METHODS.includes(vaultMethod) && !authPayload) {
|
||||||
|
throw Error(`Sorry, the provided authentication method ${vaultMethod} is not currently supported and no custom authPayload was provided.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
let vaultToken = null;
|
const defaultOptions = {
|
||||||
switch (vaultMethod) {
|
prefixUrl: vaultUrl,
|
||||||
case 'approle':
|
headers: {}
|
||||||
const vaultRoleId = core.getInput('roleId', { required: true });
|
|
||||||
const vaultSecretId = core.getInput('secretId', { required: true });
|
|
||||||
core.debug('Try to retrieve Vault Token from approle');
|
|
||||||
var options = {
|
|
||||||
headers: {},
|
|
||||||
json: { role_id: vaultRoleId, secret_id: vaultSecretId },
|
|
||||||
responseType: 'json'
|
|
||||||
};
|
|
||||||
|
|
||||||
if (vaultNamespace != null) {
|
|
||||||
options.headers["X-Vault-Namespace"] = vaultNamespace;
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await got.post(`${vaultUrl}/v1/auth/approle/login`, options);
|
|
||||||
if (result && result.body && result.body.auth && result.body.auth.client_token) {
|
|
||||||
vaultToken = result.body.auth.client_token;
|
|
||||||
core.debug('✔ Vault Token has retrieved from approle');
|
|
||||||
} else {
|
|
||||||
throw Error(`No token was retrieved with the role_id and secret_id provided.`);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
vaultToken = core.getInput('token', { required: true });
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const [headerName, headerValue] of extraHeaders) {
|
||||||
|
defaultOptions.headers[headerName] = headerValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vaultNamespace != null) {
|
||||||
|
defaultOptions.headers["X-Vault-Namespace"] = vaultNamespace;
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = got.extend(defaultOptions);
|
||||||
|
const vaultToken = await retrieveToken(vaultMethod, client);
|
||||||
|
|
||||||
if (!enginePath) {
|
if (!enginePath) {
|
||||||
enginePath = 'secret';
|
enginePath = 'secret';
|
||||||
}
|
}
|
||||||
@@ -64,18 +57,22 @@ async function exportSecrets() {
|
|||||||
|
|
||||||
const responseCache = new Map();
|
const responseCache = new Map();
|
||||||
for (const secretRequest of secretRequests) {
|
for (const secretRequest of secretRequests) {
|
||||||
const { secretPath, outputName, secretSelector, isJSONPath } = secretRequest;
|
const { secretPath, outputVarName, envVarName, secretSelector, isJSONPath } = secretRequest;
|
||||||
const requestOptions = {
|
const requestOptions = {
|
||||||
headers: {
|
headers: {
|
||||||
'X-Vault-Token': vaultToken
|
'X-Vault-Token': vaultToken
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
for (const [headerName, headerValue] of extraHeaders) {
|
||||||
|
requestOptions.headers[headerName] = headerValue;
|
||||||
|
}
|
||||||
|
|
||||||
if (vaultNamespace != null) {
|
if (vaultNamespace != null) {
|
||||||
requestOptions.headers["X-Vault-Namespace"] = vaultNamespace;
|
requestOptions.headers["X-Vault-Namespace"] = vaultNamespace;
|
||||||
}
|
}
|
||||||
|
|
||||||
let requestPath = `${vaultUrl}/v1`;
|
let requestPath = `v1`;
|
||||||
const kvRequest = !secretPath.startsWith('/')
|
const kvRequest = !secretPath.startsWith('/')
|
||||||
if (!kvRequest) {
|
if (!kvRequest) {
|
||||||
requestPath += secretPath;
|
requestPath += secretPath;
|
||||||
@@ -90,7 +87,7 @@ async function exportSecrets() {
|
|||||||
body = responseCache.get(requestPath);
|
body = responseCache.get(requestPath);
|
||||||
core.debug('ℹ using cached response');
|
core.debug('ℹ using cached response');
|
||||||
} else {
|
} else {
|
||||||
const result = await got(requestPath, requestOptions);
|
const result = await client.get(requestPath, requestOptions);
|
||||||
body = result.body;
|
body = result.body;
|
||||||
responseCache.set(requestPath, body);
|
responseCache.set(requestPath, body);
|
||||||
}
|
}
|
||||||
@@ -98,13 +95,24 @@ async function exportSecrets() {
|
|||||||
let dataDepth = isJSONPath === true ? 0 : kvRequest === false ? 1 : kvVersion;
|
let dataDepth = isJSONPath === true ? 0 : kvRequest === false ? 1 : kvVersion;
|
||||||
|
|
||||||
const secretData = getResponseData(body, dataDepth);
|
const secretData = getResponseData(body, dataDepth);
|
||||||
const value = selectData(secretData, secretSelector);
|
const value = selectData(secretData, secretSelector, isJSONPath);
|
||||||
command.issue('add-mask', value);
|
command.issue('add-mask', value);
|
||||||
core.exportVariable(outputName, `${value}`);
|
if (exportEnv) {
|
||||||
core.debug(`✔ ${secretPath} => ${outputName}`);
|
core.exportVariable(envVarName, `${value}`);
|
||||||
|
}
|
||||||
|
core.setOutput(outputVarName, `${value}`);
|
||||||
|
core.debug(`✔ ${secretPath} => outputs.${outputVarName}${exportEnv ? ` | env.${envVarName}` : ''}`);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** @typedef {Object} SecretRequest
|
||||||
|
* @property {string} secretPath
|
||||||
|
* @property {string} envVarName
|
||||||
|
* @property {string} outputVarName
|
||||||
|
* @property {string} secretSelector
|
||||||
|
* @property {boolean} isJSONPath
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parses a secrets input string into key paths and their resulting environment variable name.
|
* Parses a secrets input string into key paths and their resulting environment variable name.
|
||||||
* @param {string} secretsInput
|
* @param {string} secretsInput
|
||||||
@@ -116,18 +124,18 @@ function parseSecretsInput(secretsInput) {
|
|||||||
.map(key => key.trim())
|
.map(key => key.trim())
|
||||||
.filter(key => key.length !== 0);
|
.filter(key => key.length !== 0);
|
||||||
|
|
||||||
/** @type {{ secretPath: string; outputName: string; dataKey: string; }[]} */
|
/** @type {SecretRequest[]} */
|
||||||
const output = [];
|
const output = [];
|
||||||
for (const secret of secrets) {
|
for (const secret of secrets) {
|
||||||
let path = secret;
|
let path = secret;
|
||||||
let outputName = null;
|
let outputVarName = null;
|
||||||
|
|
||||||
const renameSigilIndex = secret.lastIndexOf('|');
|
const renameSigilIndex = secret.lastIndexOf('|');
|
||||||
if (renameSigilIndex > -1) {
|
if (renameSigilIndex > -1) {
|
||||||
path = secret.substring(0, renameSigilIndex).trim();
|
path = secret.substring(0, renameSigilIndex).trim();
|
||||||
outputName = secret.substring(renameSigilIndex + 1).trim();
|
outputVarName = secret.substring(renameSigilIndex + 1).trim();
|
||||||
|
|
||||||
if (outputName.length < 1) {
|
if (outputVarName.length < 1) {
|
||||||
throw Error(`You must provide a value when mapping a secret to a name. Input: "${secret}"`);
|
throw Error(`You must provide a value when mapping a secret to a name. Input: "${secret}"`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -138,21 +146,29 @@ function parseSecretsInput(secretsInput) {
|
|||||||
.filter(part => part.length !== 0);
|
.filter(part => part.length !== 0);
|
||||||
|
|
||||||
if (pathParts.length !== 2) {
|
if (pathParts.length !== 2) {
|
||||||
throw Error(`You must provide a valid path and key. Input: "${secret}"`)
|
throw Error(`You must provide a valid path and key. Input: "${secret}"`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const [secretPath, secretSelector] = pathParts;
|
const [secretPath, secretSelector] = pathParts;
|
||||||
|
|
||||||
// If we're not using a mapped name, normalize the key path into a variable name.
|
const isJSONPath = secretSelector.includes('.');
|
||||||
if (!outputName) {
|
|
||||||
outputName = normalizeOutputKey(secretSelector);
|
if (isJSONPath && !outputVarName) {
|
||||||
|
throw Error(`You must provide a name for the output key when using json selectors. Input: "${secret}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
let envVarName = outputVarName;
|
||||||
|
if (!outputVarName) {
|
||||||
|
outputVarName = secretSelector;
|
||||||
|
envVarName = normalizeOutputKey(outputVarName);
|
||||||
}
|
}
|
||||||
|
|
||||||
output.push({
|
output.push({
|
||||||
secretPath,
|
secretPath,
|
||||||
outputName,
|
envVarName,
|
||||||
|
outputVarName,
|
||||||
secretSelector,
|
secretSelector,
|
||||||
isJSONPath: secretSelector.startsWith('$')
|
isJSONPath
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return output;
|
return output;
|
||||||
@@ -161,7 +177,7 @@ function parseSecretsInput(secretsInput) {
|
|||||||
/**
|
/**
|
||||||
* Parses a JSON response and returns the secret data
|
* Parses a JSON response and returns the secret data
|
||||||
* @param {string} responseBody
|
* @param {string} responseBody
|
||||||
* @param {number} kvVersion
|
* @param {number} dataLevel
|
||||||
*/
|
*/
|
||||||
function getResponseData(responseBody, dataLevel) {
|
function getResponseData(responseBody, dataLevel) {
|
||||||
let secretData = JSON.parse(responseBody);
|
let secretData = JSON.parse(responseBody);
|
||||||
@@ -193,16 +209,35 @@ function normalizeOutputKey(dataKey) {
|
|||||||
return dataKey.replace('/', '__').replace(/[^\w-]/, '').toUpperCase();
|
return dataKey.replace('/', '__').replace(/[^\w-]/, '').toUpperCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseBoolInput(input) {
|
/**
|
||||||
if (input === null || input === undefined || input.trim() === '') {
|
* @param {string} inputKey
|
||||||
return null;
|
* @param {any} inputOptions
|
||||||
}
|
*/
|
||||||
return Boolean(input);
|
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 = {
|
module.exports = {
|
||||||
exportSecrets,
|
exportSecrets,
|
||||||
parseSecretsInput,
|
parseSecretsInput,
|
||||||
parseResponse: getResponseData,
|
parseResponse: getResponseData,
|
||||||
normalizeOutputKey
|
normalizeOutputKey,
|
||||||
|
parseHeadersInput
|
||||||
};
|
};
|
||||||
@@ -7,7 +7,8 @@ const got = require('got');
|
|||||||
const {
|
const {
|
||||||
exportSecrets,
|
exportSecrets,
|
||||||
parseSecretsInput,
|
parseSecretsInput,
|
||||||
parseResponse
|
parseResponse,
|
||||||
|
parseHeadersInput
|
||||||
} = require('./action');
|
} = require('./action');
|
||||||
|
|
||||||
const { when } = require('jest-when');
|
const { when } = require('jest-when');
|
||||||
@@ -18,7 +19,8 @@ describe('parseSecretsInput', () => {
|
|||||||
expect(output).toContainEqual({
|
expect(output).toContainEqual({
|
||||||
secretPath: 'test',
|
secretPath: 'test',
|
||||||
secretSelector: 'key',
|
secretSelector: 'key',
|
||||||
outputName: 'KEY',
|
outputVarName: 'key',
|
||||||
|
envVarName: 'KEY',
|
||||||
isJSONPath: false
|
isJSONPath: false
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -27,7 +29,8 @@ describe('parseSecretsInput', () => {
|
|||||||
const output = parseSecretsInput('test key|testName');
|
const output = parseSecretsInput('test key|testName');
|
||||||
expect(output).toHaveLength(1);
|
expect(output).toHaveLength(1);
|
||||||
expect(output[0]).toMatchObject({
|
expect(output[0]).toMatchObject({
|
||||||
outputName: 'testName',
|
outputVarName: 'testName',
|
||||||
|
envVarName: 'testName',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -58,10 +61,12 @@ describe('parseSecretsInput', () => {
|
|||||||
|
|
||||||
expect(output).toHaveLength(2);
|
expect(output).toHaveLength(2);
|
||||||
expect(output[0]).toMatchObject({
|
expect(output[0]).toMatchObject({
|
||||||
outputName: 'A',
|
outputVarName: 'a',
|
||||||
|
envVarName: 'A',
|
||||||
});
|
});
|
||||||
expect(output[1]).toMatchObject({
|
expect(output[1]).toMatchObject({
|
||||||
outputName: 'secondName',
|
outputVarName: 'secondName',
|
||||||
|
envVarName: 'secondName'
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -76,14 +81,56 @@ describe('parseSecretsInput', () => {
|
|||||||
secretPath: 'first',
|
secretPath: 'first',
|
||||||
});
|
});
|
||||||
expect(output[1]).toMatchObject({
|
expect(output[1]).toMatchObject({
|
||||||
outputName: 'B',
|
outputVarName: 'b',
|
||||||
|
envVarName: 'B'
|
||||||
});
|
});
|
||||||
expect(output[2]).toMatchObject({
|
expect(output[2]).toMatchObject({
|
||||||
outputName: 'SOME_C',
|
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('parseResponse', () => {
|
describe('parseResponse', () => {
|
||||||
// https://www.vaultproject.io/api/secret/kv/kv-v1.html#sample-response
|
// https://www.vaultproject.io/api/secret/kv/kv-v1.html#sample-response
|
||||||
it('parses K/V version 1 response', () => {
|
it('parses K/V version 1 response', () => {
|
||||||
@@ -142,22 +189,24 @@ describe('exportSecrets', () => {
|
|||||||
.mockReturnValueOnce(version);
|
.mockReturnValueOnce(version);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function mockExtraHeaders(headerString) {
|
||||||
|
when(core.getInput)
|
||||||
|
.calledWith('extraHeaders')
|
||||||
|
.mockReturnValueOnce(headerString);
|
||||||
|
}
|
||||||
|
|
||||||
function mockVaultData(data, version='2') {
|
function mockVaultData(data, version='2') {
|
||||||
switch(version) {
|
switch(version) {
|
||||||
case '1':
|
case '1':
|
||||||
got.mockResolvedValue({
|
got.extend.mockReturnValue({
|
||||||
body: JSON.stringify({
|
get: async () => ({ body: JSON.stringify({ data }) })
|
||||||
data
|
|
||||||
})
|
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case '2':
|
case '2':
|
||||||
got.mockResolvedValue({
|
got.extend.mockReturnValue({
|
||||||
body: JSON.stringify({
|
get: async () => ({ body: JSON.stringify({ data: {
|
||||||
data: {
|
data
|
||||||
data
|
} }) })
|
||||||
}
|
|
||||||
})
|
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -172,6 +221,7 @@ describe('exportSecrets', () => {
|
|||||||
await exportSecrets();
|
await exportSecrets();
|
||||||
|
|
||||||
expect(core.exportVariable).toBeCalledWith('KEY', '1');
|
expect(core.exportVariable).toBeCalledWith('KEY', '1');
|
||||||
|
expect(core.setOutput).toBeCalledWith('key', '1');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('mapped secret retrieval', async () => {
|
it('mapped secret retrieval', async () => {
|
||||||
@@ -183,11 +233,29 @@ describe('exportSecrets', () => {
|
|||||||
await exportSecrets();
|
await exportSecrets();
|
||||||
|
|
||||||
expect(core.exportVariable).toBeCalledWith('TEST_NAME', '1');
|
expect(core.exportVariable).toBeCalledWith('TEST_NAME', '1');
|
||||||
|
expect(core.setOutput).toBeCalledWith('TEST_NAME', '1');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('simple secret retrieval from K/V v1', async () => {
|
it('simple secret retrieval from K/V v1', async () => {
|
||||||
const version = '1';
|
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');
|
mockInput('test key');
|
||||||
mockVersion(version);
|
mockVersion(version);
|
||||||
mockVaultData({
|
mockVaultData({
|
||||||
@@ -197,5 +265,6 @@ describe('exportSecrets', () => {
|
|||||||
await exportSecrets();
|
await exportSecrets();
|
||||||
|
|
||||||
expect(core.exportVariable).toBeCalledWith('KEY', '1');
|
expect(core.exportVariable).toBeCalledWith('KEY', '1');
|
||||||
|
expect(core.setOutput).toBeCalledWith('key', '1');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
+81
@@ -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,
|
||||||
|
};
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "commonjs",
|
||||||
|
"target": "es2019",
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"allowJs": true,
|
||||||
|
"noEmit": true
|
||||||
|
},
|
||||||
|
"exclude": [
|
||||||
|
"node_modules"
|
||||||
|
]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user