diff --git a/docs/src/content/docs/contributing.md b/docs/src/content/docs/contributing.md index f8f9b4fc41..e83b168ec1 100644 --- a/docs/src/content/docs/contributing.md +++ b/docs/src/content/docs/contributing.md @@ -71,6 +71,7 @@ cli/ │ │ ├── release/ # archive, create, delete, deploy, deploys, finalize, list, propose-version, restore, set-commits, view │ │ ├── replay/ # list, view │ │ ├── repo/ # list +│ │ ├── snapshots/ # download │ │ ├── sourcemap/ # inject, resolve, upload │ │ ├── span/ # list, view │ │ ├── team/ # list diff --git a/docs/src/fragments/commands/snapshots.md b/docs/src/fragments/commands/snapshots.md new file mode 100644 index 0000000000..3e7a8be6cc --- /dev/null +++ b/docs/src/fragments/commands/snapshots.md @@ -0,0 +1,29 @@ + + +## Examples + +```bash +# Download a specific baseline snapshot by ID +sentry snapshots download --snapshot-id 1234567890 + +# Download the latest baseline for an app, filtered by branch +sentry snapshots download --app-id my-app --branch main + +# Extract images to a specific directory +sentry snapshots download --app-id my-app --output ./baseline/ +``` + +## Important Notes + +- `snapshots download` fetches baseline snapshot images from Sentry's preprod + system and extracts them to a local directory. **Sentry SaaS only.** +- Provide exactly one of `--snapshot-id` (a direct artifact ID) or `--app-id` + (resolves the latest baseline). `--branch` only applies with `--app-id`. +- With org auth tokens, resolving by `--app-id` requires `--project` (a project + ID or slug). +- If the downloadable archive has not been built yet, the command triggers a + build and waits for it (up to 5 minutes). +- Images are extracted to `./snapshots-base/` by default; override with + `--output`. +- The organization is resolved from `--org`, `SENTRY_ORG`, config defaults, or a + detected DSN. diff --git a/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/plugins/sentry-cli/skills/sentry-cli/SKILL.md index f547d655bc..a183b8f547 100644 --- a/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -520,6 +520,14 @@ Work with Sentry cron monitors → Full flags and examples: `references/monitor.md` +### Snapshots + +Manage and compare snapshots + +- `sentry snapshots download` — Download baseline snapshot images + +→ Full flags and examples: `references/snapshots.md` + ### Sourcemap Manage sourcemaps diff --git a/plugins/sentry-cli/skills/sentry-cli/references/snapshots.md b/plugins/sentry-cli/skills/sentry-cli/references/snapshots.md new file mode 100644 index 0000000000..70ff99515b --- /dev/null +++ b/plugins/sentry-cli/skills/sentry-cli/references/snapshots.md @@ -0,0 +1,37 @@ +--- +name: sentry-cli-snapshots +version: 0.39.0-dev.0 +description: Manage and compare snapshots +requires: + bins: ["sentry"] + auth: true +--- + +# Snapshots Commands + +Manage and compare snapshots + +### `sentry snapshots download` + +Download baseline snapshot images + +**Flags:** +- `--app-id - App identifier (e.g. my-app) to resolve the latest baseline; mutually exclusive with --snapshot-id` +- `--snapshot-id - Direct snapshot artifact ID; mutually exclusive with --app-id` +- `--branch - Git branch filter (only with --app-id)` +- `-o, --output - Directory for extracted images (default: ./snapshots-base/)` + +**Examples:** + +```bash +# Download a specific baseline snapshot by ID +sentry snapshots download --snapshot-id 1234567890 + +# Download the latest baseline for an app, filtered by branch +sentry snapshots download --app-id my-app --branch main + +# Extract images to a specific directory +sentry snapshots download --app-id my-app --output ./baseline/ +``` + +All commands also support `--json`, `--fields`, `--help`, `--log-level`, and `--verbose` flags. diff --git a/src/app.ts b/src/app.ts index d1fd038c27..20a5cc419c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -43,6 +43,7 @@ import { listCommand as repoListCommand } from "./commands/repo/list.js"; import { schemaCommand } from "./commands/schema.js"; import { sendEnvelopeCommand } from "./commands/send-envelope.js"; import { sendEventCommand } from "./commands/send-event.js"; +import { snapshotsRoute } from "./commands/snapshots/index.js"; import { sourcemapRoute } from "./commands/sourcemap/index.js"; import { spanRoute } from "./commands/span/index.js"; import { listCommand as spanListCommand } from "./commands/span/list.js"; @@ -117,6 +118,7 @@ export const routes = buildRouteMap({ explore: exploreCommand, log: logRoute, monitor: monitorRoute, + snapshots: snapshotsRoute, sourcemap: sourcemapRoute, sourcemaps: sourcemapRoute, span: spanRoute, diff --git a/src/commands/snapshots/download.ts b/src/commands/snapshots/download.ts new file mode 100644 index 0000000000..39bf4bf430 --- /dev/null +++ b/src/commands/snapshots/download.ts @@ -0,0 +1,230 @@ +/** + * sentry snapshots download + * + * Download baseline snapshot images from Sentry's preprod system to a local + * directory. Resolve a snapshot by `--snapshot-id`, or the latest baseline for + * an app via `--app-id` (optionally filtered by `--branch`). Ensures the + * downloadable archive is built (triggering + polling if needed), then extracts + * the images. + * + * Org-scoped. Sentry SaaS only. + */ + +import { resolve } from "node:path"; +import type { SentryContext } from "../../context.js"; +import { + downloadSnapshotArchive, + getLatestBaseSnapshot, + waitForSnapshotArchive, +} from "../../lib/api/preprod-artifacts.js"; +import { buildCommand } from "../../lib/command.js"; +import { getDefaultProject } from "../../lib/db/defaults.js"; +import { + ContextError, + ResolutionError, + ValidationError, +} from "../../lib/errors.js"; +import { mdKvTable, renderMarkdown } from "../../lib/formatters/markdown.js"; +import { CommandOutput } from "../../lib/formatters/output.js"; +import { logger } from "../../lib/logger.js"; +import { resolveOrg } from "../../lib/resolve-target.js"; +import { extractZipToDir } from "../../lib/snapshots/archive.js"; + +const log = logger.withTag("snapshots.download"); + +const USAGE_HINT = + "sentry snapshots download --app-id | --snapshot-id "; +const DEFAULT_OUTPUT = "./snapshots-base/"; + +/** Flags accepted by `snapshots download`. */ +type DownloadFlags = { + "app-id"?: string; + "snapshot-id"?: string; + branch?: string; + output?: string; +}; + +/** Structured result for `snapshots download`. */ +type SnapshotDownloadResult = { + /** Organization slug. */ + org: string; + /** The resolved snapshot artifact ID. */ + snapshotId: string; + /** Local directory the images were extracted to. */ + output: string; + /** Number of images extracted. */ + imageCount: number; +}; + +/** Human-readable formatter for the download result. */ +function formatDownloadResult(data: SnapshotDownloadResult): string { + return renderMarkdown( + mdKvTable([ + ["Snapshot ID", data.snapshotId], + ["Images", String(data.imageCount)], + ["Saved to", data.output], + ]) + ); +} + +/** + * Validate the mutually exclusive `--snapshot-id` / `--app-id` flags (and + * `--branch`'s dependency on `--app-id`) before any I/O. + * + * @throws {ValidationError} On conflicting/misused flags. + * @throws {ContextError} When neither ID flag is provided. + */ +function validateSnapshotFlags(flags: DownloadFlags): void { + const appId = flags["app-id"]; + const snapshotId = flags["snapshot-id"]; + + if (appId && snapshotId) { + throw new ValidationError( + "Provide only one of --app-id or --snapshot-id", + "app-id" + ); + } + if (flags.branch && !appId) { + throw new ValidationError( + "--branch can only be used with --app-id", + "branch" + ); + } + if (!(appId || snapshotId)) { + throw new ContextError("Snapshot", USAGE_HINT, []); + } +} + +/** + * Resolve the optional project (for `--app-id` with org auth tokens) from + * `SENTRY_PROJECT` (honoring `/` combo notation) then the + * configured default project. + */ +function resolveOptionalProject(env: NodeJS.ProcessEnv): string | undefined { + const raw = env.SENTRY_PROJECT?.trim(); + if (raw) { + const parts = raw.split("/"); + return parts.length === 2 ? parts[1] : raw; + } + return getDefaultProject() ?? undefined; +} + +/** + * Resolve the snapshot ID to download. Assumes {@link validateSnapshotFlags} + * has run, so exactly one of `--snapshot-id` / `--app-id` is set. + */ +async function resolveSnapshotId( + org: string, + flags: DownloadFlags, + project: string | undefined +): Promise { + const snapshotId = flags["snapshot-id"]; + if (snapshotId) { + return snapshotId; + } + + const appId = flags["app-id"] as string; + log.info(`Resolving latest baseline snapshot for app '${appId}'...`); + const latest = await getLatestBaseSnapshot(org, appId, { + branch: flags.branch, + project, + }); + if (!latest) { + const branchMsg = flags.branch ? ` on branch '${flags.branch}'` : ""; + throw new ResolutionError( + `Baseline snapshot for app '${appId}'${branchMsg}`, + "not found", + USAGE_HINT, + ["No baseline snapshot exists for this app yet."] + ); + } + log.info( + `Found snapshot ${latest.headArtifactId} (${latest.imageCount} images)` + ); + return latest.headArtifactId; +} + +export const downloadCommand = buildCommand({ + docs: { + brief: "Download baseline snapshot images", + fullDescription: + "Download baseline snapshot images from Sentry's preprod system to a " + + "local directory.\n\n" + + "Use --snapshot-id to download a specific snapshot, or --app-id to " + + "resolve the latest baseline (org auth tokens require --project with a " + + "project ID or slug for --app-id).\n\n" + + "This feature only works with Sentry SaaS.\n\n" + + "Usage:\n" + + " sentry snapshots download --snapshot-id 1234567890\n" + + " sentry snapshots download --app-id my-app --branch main\n" + + " sentry snapshots download --app-id my-app --output ./baseline/", + }, + output: { + human: formatDownloadResult, + }, + parameters: { + flags: { + "app-id": { + kind: "parsed", + parse: String, + brief: + "App identifier (e.g. my-app) to resolve the latest baseline; mutually exclusive with --snapshot-id", + optional: true, + }, + "snapshot-id": { + kind: "parsed", + parse: String, + brief: "Direct snapshot artifact ID; mutually exclusive with --app-id", + optional: true, + }, + branch: { + kind: "parsed", + parse: String, + brief: "Git branch filter (only with --app-id)", + optional: true, + }, + output: { + kind: "parsed", + parse: String, + brief: `Directory for extracted images (default: ${DEFAULT_OUTPUT})`, + optional: true, + }, + }, + aliases: { + o: "output", + }, + }, + async *func(this: SentryContext, flags: DownloadFlags) { + // Validate flag combinations before any I/O so bad usage fails fast. + validateSnapshotFlags(flags); + + const resolved = await resolveOrg({ cwd: this.cwd }); + if (!resolved) { + throw new ContextError("Organization", USAGE_HINT); + } + const { org } = resolved; + const project = resolveOptionalProject(this.env); + + const snapshotId = await resolveSnapshotId(org, flags, project); + + await waitForSnapshotArchive(org, snapshotId, () => + log.info("Building snapshot archive...") + ); + + log.info(`Downloading snapshot ${snapshotId}...`); + const zip = await downloadSnapshotArchive(org, snapshotId); + + const output = resolve(this.cwd, flags.output ?? DEFAULT_OUTPUT); + const imageCount = extractZipToDir(zip, output); + + yield new CommandOutput({ + org, + snapshotId, + output, + imageCount, + }); + return { + hint: `Downloaded ${imageCount} image(s) from snapshot ${snapshotId} to ${output}`, + }; + }, +}); diff --git a/src/commands/snapshots/index.ts b/src/commands/snapshots/index.ts new file mode 100644 index 0000000000..f81fe217f0 --- /dev/null +++ b/src/commands/snapshots/index.ts @@ -0,0 +1,17 @@ +/** + * `sentry snapshots` — manage and compare preprod snapshot images. + * + * Currently exposes `download`. `diff` and `upload` are ported separately. + */ + +import { buildRouteMap } from "../../lib/route-map.js"; +import { downloadCommand } from "./download.js"; + +export const snapshotsRoute = buildRouteMap({ + routes: { + download: downloadCommand, + }, + docs: { + brief: "Manage and compare snapshots", + }, +}); diff --git a/src/lib/api/preprod-artifacts.ts b/src/lib/api/preprod-artifacts.ts index 7b735e4fa4..adcb5026bc 100644 --- a/src/lib/api/preprod-artifacts.ts +++ b/src/lib/api/preprod-artifacts.ts @@ -18,7 +18,7 @@ import { pipeline } from "node:stream/promises"; import { z } from "zod"; import { customFetch } from "../custom-ca.js"; import { getAuthToken } from "../db/auth.js"; -import { ApiError, ValidationError } from "../errors.js"; +import { ApiError, TimeoutError, ValidationError } from "../errors.js"; import { logger } from "../logger.js"; import { resolveOrgRegion } from "../region.js"; import { @@ -31,7 +31,10 @@ import { pickUploadEncoding, uploadMissingBufferChunks, } from "./chunk-upload.js"; -import { apiRequestToRegion } from "./infrastructure.js"; +import { + apiRequestToRegion, + apiRequestToRegionNoContent, +} from "./infrastructure.js"; const log = logger.withTag("api.preprod-artifacts"); @@ -305,3 +308,186 @@ export async function uploadBuild( endpoint ); } + +/** Strip trailing slashes without a regex (avoids ReDoS heuristics). */ +function stripTrailingSlashes(url: string): string { + let end = url.length; + while (end > 0 && url[end - 1] === "/") { + end -= 1; + } + return url.slice(0, end); +} + +/** Poll interval while waiting for a snapshot archive to build. */ +export const SNAPSHOT_ARCHIVE_POLL_MS = 2000; +/** Maximum time to wait for a snapshot archive to build. */ +export const SNAPSHOT_ARCHIVE_TIMEOUT_MS = 300_000; + +/** + * Raw latest-baseline response. The server returns snake_case fields (no + * `camelCase` rename on the Rust `LatestBaseSnapshotResponse`); callers get the + * camelCase {@link LatestBaseSnapshot} after mapping. + */ +export const LatestBaseSnapshotSchema = z.object({ + /** Artifact ID of the baseline snapshot. */ + head_artifact_id: z.string(), + /** Number of images in the snapshot. */ + image_count: z.number(), +}); + +/** Latest baseline snapshot for an app (camelCase, for callers). */ +export type LatestBaseSnapshot = { + headArtifactId: string; + imageCount: number; +}; + +/** Build the `.../snapshots/{id}/archive/` endpoint path. */ +function snapshotArchiveEndpoint(org: string, snapshotId: string): string { + return `organizations/${org}/preprodartifacts/snapshots/${encodeURIComponent( + snapshotId + )}/archive/`; +} + +/** + * Resolve the latest baseline snapshot for an app. + * + * @param org - Organization slug. + * @param appId - App identifier (e.g. `sentry-frontend`). + * @param opts - Optional `branch` filter and `project` (numeric ID, required + * with org auth tokens). + * @returns The latest baseline snapshot, or `null` when none exists. + * @throws {ApiError} On a non-2xx response other than 404. + */ +export async function getLatestBaseSnapshot( + org: string, + appId: string, + opts: { branch?: string; project?: string } = {} +): Promise { + const regionUrl = await resolveOrgRegion(org); + try { + const { data } = await apiRequestToRegion( + regionUrl, + `organizations/${org}/preprodartifacts/snapshots/latest-base/`, + { + params: { app_id: appId, branch: opts.branch, project: opts.project }, + schema: LatestBaseSnapshotSchema.nullable(), + } + ); + return data + ? { headArtifactId: data.head_artifact_id, imageCount: data.image_count } + : null; + } catch (err) { + if (err instanceof ApiError && err.status === 404) { + return null; + } + throw err; + } +} + +const SnapshotArchiveStatusSchema = z.object({ ready: z.boolean() }); + +/** + * Check whether a snapshot's downloadable archive has been built. + * + * @throws {ApiError} On a non-2xx response. + */ +export async function getSnapshotArchiveReady( + org: string, + snapshotId: string +): Promise { + const regionUrl = await resolveOrgRegion(org); + const { data } = await apiRequestToRegion( + regionUrl, + snapshotArchiveEndpoint(org, snapshotId), + { schema: SnapshotArchiveStatusSchema } + ); + return data.ready; +} + +/** + * Trigger a build of a snapshot's downloadable archive. + * + * @throws {ApiError} On a non-2xx response. + */ +export async function triggerSnapshotArchiveBuild( + org: string, + snapshotId: string +): Promise { + const regionUrl = await resolveOrgRegion(org); + await apiRequestToRegionNoContent( + regionUrl, + snapshotArchiveEndpoint(org, snapshotId), + { method: "POST" } + ); +} + +/** + * Ensure a snapshot's archive is built, triggering a build and polling if needed. + * + * @param onBuildStarted - Invoked once when a build is triggered (for progress + * messaging); the API layer does no user-facing output itself. + * @throws {TimeoutError} When the archive is not ready within the timeout. + * @throws {ApiError} On a non-2xx response. + */ +export async function waitForSnapshotArchive( + org: string, + snapshotId: string, + onBuildStarted?: () => void +): Promise { + if (await getSnapshotArchiveReady(org, snapshotId)) { + return; + } + await triggerSnapshotArchiveBuild(org, snapshotId); + onBuildStarted?.(); + + const deadline = Date.now() + SNAPSHOT_ARCHIVE_TIMEOUT_MS; + while (!(await getSnapshotArchiveReady(org, snapshotId))) { + if (Date.now() >= deadline) { + throw new TimeoutError( + `Snapshot archive was not ready after ${ + SNAPSHOT_ARCHIVE_TIMEOUT_MS / 1000 + }s. The build may still be running; try again shortly.` + ); + } + await new Promise((r) => setTimeout(r, SNAPSHOT_ARCHIVE_POLL_MS)); + } +} + +/** + * Download a snapshot's archive ZIP into memory. + * + * The endpoint streams the ZIP directly from the region origin (no redirect), so + * the auth token is only ever sent to the region host. Should the server ever + * 302 to third-party storage, undici strips `Authorization` cross-origin. + * + * The whole archive is buffered and later extracted in memory (see + * {@link extractZipToDir}); acceptable for typical screenshot baselines, but a + * very large archive (the server caps at ~1 GB) would need streaming extraction. + * + * @throws {ApiError} On a non-2xx response. + */ +export async function downloadSnapshotArchive( + org: string, + snapshotId: string +): Promise { + const regionUrl = stripTrailingSlashes(await resolveOrgRegion(org)); + const url = `${regionUrl}/api/0/${snapshotArchiveEndpoint( + org, + snapshotId + )}?download`; + const headers: Record = {}; + const token = getAuthToken(); + if (token) { + headers.Authorization = `Bearer ${token}`; + } + const response = await customFetch(url, { headers }); + if (!response.ok) { + throw new ApiError( + "Failed to download snapshot archive", + response.status, + response.statusText || "Download failed", + url + ); + } + return Buffer.from(await response.arrayBuffer()); +} diff --git a/src/lib/snapshots/archive.ts b/src/lib/snapshots/archive.ts new file mode 100644 index 0000000000..ae3f446c30 --- /dev/null +++ b/src/lib/snapshots/archive.ts @@ -0,0 +1,54 @@ +/** + * Snapshot archive extraction. + * + * Extracts a downloaded snapshot ZIP (baseline images) to a local directory, + * guarding against path traversal (Zip Slip): entries resolving outside the + * output directory, and absolute paths, are skipped. + */ + +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, isAbsolute, relative, resolve, sep } from "node:path"; +import { unzipSync } from "fflate"; +import { logger } from "../logger.js"; + +const log = logger.withTag("snapshots.extract"); + +/** + * Extract a ZIP archive's file entries into a directory. + * + * Directory entries are skipped; parent directories are created as needed. + * Entries that would escape `outDir` are skipped with a warning. + * + * @param zip - The ZIP archive bytes. + * @param outDir - Destination directory (created if missing). + * @returns The number of files written. + */ +export function extractZipToDir(zip: Uint8Array, outDir: string): number { + const entries = unzipSync(zip); + const root = resolve(outDir); + mkdirSync(root, { recursive: true }); + + let written = 0; + for (const [name, bytes] of Object.entries(entries)) { + // fflate represents directories as zero-length entries with a trailing "/". + // Skip those and any empty name (which would resolve to `root` itself). + if (!name || name.endsWith("/")) { + continue; + } + + const dest = resolve(root, name); + const rel = relative(root, dest); + // Segment-aware traversal check: reject entries that escape `root` (rel is + // ".." or begins "../") or resolve to an absolute path — without rejecting + // legitimate names that merely start with ".." (e.g. "..config.png"). + if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) { + log.warn(`Skipping unsafe archive entry: ${name}`); + continue; + } + + mkdirSync(dirname(dest), { recursive: true }); + writeFileSync(dest, bytes); + written += 1; + } + return written; +} diff --git a/test/commands/snapshots/download.test.ts b/test/commands/snapshots/download.test.ts new file mode 100644 index 0000000000..45e387027c --- /dev/null +++ b/test/commands/snapshots/download.test.ts @@ -0,0 +1,141 @@ +/** + * Tests for `sentry snapshots download`. + * + * Drives the command via its wrapper `loader()`. Org resolution and the + * snapshot API are spied; extraction runs for real against an in-memory ZIP + * built with fflate, writing into a temp output directory. + */ + +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { strToU8, zipSync } from "fflate"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { downloadCommand } from "../../../src/commands/snapshots/download.js"; +// biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking +import * as preprod from "../../../src/lib/api/preprod-artifacts.js"; +import { ContextError, ValidationError } from "../../../src/lib/errors.js"; +// biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking +import * as resolveTarget from "../../../src/lib/resolve-target.js"; + +let tmpDir: string; + +function createContext() { + const writes: string[] = []; + return { + context: { + stdout: { + write: (data: string | Uint8Array) => { + writes.push( + typeof data === "string" ? data : new TextDecoder().decode(data) + ); + return true; + }, + }, + stderr: { write: () => true }, + cwd: tmpDir, + env: {} as NodeJS.ProcessEnv, + process: { ...process, exitCode: undefined } as typeof process, + }, + output: () => writes.join(""), + }; +} + +function snapshotZip(): Buffer { + return Buffer.from( + zipSync({ "img1.png": strToU8("A"), "img2.png": strToU8("B") }) + ); +} + +describe("snapshots download", () => { + let downloadSpy: ReturnType; + let latestSpy: ReturnType; + let waitSpy: ReturnType; + + beforeEach(async () => { + tmpDir = await mkdtemp(join(tmpdir(), "snap-dl-")); + vi.spyOn(resolveTarget, "resolveOrg").mockResolvedValue({ + org: "test-org", + }); + waitSpy = vi + .spyOn(preprod, "waitForSnapshotArchive") + .mockResolvedValue(undefined); + downloadSpy = vi + .spyOn(preprod, "downloadSnapshotArchive") + .mockResolvedValue(snapshotZip()); + latestSpy = vi.spyOn(preprod, "getLatestBaseSnapshot").mockResolvedValue({ + headArtifactId: "resolved-art", + imageCount: 2, + }); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await rm(tmpDir, { recursive: true, force: true }); + }); + + test("downloads a snapshot by --snapshot-id and extracts images", async () => { + const out = join(tmpDir, "base"); + const harness = createContext(); + const func = await downloadCommand.loader(); + + await func.call(harness.context, { + "snapshot-id": "snap-1", + output: out, + }); + + expect(waitSpy).toHaveBeenCalledWith( + "test-org", + "snap-1", + expect.any(Function) + ); + expect(downloadSpy).toHaveBeenCalledWith("test-org", "snap-1"); + expect(latestSpy).not.toHaveBeenCalled(); + expect(harness.output()).toContain("snap-1"); + expect(harness.output()).toContain("2"); + }); + + test("resolves the latest baseline by --app-id", async () => { + const harness = createContext(); + const func = await downloadCommand.loader(); + + await func.call(harness.context, { + "app-id": "my-app", + branch: "main", + output: join(tmpDir, "base"), + }); + + expect(latestSpy).toHaveBeenCalledWith("test-org", "my-app", { + branch: "main", + project: undefined, + }); + expect(downloadSpy).toHaveBeenCalledWith("test-org", "resolved-art"); + }); + + test("rejects when both --app-id and --snapshot-id are given", async () => { + const func = await downloadCommand.loader(); + await expect( + func.call(createContext().context, { + "app-id": "a", + "snapshot-id": "s", + }) + ).rejects.toThrow(ValidationError); + }); + + test("rejects when neither --app-id nor --snapshot-id is given", async () => { + const func = await downloadCommand.loader(); + await expect(func.call(createContext().context, {})).rejects.toThrow( + ContextError + ); + }); + + test("rejects --branch without --app-id", async () => { + const func = await downloadCommand.loader(); + await expect( + func.call(createContext().context, { + "snapshot-id": "s", + branch: "main", + }) + ).rejects.toThrow(ValidationError); + }); +}); diff --git a/test/lib/api/preprod-artifacts.test.ts b/test/lib/api/preprod-artifacts.test.ts index 0536247be1..5914d3d701 100644 --- a/test/lib/api/preprod-artifacts.test.ts +++ b/test/lib/api/preprod-artifacts.test.ts @@ -16,11 +16,13 @@ import { ApiError, ValidationError } from "../../../src/lib/errors.js"; const { customFetchMock, apiRequestToRegionMock, + apiRequestToRegionNoContentMock, getAuthTokenMock, uploadMissingBufferChunksMock, } = vi.hoisted(() => ({ customFetchMock: vi.fn(), apiRequestToRegionMock: vi.fn(), + apiRequestToRegionNoContentMock: vi.fn(() => Promise.resolve()), getAuthTokenMock: vi.fn<() => string | undefined>(() => "secret-token"), uploadMissingBufferChunksMock: vi.fn(() => Promise.resolve()), })); @@ -30,6 +32,7 @@ vi.mock("../../../src/lib/region.js", () => ({ })); vi.mock("../../../src/lib/api/infrastructure.js", () => ({ apiRequestToRegion: apiRequestToRegionMock, + apiRequestToRegionNoContent: apiRequestToRegionNoContentMock, })); vi.mock("../../../src/lib/custom-ca.js", () => ({ customFetch: customFetchMock, @@ -60,9 +63,13 @@ vi.mock("../../../src/lib/api/chunk-upload.js", async (importOriginal) => { import { buildFormatFromUrl, downloadBuildArtifact, + downloadSnapshotArchive, getBuildInstallDetails, + getLatestBaseSnapshot, + LatestBaseSnapshotSchema, toBinaryDownloadUrl, uploadBuild, + waitForSnapshotArchive, } from "../../../src/lib/api/preprod-artifacts.js"; describe("toBinaryDownloadUrl", () => { @@ -340,3 +347,106 @@ describe("uploadBuild", () => { ).rejects.toThrow(/no artifact URL/i); }); }); + +describe("snapshots", () => { + beforeEach(() => { + apiRequestToRegionMock.mockReset(); + apiRequestToRegionNoContentMock.mockClear(); + customFetchMock.mockReset(); + }); + + test("LatestBaseSnapshotSchema expects snake_case (server contract)", () => { + // The server returns snake_case; the schema must accept it and reject + // camelCase, guarding against the C1 regression. + expect( + LatestBaseSnapshotSchema.safeParse({ + head_artifact_id: "art-1", + image_count: 5, + }).success + ).toBe(true); + expect( + LatestBaseSnapshotSchema.safeParse({ + headArtifactId: "art-1", + imageCount: 5, + }).success + ).toBe(false); + }); + + test("getLatestBaseSnapshot maps the response and forwards params", async () => { + // apiRequestToRegion returns schema-validated snake_case data. + apiRequestToRegionMock.mockResolvedValue({ + data: { head_artifact_id: "art-1", image_count: 5 }, + headers: new Headers(), + }); + + await expect( + getLatestBaseSnapshot("my-org", "my-app", { + branch: "main", + project: "proj-1", + }) + ).resolves.toEqual({ headArtifactId: "art-1", imageCount: 5 }); + // app_id + optional branch/project go through as query params. + const params = apiRequestToRegionMock.mock.calls.at(-1)?.[2]?.params; + expect(params).toEqual({ + app_id: "my-app", + branch: "main", + project: "proj-1", + }); + }); + + test("getLatestBaseSnapshot returns null on 404", async () => { + apiRequestToRegionMock.mockRejectedValue( + new ApiError("not found", 404, "", "endpoint") + ); + await expect( + getLatestBaseSnapshot("my-org", "missing") + ).resolves.toBeNull(); + }); + + test("waitForSnapshotArchive triggers a build then resolves when ready", async () => { + apiRequestToRegionMock + .mockResolvedValueOnce({ data: { ready: false }, headers: new Headers() }) + .mockResolvedValueOnce({ data: { ready: true }, headers: new Headers() }); + const onBuild = vi.fn(); + + await waitForSnapshotArchive("my-org", "snap-1", onBuild); + + expect(apiRequestToRegionNoContentMock).toHaveBeenCalledTimes(1); + expect(onBuild).toHaveBeenCalledTimes(1); + }); + + test("waitForSnapshotArchive skips the build when already ready", async () => { + apiRequestToRegionMock.mockResolvedValue({ + data: { ready: true }, + headers: new Headers(), + }); + const onBuild = vi.fn(); + + await waitForSnapshotArchive("my-org", "snap-1", onBuild); + + expect(apiRequestToRegionNoContentMock).not.toHaveBeenCalled(); + expect(onBuild).not.toHaveBeenCalled(); + }); + + test("downloadSnapshotArchive returns the archive bytes", async () => { + customFetchMock.mockResolvedValue({ + ok: true, + arrayBuffer: () => + Promise.resolve(new TextEncoder().encode("zip-bytes").buffer), + }); + + const buf = await downloadSnapshotArchive("my-org", "snap-1"); + expect(buf.toString()).toBe("zip-bytes"); + }); + + test("downloadSnapshotArchive throws on a non-2xx response", async () => { + customFetchMock.mockResolvedValue({ + ok: false, + status: 500, + statusText: "Server Error", + }); + await expect(downloadSnapshotArchive("my-org", "snap-1")).rejects.toThrow( + ApiError + ); + }); +}); diff --git a/test/lib/snapshots/archive.test.ts b/test/lib/snapshots/archive.test.ts new file mode 100644 index 0000000000..bf9e01c6a2 --- /dev/null +++ b/test/lib/snapshots/archive.test.ts @@ -0,0 +1,65 @@ +/** + * Tests for snapshot archive extraction, including Zip-Slip protection. + */ + +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { strToU8, zipSync } from "fflate"; +import { afterEach, describe, expect, test } from "vitest"; +import { extractZipToDir } from "../../../src/lib/snapshots/archive.js"; + +const dirs: string[] = []; +function tempDir(): string { + const dir = mkdtempSync(join(tmpdir(), "snap-extract-")); + dirs.push(dir); + return dir; +} + +afterEach(() => { + while (dirs.length > 0) { + const dir = dirs.pop(); + if (dir) { + rmSync(dir, { recursive: true, force: true }); + } + } +}); + +describe("extractZipToDir", () => { + test("extracts files (incl. nested) and skips directory entries", () => { + const zip = zipSync({ + "a.png": strToU8("A"), + "sub/b.png": strToU8("B"), + "emptydir/": new Uint8Array(), + }); + const out = tempDir(); + + const count = extractZipToDir(zip, out); + + expect(count).toBe(2); + expect(readFileSync(join(out, "a.png"), "utf8")).toBe("A"); + expect(readFileSync(join(out, "sub", "b.png"), "utf8")).toBe("B"); + }); + + test("skips traversal, absolute, and empty entries but keeps safe names", () => { + const zip = zipSync({ + "../evil.png": strToU8("X"), + "a/../../evil2.png": strToU8("X"), + "/etc/evil3.png": strToU8("X"), + "": strToU8("X"), + // Legitimate name that merely starts with ".." — must NOT be skipped. + "..config.png": strToU8("C"), + "ok.png": strToU8("Y"), + }); + const out = tempDir(); + + const count = extractZipToDir(zip, out); + + expect(count).toBe(2); // "..config.png" + "ok.png" + expect(existsSync(join(out, "ok.png"))).toBe(true); + expect(readFileSync(join(out, "..config.png"), "utf8")).toBe("C"); + // No traversal entry escaped the output dir. + expect(existsSync(join(out, "..", "evil.png"))).toBe(false); + expect(existsSync(join(out, "..", "..", "evil2.png"))).toBe(false); + }); +});