Compare commits

..
17 Commits
Author SHA1 Message Date
Diógenes Fernandes a1320f8929 release docs and bump to 2.0.2 (#127)
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
2026-06-29 08:51:33 -03:00
somaz d3dc77de53 feat: verify download against published SHA256SUMS by default (#121)
Signed-off-by: somaz <genius5711@gmail.com>
2026-06-26 12:42:14 -03:00
dependabot[bot]andDiogenes Fernandes 56007213a1 chore(deps): Bump semver from 7.8.1 to 7.8.3 (#123)
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Diogenes Fernandes <diofeher@gmail.com>
2026-06-16 08:54:54 -03:00
dependabot[bot] 7051243a57 chore(deps): Bump actions/checkout from 6.0.2 to 6.0.3 (#124)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-15 21:00:46 -03:00
dependabot[bot] 50e079f741 chore(deps): Bump actions/checkout from 6 to 6.0.2
Bumps [actions/checkout](https://github.com/actions/checkout) from 6 to 6.0.2.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v6...v6.0.2)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: 6.0.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-05 08:40:43 -07:00
dependabot[bot]andDiogenes Fernandes 0c73a96b62 chore(deps): Bump semver from 7.8.0 to 7.8.1 (#119)
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Diogenes Fernandes <diofeher@gmail.com>
2026-06-03 12:02:29 -03:00
dependabot[bot]andMartin Atkins 7526f4bce4 chore(deps): Bump semver from 7.7.4 to 7.8.0
Bumps [semver](https://github.com/npm/node-semver) from 7.7.4 to 7.8.0.
- [Release notes](https://github.com/npm/node-semver/releases)
- [Changelog](https://github.com/npm/node-semver/blob/main/CHANGELOG.md)
- [Commits](https://github.com/npm/node-semver/compare/v7.7.4...v7.8.0)

---
updated-dependencies:
- dependency-name: semver
  dependency-version: 7.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Co-authored-by: Martin Atkins <mart@degeneration.co.uk>
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Martin Atkins <mart@degeneration.co.uk>
2026-05-19 13:45:38 -07:00
dependabot[bot] a630d3b887 chore(deps-dev): Bump jest from 30.3.0 to 30.4.2
Bumps [jest](https://github.com/jestjs/jest/tree/HEAD/packages/jest) from 30.3.0 to 30.4.2.
- [Release notes](https://github.com/jestjs/jest/releases)
- [Changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jestjs/jest/commits/v30.4.2/packages/jest)

---
updated-dependencies:
- dependency-name: jest
  dependency-version: 30.4.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-19 13:31:53 -07:00
dependabot[bot] 7e2b8769cc chore(deps): Bump @actions/core from 3.0.0 to 3.0.1
Bumps [@actions/core](https://github.com/actions/toolkit/tree/HEAD/packages/core) from 3.0.0 to 3.0.1.
- [Changelog](https://github.com/actions/toolkit/blob/main/packages/core/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/core)

---
updated-dependencies:
- dependency-name: "@actions/core"
  dependency-version: 3.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-19 13:30:44 -07:00
dependabot[bot]andDiogenes Fernandes 847eaa4afe chore(deps): Bump @actions/http-client from 4.0.0 to 4.0.1 (#114)
Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Diogenes Fernandes <diofeher@gmail.com>
2026-05-05 06:34:17 -03:00
Anthony Hoivik 34bf4e3161 feat(acc): Add provider_acceptance_tests input for automated acceptance test setup (#97)
Signed-off-by: hoivikaj <github@hoivik.co>
Signed-off-by: Anthony Hoivik <38190936+hoivikaj@users.noreply.github.com>
2026-04-15 23:08:57 -03:00
Kim Wagner 4bcfe8cded feat: added support for providing optional checksums for ZIP validation (#107)
Signed-off-by: Kim <kim.peter.wagner@gmail.com>
2026-04-13 16:46:38 -03:00
Diógenes Fernandes 03a9076efe deps: picomatch in npm audit (#103)
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
2026-03-26 16:00:33 -03:00
Anthony HoivikandDiógenes Fernandes ba1f8b8e04 chore(ci): dependabot actions ecosystem, conventional commits (#98)
Signed-off-by: hoivikaj <github@hoivik.co>
Signed-off-by: Diógenes Fernandes <diofeher@gmail.com>
Co-authored-by: Diógenes Fernandes <diofeher@gmail.com>
2026-03-26 14:10:12 -03:00
Andy Brody 26ccb9be2d Update README with latest action versions. (#99)
Signed-off-by: Andy Brody <git@abrody.com>
2026-03-20 11:23:02 -04:00
Anthony Hoivik b572e07b01 feat(error-handling): error notification for network failures (#94)
Signed-off-by: hoivikaj <github@hoivik.co>
2026-03-17 15:23:28 -03:00
Diogenes Fernandes 4959f8f18c fix: npm audit
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
2026-03-17 15:13:56 -03:00
18 changed files with 2467 additions and 854 deletions

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
## Releasing
Releases are made on a reasonably regular basis by the maintainers. The following notes are only relevant to maintainers.
Release process:
1. Create a PR against `main` with the following changes:
- Update the version in `package.json`:
```shell
npm version patch|minor|major --no-git-tag-version
```
- Run the build to update the `dist/` directory:
```shell
npm run build
```
2. Review and merge the PR.
3. [Create and publish a GitHub release](https://github.com/opentofu/setup-opentofu/releases/new) with tag `vX.Y.Z`, using the auto-generated release notes as the release body.
4. Update the rolling major version tag to point to the new release:
```shell
git tag -f v2 vX.Y.Z
git push --force origin v2
```
This allows users to pin to `opentofu/setup-opentofu@v2` and always get the latest version of the rolling tag.
+6
View File
@@ -6,3 +6,9 @@ updates:
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "github-actions"
cooldown:
default-days: 7
directory: "/"
schedule:
interval: "weekly"
-21
View File
@@ -1,21 +0,0 @@
name: Retag
on:
push:
tags:
- 'v[1-2].[0-9]+.[0-9]+*'
defaults:
run:
shell: bash
jobs:
tag:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- run: |
set -o pipefail
git tag --force "$(grep '^v[1-2]\.[0-9]\+\.[0-9]\+\(.*\)\?$' <<< ${GITHUB_REF#refs/*/} | sed 's/^v\([1-2]\)\..*/v\1/')"
git push --tag --force
+7 -7
View File
@@ -23,7 +23,7 @@ jobs:
tofu-version-files: ['./.github/workflows/data/local/.opentofu-version']
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v6.0.3
- name: Setup OpenTofu - ${{ matrix['tofu-version-files'] }}
uses: ./
@@ -43,7 +43,7 @@ jobs:
tofu-wrapper: [true, false]
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v6.0.3
- name: Setup OpenTofu - ${{ matrix['tofu-versions'] }}
uses: ./
@@ -66,7 +66,7 @@ jobs:
tofu-wrapper: [true, false]
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v6.0.3
- name: Setup OpenTofu
uses: ./
@@ -103,7 +103,7 @@ jobs:
working-directory: ./.github/workflows/data/local
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v6.0.3
- name: Setup OpenTofu
uses: ./
@@ -133,7 +133,7 @@ jobs:
TF_CLOUD_API_TOKEN: 'XXXXXXXXXXXXXX.atlasv1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v6.0.3
- name: Setup OpenTofu
uses: ./
@@ -162,7 +162,7 @@ jobs:
TF_CLOUD_API_TOKEN: 'XXXXXXXXXXXXXX.atlasv1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v6.0.3
- name: Setup OpenTofu
uses: ./
@@ -190,7 +190,7 @@ jobs:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v6.0.3
- name: Setup OpenTofu
uses: ./
+43 -12
View File
@@ -16,14 +16,14 @@ The default configuration installs the latest version of OpenTofu CLI and instal
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
```
A specific version of OpenTofu CLI can be installed:
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
tofu_version: 1.6.0
```
@@ -32,7 +32,7 @@ You can also specify the version in a file (e.g., `.opentofu-version`):
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
tofu_version_file: .opentofu-version
```
@@ -43,7 +43,7 @@ Credentials for Terraform Cloud ([app.terraform.io](https://app.terraform.io/))
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }}
```
@@ -52,7 +52,7 @@ Credentials for Terraform Enterprise (TFE) can be configured:
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
cli_config_credentials_hostname: 'tofu.example.com'
cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }}
@@ -62,7 +62,7 @@ The wrapper script installation can be skipped by setting the `tofu_wrapper` var
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
tofu_wrapper: false
```
@@ -71,16 +71,42 @@ Caching can be enabled to reduce download time on subsequent workflow runs by st
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
with:
cache: true
```
Provider acceptance test environment variables can be configured automatically by setting `provider_acceptance_tests` to `true`. This exports `TF_ACC`, `TF_ACC_PROVIDER_NAMESPACE`, `TF_ACC_PROVIDER_HOST`, and `TF_ACC_TERRAFORM_PATH` so you don't need to set them manually:
```yaml
steps:
- uses: opentofu/setup-opentofu@v2
with:
tofu_wrapper: false
provider_acceptance_tests: true
- run: go mod download
- run: go test -v -cover ./...
timeout-minutes: 10
```
By default, the action verifies the downloaded OpenTofu CLI ZIP against the SHA-256 checksum published in the release's `SHA256SUMS` file, so the default install path is verified out of the box. Verification is skipped (with a warning) only when the published checksum cannot be retrieved.
To pin the expected hashes yourself instead, pass a newline-delimited list of checksums. When set, this list takes precedence over the published `SHA256SUMS`:
```yaml
steps:
- uses: opentofu/setup-opentofu@v2
with:
checksums: |
933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad
d3d29f51e75a701fc7cf67c0644a8c883a85f36cf1621461988baffd88e7f361
```
Subsequent steps can access outputs when the wrapper script is installed:
```yaml
steps:
- uses: opentofu/setup-opentofu@v1
- uses: opentofu/setup-opentofu@v2
- run: tofu init
@@ -107,8 +133,8 @@ defaults:
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v3
- uses: opentofu/setup-opentofu@v1
- uses: actions/checkout@v6
- uses: opentofu/setup-opentofu@v2
- name: OpenTofu fmt
id: fmt
@@ -175,8 +201,8 @@ defaults:
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v3
- uses: opentofu/setup-opentofu@v1
- uses: actions/checkout@v6
- uses: opentofu/setup-opentofu@v2
- name: OpenTofu fmt
id: fmt
@@ -274,7 +300,12 @@ The action supports the following inputs:
the `tofu` binary and expose its STDOUT, STDERR, and exit code as outputs
named `stdout`, `stderr`, and `exitcode` respectively. Defaults to `true`.
- `cache` - (optional) Whether to use GitHub Actions tool-cache to store and reuse downloaded OpenTofu binaries. Defaults to `false`.
- `provider_acceptance_tests` - (optional) Whether to automatically set environment variables for running
OpenTofu provider acceptance tests. When set to `true`, the following environment variables are exported:
`TF_ACC=1`, `TF_ACC_PROVIDER_NAMESPACE=hashicorp`, `TF_ACC_PROVIDER_HOST=registry.opentofu.org`, and
`TF_ACC_TERRAFORM_PATH=<path to tofu binary>`. Defaults to `false`.
- `github_token` - (optional) Override the GitHub token read from the environment variable. Defaults to the value of the `GITHUB_TOKEN` environment variable unless running on Forgejo or Gitea.
- `checksums` - (optional) A newline-delimited list of valid checksums (SHA256) for the downloaded OpenTofu CLI ZIP. When set, the action will verify the ZIP matches one of the checksums before proceeding. When unset, the action verifies the ZIP against the SHA-256 checksum published in the release's `SHA256SUMS` file by default. Defaults to `[]`
## Outputs
+7
View File
@@ -28,6 +28,13 @@ inputs:
description: 'API token for GitHub to increase the rate limit. Defaults to the GITHUB_TOKEN environment variable unless running on Forgejo/Gitea.'
default: ''
required: false
provider_acceptance_tests:
description: 'Whether to automatically set environment variables for running OpenTofu provider acceptance tests (TF_ACC, TF_ACC_PROVIDER_NAMESPACE, TF_ACC_PROVIDER_HOST, TF_ACC_TERRAFORM_PATH). Defaults to `false`.'
default: 'false'
required: false
checksums:
description: Newline-delimited list of valid checksums (SHA256 hashes) for the downloaded OpenTofu binary. When set, the action verifies the binary matches one of these checksums before proceeding. When unset, the action verifies the binary against the SHA-256 checksum published in the release's SHA256SUMS file by default.
required: false
outputs:
stdout:
description: 'The STDOUT stream of the call to the `tofu` binary.'
+757 -116
View File
File diff suppressed because it is too large. Load diff
+375 -92
View File
@@ -2930,6 +2930,24 @@ class SecureProxyConnectionError extends UndiciError {
[kSecureProxyConnectionError] = true
}
const kMessageSizeExceededError = Symbol.for('undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED')
class MessageSizeExceededError extends UndiciError {
constructor (message) {
super(message)
this.name = 'MessageSizeExceededError'
this.message = message || 'Max decompressed message size exceeded'
this.code = 'UND_ERR_WS_MESSAGE_SIZE_EXCEEDED'
}
static [Symbol.hasInstance] (instance) {
return instance && instance[kMessageSizeExceededError] === true
}
get [kMessageSizeExceededError] () {
return true
}
}
module.exports = {
AbortError,
HTTPParserError,
@@ -2953,7 +2971,8 @@ module.exports = {
ResponseExceededMaxSizeError,
RequestRetryError,
ResponseError,
SecureProxyConnectionError
SecureProxyConnectionError,
MessageSizeExceededError
}
@@ -3030,6 +3049,10 @@ class Request {
throw new InvalidArgumentError('upgrade must be a string')
}
if (upgrade && !isValidHeaderValue(upgrade)) {
throw new InvalidArgumentError('invalid upgrade header')
}
if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
throw new InvalidArgumentError('invalid headersTimeout')
}
@@ -3324,13 +3347,19 @@ function processHeader (request, key, val) {
val = `${val}`
}
if (request.host === null && headerName === 'host') {
if (headerName === 'host') {
if (request.host !== null) {
throw new InvalidArgumentError('duplicate host header')
}
if (typeof val !== 'string') {
throw new InvalidArgumentError('invalid host header')
}
// Consumed by Client
request.host = val
} else if (request.contentLength === null && headerName === 'content-length') {
} else if (headerName === 'content-length') {
if (request.contentLength !== null) {
throw new InvalidArgumentError('duplicate content-length header')
}
request.contentLength = parseInt(val, 10)
if (!Number.isFinite(request.contentLength)) {
throw new InvalidArgumentError('invalid content-length header')
@@ -4349,8 +4378,6 @@ function defaultFactory (origin, opts) {
class Agent extends DispatcherBase {
constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
super()
if (typeof factory !== 'function') {
throw new InvalidArgumentError('factory must be a function.')
}
@@ -4363,6 +4390,8 @@ class Agent extends DispatcherBase {
throw new InvalidArgumentError('maxRedirections must be a positive number')
}
super(options)
if (connect && typeof connect !== 'function') {
connect = { ...connect }
}
@@ -4734,6 +4763,9 @@ const EMPTY_BUF = Buffer.alloc(0)
const FastBuffer = Buffer[Symbol.species]
const addListener = util.addListener
const removeAllListeners = util.removeAllListeners
const kIdleSocketValidation = Symbol('kIdleSocketValidation')
const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout')
const kSocketUsed = Symbol('kSocketUsed')
let extractBody
@@ -4956,29 +4988,71 @@ class Parser {
const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
if (ret === constants.ERROR.PAUSED_UPGRADE) {
this.onUpgrade(data.slice(offset))
} else if (ret === constants.ERROR.PAUSED) {
this.paused = true
socket.unshift(data.slice(offset))
} else if (ret !== constants.ERROR.OK) {
const ptr = llhttp.llhttp_get_error_reason(this.ptr)
let message = ''
/* istanbul ignore else: difficult to make a test case for */
if (ptr) {
const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
message =
'Response does not match the HTTP/1.1 protocol (' +
Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
')'
if (ret !== constants.ERROR.OK) {
const body = data.subarray(offset)
if (ret === constants.ERROR.PAUSED_UPGRADE) {
this.onUpgrade(body)
} else if (ret === constants.ERROR.PAUSED) {
this.paused = true
socket.unshift(body)
} else {
throw this.createError(ret, body)
}
throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
}
} catch (err) {
util.destroy(socket, err)
}
}
finish () {
assert(currentParser === null)
assert(this.ptr != null)
assert(!this.paused)
const { llhttp } = this
let ret
try {
currentParser = this
ret = llhttp.llhttp_finish(this.ptr)
} finally {
currentParser = null
}
if (ret === constants.ERROR.OK) {
return null
}
if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) {
this.paused = true
return null
}
return this.createError(ret, EMPTY_BUF)
}
createError (ret, data) {
const { llhttp, contentLength, bytesRead } = this
if (contentLength && bytesRead !== parseInt(contentLength, 10)) {
return new ResponseContentLengthMismatchError()
}
const ptr = llhttp.llhttp_get_error_reason(this.ptr)
let message = ''
if (ptr) {
const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
message =
'Response does not match the HTTP/1.1 protocol (' +
Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
')'
}
return new HTTPParserError(message, constants.ERROR[ret], data)
}
destroy () {
assert(this.ptr != null)
assert(currentParser == null)
@@ -5006,6 +5080,11 @@ class Parser {
return -1
}
if (client[kRunning] === 0) {
util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
return -1
}
const request = client[kQueue][client[kRunningIdx]]
if (!request) {
return -1
@@ -5109,6 +5188,11 @@ class Parser {
return -1
}
if (client[kRunning] === 0) {
util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
return -1
}
const request = client[kQueue][client[kRunningIdx]]
/* istanbul ignore next: difficult to make a test case for */
@@ -5282,6 +5366,7 @@ class Parser {
request.onComplete(headers)
client[kQueue][client[kRunningIdx]++] = null
socket[kSocketUsed] = true
if (socket[kWriting]) {
assert(client[kRunning] === 0)
@@ -5340,6 +5425,9 @@ async function connectH1 (client, socket) {
socket[kWriting] = false
socket[kReset] = false
socket[kBlocking] = false
socket[kIdleSocketValidation] = 0
socket[kIdleSocketValidationTimeout] = null
socket[kSocketUsed] = false
socket[kParser] = new Parser(client, socket, llhttpInstance)
addListener(socket, 'error', function (err) {
@@ -5350,8 +5438,11 @@ async function connectH1 (client, socket) {
// On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
// to the user.
if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
// We treat all incoming data so for as a valid response.
parser.onMessageComplete()
const parserErr = parser.finish()
if (parserErr) {
this[kError] = parserErr
this[kClient][kOnError](parserErr)
}
return
}
@@ -5370,8 +5461,10 @@ async function connectH1 (client, socket) {
const parser = this[kParser]
if (parser.statusCode && !parser.shouldKeepAlive) {
// We treat all incoming data so far as a valid response.
parser.onMessageComplete()
const parserErr = parser.finish()
if (parserErr) {
util.destroy(this, parserErr)
}
return
}
@@ -5381,10 +5474,11 @@ async function connectH1 (client, socket) {
const client = this[kClient]
const parser = this[kParser]
clearIdleSocketValidation(this)
if (parser) {
if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
// We treat all incoming data so far as a valid response.
parser.onMessageComplete()
this[kError] = parser.finish() || this[kError]
}
this[kParser].destroy()
@@ -5447,7 +5541,7 @@ async function connectH1 (client, socket) {
return socket.destroyed
},
busy (request) {
if (socket[kWriting] || socket[kReset] || socket[kBlocking]) {
if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) {
return true
}
@@ -5485,6 +5579,31 @@ async function connectH1 (client, socket) {
}
}
function clearIdleSocketValidation (socket) {
if (socket[kIdleSocketValidationTimeout]) {
clearTimeout(socket[kIdleSocketValidationTimeout])
socket[kIdleSocketValidationTimeout] = null
}
socket[kIdleSocketValidation] = 0
}
function scheduleIdleSocketValidation (client, socket) {
socket[kIdleSocketValidation] = 1
socket[kIdleSocketValidationTimeout] = setTimeout(() => {
socket[kIdleSocketValidationTimeout] = null
socket[kIdleSocketValidation] = 2
if (client[kSocket] === socket && !socket.destroyed) {
client[kResume]()
}
}, 0)
socket[kIdleSocketValidationTimeout].unref?.()
}
/**
* @param {import('./client.js')} client
*/
function resumeH1 (client) {
const socket = client[kSocket]
@@ -5499,6 +5618,32 @@ function resumeH1 (client) {
socket[kNoRef] = false
}
if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
if (socket[kIdleSocketValidation] === 0) {
scheduleIdleSocketValidation(client, socket)
socket[kParser].readMore()
if (socket.destroyed) {
return
}
return
}
if (socket[kIdleSocketValidation] === 1) {
socket[kParser].readMore()
if (socket.destroyed) {
return
}
return
}
}
if (client[kRunning] === 0) {
socket[kParser].readMore()
if (socket.destroyed) {
return
}
}
if (client[kSize] === 0) {
if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)
@@ -5592,6 +5737,7 @@ function writeH1 (client, request) {
}
const socket = client[kSocket]
clearIdleSocketValidation(socket)
const abort = (err) => {
if (request.aborted || request.completed) {
@@ -6911,9 +7057,10 @@ class Client extends DispatcherBase {
autoSelectFamilyAttemptTimeout,
// h2
maxConcurrentStreams,
allowH2
allowH2,
webSocket
} = {}) {
super()
super({ webSocket })
if (keepAlive !== undefined) {
throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
@@ -7445,15 +7592,24 @@ const { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = __nc
const kOnDestroyed = Symbol('onDestroyed')
const kOnClosed = Symbol('onClosed')
const kInterceptedDispatch = Symbol('Intercepted Dispatch')
const kWebSocketOptions = Symbol('webSocketOptions')
class DispatcherBase extends Dispatcher {
constructor () {
constructor (opts) {
super()
this[kDestroyed] = false
this[kOnDestroyed] = null
this[kClosed] = false
this[kOnClosed] = []
this[kWebSocketOptions] = opts?.webSocket ?? {}
}
get webSocketOptions () {
return {
maxFragments: this[kWebSocketOptions].maxFragments ?? 131072,
maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024
}
}
get destroyed () {
@@ -8013,8 +8169,8 @@ const kRemoveClient = Symbol('remove client')
const kStats = Symbol('stats')
class PoolBase extends DispatcherBase {
constructor () {
super()
constructor (opts) {
super(opts)
this[kQueue] = new FixedQueue()
this[kClients] = []
@@ -8273,8 +8429,6 @@ class Pool extends PoolBase {
allowH2,
...options
} = {}) {
super()
if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
throw new InvalidArgumentError('invalid connections')
}
@@ -8299,6 +8453,8 @@ class Pool extends PoolBase {
})
}
super(options)
this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool)
? options.interceptors.Pool
: []
@@ -13351,32 +13507,25 @@ function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {})
// If the attribute-name case-insensitively matches the string
// "SameSite", the user agent MUST process the cookie-av as follows:
// 1. Let enforcement be "Default".
let enforcement = 'Default'
const attributeValueLowercase = attributeValue.toLowerCase()
// 2. If cookie-av's attribute-value is a case-insensitive match for
// "None", set enforcement to "None".
if (attributeValueLowercase.includes('none')) {
enforcement = 'None'
}
// 3. If cookie-av's attribute-value is a case-insensitive match for
// "Strict", set enforcement to "Strict".
if (attributeValueLowercase.includes('strict')) {
enforcement = 'Strict'
// 1. If cookie-av's attribute-value is a case-insensitive match for
// "None", append an attribute to the cookie-attribute-list with an
// attribute-name of "SameSite" and an attribute-value of "None".
if (attributeValueLowercase === 'none') {
cookieAttributeList.sameSite = 'None'
} else if (attributeValueLowercase === 'strict') {
// 2. If cookie-av's attribute-value is a case-insensitive match for
// "Strict", append an attribute to the cookie-attribute-list with
// an attribute-name of "SameSite" and an attribute-value of
// "Strict".
cookieAttributeList.sameSite = 'Strict'
} else if (attributeValueLowercase === 'lax') {
// 3. If cookie-av's attribute-value is a case-insensitive match for
// "Lax", append an attribute to the cookie-attribute-list with an
// attribute-name of "SameSite" and an attribute-value of "Lax".
cookieAttributeList.sameSite = 'Lax'
}
// 4. If cookie-av's attribute-value is a case-insensitive match for
// "Lax", set enforcement to "Lax".
if (attributeValueLowercase.includes('lax')) {
enforcement = 'Lax'
}
// 5. Append an attribute to the cookie-attribute-list with an
// attribute-name of "SameSite" and an attribute-value of
// enforcement.
cookieAttributeList.sameSite = enforcement
} else {
cookieAttributeList.unparsed ??= []
@@ -26047,6 +26196,7 @@ module.exports = {
const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __nccwpck_require__(8522)
const { isValidClientWindowBits } = __nccwpck_require__(8625)
const { MessageSizeExceededError } = __nccwpck_require__(8707)
const tail = Buffer.from([0x00, 0x00, 0xff, 0xff])
const kBuffer = Symbol('kBuffer')
@@ -26058,17 +26208,29 @@ class PerMessageDeflate {
#options = {}
constructor (extensions) {
#maxPayloadSize = 0
/**
* @param {Map<string, string>} extensions
*/
constructor (extensions, options) {
this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover')
this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits')
this.#maxPayloadSize = options.maxPayloadSize
}
/**
* Decompress a compressed payload.
* @param {Buffer} chunk Compressed data
* @param {boolean} fin Final fragment flag
* @param {Function} callback Callback function
*/
decompress (chunk, fin, callback) {
// An endpoint uses the following algorithm to decompress a message.
// 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the
// payload of the message.
// 2. Decompress the resulting data using DEFLATE.
if (!this.#inflate) {
let windowBits = Z_DEFAULT_WINDOWBITS
@@ -26081,13 +26243,26 @@ class PerMessageDeflate {
windowBits = Number.parseInt(this.#options.serverMaxWindowBits)
}
this.#inflate = createInflateRaw({ windowBits })
try {
this.#inflate = createInflateRaw({ windowBits })
} catch (err) {
callback(err)
return
}
this.#inflate[kBuffer] = []
this.#inflate[kLength] = 0
this.#inflate.on('data', (data) => {
this.#inflate[kBuffer].push(data)
this.#inflate[kLength] += data.length
if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) {
callback(new MessageSizeExceededError())
this.#inflate.removeAllListeners()
this.#inflate = null
return
}
this.#inflate[kBuffer].push(data)
})
this.#inflate.on('error', (err) => {
@@ -26102,6 +26277,10 @@ class PerMessageDeflate {
}
this.#inflate.flush(() => {
if (!this.#inflate) {
return
}
const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength])
this.#inflate[kBuffer].length = 0
@@ -26140,6 +26319,12 @@ const {
const { WebsocketFrameSend } = __nccwpck_require__(3264)
const { closeWebSocketConnection } = __nccwpck_require__(6897)
const { PerMessageDeflate } = __nccwpck_require__(9469)
const { MessageSizeExceededError } = __nccwpck_require__(8707)
function failWebsocketConnectionWithCode (ws, code, reason) {
closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason))
failWebsocketConnection(ws, reason)
}
// This code was influenced by ws released under the MIT license.
// Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
@@ -26148,6 +26333,7 @@ const { PerMessageDeflate } = __nccwpck_require__(9469)
class ByteParser extends Writable {
#buffers = []
#fragmentsBytes = 0
#byteOffset = 0
#loop = false
@@ -26159,14 +26345,27 @@ class ByteParser extends Writable {
/** @type {Map<string, PerMessageDeflate>} */
#extensions
constructor (ws, extensions) {
/** @type {number} */
#maxFragments
/** @type {number} */
#maxPayloadSize
/**
* @param {import('./websocket').WebSocket} ws
* @param {Map<string, string>|null} extensions
* @param {{ maxFragments?: number, maxPayloadSize?: number }} [options]
*/
constructor (ws, extensions, options = {}) {
super()
this.ws = ws
this.#extensions = extensions == null ? new Map() : extensions
this.#maxFragments = options.maxFragments ?? 0
this.#maxPayloadSize = options.maxPayloadSize ?? 0
if (this.#extensions.has('permessage-deflate')) {
this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions))
this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions, options))
}
}
@@ -26182,6 +26381,19 @@ class ByteParser extends Writable {
this.run(callback)
}
#validatePayloadLength () {
if (
this.#maxPayloadSize > 0 &&
!isControlFrame(this.#info.opcode) &&
this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize
) {
failWebsocketConnectionWithCode(this.ws, 1009, 'Payload size exceeds maximum allowed size')
return false
}
return true
}
/**
* Runs whenever a new chunk is received.
* Callback is called whenever there are no more chunks buffering,
@@ -26270,6 +26482,10 @@ class ByteParser extends Writable {
if (payloadLength <= 125) {
this.#info.payloadLength = payloadLength
this.#state = parserStates.READ_DATA
if (!this.#validatePayloadLength()) {
return
}
} else if (payloadLength === 126) {
this.#state = parserStates.PAYLOADLENGTH_16
} else if (payloadLength === 127) {
@@ -26294,6 +26510,10 @@ class ByteParser extends Writable {
this.#info.payloadLength = buffer.readUInt16BE(0)
this.#state = parserStates.READ_DATA
if (!this.#validatePayloadLength()) {
return
}
} else if (this.#state === parserStates.PAYLOADLENGTH_64) {
if (this.#byteOffset < 8) {
return callback()
@@ -26301,6 +26521,7 @@ class ByteParser extends Writable {
const buffer = this.consume(8)
const upper = buffer.readUInt32BE(0)
const lower = buffer.readUInt32BE(4)
// 2^31 is the maximum bytes an arraybuffer can contain
// on 32-bit systems. Although, on 64-bit systems, this is
@@ -26308,15 +26529,17 @@ class ByteParser extends Writable {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275
// https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e
if (upper > 2 ** 31 - 1) {
if (upper !== 0 || lower > 2 ** 31 - 1) {
failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')
return
}
const lower = buffer.readUInt32BE(4)
this.#info.payloadLength = (upper << 8) + lower
this.#info.payloadLength = lower
this.#state = parserStates.READ_DATA
if (!this.#validatePayloadLength()) {
return
}
} else if (this.#state === parserStates.READ_DATA) {
if (this.#byteOffset < this.#info.payloadLength) {
return callback()
@@ -26329,42 +26552,58 @@ class ByteParser extends Writable {
this.#state = parserStates.INFO
} else {
if (!this.#info.compressed) {
this.#fragments.push(body)
if (!this.writeFragments(body)) {
return
}
if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) {
failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message)
return
}
// If the frame is not fragmented, a message has been received.
// If the frame is fragmented, it will terminate with a fin bit set
// and an opcode of 0 (continuation), therefore we handle that when
// parsing continuation frames, not here.
if (!this.#info.fragmented && this.#info.fin) {
const fullMessage = Buffer.concat(this.#fragments)
websocketMessageReceived(this.ws, this.#info.binaryType, fullMessage)
this.#fragments.length = 0
websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments())
}
this.#state = parserStates.INFO
} else {
this.#extensions.get('permessage-deflate').decompress(body, this.#info.fin, (error, data) => {
if (error) {
closeWebSocketConnection(this.ws, 1007, error.message, error.message.length)
return
}
this.#extensions.get('permessage-deflate').decompress(
body,
this.#info.fin,
(error, data) => {
if (error) {
const code = error instanceof MessageSizeExceededError ? 1009 : 1007
failWebsocketConnectionWithCode(this.ws, code, error.message)
return
}
this.#fragments.push(data)
if (!this.writeFragments(data)) {
return
}
if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) {
failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message)
return
}
if (!this.#info.fin) {
this.#state = parserStates.INFO
this.#loop = true
this.run(callback)
return
}
websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments())
if (!this.#info.fin) {
this.#state = parserStates.INFO
this.#loop = true
this.#state = parserStates.INFO
this.run(callback)
return
}
websocketMessageReceived(this.ws, this.#info.binaryType, Buffer.concat(this.#fragments))
this.#loop = true
this.#state = parserStates.INFO
this.#fragments.length = 0
this.run(callback)
})
)
this.#loop = false
break
@@ -26416,6 +26655,35 @@ class ByteParser extends Writable {
return buffer
}
writeFragments (fragment) {
if (
this.#maxFragments > 0 &&
this.#fragments.length === this.#maxFragments
) {
failWebsocketConnectionWithCode(this.ws, 1008, 'Too many message fragments')
return false
}
this.#fragmentsBytes += fragment.length
this.#fragments.push(fragment)
return true
}
consumeFragments () {
const fragments = this.#fragments
if (fragments.length === 1) {
this.#fragmentsBytes = 0
return fragments.shift()
}
const output = Buffer.concat(fragments, this.#fragmentsBytes)
this.#fragments = []
this.#fragmentsBytes = 0
return output
}
parseCloseBody (data) {
assert(data.length !== 1)
@@ -26949,6 +27217,12 @@ function parseExtensions (extensions) {
* @param {string} value
*/
function isValidClientWindowBits (value) {
// Must have at least one character
if (value.length === 0) {
return false
}
// Check all characters are ASCII digits
for (let i = 0; i < value.length; i++) {
const byte = value.charCodeAt(i)
@@ -26957,7 +27231,9 @@ function isValidClientWindowBits (value) {
}
}
return true
// Check numeric range: zlib requires windowBits in range 8-15
const num = Number.parseInt(value, 10)
return num >= 8 && num <= 15
}
// https://nodejs.org/api/intl.html#detecting-internationalization-support
@@ -27435,11 +27711,18 @@ class WebSocket extends EventTarget {
* @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
*/
#onConnectionEstablished (response, parsedExtensions) {
// processResponse is called when the "response’s header list has been received and initialized."
// processResponse is called when the "response's header list has been received and initialized."
// once this happens, the connection is open
this[kResponse] = response
const parser = new ByteParser(this, parsedExtensions)
const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions
const maxFragments = webSocketOptions?.maxFragments
const maxPayloadSize = webSocketOptions?.maxPayloadSize
const parser = new ByteParser(this, parsedExtensions, {
maxFragments,
maxPayloadSize
})
parser.on('drain', onParserDrain)
parser.on('error', onParserError.bind(this))
+5 -2
View File
@@ -4,14 +4,17 @@
* SPDX-License-Identifier: MPL-2.0
*/
import { setFailed } from '@actions/core';
import { setFailed, debug } from '@actions/core';
import setup from './lib/setup-tofu.js';
import { getErrorMessage, getErrorDetail } from './lib/error-utils.js';
(async () => {
try {
await setup();
} catch (error) {
setFailed(error.message);
const message = getErrorMessage(error);
debug(getErrorDetail(error));
setFailed(message);
}
})();
+75
View File
@@ -0,0 +1,75 @@
/**
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*
* Normalizes errors (including AggregateError from fetch/undici) into
* a single, actionable message for GitHub Actions logs.
*/
/**
* Get a user-friendly message from any error.
* - AggregateError: flattens error.errors so network/download causes are visible.
* - Standard Error: returns message; includes cause if present (Node 16+).
*
* @param {unknown} error - Caught value (Error, AggregateError, or other).
* @returns {string} Single-line message suitable for core.setFailed().
*/
function getErrorMessage (error) {
if (error instanceof AggregateError && Array.isArray(error.errors)) {
if (error.errors.length === 0) {
return 'AggregateError (one or more operations failed)';
}
const parts = error.errors.map((e) => (e && typeof e.message === 'string' ? e.message : String(e)));
const combined = parts.join('; ');
return combined || 'AggregateError (one or more operations failed)';
}
if (error instanceof Error) {
if (error.cause instanceof Error) {
return `${error.message}: ${error.cause.message}`;
}
return error.message;
}
return String(error);
}
/**
* Get a detailed string for logging (e.g. core.debug or core.error).
* Includes stack and, for AggregateError, each nested error.
*
* @param {unknown} error - Caught value.
* @returns {string} Multi-line detail string.
*/
function getErrorDetail (error) {
const lines = [];
if (error instanceof AggregateError && Array.isArray(error.errors)) {
lines.push(`AggregateError (${error.errors.length} error(s)):`);
error.errors.forEach((e, i) => {
lines.push(` [${i + 1}] ${e instanceof Error ? e.message : String(e)}`);
if (e instanceof Error && e.stack) {
lines.push(e.stack.split('\n').map((l) => ' ' + l).join('\n'));
}
});
if (error.stack) {
lines.push('Outer stack:');
lines.push(error.stack);
}
return lines.join('\n');
}
if (error instanceof Error) {
lines.push(error.message);
if (error.stack) lines.push(error.stack);
if (error.cause) {
lines.push('Caused by:');
lines.push(getErrorDetail(error.cause));
}
return lines.join('\n');
}
return String(error);
}
export { getErrorMessage, getErrorDetail };
+104 -4
View File
@@ -6,6 +6,7 @@
import { HttpClient, HttpCodes } from '@actions/http-client';
import semver from 'semver';
import { getErrorMessage } from './error-utils.js';
class Build {
constructor (version, name) {
@@ -44,7 +45,13 @@ async function fetchReleases (githubToken) {
Accept: 'application/json'
};
const resp = await http.get(url, headers);
let resp;
try {
resp = await http.get(url, headers);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to fetch OpenTofu releases from ${url}: ${cause}`);
}
if (resp.message.statusCode !== HttpCodes.OK) {
throw new Error(
@@ -52,8 +59,21 @@ async function fetchReleases (githubToken) {
);
}
const body = await resp.readBody();
const releasesMeta = JSON.parse(body);
let body;
try {
body = await resp.readBody();
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to read releases response: ${cause}`);
}
let releasesMeta;
try {
releasesMeta = JSON.parse(body);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Invalid releases JSON from ${url}: ${cause}`);
}
/**
* @type {Array}
@@ -63,6 +83,86 @@ async function fetchReleases (githubToken) {
return versions.map((releaseMeta) => new Release(releaseMeta));
}
/**
* Fetches the raw SHA256SUMS file published alongside an OpenTofu release.
*
* @param {string} version: Release version (without the leading `v`).
* @return {string} Raw SHA256SUMS file body.
*/
async function fetchSHA256SUMS (version) {
const userAgent = 'opentofu/setup-opentofu';
const http = new HttpClient(userAgent);
const url = `https://github.com/opentofu/opentofu/releases/download/v${version}/tofu_${version}_SHA256SUMS`;
let resp;
try {
resp = await http.get(url);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to fetch SHA256SUMS from ${url}: ${cause}`);
}
if (resp.message.statusCode !== HttpCodes.OK) {
throw new Error(
`failed fetching SHA256SUMS for ${url} (${resp.message.statusCode})`
);
}
return resp.readBody();
}
/**
* Parses a SHA256SUMS file body and returns the checksum for a given file name.
*
* Each line follows the `sha256sum` format: a lowercase hex digest, whitespace,
* then the file name (binary-mode lines prefix the name with `*`).
*
* @param {string} body: Raw SHA256SUMS file body.
* @param {string} fileName: Asset file name to look up.
* @return {string|null} Lowercase hex SHA-256 checksum, or null when not found.
*/
function parseChecksum (body, fileName) {
for (const line of body.split('\n')) {
const trimmed = line.trim();
if (trimmed === '') {
continue;
}
const separatorIndex = trimmed.search(/\s/);
if (separatorIndex === -1) {
continue;
}
const checksum = trimmed.slice(0, separatorIndex);
const name = trimmed.slice(separatorIndex).trim().replace(/^\*/, '');
if (name === fileName) {
return checksum.toLowerCase();
}
}
return null;
}
/**
* Resolves the published SHA-256 checksum for a release asset by fetching the
* release's SHA256SUMS file and looking up the asset's file name.
*
* @param {string} version: Release version (without the leading `v`).
* @param {string} fileName: Asset file name to look up.
* @param {function} fetchSumsFn: Optional fetcher for the SHA256SUMS body (for testing).
* @return {string|null} Lowercase hex SHA-256 checksum, or null when not found.
*/
async function getDownloadChecksum (
version,
fileName,
fetchSumsFn = fetchSHA256SUMS
) {
const body = await fetchSumsFn(version);
return parseChecksum(body, fileName);
}
async function findLatestVersion (versions) {
return versions
.filter((v) => semver.prerelease(v) === null)
@@ -125,4 +225,4 @@ async function getRelease (
return releases.find((release) => release.version === versionSelected);
}
export { getRelease, Release };
export { getRelease, getDownloadChecksum, parseChecksum, Release };
+93 -15
View File
@@ -7,7 +7,7 @@
// Node.js core
import { promises as fs } from 'fs';
import { platform, arch } from 'os';
import { sep, resolve, dirname } from 'path';
import { sep, join, resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
// External
@@ -16,12 +16,15 @@ import {
error as logError,
exportVariable,
getInput,
getMultilineInput,
warning,
addPath
} from '@actions/core';
import { downloadTool, extractZip, find, cacheDir } from '@actions/tool-cache';
import { mv, cp, mkdirP } from '@actions/io';
import { getRelease } from './releases.js';
import { getRelease, getDownloadChecksum } from './releases.js';
import { getErrorMessage } from './error-utils.js';
import { fileSHA256 } from './util.js';
// __dirname is not available in ES modules, so we need to construct it ourselves
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -45,9 +48,29 @@ function mapOS (os) {
return os;
}
async function downloadAndExtractCLI (url) {
async function downloadAndExtractCLI (url, checksums) {
debug(`Downloading OpenTofu CLI from ${url}`);
const pathToCLIZip = await downloadTool(url);
let pathToCLIZip;
try {
pathToCLIZip = await downloadTool(url);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to download OpenTofu from ${url}: ${cause}`);
}
if (checksums.length > 0) {
let checksum;
try {
checksum = await fileSHA256(pathToCLIZip);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to calculate the checksum for the OpenTofu CLI zip: ${cause}`);
}
if (!checksums.includes(checksum)) {
throw new Error(`Failed to validate OpenTofu CLI zip checksum. Received: ${checksum}. Valid checksums: ${checksums.join(', ')}`);
}
}
if (!pathToCLIZip) {
throw new Error(`Unable to download OpenTofu from ${url}`);
@@ -56,14 +79,19 @@ async function downloadAndExtractCLI (url) {
let pathToCLI;
debug('Extracting OpenTofu CLI zip file');
if (platform().startsWith('win')) {
debug(`OpenTofu CLI Download Path is ${pathToCLIZip}`);
const fixedPathToCLIZip = `${pathToCLIZip}.zip`;
await mv(pathToCLIZip, fixedPathToCLIZip);
debug(`Moved download to ${fixedPathToCLIZip}`);
pathToCLI = await extractZip(fixedPathToCLIZip);
} else {
pathToCLI = await extractZip(pathToCLIZip);
try {
if (platform().startsWith('win')) {
debug(`OpenTofu CLI Download Path is ${pathToCLIZip}`);
const fixedPathToCLIZip = `${pathToCLIZip}.zip`;
await mv(pathToCLIZip, fixedPathToCLIZip);
debug(`Moved download to ${fixedPathToCLIZip}`);
pathToCLI = await extractZip(fixedPathToCLIZip);
} else {
pathToCLI = await extractZip(pathToCLIZip);
}
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to extract OpenTofu archive: ${cause}`);
}
debug(`OpenTofu CLI path is ${pathToCLI}.`);
@@ -75,6 +103,42 @@ async function downloadAndExtractCLI (url) {
return pathToCLI;
}
// Resolve the checksums to validate the downloaded archive against. An explicit
// `checksums` input always wins. Otherwise the action falls back to the SHA-256
// checksum published in the release's SHA256SUMS file, so the default install
// path is verified rather than left unchecked. Verification is skipped (with a
// warning) only when no published checksum can be retrieved.
async function resolveChecksums (checksums, version, fileName) {
if (checksums.length > 0) {
return checksums;
}
debug(
`No checksums input provided; fetching published SHA256SUMS for ${fileName}`
);
let publishedChecksum;
try {
publishedChecksum = await getDownloadChecksum(version, fileName);
} catch (error) {
warning(
`Failed to fetch published SHA256SUMS for OpenTofu ${version}: ${getErrorMessage(
error
)}. Proceeding without checksum verification.`
);
return [];
}
if (!publishedChecksum) {
warning(
`Could not find a published SHA256 checksum for ${fileName}. Proceeding without checksum verification.`
);
return [];
}
return [publishedChecksum];
}
async function installWrapper (pathToCLI) {
let source, target;
@@ -149,7 +213,9 @@ async function run () {
const credentialsHostname = getInput('cli_config_credentials_hostname');
const credentialsToken = getInput('cli_config_credentials_token');
const wrapper = getInput('tofu_wrapper') === 'true';
const providerAcceptanceTest = getInput('provider_acceptance_tests') === 'true';
const useCache = getInput('cache') === 'true';
const checksums = getMultilineInput('checksums');
let githubToken = getInput('github_token');
if (
githubToken === '' &&
@@ -205,12 +271,14 @@ async function run () {
pathToCLI = cachedPath;
} else {
debug(`OpenTofu version ${release.version} not found in cache, downloading...`);
const extractedPath = await downloadAndExtractCLI(build.url);
const effectiveChecksums = await resolveChecksums(checksums, release.version, build.name);
const extractedPath = await downloadAndExtractCLI(build.url, effectiveChecksums);
debug(`Caching OpenTofu version ${release.version} to tool cache`);
pathToCLI = await cacheDir(extractedPath, 'tofu', release.version, buildArch);
}
} else {
pathToCLI = await downloadAndExtractCLI(build.url);
const effectiveChecksums = await resolveChecksums(checksums, release.version, build.name);
pathToCLI = await downloadAndExtractCLI(build.url, effectiveChecksums);
}
// Install our wrapper
@@ -221,13 +289,23 @@ async function run () {
// Add to path
addPath(pathToCLI);
// Set up provider acceptance test environment variables
if (providerAcceptanceTest) {
const exeSuffix = platform().startsWith('win') ? '.exe' : '';
const binaryName = wrapper ? `tofu-bin${exeSuffix}` : `tofu${exeSuffix}`;
exportVariable('TF_ACC', '1');
exportVariable('TF_ACC_PROVIDER_NAMESPACE', 'hashicorp');
exportVariable('TF_ACC_PROVIDER_HOST', 'registry.opentofu.org');
exportVariable('TF_ACC_TERRAFORM_PATH', join(pathToCLI, binaryName));
}
// Add credentials to file if they are provided
if (credentialsHostname && credentialsToken) {
await addCredentials(credentialsHostname, credentialsToken, osPlatform);
}
return release;
} catch (error) {
logError(error);
logError(getErrorMessage(error));
throw error;
}
}
+62
View File
@@ -0,0 +1,62 @@
/**
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { getErrorMessage, getErrorDetail } from '../error-utils.js';
describe('error-utils', () => {
describe('getErrorMessage', () => {
it('returns message for standard Error', () => {
expect(getErrorMessage(new Error('Something failed'))).toBe('Something failed');
});
it('includes cause for Error with cause (Node 16+)', () => {
const cause = new Error('Network timeout');
const err = new Error('Download failed');
err.cause = cause;
expect(getErrorMessage(err)).toBe('Download failed: Network timeout');
});
it('flattens AggregateError into a single message', () => {
const err = new AggregateError(
[new Error('ECONNREFUSED'), new Error('getaddrinfo ENOTFOUND')],
'AggregateError'
);
const msg = getErrorMessage(err);
expect(msg).toContain('ECONNREFUSED');
expect(msg).toContain('getaddrinfo ENOTFOUND');
expect(msg).not.toBe('AggregateError');
});
it('returns fallback for AggregateError with empty errors', () => {
const err = new AggregateError([], 'AggregateError');
expect(getErrorMessage(err)).toBe('AggregateError (one or more operations failed)');
});
it('coerces non-Error to string', () => {
expect(getErrorMessage('oops')).toBe('oops');
expect(getErrorMessage(123)).toBe('123');
});
});
describe('getErrorDetail', () => {
it('includes stack for Error', () => {
const err = new Error('test');
const detail = getErrorDetail(err);
expect(detail).toContain('test');
expect(detail).toContain('Error');
});
it('includes each nested error for AggregateError', () => {
const err = new AggregateError(
[new Error('A'), new Error('B')],
'AggregateError'
);
const detail = getErrorDetail(err);
expect(detail).toContain('A');
expect(detail).toContain('B');
expect(detail).toContain('2 error(s)');
});
});
});
+69 -1
View File
@@ -4,7 +4,7 @@
* SPDX-License-Identifier: MPL-2.0
*/
import { Release, getRelease } from '../releases.js';
import { Release, getRelease, getDownloadChecksum, parseChecksum } from '../releases.js';
describe('getRelease', () => {
function mockFetchReleases () {
@@ -196,3 +196,71 @@ describe('getRelease', () => {
}
);
});
describe('parseChecksum', () => {
const sums = [
'933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad tofu_1.6.0_linux_amd64.zip',
'd3d29f51e75a701fc7cf67c0644a8c883a85f36cf1621461988baffd88e7f361 tofu_1.6.0_darwin_arm64.zip'
].join('\n') + '\n';
it('returns the lowercase checksum for a matching file name', () => {
expect(parseChecksum(sums, 'tofu_1.6.0_darwin_arm64.zip')).toBe(
'd3d29f51e75a701fc7cf67c0644a8c883a85f36cf1621461988baffd88e7f361'
);
});
it('returns null when the file name is not listed', () => {
expect(parseChecksum(sums, 'tofu_1.6.0_windows_amd64.zip')).toBeNull();
});
it('ignores blank lines and binary-mode "*" prefixes', () => {
const body = '\nABCDEF0123456789 *tofu_1.6.0_linux_arm64.zip\n\n';
expect(parseChecksum(body, 'tofu_1.6.0_linux_arm64.zip')).toBe(
'abcdef0123456789'
);
});
it('returns null for an empty body', () => {
expect(parseChecksum('', 'tofu_1.6.0_linux_amd64.zip')).toBeNull();
});
});
describe('getDownloadChecksum', () => {
it('fetches the SHA256SUMS and returns the matching checksum', async () => {
const fetchSumsFn = async (version) => {
expect(version).toBe('1.6.0');
return '933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad tofu_1.6.0_linux_amd64.zip\n';
};
const got = await getDownloadChecksum(
'1.6.0',
'tofu_1.6.0_linux_amd64.zip',
fetchSumsFn
);
expect(got).toBe(
'933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad'
);
});
it('returns null when the asset is absent from the SHA256SUMS', async () => {
const fetchSumsFn = async () =>
'933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad tofu_1.6.0_linux_amd64.zip\n';
const got = await getDownloadChecksum(
'1.6.0',
'tofu_1.6.0_windows_amd64.zip',
fetchSumsFn
);
expect(got).toBeNull();
});
it('propagates fetch errors', async () => {
const fetchSumsFn = async () => {
throw new Error('boom');
};
await expect(
getDownloadChecksum('1.6.0', 'tofu_1.6.0_linux_amd64.zip', fetchSumsFn)
).rejects.toThrow('boom');
});
});
+183 -3
View File
@@ -14,6 +14,7 @@ import { join } from 'path';
// Set up mocks BEFORE dynamic imports
jest.unstable_mockModule('@actions/core', () => ({
getInput: jest.fn(),
getMultilineInput: jest.fn(),
setOutput: jest.fn(),
setFailed: jest.fn(),
debug: jest.fn(),
@@ -38,15 +39,21 @@ jest.unstable_mockModule('@actions/tool-cache', () => ({
jest.unstable_mockModule('../releases.js', () => ({
getRelease: jest.fn(),
getDownloadChecksum: jest.fn(),
Release: jest.fn()
}));
jest.unstable_mockModule('../util.js', () => ({
fileSHA256: jest.fn()
}));
// Dynamic imports pick up the mocks
const { getInput, warning } = await import('@actions/core');
const { getInput, warning, exportVariable, getMultilineInput } = await import('@actions/core');
const tc = await import('@actions/tool-cache');
const io = await import('@actions/io');
const { getRelease } = await import('../releases.js');
const { getRelease, getDownloadChecksum } = await import('../releases.js');
const { default: setup } = await import('../setup-tofu.js');
const { fileSHA256 } = await import('../util.js');
// Set up global test fixtures
const fallbackVersion = 'latest';
@@ -70,10 +77,17 @@ describe('setup-tofu', () => {
const mockRelease = {
version: '1.10.5',
getBuild: jest.fn().mockReturnValue({ url: 'mock-url' })
getBuild: jest.fn().mockReturnValue({
url: 'mock-url',
name: 'tofu_1.10.5_linux_amd64.zip'
})
};
getRelease.mockResolvedValue(mockRelease);
// Default to "no published checksum retrievable" so tests that don't
// exercise checksum behaviour keep skipping verification, as before.
getDownloadChecksum.mockResolvedValue(null);
// Write version file to temporary directory
tempDirPath = join(tmpdir(), 'setup-tofu-');
tempDir = await fs.mkdtemp(tempDirPath);
@@ -88,12 +102,20 @@ describe('setup-tofu', () => {
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'true',
provider_acceptance_tests: 'false',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: []
};
return defaults[name] || [];
});
// Mock environment variables
process.env.GITHUB_TOKEN = 'mock-github-token';
});
@@ -264,6 +286,7 @@ describe('setup-tofu', () => {
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'true',
provider_acceptance_tests: 'false',
cache: 'false',
github_token: ''
};
@@ -278,4 +301,161 @@ describe('setup-tofu', () => {
expect(tc.cacheDir).not.toHaveBeenCalled();
});
});
describe('provider_acceptance_tests functionality', () => {
it('should export acceptance test env vars when enabled without wrapper', async () => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'false',
provider_acceptance_tests: 'true',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(exportVariable).toHaveBeenCalledWith('TF_ACC', '1');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_NAMESPACE', 'hashicorp');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_HOST', 'registry.opentofu.org');
expect(exportVariable).toHaveBeenCalledWith(
'TF_ACC_TERRAFORM_PATH',
expect.stringContaining('tofu')
);
expect(exportVariable).not.toHaveBeenCalledWith(
'TF_ACC_TERRAFORM_PATH',
expect.stringContaining('tofu-bin')
);
});
it('should point TF_ACC_TERRAFORM_PATH to tofu-bin when wrapper is enabled', async () => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'true',
provider_acceptance_tests: 'true',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(exportVariable).toHaveBeenCalledWith('TF_ACC', '1');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_NAMESPACE', 'hashicorp');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_HOST', 'registry.opentofu.org');
expect(exportVariable).toHaveBeenCalledWith(
'TF_ACC_TERRAFORM_PATH',
expect.stringContaining('tofu-bin')
);
});
it('should not export acceptance test env vars when disabled', async () => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'false',
provider_acceptance_tests: 'false',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC', expect.anything());
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC_PROVIDER_NAMESPACE', expect.anything());
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC_PROVIDER_HOST', expect.anything());
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC_TERRAFORM_PATH', expect.anything());
});
});
describe('checksum validation', () => {
const mockChecksum = 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6';
const mockChecksum2 = 'fcfac0a865b57e0711cb8bae47c8fc70ad93198fa6146a40020ea459715fda83';
const mockInvalidChecksum = 'invalidchecksuminvalidchecksuminvalidchecksuminvalidchecksum';
fileSHA256.mockResolvedValue(mockChecksum);
it('should validate checksum when checksums are provided', async () => {
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: [mockInvalidChecksum, mockChecksum]
};
return defaults[name] ?? [];
});
await setup();
expect(fileSHA256).toHaveBeenCalled();
// An explicit checksums input wins; the published SHA256SUMS is not fetched.
expect(getDownloadChecksum).not.toHaveBeenCalled();
});
it('should validate against the published SHA256SUMS when no checksums input is provided', async () => {
fileSHA256.mockResolvedValue(mockChecksum);
getDownloadChecksum.mockResolvedValue(mockChecksum);
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: []
};
return defaults[name] ?? [];
});
await setup();
expect(getDownloadChecksum).toHaveBeenCalledWith(
'1.10.5',
'tofu_1.10.5_linux_amd64.zip'
);
expect(fileSHA256).toHaveBeenCalled();
});
it('should skip verification when no published checksum can be retrieved', async () => {
getDownloadChecksum.mockResolvedValue(null);
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: []
};
return defaults[name] ?? [];
});
await setup();
expect(getDownloadChecksum).toHaveBeenCalled();
expect(fileSHA256).not.toHaveBeenCalled();
expect(warning).toHaveBeenCalledWith(
expect.stringContaining('Proceeding without checksum verification')
);
});
it('should throw error when checksum validation fails', async () => {
fileSHA256.mockResolvedValue(mockInvalidChecksum);
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: [mockChecksum, mockChecksum2]
};
return defaults[name] ?? [];
});
await expect(setup()).rejects.toMatchObject(new Error(
`Failed to validate OpenTofu CLI zip checksum. Received: ${mockInvalidChecksum}. Valid checksums: ${mockChecksum}, ${mockChecksum2}`));
expect(fileSHA256).toHaveBeenCalled();
});
});
});
+16
View File
@@ -0,0 +1,16 @@
/**
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { createHash } from 'crypto';
import { createReadStream } from 'fs';
import { pipeline } from 'stream/promises';
export async function fileSHA256 (filePath) {
const hash = createHash('sha256');
const fileStream = createReadStream(filePath);
await pipeline(fileStream, hash);
return hash.digest('hex');
}
+634 -576
View File
File diff suppressed because it is too large. Load diff
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "setup-opentofu",
"version": "1.0.1",
"version": "2.0.2",
"description": "Setup OpenTofu CLI for GitHub Actions",
"type": "module",
"license": "MPL-2.0",
@@ -20,17 +20,17 @@
"keywords": [],
"author": "",
"dependencies": {
"@actions/core": "^3.0.0",
"@actions/core": "^3.0.1",
"@actions/exec": "^3.0.0",
"@actions/http-client": "^4.0.0",
"@actions/http-client": "4.0.1",
"@actions/io": "^3.0.2",
"@actions/tool-cache": "^4.0.0",
"semver": "^7.7.4"
"semver": "^7.8.3"
},
"devDependencies": {
"@vercel/ncc": "0.38.4",
"husky": "9.1.7",
"jest": "^30.3.0",
"jest": "^30.4.2",
"semistandard": "17.0.0"
},
"semistandard": {