Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/hosted/self-host/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ the staged version against the host version, `runtime.json` and the framework
reference. It downloads the listed tarball, verifies registry integrity and
compares every packaged file with this build. Missing versions, unavailable
archives and different content stop deployment. It never publishes by default.
The tarball and every redirect hop must stay on the registry's own origin, and
the gate follows only the redirects the builder follows (301, 302, 303, 307 and
308). A Verdaccio behind a proxy that advertises another host in `dist.tarball`
fails this check; set its public URL (`url_prefix`) to the origin in
`EXECUTOR_NPM_REGISTRY`.
Do not continue after a failed gate. A healthy `/health` is not an SDK gate.

After the gate passes, start the local installation:
Expand Down
11 changes: 8 additions & 3 deletions apps/hosted/server/src/implementation/provisioning.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/** Host-owned lifecycle jobs. No browser session, secrets, or live request enters the queue. */
import { StorageError } from "@executor-js/sdk/core";
import { BuildStage, StorageError } from "@executor-js/sdk/core";
import { Effect, Exit, Schedule, Schema } from "effect";
import { SqlClient } from "effect/sql";
import { traceFailure } from "@executor-js/telemetry/failed-span";
Expand Down Expand Up @@ -31,6 +31,8 @@ const Manager = Schema.Struct({ userId: Schema.String, name: Schema.String });
*/
const FailureCause = Schema.Struct({
tag: Schema.String,
/** The build step a failed build names, such as `dependencies`; a closed set, never text. */
stage: Schema.optional(BuildStage),
package: Schema.optional(Schema.String),
version: Schema.optional(Schema.String),
registry: Schema.optional(Schema.String),
Expand Down Expand Up @@ -70,22 +72,24 @@ const causeOrigin = (value: unknown) => {
};
/**
* Project a failure onto the fields that may reach a background log: its tagged name and, when an
* error or its cause chain states them as typed fields, the package, version, registry origin and
* HTTP status. An error that states none of them is named by its tag alone.
* error or its cause chain states them as typed fields, the build stage, package, version, registry
* origin and HTTP status. An error that states none of them is named by its tag alone.
*/
const failureCause = (error: unknown): FailureCause => {
let tag = "Unknown";
let packageName: string | undefined;
let version: string | undefined;
let registry: string | undefined;
let status: number | undefined;
let stage: typeof BuildStage.Type | undefined;
let current: unknown = error;
for (let depth = 0; depth < 4 && typeof current === "object" && current !== null; depth += 1) {
const value = current as Record<string, unknown>;
tag = tag === "Unknown" ? (causeTag(value) ?? tag) : tag;
packageName ??= causeName(value.dependency) ?? causeName(value.package);
version ??= causeName(value.version);
registry ??= causeOrigin(value.registry);
stage ??= Schema.is(BuildStage)(value.stage) ? value.stage : undefined;
status ??=
typeof value.status === "number" &&
Number.isInteger(value.status) &&
Expand All @@ -97,6 +101,7 @@ const failureCause = (error: unknown): FailureCause => {
}
return {
tag,
...(stage === undefined ? {} : { stage }),
...(packageName === undefined ? {} : { package: packageName }),
...(version === undefined ? {} : { version }),
...(registry === undefined ? {} : { registry }),
Expand Down
39 changes: 38 additions & 1 deletion e2e/tests/apps-published.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ const registry = (
readonly tarball?: string;
/** The archive's own URL answers this redirect instead of an archive. */
readonly redirect?: string;
/** The redirect's status; 302 when not given. */
readonly redirectStatus?: number;
} = {},
) => {
let requests = 0;
Expand All @@ -101,6 +103,8 @@ const registry = (
let firstArchiveRequest: number | undefined;
let cachedUntil = 0;
const tarball = `/apps/-/apps-${version}.tgz`;
/** Where a same-origin redirect can send the archive request; it serves the origin's answer. */
const moved = `/apps/-/moved/apps-${version}.tgz`;
const origin = (): Archive => {
if (Array.isArray(archive)) return archive[Math.min(originRequests, archive.length - 1)]!;
const { stored } = archive as { readonly stored: { afterMs: number; bytes: Uint8Array } };
Expand All @@ -127,7 +131,7 @@ const registry = (
}
if (url.pathname === tarball) {
if (options.redirect !== undefined) {
response.writeHead(302, { location: options.redirect });
response.writeHead(options.redirectStatus ?? 302, { location: options.redirect });
response.end();
return;
}
Expand All @@ -151,6 +155,12 @@ const registry = (
response.end(answer.bytes ?? "");
return;
}
if (url.pathname === moved) {
const answer = origin();
response.writeHead(answer.status, { "content-type": "application/octet-stream" });
response.end(answer.bytes ?? "");
return;
}
response.writeHead(404);
response.end();
});
Expand Down Expand Up @@ -281,6 +291,33 @@ layer(NodeServices.layer)("apps release check", (it) => {
}).pipe(Effect.scoped),
);

it.effect("self-host gate follows only the redirects the builder follows", () =>
Effect.gen(function* () {
const { version, local } = yield* archives;
const integrity = integrityOf(local);
// The builder follows 301, 302, 303, 307 and 308 and treats any other 3xx as a failed
// download, so a same-origin 300 or 304 carrying a Location must not pass the gate.
for (const [redirectStatus, succeeds] of [
[300, false],
[304, false],
[302, true],
[308, true],
] as const) {
const npm = yield* registry(version, integrity, [{ status: 200, bytes: local }], {
redirect: `/apps/-/moved/apps-${version}.tgz`,
redirectStatus,
});
const run = yield* check(npm.url(), "", {}, true);
expect(run.exitCode, `${redirectStatus}: ${run.log}`).toBe(succeeds ? 0 : 1);
expect(run.log).toContain(
succeeds
? `Builder registry serves matching apps@${version}`
: `Builder SDK tarball is unavailable (status ${redirectStatus})`,
);
}
}).pipe(Effect.scoped),
);

it.effect("self-host gate refuses missing archives and corrupt registry integrity", () =>
Effect.gen(function* () {
const { version, local, different } = yield* archives;
Expand Down
11 changes: 9 additions & 2 deletions e2e/tests/self-host-provisioning-failure.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,17 @@ layer(TestLive, { excludeTestServices: true })("Self-host provisioning failure",
if (failed === undefined || retried === undefined)
return yield* Effect.die("Provisioning failure lines missing");
expect(failed.fields["reason"]).toBe("dependency");
expect(failed.fields["cause"]).toMatchObject({ tag: "VersionBuildFailed" });
// The failed build's stage is a closed name, so the log can say which step broke.
expect(failed.fields["cause"]).toMatchObject({
tag: "VersionBuildFailed",
stage: "dependencies",
});
expect(retried.fields["attempts"]).toBeGreaterThanOrEqual(1);
expect(retried.fields["outcome"]).toBe("requeued");
expect(retried.fields["cause"]).toMatchObject({ tag: "VersionBuildFailed" });
expect(retried.fields["cause"]).toMatchObject({
tag: "VersionBuildFailed",
stage: "dependencies",
});

// The registry's credentials, path and query stay out of both lines.
for (const { line } of [...step, ...attempt])
Expand Down
13 changes: 9 additions & 4 deletions scripts/releases/apps-self-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,13 @@ const args = process.argv.slice(2);
const publish = args.includes("--publish");
const packageIndex = args.indexOf("--package");
const packageDirectory = packageIndex < 0 ? staged : args[packageIndex + 1];
/** At most the builder's own hop limit (10), so the gate never passes a chain the builder refuses. */
const redirectLimit = 5;
/**
* The redirects the app builder follows (`patches/@cloudflare%[email protected]`). It
* treats any other 3xx as a failed download, so the gate returns that answer as the archive too.
*/
const followedRedirects: ReadonlySet<number> = new Set([301, 302, 303, 307, 308]);

/** The origin of an absolute URL, or `undefined` when the text is not one. */
const originOf = (url: string) => {
Expand All @@ -54,14 +60,13 @@ const downloadFromRegistry = (url: string, origin: string) =>
.get(target)
.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
const location = response.headers.location;
if (response.status < 300 || response.status >= 400 || location === undefined)
return response;
if (!followedRedirects.has(response.status) || location === undefined) return response;
yield* response.text;
const parsed = Url.fromString(location, target);
const next = Result.isSuccess(parsed) ? parsed.success : undefined;
if (next === undefined || next.origin !== origin)
return yield* new AppsReleaseMismatch({
message: `Builder SDK tarball on ${origin} redirects to ${next?.origin ?? location}, outside the builder registry's origin. The builder refuses that tarball, so deployment is refused.`,
message: `Builder SDK tarball on ${origin} redirects to ${next?.origin ?? location}, outside the builder registry's origin. The gate accepts only tarballs served on the registry's own origin, so deployment is refused. If the registry is Verdaccio behind a proxy, set its public URL (url_prefix) to EXECUTOR_NPM_REGISTRY's origin.`,
});
if (hop >= redirectLimit)
return yield* new AppsReleaseMismatch({
Expand Down Expand Up @@ -166,7 +171,7 @@ NodeRuntime.runMain(
const tarballOrigin = originOf(published.dist.tarball);
if (registryOrigin === undefined || tarballOrigin !== registryOrigin)
return yield* new AppsReleaseMismatch({
message: `Builder registry metadata at ${registryOrigin ?? registry} serves its SDK tarball at ${published.dist.tarball} (${tarballOrigin ?? "not an absolute URL"}), outside the builder registry's origin. The builder refuses that tarball, so deployment is refused.`,
message: `Builder registry metadata at ${registryOrigin ?? registry} serves its SDK tarball at ${published.dist.tarball} (${tarballOrigin ?? "not an absolute URL"}), outside the builder registry's origin. The builder refuses that tarball, so deployment is refused. If the registry is Verdaccio behind a proxy, set its public URL (url_prefix) to EXECUTOR_NPM_REGISTRY's origin.`,
});
const archive = yield* downloadFromRegistry(published.dist.tarball, registryOrigin);
if (archive.status !== 200) {
Expand Down
Loading