mirror of
https://github.com/opentofu/setup-opentofu.git
synced 2026-11-29 11:34:36 +01:00
feat: verify download against published SHA256SUMS by default (#121)
Signed-off-by: somaz <genius5711@gmail.com>
This commit is contained in:
1 parent
56007213a1
commit
d3dc77de53
7 files changed
+354
-13
No files matched your search
+81
-1
@@ -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 };
|
||||
+41
-3
@@ -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
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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 () => {
|
||||
|
||||
Reference in new issue
Block a user