Add the require-checksums input (#1139)

Adds `require-checksums`, which enforces the "intrinsic or explicitly
provided checksum" idea. See #1032.

<details>
<summary>Automated notes</summary>

Add the opt-in input `require-checksums`. When enabled, setup-uv
verifies the archive against the workflow's `checksum` input or the
digest bundled for the resolved uv version, architecture, and platform.
If neither is available, setup fails before downloading the archive. By
default, setup-uv continues to accept manifest checksums as it does
today.

The setting also applies to custom manifests, which can still supply
download URLs. On persistent runners, strict mode keys tool-cache
entries by the expected archive digest so a previous manifest-verified
installation cannot bypass the check.

Closes #1032. Builds on #1033.

## Validation

- `npm ci --ignore-scripts` and `npm run all` passed under Node 24 (182
tests).
- The packaged-action regression test installs a custom build into a
temporary runner tool cache. It checks that strict mode rejects a
manifest-only version even with a warm cache, reuses a verified
installation for the same digest, and rejects a changed digest or a
custom build that conflicts with the bundled digest.

</details>

---------

Signed-off-by: William Woodruff <william@yossarian.net>
This commit is contained in:
William Woodruff authored and GitHub committed 2026-11-16 22:24:53 +01:00
1 parent fc0acc2d6f
commit de938e707d
16 files changed
+235 -43

No files matched your search

+4 -1
View File
@@ -6,7 +6,7 @@ Set up your GitHub Actions workflow with a specific version of [uv](https://docs
- Cache the installed version of uv to speed up consecutive runs on self-hosted runners - Cache the installed version of uv to speed up consecutive runs on self-hosted runners
- Register problem matchers for error output - Register problem matchers for error output
- (Optional) Persist the uv's cache in the GitHub Actions Cache - (Optional) Persist the uv's cache in the GitHub Actions Cache
- (Optional) Verify the checksum of the downloaded uv executable - Verify the SHA-256 checksum of the downloaded uv archive
## Contents ## Contents
@@ -75,6 +75,9 @@ Have a look under [Advanced Configuration](#advanced-configuration) for detailed
# The checksum of the uv version to install # The checksum of the uv version to install
checksum: "" checksum: ""
# Require a checksum bundled with setup-uv or supplied through the checksum input
require-checksums: "false"
# Used when downloading uv from GitHub releases # Used when downloading uv from GitHub releases
github-token: ${{ github.token }} github-token: ${{ github.token }}
+2 -2
View File
@@ -56,7 +56,7 @@ test("manifest checksums are used when no known checksum exists", async () => {
).rejects.toThrow("did not match"); ).rejects.toThrow("did not match");
}); });
test("empty manifest checksums are rejected", async () => { test.each(["", undefined])("rejects missing checksums (%s)", async (hash) => {
await expect( await expect(
validateChecksum( validateChecksum(
undefined, undefined,
@@ -64,7 +64,7 @@ test("empty manifest checksums are rejected", async () => {
"aarch64", "aarch64",
"pc-windows-msvc", "pc-windows-msvc",
"1.2.3", "1.2.3",
"", hash,
), ),
).rejects.toThrow("No checksum found"); ).rejects.toThrow("No checksum found");
}); });
@@ -0,0 +1,93 @@
import { execFile, execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import fs from "node:fs";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { expect, test } from "@jest/globals";
import { getArch, getPlatform } from "../../src/utils/platforms";
test("enforces intrinsic checksums on downloads and tool-cache hits", async () => {
const platform = await getPlatform();
const target = `${getArch()}-${platform}`;
const windows = platform === "pc-windows-msvc";
const dir = fs.mkdtempSync(path.join(tmpdir(), "setup-uv-checksums-"));
const server = createServer();
try {
const member = windows ? "uv.exe" : `uv-${target}/uv`;
const archiveName = windows ? "uv.zip" : "uv.tar.gz";
fs.mkdirSync(path.dirname(path.join(dir, member)), { recursive: true });
fs.writeFileSync(path.join(dir, member), "test build");
execFileSync("tar", ["-acf", archiveName, member], { cwd: dir });
const archive = fs.readFileSync(path.join(dir, archiveName));
const digest = createHash("sha256").update(archive).digest("hex");
let downloads = 0;
server.on("request", (_req, res) => {
downloads++;
res.end(archive);
});
await new Promise<void>((resolve) =>
server.listen(0, "127.0.0.1", resolve),
);
const address = server.address() as AddressInfo;
function install(version: string, strict: boolean, checksum = "") {
const manifest = JSON.stringify({
artifacts: [
{
archive_format: windows ? "zip" : "tar.gz",
platform: target,
sha256: digest,
url: `http://127.0.0.1:${address.port}/${archiveName}`,
},
],
version,
});
return promisify(execFile)(process.execPath, ["dist/setup/index.cjs"], {
env: {
"INPUT_ACTIVATE-ENVIRONMENT": "false",
INPUT_CHECKSUM: checksum,
"INPUT_MANIFEST-FILE": `data:application/json,${encodeURIComponent(manifest)}`,
"INPUT_NO-PROJECT": "false",
"INPUT_PYTHON-VERSION": "3.13",
"INPUT_REQUIRE-CHECKSUMS": String(strict),
INPUT_VERSION: version,
"INPUT_WORKING-DIRECTORY": dir,
PATH: process.env.PATH,
RUNNER_TEMP: dir,
RUNNER_TOOL_CACHE: path.join(dir, "cache"),
SystemRoot: process.env.SystemRoot,
},
timeout: 10_000,
});
}
const version = "99.0.0";
await install(version, false);
await expect(install(version, true)).rejects.toMatchObject({
stdout: expect.stringContaining(
`No bundled checksum for ${target}-${version}`,
),
});
expect(downloads).toBe(1);
await install(version, true, digest);
expect(downloads).toBe(2);
await install(version, true, digest);
expect(downloads).toBe(2);
await expect(install(version, true, "0".repeat(64))).rejects.toMatchObject({
stdout: expect.stringContaining("did not match"),
});
// The custom manifest also offers these bytes under a known release version.
await expect(install("0.9.26", true)).rejects.toMatchObject({
stdout: expect.stringContaining("did not match"),
});
await expect(install(version, true, "../uv")).rejects.toMatchObject({
stdout: expect.stringContaining("Expected a SHA-256 checksum"),
});
} finally {
server.close();
fs.rmSync(dir, { force: true, recursive: true });
}
}, 30_000);
+1
View File
@@ -26,6 +26,7 @@ export function createSetupInputs(
pythonDir: "/tmp/uv-python-dir", pythonDir: "/tmp/uv-python-dir",
pythonVersion: "", pythonVersion: "",
quiet: false, quiet: false,
requireChecksums: false,
resolutionStrategy: "highest", resolutionStrategy: "highest",
restoreCache: false, restoreCache: false,
saveCache: true, saveCache: true,
+6
View File
@@ -109,9 +109,15 @@ describe("loadInputs", () => {
expect(inputs.exportPythonArch).toBe(false); expect(inputs.exportPythonArch).toBe(false);
expect(inputs.venvPath).toBe("/workspace/.venv"); expect(inputs.venvPath).toBe("/workspace/.venv");
expect(inputs.manifestFile).toBeUndefined(); expect(inputs.manifestFile).toBeUndefined();
expect(inputs.requireChecksums).toBe(false);
expect(inputs.resolutionStrategy).toBe("highest"); expect(inputs.resolutionStrategy).toBe("highest");
}); });
it("loads require-checksums", () => {
mockInputs["require-checksums"] = "true";
expect(loadInputs().requireChecksums).toBe(true);
});
it("uses the Python version from an explicitly selected .tool-versions file", () => { it("uses the Python version from an explicitly selected .tool-versions file", () => {
mockInputs["working-directory"] = createTempProject({ mockInputs["working-directory"] = createTempProject({
".tool-versions": "uv 0.12.3\npython 3.13.1t\n", ".tool-versions": "uv 0.12.3\npython 3.13.1t\n",
+2
View File
@@ -19,6 +19,8 @@ inputs:
type: string type: string
checksum: checksum:
type: string type: string
require-checksums:
type: boolean
github-token: github-token:
type: string type: string
enable-cache: enable-cache:
+3
View File
@@ -30,6 +30,9 @@ inputs:
checksum: checksum:
description: "The checksum of the uv version to install" description: "The checksum of the uv version to install"
required: false required: false
require-checksums:
description: "Require a SHA-256 checksum bundled with setup-uv or supplied through the checksum input."
default: "false"
github-token: github-token:
description: description:
"Used when downloading uv from GitHub releases." "Used when downloading uv from GitHub releases."
Generated Vendored
+2
View File
@@ -66242,6 +66242,7 @@ function loadInputs() {
const noProject = getBooleanInput("no-project"); const noProject = getBooleanInput("no-project");
const venvPath = getVenvPath(workingDirectory, activateEnvironment); const venvPath = getVenvPath(workingDirectory, activateEnvironment);
const checksum = getInput("checksum"); const checksum = getInput("checksum");
const requireChecksums = getBooleanInput("require-checksums");
const enableCache = getEnableCache(); const enableCache = getEnableCache();
const restoreCache2 = getInput("restore-cache") === "true"; const restoreCache2 = getInput("restore-cache") === "true";
const saveCache4 = getSaveCache(); const saveCache4 = getSaveCache();
@@ -66286,6 +66287,7 @@ function loadInputs() {
pythonDir, pythonDir,
pythonVersion, pythonVersion,
quiet: quiet2, quiet: quiet2,
requireChecksums,
resolutionStrategy, resolutionStrategy,
restoreCache: restoreCache2, restoreCache: restoreCache2,
saveCache: saveCache4, saveCache: saveCache4,
Generated Vendored
+42 -21
View File
@@ -101009,11 +101009,7 @@ async function validateChecksum(checksum, downloadPath, arch3, platform2, versio
const hasManifestChecksum = manifestChecksum !== void 0 && manifestChecksum !== ""; const hasManifestChecksum = manifestChecksum !== void 0 && manifestChecksum !== "";
const checksumToUse = hasProvidedChecksum ? checksum : knownChecksum ?? (hasManifestChecksum ? manifestChecksum : void 0); const checksumToUse = hasProvidedChecksum ? checksum : knownChecksum ?? (hasManifestChecksum ? manifestChecksum : void 0);
if (checksumToUse === void 0) { if (checksumToUse === void 0) {
if (manifestChecksum !== void 0) { throw new Error(`No checksum found for ${key} in manifest.`);
throw new Error(`No checksum found for ${key} in manifest.`);
}
debug(`No checksum found for ${key}.`);
return;
} }
const checksumSource = hasProvidedChecksum ? "provided checksum" : knownChecksum !== void 0 ? `KNOWN_CHECKSUMS entry for ${key}` : "manifest checksum"; const checksumSource = hasProvidedChecksum ? "provided checksum" : knownChecksum !== void 0 ? `KNOWN_CHECKSUMS entry for ${key}` : "manifest checksum";
debug(`Validating checksum using ${checksumSource}.`); debug(`Validating checksum using ${checksumSource}.`);
@@ -102888,18 +102884,30 @@ function minSatisfying3(versions, version3) {
} }
// src/download/download-version.ts // src/download/download-version.ts
function tryGetFromToolCache(arch3, version3) { function getIntrinsicChecksum(key, providedChecksum) {
const checksum = providedChecksum || KNOWN_CHECKSUMS[key];
if (!checksum) {
throw new Error(
`No bundled checksum for ${key}. With require-checksums enabled, update setup-uv or provide the checksum input for this archive.`
);
}
if (!/^[a-f0-9]{64}$/.test(checksum)) {
throw new Error(`Expected a SHA-256 checksum for ${key}.`);
}
return checksum;
}
function tryGetFromToolCache(arch3, version3, toolCacheName = TOOL_CACHE_NAME) {
debug(`Trying to get uv from tool cache for ${version3}...`); debug(`Trying to get uv from tool cache for ${version3}...`);
const cachedVersions = findAllVersions(TOOL_CACHE_NAME, arch3); const cachedVersions = findAllVersions(toolCacheName, arch3);
debug(`Cached versions: ${cachedVersions}`); debug(`Cached versions: ${cachedVersions}`);
let resolvedVersion = evaluateVersions(cachedVersions, version3); let resolvedVersion = evaluateVersions(cachedVersions, version3);
if (resolvedVersion === "") { if (resolvedVersion === "") {
resolvedVersion = version3; resolvedVersion = version3;
} }
const installedPath = find(TOOL_CACHE_NAME, resolvedVersion, arch3); const installedPath = find(toolCacheName, resolvedVersion, arch3);
return { installedPath, version: resolvedVersion }; return { installedPath, version: resolvedVersion };
} }
async function downloadVersion(platform2, arch3, version3, checksum, githubToken, manifestUrl, downloadFromAstralMirror = true) { async function downloadVersion(platform2, arch3, version3, checksum, githubToken, manifestUrl, downloadFromAstralMirror = true, toolCacheName = TOOL_CACHE_NAME) {
const artifact = await getArtifact(version3, arch3, platform2, manifestUrl); const artifact = await getArtifact(version3, arch3, platform2, manifestUrl);
if (!artifact) { if (!artifact) {
throw new Error( throw new Error(
@@ -102919,7 +102927,8 @@ async function downloadVersion(platform2, arch3, version3, checksum, githubToken
version3, version3,
resolvedChecksum, resolvedChecksum,
manifestChecksum, manifestChecksum,
githubTokenForUrl(downloadUrl, githubToken) githubTokenForUrl(downloadUrl, githubToken),
toolCacheName
); );
} catch (err) { } catch (err) {
if (mirrorUrl === void 0) { if (mirrorUrl === void 0) {
@@ -102936,7 +102945,8 @@ async function downloadVersion(platform2, arch3, version3, checksum, githubToken
version3, version3,
resolvedChecksum, resolvedChecksum,
manifestChecksum, manifestChecksum,
githubTokenForUrl(artifact.downloadUrl, githubToken) githubTokenForUrl(artifact.downloadUrl, githubToken),
toolCacheName
); );
} }
} }
@@ -102953,7 +102963,7 @@ function githubTokenForUrl(downloadUrl, githubToken) {
return void 0; return void 0;
} }
} }
async function downloadArtifact(downloadUrl, artifactName, platform2, arch3, version3, checksum, manifestChecksum, githubToken) { async function downloadArtifact(downloadUrl, artifactName, platform2, arch3, version3, checksum, manifestChecksum, githubToken, toolCacheName) {
info2(`Downloading uv from "${downloadUrl}" ...`); info2(`Downloading uv from "${downloadUrl}" ...`);
const downloadPath = await downloadTool( const downloadPath = await downloadTool(
downloadUrl, downloadUrl,
@@ -102985,12 +102995,7 @@ async function downloadArtifact(downloadUrl, artifactName, platform2, arch3, ver
const extractedDir = await extractTar2(downloadPath); const extractedDir = await extractTar2(downloadPath);
uvDir = path15.join(extractedDir, artifactName); uvDir = path15.join(extractedDir, artifactName);
} }
const cachedToolDir = await cacheDir( const cachedToolDir = await cacheDir(uvDir, toolCacheName, version3, arch3);
uvDir,
TOOL_CACHE_NAME,
version3,
arch3
);
return { cachedToolDir, version: version3 }; return { cachedToolDir, version: version3 };
} }
function getMissingArtifactMessage(version3, arch3, platform2, manifestUrl) { function getMissingArtifactMessage(version3, arch3, platform2, manifestUrl) {
@@ -103021,6 +103026,7 @@ function loadInputs() {
const noProject = getBooleanInput("no-project"); const noProject = getBooleanInput("no-project");
const venvPath = getVenvPath(workingDirectory, activateEnvironment2); const venvPath = getVenvPath(workingDirectory, activateEnvironment2);
const checksum = getInput("checksum"); const checksum = getInput("checksum");
const requireChecksums = getBooleanInput("require-checksums");
const enableCache = getEnableCache(); const enableCache = getEnableCache();
const restoreCache3 = getInput("restore-cache") === "true"; const restoreCache3 = getInput("restore-cache") === "true";
const saveCache2 = getSaveCache(); const saveCache2 = getSaveCache();
@@ -103065,6 +103071,7 @@ function loadInputs() {
pythonDir, pythonDir,
pythonVersion, pythonVersion,
quiet: quiet2, quiet: quiet2,
requireChecksums,
resolutionStrategy, resolutionStrategy,
restoreCache: restoreCache3, restoreCache: restoreCache3,
saveCache: saveCache2, saveCache: saveCache2,
@@ -103502,7 +103509,20 @@ async function setupUv(inputs, platform2, arch3) {
versionFile: inputs.versionFile, versionFile: inputs.versionFile,
workingDirectory: inputs.workingDirectory workingDirectory: inputs.workingDirectory
}); });
const toolCacheResult = tryGetFromToolCache(arch3, resolvedVersion); let checksum = inputs.checksum;
let toolCacheName = TOOL_CACHE_NAME;
if (inputs.requireChecksums) {
checksum = getIntrinsicChecksum(
`${arch3}-${platform2}-${resolvedVersion}`,
inputs.checksum
);
toolCacheName = `${TOOL_CACHE_NAME}-${checksum}`;
}
const toolCacheResult = tryGetFromToolCache(
arch3,
resolvedVersion,
toolCacheName
);
if (toolCacheResult.installedPath) { if (toolCacheResult.installedPath) {
info2(`Found uv in tool-cache for ${toolCacheResult.version}`); info2(`Found uv in tool-cache for ${toolCacheResult.version}`);
return { return {
@@ -103514,10 +103534,11 @@ async function setupUv(inputs, platform2, arch3) {
platform2, platform2,
arch3, arch3,
resolvedVersion, resolvedVersion,
inputs.checksum, checksum,
inputs.githubToken, inputs.githubToken,
inputs.manifestFile, inputs.manifestFile,
inputs.downloadFromAstralMirror inputs.downloadFromAstralMirror,
toolCacheName
); );
return { return {
uvDir: downloadResult.cachedToolDir, uvDir: downloadResult.cachedToolDir,
+3 -1
View File
@@ -15,7 +15,9 @@ This document covers advanced options for configuring which version of uv to ins
Use `latest-known` to install the newest uv version whose checksums were bundled with the version of setup-uv used by your workflow. Version resolution is performed locally without fetching the latest release, so updating setup-uv also updates the version selected by `latest-known`. Use `latest-known` to install the newest uv version whose checksums were bundled with the version of setup-uv used by your workflow. Version resolution is performed locally without fetching the latest release, so updating setup-uv also updates the version selected by `latest-known`.
When `manifest-file` is set, `latest-known` still selects a version from setup-uv's bundled checksum table, but the artifact and checksum come from the custom manifest. When `manifest-file` is set, `latest-known` still selects a version from setup-uv's bundled checksum table.
By default the custom manifest supplies the artifact and checksum. To require a bundled or explicitly
supplied checksum, enable `require-checksums`. [Checksum validation](customization.md#validate-checksum)
```yaml ```yaml
- name: Install the latest version of uv known to setup-uv - name: Install the latest version of uv known to setup-uv
+24 -1
View File
@@ -4,7 +4,7 @@ This document covers advanced customization options including checksum validatio
## Validate checksum ## Validate checksum
Downloaded executables are automatically verified using checksums bundled with this action or, Downloaded archives are automatically verified using checksums bundled with this action or,
for newer, not yet bundled versions, the checksum from [`astral-sh/versions`](https://github.com/astral-sh/versions). for newer, not yet bundled versions, the checksum from [`astral-sh/versions`](https://github.com/astral-sh/versions).
You can specify a checksum to override those values. The sha256 hashes can also be found on the You can specify a checksum to override those values. The sha256 hashes can also be found on the
[releases page](https://github.com/astral-sh/uv/releases) of the uv repo. [releases page](https://github.com/astral-sh/uv/releases) of the uv repo.
@@ -17,6 +17,29 @@ You can specify a checksum to override those values. The sha256 hashes can also
checksum: "e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8" checksum: "e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8"
``` ```
For an additional layer of protection, you can set `require-checksums: true`.
This prevents setup-uv from trusting an unknown version's checksum from
[`astral-sh/versions`](https://github.com/astral-sh/versions) *unless* it is also
present in the action's own bundled data *or* explicitly provided with `checksum`.
This can be combined with `version: latest-known` to select the newest bundled release,
meaning that this newer requires an external checksum source:
```yaml
- name: Install the latest known version of uv
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
version: latest-known
require-checksums: true
```
With this mode, you'll need to update setup-uv itself to get newer uv versions
*unless* you explicitly pass in a `checksum` with a version that post-dates the setup-uv
release.
On runners with a persistent tool cache, this mode reuses only installations previously verified
against the same digest. The first run may download uv again.
## Manifest file ## Manifest file
By default, setup-uv reads version metadata from By default, setup-uv reads version metadata from
+1 -1
View File
@@ -38,7 +38,7 @@ Material failures are unauthorized executable selection, credential disclosure,
### Security invariants ### Security invariants
1. **Published runtime:** review `action.yml`, committed `dist/*.cjs`, and runner-interpreted shipped files; source-only fixes do not protect consumers. 1. **Published runtime:** review `action.yml`, committed `dist/*.cjs`, and runner-interpreted shipped files; source-only fixes do not protect consumers.
2. **Executable identity:** precedence is workflow version, version file, project configuration, then `latest`. Manifest authority, platform, variant, URL, checksum, mirror fallback, extraction, and cache placement must bind the intended artifact. A tool-cache hit bypasses download validation and depends on cache provenance. 2. **Executable identity:** precedence is workflow version, version file, project configuration, then `latest`. Manifest authority, platform, variant, URL, checksum, mirror fallback, extraction, and cache placement must bind the intended artifact. A tool-cache hit bypasses download validation and depends on cache provenance. With `require-checksums`, only entries keyed by the explicit or bundled archive digest are eligible.
3. **Credential recipients:** tokens and URL credentials may reach only workflow-authorized origins, redirects, paths, and logs. Metadata authority does not imply token-recipient authority. 3. **Credential recipients:** tokens and URL credentials may reach only workflow-authorized origins, redirects, paths, and logs. Metadata authority does not imply token-recipient authority.
4. **Executable boundaries:** checkout-selected interpreters are authorized by default. Explicit workflow selections must win, and independent cache, runner, or remote state must not substitute executables or gain additional authority. 4. **Executable boundaries:** checkout-selected interpreters are authorized by default. Explicit workflow selections must win, and independent cache, runner, or remote state must not substitute executables or gain additional authority.
5. **Paths and action channels:** path/environment changes, virtual-environment clearing, outputs, state, and problem matchers must affect only authorized targets and keep untrusted values as data. 5. **Paths and action channels:** path/environment changes, virtual-environment clearing, outputs, state, and problem matchers must affect only authorized targets and keep untrusted values as data.
+1 -5
View File
@@ -23,11 +23,7 @@ export async function validateChecksum(
: (knownChecksum ?? (hasManifestChecksum ? manifestChecksum : undefined)); : (knownChecksum ?? (hasManifestChecksum ? manifestChecksum : undefined));
if (checksumToUse === undefined) { if (checksumToUse === undefined) {
if (manifestChecksum !== undefined) { throw new Error(`No checksum found for ${key} in manifest.`);
throw new Error(`No checksum found for ${key} in manifest.`);
}
core.debug(`No checksum found for ${key}.`);
return;
} }
const checksumSource = hasProvidedChecksum const checksumSource = hasProvidedChecksum
+25 -8
View File
@@ -11,22 +11,40 @@ import {
import * as log from "../utils/logging"; import * as log from "../utils/logging";
import type { Architecture, Platform } from "../utils/platforms"; import type { Architecture, Platform } from "../utils/platforms";
import { validateChecksum } from "./checksum/checksum"; import { validateChecksum } from "./checksum/checksum";
import { KNOWN_CHECKSUMS } from "./checksum/known-checksums";
import { getArtifact } from "./manifest"; import { getArtifact } from "./manifest";
export { resolveVersion } from "../version/resolve"; export { resolveVersion } from "../version/resolve";
export function getIntrinsicChecksum(
key: string,
providedChecksum: string,
): string {
const checksum = providedChecksum || KNOWN_CHECKSUMS[key];
if (!checksum) {
throw new Error(
`No bundled checksum for ${key}. With require-checksums enabled, update setup-uv or provide the checksum input for this archive.`,
);
}
if (!/^[a-f0-9]{64}$/.test(checksum)) {
throw new Error(`Expected a SHA-256 checksum for ${key}.`);
}
return checksum;
}
export function tryGetFromToolCache( export function tryGetFromToolCache(
arch: Architecture, arch: Architecture,
version: string, version: string,
toolCacheName = TOOL_CACHE_NAME,
): { version: string; installedPath: string | undefined } { ): { version: string; installedPath: string | undefined } {
core.debug(`Trying to get uv from tool cache for ${version}...`); core.debug(`Trying to get uv from tool cache for ${version}...`);
const cachedVersions = tc.findAllVersions(TOOL_CACHE_NAME, arch); const cachedVersions = tc.findAllVersions(toolCacheName, arch);
core.debug(`Cached versions: ${cachedVersions}`); core.debug(`Cached versions: ${cachedVersions}`);
let resolvedVersion = tc.evaluateVersions(cachedVersions, version); let resolvedVersion = tc.evaluateVersions(cachedVersions, version);
if (resolvedVersion === "") { if (resolvedVersion === "") {
resolvedVersion = version; resolvedVersion = version;
} }
const installedPath = tc.find(TOOL_CACHE_NAME, resolvedVersion, arch); const installedPath = tc.find(toolCacheName, resolvedVersion, arch);
return { installedPath, version: resolvedVersion }; return { installedPath, version: resolvedVersion };
} }
@@ -38,6 +56,7 @@ export async function downloadVersion(
githubToken: string, githubToken: string,
manifestUrl?: string, manifestUrl?: string,
downloadFromAstralMirror = true, downloadFromAstralMirror = true,
toolCacheName = TOOL_CACHE_NAME,
): Promise<{ version: string; cachedToolDir: string }> { ): Promise<{ version: string; cachedToolDir: string }> {
const artifact = await getArtifact(version, arch, platform, manifestUrl); const artifact = await getArtifact(version, arch, platform, manifestUrl);
@@ -71,6 +90,7 @@ export async function downloadVersion(
resolvedChecksum, resolvedChecksum,
manifestChecksum, manifestChecksum,
githubTokenForUrl(downloadUrl, githubToken), githubTokenForUrl(downloadUrl, githubToken),
toolCacheName,
); );
} catch (err) { } catch (err) {
if (mirrorUrl === undefined) { if (mirrorUrl === undefined) {
@@ -90,6 +110,7 @@ export async function downloadVersion(
resolvedChecksum, resolvedChecksum,
manifestChecksum, manifestChecksum,
githubTokenForUrl(artifact.downloadUrl, githubToken), githubTokenForUrl(artifact.downloadUrl, githubToken),
toolCacheName,
); );
} }
} }
@@ -128,6 +149,7 @@ async function downloadArtifact(
checksum: string | undefined, checksum: string | undefined,
manifestChecksum: string | undefined, manifestChecksum: string | undefined,
githubToken: string | undefined, githubToken: string | undefined,
toolCacheName: string,
): Promise<{ version: string; cachedToolDir: string }> { ): Promise<{ version: string; cachedToolDir: string }> {
log.info(`Downloading uv from "${downloadUrl}" ...`); log.info(`Downloading uv from "${downloadUrl}" ...`);
const downloadPath = await tc.downloadTool( const downloadPath = await tc.downloadTool(
@@ -165,12 +187,7 @@ async function downloadArtifact(
uvDir = path.join(extractedDir, artifactName); uvDir = path.join(extractedDir, artifactName);
} }
const cachedToolDir = await tc.cacheDir( const cachedToolDir = await tc.cacheDir(uvDir, toolCacheName, version, arch);
uvDir,
TOOL_CACHE_NAME,
version,
arch,
);
return { cachedToolDir, version }; return { cachedToolDir, version };
} }
+23 -3
View File
@@ -5,9 +5,14 @@ import * as exec from "@actions/exec";
import { restoreCache } from "./cache/restore-cache"; import { restoreCache } from "./cache/restore-cache";
import { import {
downloadVersion, downloadVersion,
getIntrinsicChecksum,
tryGetFromToolCache, tryGetFromToolCache,
} from "./download/download-version"; } from "./download/download-version";
import { STATE_UV_PATH, STATE_UV_VERSION } from "./utils/constants"; import {
STATE_UV_PATH,
STATE_UV_VERSION,
TOOL_CACHE_NAME,
} from "./utils/constants";
import { CacheLocalSource, loadInputs, type SetupInputs } from "./utils/inputs"; import { CacheLocalSource, loadInputs, type SetupInputs } from "./utils/inputs";
import * as log from "./utils/logging"; import * as log from "./utils/logging";
import { import {
@@ -147,7 +152,21 @@ async function setupUv(
versionFile: inputs.versionFile, versionFile: inputs.versionFile,
workingDirectory: inputs.workingDirectory, workingDirectory: inputs.workingDirectory,
}); });
const toolCacheResult = tryGetFromToolCache(arch, resolvedVersion); let checksum = inputs.checksum;
let toolCacheName = TOOL_CACHE_NAME;
if (inputs.requireChecksums) {
checksum = getIntrinsicChecksum(
`${arch}-${platform}-${resolvedVersion}`,
inputs.checksum,
);
// A regular tool-cache entry may have been verified using a manifest checksum.
toolCacheName = `${TOOL_CACHE_NAME}-${checksum}`;
}
const toolCacheResult = tryGetFromToolCache(
arch,
resolvedVersion,
toolCacheName,
);
if (toolCacheResult.installedPath) { if (toolCacheResult.installedPath) {
log.info(`Found uv in tool-cache for ${toolCacheResult.version}`); log.info(`Found uv in tool-cache for ${toolCacheResult.version}`);
return { return {
@@ -160,10 +179,11 @@ async function setupUv(
platform, platform,
arch, arch,
resolvedVersion, resolvedVersion,
inputs.checksum, checksum,
inputs.githubToken, inputs.githubToken,
inputs.manifestFile, inputs.manifestFile,
inputs.downloadFromAstralMirror, inputs.downloadFromAstralMirror,
toolCacheName,
); );
return { return {
+3
View File
@@ -30,6 +30,7 @@ export interface SetupInputs {
noProject: boolean; noProject: boolean;
venvPath: string; venvPath: string;
checksum: string; checksum: string;
requireChecksums: boolean;
enableCache: boolean; enableCache: boolean;
restoreCache: boolean; restoreCache: boolean;
saveCache: boolean; saveCache: boolean;
@@ -63,6 +64,7 @@ export function loadInputs(): SetupInputs {
const noProject = core.getBooleanInput("no-project"); const noProject = core.getBooleanInput("no-project");
const venvPath = getVenvPath(workingDirectory, activateEnvironment); const venvPath = getVenvPath(workingDirectory, activateEnvironment);
const checksum = core.getInput("checksum"); const checksum = core.getInput("checksum");
const requireChecksums = core.getBooleanInput("require-checksums");
const enableCache = getEnableCache(); const enableCache = getEnableCache();
const restoreCache = core.getInput("restore-cache") === "true"; const restoreCache = core.getInput("restore-cache") === "true";
const saveCache = getSaveCache(); const saveCache = getSaveCache();
@@ -110,6 +112,7 @@ export function loadInputs(): SetupInputs {
pythonDir, pythonDir,
pythonVersion, pythonVersion,
quiet, quiet,
requireChecksums,
resolutionStrategy, resolutionStrategy,
restoreCache, restoreCache,
saveCache, saveCache,