From d3dc77de537f519cb63f30a712191a592cc8deac Mon Sep 17 00:00:00 2001 From: somaz <112675579+somaz94@users.noreply.github.com> Date: Sat, 27 Jun 2026 00:42:14 +0900 Subject: [PATCH] feat: verify download against published SHA256SUMS by default (#121) Signed-off-by: somaz --- README.md | 6 +- action.yml | 2 +- dist/index.js | 122 +++++++++++++++++++++++++++++++++++- lib/releases.js | 82 +++++++++++++++++++++++- lib/setup-tofu.js | 44 ++++++++++++- lib/test/releases.test.js | 70 ++++++++++++++++++++- lib/test/setup-tofu.test.js | 41 +++++++++++- 7 files changed, 354 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index d4bd250..f2445a7 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,9 @@ steps: timeout-minutes: 10 ``` -Validation can be enabled to check the downloaded OpenTofu CLI SHA256 hash against a newline-delimited list of checksums: +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: @@ -303,7 +305,7 @@ The action supports the following inputs: `TF_ACC=1`, `TF_ACC_PROVIDER_NAMESPACE=hashicorp`, `TF_ACC_PROVIDER_HOST=registry.opentofu.org`, and `TF_ACC_TERRAFORM_PATH=`. 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 `[]` +- `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 diff --git a/action.yml b/action.yml index 19a2d95..61eca1e 100644 --- a/action.yml +++ b/action.yml @@ -33,7 +33,7 @@ inputs: default: 'false' 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. + 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: diff --git a/dist/index.js b/dist/index.js index b61613e..1fe98fb 100644 --- a/dist/index.js +++ b/dist/index.js @@ -34638,6 +34638,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 lib_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) => node_modules_semver.prerelease(v) === null) @@ -34820,6 +34900,42 @@ async function downloadAndExtractCLI (url, checksums) { 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; + } + + core_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; @@ -34950,12 +35066,14 @@ async function run () { pathToCLI = cachedPath; } else { core_debug(`OpenTofu version ${release.version} not found in cache, downloading...`); - const extractedPath = await downloadAndExtractCLI(build.url, checksums); + const effectiveChecksums = await resolveChecksums(checksums, release.version, build.name); + const extractedPath = await downloadAndExtractCLI(build.url, effectiveChecksums); core_debug(`Caching OpenTofu version ${release.version} to tool cache`); pathToCLI = await cacheDir(extractedPath, 'tofu', release.version, buildArch); } } else { - pathToCLI = await downloadAndExtractCLI(build.url, checksums); + const effectiveChecksums = await resolveChecksums(checksums, release.version, build.name); + pathToCLI = await downloadAndExtractCLI(build.url, effectiveChecksums); } // Install our wrapper diff --git a/lib/releases.js b/lib/releases.js index 16a27b0..fed827a 100644 --- a/lib/releases.js +++ b/lib/releases.js @@ -83,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) @@ -145,4 +225,4 @@ async function getRelease ( return releases.find((release) => release.version === versionSelected); } -export { getRelease, Release }; +export { getRelease, getDownloadChecksum, parseChecksum, Release }; diff --git a/lib/setup-tofu.js b/lib/setup-tofu.js index 43ca5ab..47e8b01 100644 --- a/lib/setup-tofu.js +++ b/lib/setup-tofu.js @@ -22,7 +22,7 @@ import { } 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'; @@ -103,6 +103,42 @@ async function downloadAndExtractCLI (url, checksums) { 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; @@ -235,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, checksums); + 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, checksums); + const effectiveChecksums = await resolveChecksums(checksums, release.version, build.name); + pathToCLI = await downloadAndExtractCLI(build.url, effectiveChecksums); } // Install our wrapper diff --git a/lib/test/releases.test.js b/lib/test/releases.test.js index a703c4b..ccb5ea6 100644 --- a/lib/test/releases.test.js +++ b/lib/test/releases.test.js @@ -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'); + }); +}); diff --git a/lib/test/setup-tofu.test.js b/lib/test/setup-tofu.test.js index 2093539..652df86 100644 --- a/lib/test/setup-tofu.test.js +++ b/lib/test/setup-tofu.test.js @@ -39,6 +39,7 @@ jest.unstable_mockModule('@actions/tool-cache', () => ({ jest.unstable_mockModule('../releases.js', () => ({ getRelease: jest.fn(), + getDownloadChecksum: jest.fn(), Release: jest.fn() })); @@ -50,7 +51,7 @@ jest.unstable_mockModule('../util.js', () => ({ 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'); @@ -76,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); @@ -392,9 +400,13 @@ describe('setup-tofu', () => { await setup(); expect(fileSHA256).toHaveBeenCalled(); + // An explicit checksums input wins; the published SHA256SUMS is not fetched. + expect(getDownloadChecksum).not.toHaveBeenCalled(); }); - it('should not validate checksum when no checksums are provided', async () => { + 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: [] @@ -405,7 +417,30 @@ describe('setup-tofu', () => { 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 () => {