From 4bcfe8cded50244b23068290db14e4d1ef4cb696 Mon Sep 17 00:00:00 2001 From: Kim Wagner Date: Mon, 13 Apr 2026 21:46:38 +0200 Subject: [PATCH] feat: added support for providing optional checksums for ZIP validation (#107) Signed-off-by: Kim --- README.md | 12 +++++++ action.yml | 3 ++ dist/index.js | 42 ++++++++++++++++++++++-- lib/setup-tofu.js | 23 +++++++++++-- lib/test/setup-tofu.test.js | 64 ++++++++++++++++++++++++++++++++++++- lib/util.js | 16 ++++++++++ 6 files changed, 153 insertions(+), 7 deletions(-) create mode 100644 lib/util.js diff --git a/README.md b/README.md index 9c48618..2479214 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,17 @@ steps: cache: true ``` +Validation can be enabled to check the downloaded OpenTofu CLI SHA256 hash against a newline-delimited list of checksums: + +```yaml +steps: +- uses: opentofu/setup-opentofu@v2 + with: + checksums: | + 933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad + d3d29f51e75a701fc7cf67c0644a8c883a85f36cf1621461988baffd88e7f361 +``` + Subsequent steps can access outputs when the wrapper script is installed: ```yaml @@ -275,6 +286,7 @@ The action supports the following inputs: 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`. - `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. Defaults to `[]` ## Outputs diff --git a/action.yml b/action.yml index 274529f..575f48e 100644 --- a/action.yml +++ b/action.yml @@ -28,6 +28,9 @@ 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 + checksums: + description: Newline-delimited list of valid checksums (SHA256 hashes) for the downloaded OpenTofu binary. When set, the action will verify that the binary matches one of these checksums before proceeding. + required: false outputs: stdout: description: 'The STDOUT stream of the call to the `tofu` binary.' diff --git a/dist/index.js b/dist/index.js index e06dcfe..1256151 100644 --- a/dist/index.js +++ b/dist/index.js @@ -34621,6 +34621,26 @@ async function getRelease ( +;// CONCATENATED MODULE: external "stream/promises" +const promises_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/promises"); +;// CONCATENATED MODULE: ./lib/util.js +/** + * Copyright (c) OpenTofu + * SPDX-License-Identifier: MPL-2.0 + */ + + + + + +async function fileSHA256 (filePath) { + const hash = (0,external_crypto_namespaceObject.createHash)('sha256'); + const fileStream = (0,external_fs_namespaceObject.createReadStream)(filePath); + + await (0,promises_namespaceObject.pipeline)(fileStream, hash); + return hash.digest('hex'); +} + ;// CONCATENATED MODULE: ./lib/setup-tofu.js /** * Copyright (c) HashiCorp, Inc. @@ -34641,6 +34661,7 @@ async function getRelease ( + // __dirname is not available in ES modules, so we need to construct it ourselves const setup_tofu_dirname = (0,external_path_namespaceObject.dirname)((0,external_url_namespaceObject.fileURLToPath)(import.meta.url)); @@ -34663,7 +34684,7 @@ function mapOS (os) { return os; } -async function downloadAndExtractCLI (url) { +async function downloadAndExtractCLI (url, checksums) { core_debug(`Downloading OpenTofu CLI from ${url}`); let pathToCLIZip; try { @@ -34673,6 +34694,20 @@ async function downloadAndExtractCLI (url) { 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}`); } @@ -34777,6 +34812,7 @@ async function run () { const credentialsToken = getInput('cli_config_credentials_token'); const wrapper = getInput('tofu_wrapper') === 'true'; const useCache = getInput('cache') === 'true'; + const checksums = getMultilineInput('checksums'); let githubToken = getInput('github_token'); if ( githubToken === '' && @@ -34832,12 +34868,12 @@ async function run () { pathToCLI = cachedPath; } else { core_debug(`OpenTofu version ${release.version} not found in cache, downloading...`); - const extractedPath = await downloadAndExtractCLI(build.url); + const extractedPath = await downloadAndExtractCLI(build.url, checksums); core_debug(`Caching OpenTofu version ${release.version} to tool cache`); pathToCLI = await cacheDir(extractedPath, 'tofu', release.version, buildArch); } } else { - pathToCLI = await downloadAndExtractCLI(build.url); + pathToCLI = await downloadAndExtractCLI(build.url, checksums); } // Install our wrapper diff --git a/lib/setup-tofu.js b/lib/setup-tofu.js index 922c70e..3218dc4 100644 --- a/lib/setup-tofu.js +++ b/lib/setup-tofu.js @@ -16,6 +16,7 @@ import { error as logError, exportVariable, getInput, + getMultilineInput, warning, addPath } from '@actions/core'; @@ -23,6 +24,7 @@ import { downloadTool, extractZip, find, cacheDir } from '@actions/tool-cache'; import { mv, cp, mkdirP } from '@actions/io'; import { getRelease } 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)); @@ -46,7 +48,7 @@ function mapOS (os) { return os; } -async function downloadAndExtractCLI (url) { +async function downloadAndExtractCLI (url, checksums) { debug(`Downloading OpenTofu CLI from ${url}`); let pathToCLIZip; try { @@ -56,6 +58,20 @@ async function downloadAndExtractCLI (url) { 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}`); } @@ -162,6 +178,7 @@ async function run () { const credentialsToken = getInput('cli_config_credentials_token'); const wrapper = getInput('tofu_wrapper') === 'true'; const useCache = getInput('cache') === 'true'; + const checksums = getMultilineInput('checksums'); let githubToken = getInput('github_token'); if ( githubToken === '' && @@ -217,12 +234,12 @@ async function run () { pathToCLI = cachedPath; } else { debug(`OpenTofu version ${release.version} not found in cache, downloading...`); - const extractedPath = await downloadAndExtractCLI(build.url); + const extractedPath = await downloadAndExtractCLI(build.url, checksums); debug(`Caching OpenTofu version ${release.version} to tool cache`); pathToCLI = await cacheDir(extractedPath, 'tofu', release.version, buildArch); } } else { - pathToCLI = await downloadAndExtractCLI(build.url); + pathToCLI = await downloadAndExtractCLI(build.url, checksums); } // Install our wrapper diff --git a/lib/test/setup-tofu.test.js b/lib/test/setup-tofu.test.js index 4f991fb..2ae4cb0 100644 --- a/lib/test/setup-tofu.test.js +++ b/lib/test/setup-tofu.test.js @@ -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(), @@ -41,12 +42,17 @@ jest.unstable_mockModule('../releases.js', () => ({ 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, getMultilineInput, warning } = await import('@actions/core'); const tc = await import('@actions/tool-cache'); const io = await import('@actions/io'); const { getRelease } = 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'; @@ -94,6 +100,13 @@ describe('setup-tofu', () => { return defaults[name] || ''; }); + getMultilineInput.mockImplementation((name) => { + const defaults = { + checksums: [] + }; + return defaults[name] || []; + }); + // Mock environment variables process.env.GITHUB_TOKEN = 'mock-github-token'; }); @@ -278,4 +291,53 @@ describe('setup-tofu', () => { expect(tc.cacheDir).not.toHaveBeenCalled(); }); }); + + 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(); + }); + + it('should not validate checksum when no checksums are provided', async () => { + getMultilineInput.mockImplementation((name) => { + const defaults = { + checksums: [] + + }; + return defaults[name] ?? []; + }); + + await setup(); + + expect(fileSHA256).not.toHaveBeenCalled(); + }); + + 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(); + }); + }); }); diff --git a/lib/util.js b/lib/util.js new file mode 100644 index 0000000..6e858ea --- /dev/null +++ b/lib/util.js @@ -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'); +}