releases.test.ts
This file
Path
apps/platform/test/releases.test.ts
622 lines · 18.9 KiB · TypeScript
Last changed by
Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–462why, one step back1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Handle } from "@repo/protocol/ids";4import { untouchable } from "@repo/testkit/untouchable";5import { Context, Effect, Layer, Option, Schema } from "effect";67import { platform } from "../src/platform.ts";8import { ReleaseManifest } from "../src/releases.ts";9import { ReleaseReads, ReleaseStoreMemory } from "../src/releases/memory.ts";10import { MemorySessions } from "../src/sessions/memory.ts";11import { fakeEnv } from "./fake-env.ts";12import { noProjects, origin, served, toolCall, toolList } from "./harness.ts";1314const linux = `${Brand.slug}-linux-x64`;1516const darwin = `${Brand.slug}-darwin-arm64`;1718const linuxBytes = new Uint8Array([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1]);1920const darwinBytes = new Uint8Array([0xcf, 0xfa, 0xed, 0xfe, 7, 0]);2122const oldLinuxBytes = new Uint8Array([0x7f, 0x45, 0x4c, 0x46, 9]);2324const linuxSha =25 "4f6a0b5c3e9d1a7b2c8e0f4d6a1b3c5e7f9a0b2c4d6e8f1a3b5c7d9e0f2a4b6c";2627const darwinSha =28 "0e1d2c3b4a5968778695a4b3c2d1e0f0123456789abcdef0123456789abcdef0";2930const oldLinuxSha =31 "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf";3233const manifest = {34 latest: "0.1.0",35 versions: {36 "0.0.9": { assets: { [linux]: { bytes: 5, sha256: oldLinuxSha } } },37 "0.1.0": {38 assets: {39 [darwin]: { bytes: 6, sha256: darwinSha },40 [linux]: { bytes: 7, sha256: linuxSha },41 },42 },43 },44};4546const script = (version: string) =>47 `#!/bin/sh\nset -eu\necho "installing ${Brand.cli} ${version}"\n`;4849const files = {50 "releases/0.0.9/install.sh": script("0.0.9"),51 [`releases/0.0.9/${linux}`]: oldLinuxBytes,52 "releases/0.1.0/install.sh": script("0.1.0"),53 [`releases/0.1.0/${darwin}`]: darwinBytes,54 [`releases/0.1.0/${linux}`]: linuxBytes,55 "releases/manifest.json": JSON.stringify(manifest),56 "secrets/operator": "never served",57};5859const sessions = MemorySessions.layer({ "alice-token": Handle.make("alice") });6061const releasesServed = (62 stored: Readonly<Record<string, string | Uint8Array>>63) =>64 Effect.gen(function* () {65 const store = yield* Layer.build(ReleaseStoreMemory.layer(stored));6667 const { fetch } = yield* served(68 Layer.mergeAll(noProjects, sessions, Layer.succeedContext(store))69 );7071 return {72 fetch,73 reads: Context.get(store, ReleaseReads).keys,74 send: (path: string, init?: RequestInit) =>75 fetch(new Request(`${origin}${path}`, init)),76 };77 });7879const textOf = (response: Response) => Effect.promise(() => response.text());8081const headersOf = (reply: Response) => ({82 cache: reply.headers.get("cache-control"),83 etag: reply.headers.get("etag"),84 length: reply.headers.get("content-length"),85 location: reply.headers.get("location"),86 status: reply.status,87 type: reply.headers.get("content-type"),88});8990const bytesOf = (response: Response) =>91 Effect.map(92 Effect.promise(() => response.arrayBuffer()),93 (buffer) => new Uint8Array(buffer)94 );9596describe("the CLI's releases, served by the platform", () => {97 it.effect(98 "answers /install.sh to anyone with the latest release's script, cached for five minutes",99 () =>100 Effect.gen(function* () {101 const { send } = yield* releasesServed(files);102103 const response = yield* send("/install.sh");104105 expect({106 cache: response.headers.get("cache-control"),107 status: response.status,108 type: response.headers.get("content-type"),109 }).toStrictEqual({110 cache: "public, max-age=300",111 status: 200,112 type: "text/x-shellscript; charset=utf-8",113 });114 expect(yield* textOf(response)).toBe(script("0.1.0"));115 })116 );117118 it.effect(119 "answers a version's binary as immutable bytes tagged with its sha256, and 304 to a client that holds them",120 () =>121 Effect.gen(function* () {122 const { send } = yield* releasesServed(files);123124 const path = `/releases/0.1.0/${linux}`;125126 const response = yield* send(path);127128 expect({129 cache: response.headers.get("cache-control"),130 etag: response.headers.get("etag"),131 length: response.headers.get("content-length"),132 status: response.status,133 type: response.headers.get("content-type"),134 }).toStrictEqual({135 cache: "public, max-age=31536000, immutable",136 etag: `"${linuxSha}"`,137 length: "7",138 status: 200,139 type: "application/octet-stream",140 });141 expect(yield* bytesOf(response)).toStrictEqual(linuxBytes);142143 const held = yield* send(path, {144 headers: { "if-none-match": `"${linuxSha}"` },145 });146147 const heldWeakly = yield* send(path, {148 headers: { "if-none-match": `"${darwinSha}", W/"${linuxSha}"` },149 });150151 const heldAny = yield* send(path, {152 headers: { "if-none-match": "*" },153 });154155 const stale = yield* send(path, {156 headers: { "if-none-match": `"${oldLinuxSha}"` },157 });158159 expect(160 [held, heldWeakly, heldAny, stale].map((each) => ({161 etag: each.headers.get("etag"),162 status: each.status,163 }))164 ).toStrictEqual([165 { etag: `"${linuxSha}"`, status: 304 },166 { etag: `"${linuxSha}"`, status: 304 },167 { etag: `"${linuxSha}"`, status: 304 },168 { etag: `"${linuxSha}"`, status: 200 },169 ]);170 expect(yield* textOf(held)).toBe("");171 })172 );173174 it.effect(175 "sends latest to the newest release's file, a redirect kept five minutes",176 () =>177 Effect.gen(function* () {178 const { send } = yield* releasesServed(files);179180 const replies = [181 yield* send(`/releases/latest/${linux}`),182 yield* send("/releases/latest/SHA256SUMS"),183 ];184185 expect(186 replies.map((reply) => ({187 cache: reply.headers.get("cache-control"),188 location: reply.headers.get("location"),189 status: reply.status,190 }))191 ).toStrictEqual([192 {193 cache: "public, max-age=300",194 location: `/releases/0.1.0/${linux}`,195 status: 302,196 },197 {198 cache: "public, max-age=300",199 location: "/releases/0.1.0/SHA256SUMS",200 status: 302,201 },202 ]);203 })204 );205206 it.effect(207 "answers the manifest as JSON, and a version's checksums as sha256sum prints them",208 () =>209 Effect.gen(function* () {210 const { send } = yield* releasesServed(files);211212 const listed = yield* send("/releases/manifest.json");213214 const sums = yield* send("/releases/0.1.0/SHA256SUMS");215216 expect({217 cache: listed.headers.get("cache-control"),218 status: listed.status,219 type: listed.headers.get("content-type"),220 }).toStrictEqual({221 cache: "public, max-age=300",222 status: 200,223 type: "application/json",224 });225 expect(yield* Effect.promise(() => listed.json())).toStrictEqual(226 manifest227 );228 expect({229 cache: sums.headers.get("cache-control"),230 status: sums.status,231 type: sums.headers.get("content-type"),232 }).toStrictEqual({233 cache: "public, max-age=31536000, immutable",234 status: 200,235 type: "text/plain; charset=utf-8",236 });237 expect(yield* textOf(sums)).toBe(238 `${darwinSha} ${darwin}\n${linuxSha} ${linux}\n`239 );240 })241 );242243 it.effect(244 "makes a version's checksums from its manifest, even when the manifest lists an uploaded SHA256SUMS",245 () =>246 Effect.gen(function* () {247 const listingSums = {248 ...manifest,249 versions: {250 ...manifest.versions,251 "0.1.0": {252 assets: {253 ...manifest.versions["0.1.0"].assets,254 SHA256SUMS: { bytes: 9, sha256: oldLinuxSha },255 },256 },257 },258 };259260 const { reads, send } = yield* releasesServed({261 ...files,262 "releases/0.1.0/SHA256SUMS": "uploaded\n",263 "releases/manifest.json": JSON.stringify(listingSums),264 });265266 const sums = yield* send("/releases/0.1.0/SHA256SUMS");267268 expect({269 body: yield* textOf(sums),270 etag: sums.headers.get("etag"),271 status: sums.status,272 type: sums.headers.get("content-type"),273 }).toStrictEqual({274 body: `${darwinSha} ${darwin}\n${linuxSha} ${linux}\n`,275 etag: null,276 status: 200,277 type: "text/plain; charset=utf-8",278 });279 expect(yield* reads).toStrictEqual(["releases/manifest.json"]);280 })281 );282283 it.effect(284 "answers 404 to a version, a file or a path it does not serve, and reads nothing outside releases/",285 () =>286 Effect.gen(function* () {287 const { reads, send } = yield* releasesServed(files);288289 const paths = [290 `/releases/9.9.9/${linux}`,291 `/releases/0.0.9/${darwin}`,292 `/releases/0.1.0/${Brand.slug}-windows-x64`,293 "/releases/0.1.0/install.sh",294 "/releases/latest/manifest.json",295 "/releases/0.1.0/..%2F..%2Fsecrets%2Foperator",296 "/releases/..%2F..%2Fsecrets/operator",297 `/releases/..%2F..%2Fsecrets%2Foperator%23/${linux}`,298 `/releases/0.1.0%2F..%2F..%2Fsecrets/${linux}`,299 `/releases/../../secrets/operator`,300 `/releases/%2e%2e/${linux}`,301 ];302303 const statuses = [];304305 for (const path of paths) {306 statuses.push((yield* send(path)).status);307 }308309 expect(statuses).toStrictEqual(paths.map(() => 404));310 expect(311 (yield* reads).filter(312 (key) => !key.startsWith("releases/") || key.includes("..")313 )314 ).toStrictEqual([]);315 })316 );317318 it.effect("refuses to take anything: every other method is 405", () =>319 Effect.gen(function* () {320 const { reads, send } = yield* releasesServed(files);321322 const replies = [323 yield* send("/install.sh", { body: "#!/bin/sh", method: "POST" }),324 yield* send(`/releases/0.1.0/${linux}`, {325 body: linuxBytes,326 method: "PUT",327 }),328 yield* send("/releases/manifest.json", { method: "DELETE" }),329 ];330331 expect(332 replies.map((reply) => ({333 allow: reply.headers.get("allow"),334 status: reply.status,335 }))336 ).toStrictEqual(replies.map(() => ({ allow: "GET, HEAD", status: 405 })));337 expect(yield* reads).toStrictEqual([]);338 })339 );340341 it.effect("answers HEAD as GET, without the body", () =>342 Effect.gen(function* () {343 const { send } = yield* releasesServed(files);344345 const paths = [346 "/install.sh",347 `/releases/0.1.0/${linux}`,348 "/releases/manifest.json",349 "/releases/0.1.0/SHA256SUMS",350 `/releases/latest/${linux}`,351 `/releases/9.9.9/${linux}`,352 ];353354 const asGot = [];355356 const asHead = [];357358 for (const path of paths) {359 const got = yield* send(path);360361 const head = yield* send(path, { method: "HEAD" });362363 asGot.push({ body: "", path, ...headersOf(got) });364 asHead.push({ body: yield* textOf(head), path, ...headersOf(head) });365 }366367 expect(asHead).toStrictEqual(asGot);368 expect(asHead[1]?.length).toBe("7");369 })370 );371372 it.effect(373 "needs no token, even a stale one, while every other route still answers 401",374 () =>375 Effect.gen(function* () {376 const { fetch, send } = yield* releasesServed(files);377378 const stale = { headers: { authorization: "Bearer stale-token" } };379380 const downloads = [381 yield* send("/install.sh", stale),382 yield* send("/releases/manifest.json", stale),383 yield* send(`/releases/latest/${linux}`, stale),384 yield* send(`/releases/0.1.0/${linux}`, stale),385 yield* send("/releases/0.1.0/SHA256SUMS", {386 headers: { authorization: "Basic c3RhbGU6dG9rZW4=" },387 }),388 ];389390 const others = [391 yield* send("/install.sh.asc", stale),392 yield* send("/releases", stale),393 yield* send("/releases/0.1.0", stale),394 yield* send("/rpc", { ...stale, body: "{}", method: "POST" }),395 yield* fetch(toolList("stale-token")),396 yield* fetch(toolCall("listProjects", {})),397 ];398399 expect(downloads.map(({ status }) => status)).toStrictEqual([400 200, 200, 302, 200, 200,401 ]);402 expect(others.map(({ status }) => status)).toStrictEqual(403 others.map(() => 401)404 );405 })406 );407408 it.effect(409 "answers 503, kept nowhere, while the manifest is broken, and 404 before anything is released",410 () =>411 Effect.gen(function* () {412 const paths = [413 "/install.sh",414 "/releases/manifest.json",415 `/releases/latest/${linux}`,416 `/releases/0.1.0/${linux}`,417 "/releases/0.1.0/SHA256SUMS",418 ];419420 const repliesTo = (421 stored: Readonly<Record<string, string | Uint8Array>>422 ) =>423 Effect.gen(function* () {424 const { send } = yield* releasesServed(stored);425426 const replies = [];427428 for (const path of paths) {429 const reply = yield* send(path);430431 replies.push({432 cache: reply.headers.get("cache-control"),433 status: reply.status,434 });435 }436437 return replies;438 });439440 const unlisted = yield* repliesTo({441 ...files,442 "releases/manifest.json": JSON.stringify({443 ...manifest,444 latest: "0.2.0",445 }),446 });447448 const truncated = yield* repliesTo({449 ...files,450 "releases/manifest.json": JSON.stringify(manifest).slice(0, 40),451 });452453 const unreleased = yield* repliesTo({});454455 expect({ truncated, unlisted, unreleased }).toStrictEqual({456 truncated: paths.map(() => ({ cache: "no-store", status: 503 })),457 unlisted: paths.map(() => ({ cache: "no-store", status: 503 })),458 unreleased: paths.map(() => ({ cache: "no-store", status: 404 })),459 });460 })461 );462Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 463–465why, one step back463 // `releases` is a name no project may take, so git's paths under it reach the gateway464 // and find no repo. The releases' own 404 has no body, so the text says the gateway465 // answered.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 466–570why, one step back466 it.effect(467 "leaves git's paths to the gateway, which knows no repo named releases",468 () =>469 Effect.gen(function* () {470 const { reads, send } = yield* releasesServed(files);471472 const reserved = yield* send(473 "/releases/info/refs?service=git-receive-pack"474 );475476 const push = yield* send("/datekit/info/refs?service=git-receive-pack");477478 expect({479 push: {480 challenge: push.headers.get("www-authenticate"),481 status: push.status,482 },483 reserved: { status: reserved.status, text: yield* textOf(reserved) },484 }).toStrictEqual({485 push: { challenge: `Basic realm="${Brand.name}"`, status: 401 },486 reserved: { status: 404, text: "no repo releases\n" },487 });488 expect(yield* reads).toStrictEqual([]);489 })490 );491});492493const bucketOf = (stored: Readonly<Record<string, string | Uint8Array>>) =>494 untouchable<R2Bucket>("RELEASES", {495 get: (key: string) =>496 Promise.resolve(497 Object.hasOwn(stored, key)498 ? untouchable<R2ObjectBody>("R2ObjectBody", {499 body: new Blob([stored[key] ?? ""]).stream(),500 size: new Blob([stored[key] ?? ""]).size,501 })502 : null503 ),504 });505506describe("the Worker's releases, from its RELEASES bucket", () => {507 it.effect("serves the script and the binaries the bucket holds", () =>508 Effect.gen(function* () {509 const { fetch } = yield* served(510 platform({ ...fakeEnv(), RELEASES: bucketOf(files) })511 );512513 const send = (path: string, init?: RequestInit) =>514 fetch(new Request(`${origin}${path}`, init));515516 const installer = yield* send("/install.sh");517518 const binary = yield* send(`/releases/0.1.0/${linux}`);519520 const head = yield* send(`/releases/0.1.0/${darwin}`, {521 method: "HEAD",522 });523524 expect(525 [installer, binary, head].map(({ headers, status }) => ({526 length: headers.get("content-length"),527 status,528 }))529 ).toStrictEqual([530 { length: String(script("0.1.0").length), status: 200 },531 { length: "7", status: 200 },532 { length: "6", status: 200 },533 ]);534 expect(yield* textOf(installer)).toBe(script("0.1.0"));535 expect(yield* bytesOf(binary)).toStrictEqual(linuxBytes);536 expect(yield* textOf(head)).toBe("");537 })538 );539540 it.effect("answers 500, and serves nothing, when the bucket fails", () =>541 Effect.gen(function* () {542 const failing = untouchable<R2Bucket>("RELEASES", {543 get: () => Promise.reject(new Error("R2 is down")),544 });545546 const { fetch } = yield* served(547 platform({ ...fakeEnv(), RELEASES: failing })548 );549550 const reply = yield* fetch(new Request(`${origin}/install.sh`));551552 expect({553 body: yield* textOf(reply),554 status: reply.status,555 }).toStrictEqual({ body: "", status: 500 });556 })557 );558});559560const holding = (561 name: string,562 asset: { readonly bytes: number | string; readonly sha256: string }563) => ({564 latest: "0.1.0",565 versions: { "0.1.0": { assets: { [name]: asset } } },566});567568describe("the release manifest", () => {569 const decode = Schema.decodeUnknownOption(ReleaseManifest);570Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6
line 571why, one step back571 it("decodes what the release script writes", () => {Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 572–622why, one step back572 expect(decode(manifest)).toStrictEqual(Option.some(manifest));573 });574575 it("refuses a digest that is not 64 lowercase hex digits", () => {576 expect(577 [linuxSha.toUpperCase(), linuxSha.slice(1), `${linuxSha.slice(1)}g`].map(578 (sha256) => decode(holding(linux, { bytes: 7, sha256 }))579 )580 ).toStrictEqual([Option.none(), Option.none(), Option.none()]);581 });582583 it("refuses a size that is not a whole count of bytes", () => {584 expect(585 [1.5, -1, "7", Number.POSITIVE_INFINITY].map((bytes) =>586 decode(holding(linux, { bytes, sha256: linuxSha }))587 )588 ).toStrictEqual([589 Option.none(),590 Option.none(),591 Option.none(),592 Option.none(),593 ]);594 });595596 it("refuses a latest it does not list", () => {597 expect(decode({ ...manifest, latest: "0.2.0" })).toStrictEqual(598 Option.none()599 );600 });601602 it("refuses a version or a file name that could leave its folder", () => {603 const asset = { bytes: 7, sha256: linuxSha };604605 expect([606 decode({607 latest: "0.1.0",608 versions: { "../x": { assets: {} }, "0.1.0": { assets: {} } },609 }),610 decode({ latest: "..", versions: { "..": { assets: {} } } }),611 decode({ latest: "0.1", versions: { "0.1": { assets: {} } } }),612 decode(holding("a/b", asset)),613 decode(holding("..", asset)),614 ]).toStrictEqual([615 Option.none(),616 Option.none(),617 Option.none(),618 Option.none(),619 Option.none(),620 ]);621 });622});