diff --git a/.github/workflows/mirror-cnb.yml b/.github/workflows/mirror-cnb.yml index 51c81c6..f25d250 100644 --- a/.github/workflows/mirror-cnb.yml +++ b/.github/workflows/mirror-cnb.yml @@ -10,8 +10,10 @@ on: - lithe-plugin-index.json - lithe-plugin-deltas.json - lithe-plugin-recommendations.json + - lithe-runtime-mirrors.json - assets/** - scripts/mirror-cnb.mjs + - scripts/validate-runtime-mirrors.mjs workflow_dispatch: inputs: plugin: diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 9fe21a1..8dc43d0 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -35,7 +35,7 @@ jobs: run: sudo apt-get install -y zstd - name: Unit tests - run: node --test scripts/store.test.mjs scripts/plugin-deltas.test.mjs + run: node --test scripts/store.test.mjs scripts/plugin-deltas.test.mjs scripts/mirror-cnb.test.mjs - name: Validate index run: node scripts/validate-index.mjs lithe-plugin-index.json @@ -43,6 +43,9 @@ jobs: - name: Validate recommendations run: node scripts/validate-recommendations.mjs lithe-plugin-recommendations.json lithe-plugin-index.json + - name: Validate runtime mirrors + run: node scripts/validate-runtime-mirrors.mjs lithe-runtime-mirrors.json + - name: Pick the base index id: base run: | diff --git a/lithe-runtime-mirrors.json b/lithe-runtime-mirrors.json new file mode 100644 index 0000000..63698a8 --- /dev/null +++ b/lithe-runtime-mirrors.json @@ -0,0 +1,13 @@ +{ + "schemaVersion": 0, + "runtimes": [ + { + "id": "eclipse-jdtls-1.61.0", + "assetName": "jdt-language-server-1.61.0-202609031315.tar.gz", + "sourceURL": "https://download.eclipse.org/jdtls/milestones/1.61.0/jdt-language-server-1.61.0-202609031315.tar.gz", + "sha256": "338e7e73d61836651ba2453919a0d34fa763eb4e7c03342092309bffb8934c64", + "license": "EPL-2.0", + "licenseURL": "https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt" + } + ] +} diff --git a/scripts/mirror-cnb.mjs b/scripts/mirror-cnb.mjs index 9423142..061c8df 100755 --- a/scripts/mirror-cnb.mjs +++ b/scripts/mirror-cnb.mjs @@ -24,8 +24,12 @@ const DEFAULT_KEEP_VERSIONS = 3; const MAX_CAPABILITY_EXTRA_VERSIONS = 2; const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024; const MAX_ICON_BYTES = 2 * 1024 * 1024; +const DEFAULT_DOWNLOAD_TIMEOUT_MS = 60_000; +const ARCHIVE_DOWNLOAD_TIMEOUT_MS = 180_000; const CHECKSUMS_ASSET = ".mirror-checksums.json"; const ICONS_TAG = "plugin-icons"; +const RUNTIMES_TAG = "managed-runtimes"; +const RUNTIMES_FILE = "lithe-runtime-mirrors.json"; const PLUGIN_TAG_PREFIX = "plugin-"; const MAX_ATTEMPTS = 3; const RETRY_DELAY_MS = 1500; @@ -282,9 +286,9 @@ class CNBClient { } } -async function downloadAndVerify(url, destPath, expectedSha256, maxBytes) { +async function downloadAndVerify(url, destPath, expectedSha256, maxBytes, timeoutMs = DEFAULT_DOWNLOAD_TIMEOUT_MS) { return await withRetry(`Download ${path.basename(destPath)}`, async () => { - const res = await fetch(url, { signal: AbortSignal.timeout(60_000) }); + const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }); if (!res.ok) { const err = new Error(`GET ${url} returned HTTP ${res.status}`); err.retryable = res.status >= 500 || res.status === 429; @@ -358,7 +362,13 @@ async function syncReleaseAssets(client, repo, { tag, title, body, targetCommiti continue; } const localFile = path.join(scratchDir, assetName); - const actualDigest = await downloadAndVerify(spec.url, localFile, spec.sha256, spec.maxBytes); + const actualDigest = await downloadAndVerify( + spec.url, + localFile, + spec.sha256, + spec.maxBytes, + spec.timeoutMs ?? DEFAULT_DOWNLOAD_TIMEOUT_MS, + ); await client.uploadAsset(repo, release.id, localFile, assetName); await rm(localFile, { force: true }); nextChecksums[assetName] = actualDigest; @@ -382,6 +392,41 @@ async function syncReleaseAssets(client, repo, { tag, title, body, targetCommiti } } +async function loadRuntimeMirrors(filePath = RUNTIMES_FILE) { + let raw; + try { + raw = await readFile(filePath, "utf8"); + } catch (err) { + if (err?.code === "ENOENT") return null; + throw err; + } + const parsed = JSON.parse(raw); + if (!parsed || typeof parsed !== "object" || parsed.schemaVersion !== 0 || !Array.isArray(parsed.runtimes)) { + throw new Error(`Invalid ${filePath}: expected schemaVersion 0 and runtimes array`); + } + for (const entry of parsed.runtimes) { + if (!entry?.id || !entry?.assetName || !entry?.sourceURL || !entry?.sha256) { + throw new Error(`Invalid runtime mirror entry in ${filePath}`); + } + if (entry.assetName === CHECKSUMS_ASSET || entry.assetName.includes("/") || entry.assetName.includes("\\") || entry.assetName === "." || entry.assetName === "..") { + throw new Error(`Unsafe runtime mirror assetName in ${filePath}: ${entry.assetName}`); + } + } + return parsed; +} + +function buildRuntimeReleaseBody(runtimes) { + const lines = [ + "CNB mirror of verified external managed runtime archives referenced by Lithe-store plugins.", + "Each archive is redistributed verbatim with upstream SHA-256 verification:", + "", + ]; + for (const item of runtimes) { + lines.push(`- \`${item.id}\` (\`${item.assetName}\`): ${item.sourceURL} — License: [${item.license}](${item.licenseURL}), SHA-256: \`${item.sha256}\``); + } + return lines.join("\n"); +} + export async function run(argv = process.argv.slice(2)) { const opts = parseArgs(argv); if (opts.help) { @@ -434,14 +479,24 @@ export async function run(argv = process.argv.slice(2)) { if (prev && prev.sha256 !== dl.sha256) { throw new Error(`Conflicting SHA-256 for asset ${assetName} in ${plugin.id}`); } - desired.set(assetName, { url: dl.downloadURL, sha256: dl.sha256, maxBytes: MAX_ARCHIVE_BYTES }); + desired.set(assetName, { + url: dl.downloadURL, + sha256: dl.sha256, + maxBytes: MAX_ARCHIVE_BYTES, + timeoutMs: ARCHIVE_DOWNLOAD_TIMEOUT_MS, + }); } } for (const patch of deltasByPlugin.get(plugin.id) || []) { if (!selectedVersionNames.has(patch.toVersion)) continue; const assetName = path.basename(new URL(patch.downloadURL).pathname); if (!assetName) continue; - desired.set(assetName, { url: patch.downloadURL, sha256: patch.sha256, maxBytes: MAX_ARCHIVE_BYTES }); + desired.set(assetName, { + url: patch.downloadURL, + sha256: patch.sha256, + maxBytes: MAX_ARCHIVE_BYTES, + timeoutMs: ARCHIVE_DOWNLOAD_TIMEOUT_MS, + }); } const tag = `${PLUGIN_TAG_PREFIX}${plugin.id}`; @@ -471,8 +526,30 @@ export async function run(argv = process.argv.slice(2)) { scratchDir, }); + const runtimeManifest = await loadRuntimeMirrors(); + if (runtimeManifest && runtimeManifest.runtimes.length > 0) { + const runtimeAssets = new Map(); + for (const entry of runtimeManifest.runtimes) { + runtimeAssets.set(entry.assetName, { + url: entry.sourceURL, + sha256: entry.sha256, + maxBytes: MAX_ARCHIVE_BYTES, + timeoutMs: ARCHIVE_DOWNLOAD_TIMEOUT_MS, + }); + } + await syncReleaseAssets(client, opts.repo, { + tag: RUNTIMES_TAG, + title: "CNB mirror for managed plugin runtimes", + body: buildRuntimeReleaseBody(runtimeManifest.runtimes), + targetCommitish: headSha, + desiredAssets: runtimeAssets, + scratchDir, + }); + } + const activeTags = new Set((index.plugins || []).map((p) => `${PLUGIN_TAG_PREFIX}${p.id}`)); activeTags.add(ICONS_TAG); + activeTags.add(RUNTIMES_TAG); for (const rel of await client.listAllReleases(opts.repo)) { const tag = rel.tag_name || ""; if (tag.startsWith(PLUGIN_TAG_PREFIX) && !activeTags.has(tag)) { diff --git a/scripts/mirror-cnb.test.mjs b/scripts/mirror-cnb.test.mjs index 24f5133..1ee08b9 100644 --- a/scripts/mirror-cnb.test.mjs +++ b/scripts/mirror-cnb.test.mjs @@ -6,6 +6,7 @@ import os from "node:os"; import path from "node:path"; import test from "node:test"; import { run, selectVersionsToMirror } from "./mirror-cnb.mjs"; +import { validateRuntimeMirrors } from "./validate-runtime-mirrors.mjs"; const sha256 = (text) => createHash("sha256").update(text).digest("hex"); @@ -305,3 +306,124 @@ test("mirror-cnb refuses to upload on SHA-256 mismatch", { timeout: 30000 }, asy await mock.close(); } }); + +test("mirror-cnb syncs managed runtime mirrors, skips unchanged assets, prunes removed entries, and rejects SHA-256 mismatch", { timeout: 30000 }, async () => { + const files = new Map([ + ["/jdtls/jdtls-1.61.0.tar.gz", "jdtls-archive-bytes"], + ["/jdtls/old-runtime.tar.gz", "old-runtime-bytes"], + ]); + const mock = await startMockServers(files); + const work = await mkdtemp(path.join(os.tmpdir(), "lithe-store-runtimes-")); + const prevCwd = process.cwd(); + const prevEnv = { ...process.env }; + try { + process.chdir(work); + process.env.CNB_TOKEN = "cnb-secret"; + process.env.CNB_API_BASE = mock.cnbBase; + process.env.CNB_WEB_BASE = mock.cnbBase; + + await writeFile(path.join(work, "lithe-plugin-index.json"), JSON.stringify({ schemaVersion: 0, plugins: [] })); + await writeFile(path.join(work, "lithe-plugin-deltas.json"), JSON.stringify({ schemaVersion: 0, patches: [] })); + await writeFile(path.join(work, "lithe-runtime-mirrors.json"), JSON.stringify({ + schemaVersion: 0, + runtimes: [{ + id: "eclipse-jdtls-1.61.0", + assetName: "jdtls-1.61.0.tar.gz", + sourceURL: `${mock.ghBase}/jdtls/jdtls-1.61.0.tar.gz`, + sha256: sha256("jdtls-archive-bytes"), + license: "EPL-2.0", + licenseURL: "https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt", + }], + })); + + await run(["--skip-git-push"]); + + const runtimesRel = mock.releases.get("managed-runtimes"); + assert.ok(runtimesRel); + assert.match(runtimesRel.body || "", /EPL-2\.0/); + assert.deepEqual( + runtimesRel.assets.map((a) => a.name).sort(), + [".mirror-checksums.json", "jdtls-1.61.0.tar.gz"], + ); + + // Rerun with identical manifest: zero re-downloads or uploads. + const eventCount = mock.events.length; + await run(["--skip-git-push"]); + const rerunEvents = mock.events.slice(eventCount); + assert.equal(rerunEvents.some((e) => e.startsWith("GH GET")), false); + assert.equal(rerunEvents.some((e) => e.startsWith("CNB PUT")), false); + + // Removing an older asset from the manifest prunes it from the release. + runtimesRel.assets.push({ id: "stale-asset", name: "stale-runtime.tar.gz" }); + await run(["--skip-git-push"]); + assert.deepEqual( + runtimesRel.assets.map((a) => a.name).sort(), + [".mirror-checksums.json", "jdtls-1.61.0.tar.gz"], + ); + + // Mismatched SHA-256 refuses to upload. + await writeFile(path.join(work, "lithe-runtime-mirrors.json"), JSON.stringify({ + schemaVersion: 0, + runtimes: [{ + id: "eclipse-jdtls-1.61.0", + assetName: "jdtls-bad.tar.gz", + sourceURL: `${mock.ghBase}/jdtls/jdtls-1.61.0.tar.gz`, + sha256: "0".repeat(64), + license: "EPL-2.0", + licenseURL: "https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt", + }], + })); + const badStart = mock.events.length; + await assert.rejects(() => run(["--skip-git-push"]), /SHA-256 mismatch/); + assert.equal(mock.events.slice(badStart).some((e) => e.startsWith("CNB PUT")), false); + } finally { + process.chdir(prevCwd); + process.env = prevEnv; + await rm(work, { recursive: true, force: true }); + await mock.close(); + } +}); + +test("validateRuntimeMirrors accepts valid manifest and rejects invalid fields, order, or unsafe URLs", () => { + const valid = { + schemaVersion: 0, + runtimes: [{ + id: "eclipse-jdtls-1.61.0", + assetName: "jdt-language-server-1.61.0-202609031315.tar.gz", + sourceURL: "https://download.eclipse.org/jdtls/milestones/1.61.0/jdt-language-server-1.61.0-202609031315.tar.gz", + sha256: "338e7e73d61836651ba2453919a0d34fa763eb4e7c03342092309bffb8934c64", + license: "EPL-2.0", + licenseURL: "https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt", + }], + }; + assert.deepEqual(validateRuntimeMirrors(valid), []); + + const bad = { + schemaVersion: 1, + runtimes: [ + { + id: "z-runtime", + assetName: "../bad.tar.gz", + sourceURL: "http://insecure.example/a.tar.gz", + sha256: "not-hex", + license: "", + licenseURL: "https://user:pass@example.com/license", + }, + { + id: "a-runtime", + assetName: "ok.tar.gz", + sourceURL: "https://example.com/ok.tar.gz", + sha256: "a".repeat(64), + license: "MIT", + licenseURL: "https://example.com/license", + }, + ], + }; + const problems = validateRuntimeMirrors(bad); + assert.ok(problems.some((p) => p.includes("schemaVersion"))); + assert.ok(problems.some((p) => p.includes("assetName"))); + assert.ok(problems.some((p) => p.includes("sourceURL"))); + assert.ok(problems.some((p) => p.includes("sha256"))); + assert.ok(problems.some((p) => p.includes("licenseURL"))); + assert.ok(problems.some((p) => p.includes("sorted"))); +}); diff --git a/scripts/validate-runtime-mirrors.mjs b/scripts/validate-runtime-mirrors.mjs new file mode 100644 index 0000000..d92ea51 --- /dev/null +++ b/scripts/validate-runtime-mirrors.mjs @@ -0,0 +1,128 @@ +#!/usr/bin/env node +// Validates lithe-runtime-mirrors.json before mirroring external managed +// runtime archives to CNB. + +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +const ROOT_FIELDS = new Set(["schemaVersion", "runtimes"]); +const ENTRY_FIELDS = new Set(["id", "assetName", "sourceURL", "sha256", "license", "licenseURL"]); +const RUNTIME_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/; +const SHA256_HEX = /^[0-9a-f]{64}$/; +const RESERVED_ASSET_NAME = ".mirror-checksums.json"; + +function isObject(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function isNonEmptyTrimmedString(value) { + return typeof value === "string" && value.length > 0 && value === value.trim(); +} + +function isValidHTTPSURL(value) { + if (!isNonEmptyTrimmedString(value)) return false; + try { + const parsed = new URL(value); + return parsed.protocol === "https:" && parsed.hostname.length > 0 && !parsed.username && !parsed.password; + } catch { + return false; + } +} + +function isValidAssetName(value) { + return isNonEmptyTrimmedString(value) + && value !== "." + && value !== ".." + && value !== RESERVED_ASSET_NAME + && !value.includes("/") + && !value.includes("\\"); +} + +/** Validates a managed runtime mirror catalog and returns human-readable errors. */ +export function validateRuntimeMirrors(manifest) { + if (!isObject(manifest)) return ["runtime mirrors root must be an object"]; + const problems = []; + + for (const key of Object.keys(manifest)) { + if (!ROOT_FIELDS.has(key)) { + problems.push(`unknown top-level field \`${key}\``); + } + } + if (manifest.schemaVersion !== 0) { + problems.push(`unsupported \`schemaVersion\`: ${JSON.stringify(manifest.schemaVersion)} (expected 0)`); + } + if (!Array.isArray(manifest.runtimes)) { + problems.push("`runtimes` must be an array"); + return problems; + } + + const seenIDs = new Set(); + const seenAssets = new Set(); + let previousID = ""; + + manifest.runtimes.forEach((entry, index) => { + const label = `runtimes[${index}]`; + if (!isObject(entry)) { + problems.push(`${label}: entry must be an object`); + return; + } + for (const key of Object.keys(entry)) { + if (!ENTRY_FIELDS.has(key)) { + problems.push(`${label}.${key}: unknown field \`${key}\``); + } + } + + if (!isNonEmptyTrimmedString(entry.id) || !RUNTIME_ID.test(entry.id)) { + problems.push(`${label}.id: must match ${RUNTIME_ID}`); + } else { + if (seenIDs.has(entry.id)) { + problems.push(`${label}.id: duplicate runtime id \`${entry.id}\``); + } + seenIDs.add(entry.id); + if (previousID && entry.id < previousID) { + problems.push(`store policy: ${label}.id \`${entry.id}\` must be sorted after \`${previousID}\``); + } + previousID = entry.id; + } + + if (!isValidAssetName(entry.assetName)) { + problems.push(`${label}.assetName: must be a safe single-segment filename`); + } else if (seenAssets.has(entry.assetName)) { + problems.push(`${label}.assetName: duplicate assetName \`${entry.assetName}\``); + } else { + seenAssets.add(entry.assetName); + } + + if (!isValidHTTPSURL(entry.sourceURL)) { + problems.push(`${label}.sourceURL: must be a valid credential-free https:// URL`); + } + if (typeof entry.sha256 !== "string" || !SHA256_HEX.test(entry.sha256)) { + problems.push(`${label}.sha256: must be a 64-character lowercase hex SHA-256 digest`); + } + if (!isNonEmptyTrimmedString(entry.license)) { + problems.push(`${label}.license: must be a non-empty license identifier`); + } + if (!isValidHTTPSURL(entry.licenseURL)) { + problems.push(`${label}.licenseURL: must be a valid credential-free https:// URL`); + } + }); + + return problems; +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) { + const targetPath = process.argv[2] || "lithe-runtime-mirrors.json"; + let parsed; + try { + parsed = JSON.parse(readFileSync(targetPath, "utf8")); + } catch (err) { + console.error(`Failed to read ${targetPath}: ${err.message}`); + process.exit(1); + } + const problems = validateRuntimeMirrors(parsed); + if (problems.length > 0) { + for (const problem of problems) console.error(problem); + process.exit(1); + } + console.log(`Validated ${parsed.runtimes.length} runtime mirror(s) in ${targetPath}.`); +}