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
51 changes: 14 additions & 37 deletions apps/hosted/server/src/implementation/provisioning.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
/** Host-owned lifecycle jobs. No browser session, secrets, or live request enters the queue. */
import { BuildStage, StorageError } from "@executor-js/sdk/core";
import {
BuildStage,
RegistryBuildFailureFields,
safeExactSemver,
safeHttpStatus,
safeNpmPackageName,
safeRegistryOrigin,
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 @@ -33,26 +41,9 @@ 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),
status: Schema.optional(Schema.Int),
...RegistryBuildFailureFields,
});
type FailureCause = typeof FailureCause.Type;
/** A log line keeps one record: no control character may enter it from a field. */
const hasControlCharacter = (value: string) =>
[...value].some((character) => {
const code = character.codePointAt(0) ?? 0;
return code < 0x20 || code === 0x7f;
});
/** A bounded name an error states as its own field, never text quoted from a response. */
const causeName = (value: unknown) =>
typeof value === "string" &&
value.length > 0 &&
value.length <= 200 &&
!hasControlCharacter(value)
? value
: undefined;
/** Only a tag an error class names, so a response cannot choose the text logged. */
const causeTag = (value: unknown) =>
typeof value === "object" &&
Expand All @@ -62,14 +53,6 @@ const causeTag = (value: unknown) =>
/^[A-Za-z][A-Za-z0-9]{0,63}$/u.test(value._tag)
? value._tag
: undefined;
const causeOrigin = (value: unknown) => {
if (typeof value !== "string" || value.length === 0) return undefined;
try {
return new URL(value).origin;
} catch {
return undefined;
}
};
/**
* 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 build stage, package, version, registry
Expand All @@ -86,17 +69,11 @@ const failureCause = (error: unknown): FailureCause => {
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);
packageName ??= safeNpmPackageName(value.package) ?? safeNpmPackageName(value.dependency);
version ??= safeExactSemver(value.version);
registry ??= safeRegistryOrigin(value.registry);
stage ??= Schema.is(BuildStage)(value.stage) ? value.stage : undefined;
status ??=
typeof value.status === "number" &&
Number.isInteger(value.status) &&
value.status >= 100 &&
value.status <= 599
? value.status
: undefined;
status ??= safeHttpStatus(value.status);
current = value.cause;
}
return {
Expand Down
95 changes: 51 additions & 44 deletions e2e/support/credentialed-registry.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/**
* A product npm registry reached through a URL that carries synthetic credentials in its userinfo
* and a token in its query, as an operator's private registry URL can. It forwards every request
* to the suite's registry, so the product starts and builds as usual.
* to the suite's registry, except the given path, which redirects there instead so the product
* sees the response on a different origin.
*
* The package installer appends each package's path to the configured URL, so with a query in
* that URL the path arrives after the token: `/mirror?token=<token>/<package>`. The server reads
Expand All @@ -11,48 +12,54 @@ import { randomUUID } from "node:crypto";
import { createServer } from "node:http";
import { Config, Effect } from "effect";

export const credentialedRegistry = Effect.gen(function* () {
const upstream = (yield* Config.String("E2E_NPM_REGISTRY").pipe(
Config.withDefault("https://registry.npmjs.org"),
)).replace(/\/$/, "");
const user = `synthetic-user-${randomUUID().slice(0, 8)}`;
const password = `synthetic-password-${randomUUID().slice(0, 8)}`;
const token = `synthetic-token-${randomUUID().slice(0, 8)}`;
const tokenPrefix = `/mirror?token=${token}`;
const server = yield* Effect.acquireRelease(
Effect.callback<ReturnType<typeof createServer>>((resume) => {
const server = createServer((request, response) => {
const url = request.url ?? "/";
const path = url.startsWith(tokenPrefix) ? url.slice(tokenPrefix.length) || "/" : url;
fetch(`${upstream}${path}`).then(
(reply) =>
reply.arrayBuffer().then((bytes) => {
response.writeHead(reply.status, {
"content-type": reply.headers.get("content-type") ?? "application/octet-stream",
});
response.end(Buffer.from(bytes));
}),
() => {
response.writeHead(502);
export const credentialedRegistry = (redirectPath: string) =>
Effect.gen(function* () {
const upstream = (yield* Config.String("E2E_NPM_REGISTRY").pipe(
Config.withDefault("https://registry.npmjs.org"),
)).replace(/\/$/, "");
const user = `synthetic-user-${randomUUID().slice(0, 8)}`;
const password = `synthetic-password-${randomUUID().slice(0, 8)}`;
const token = `synthetic-token-${randomUUID().slice(0, 8)}`;
const tokenPrefix = `/mirror?token=${token}`;
const server = yield* Effect.acquireRelease(
Effect.callback<ReturnType<typeof createServer>>((resume) => {
const server = createServer((request, response) => {
const url = request.url ?? "/";
const path = url.startsWith(tokenPrefix) ? url.slice(tokenPrefix.length) || "/" : url;
if (path === redirectPath) {
response.writeHead(302, { location: `${upstream}${path}` });
response.end();
},
);
});
server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server)));
}),
(server) =>
Effect.callback<void>((resume) => {
server.close(() => resume(Effect.void));
return;
}
fetch(`${upstream}${path}`).then(
(reply) =>
reply.arrayBuffer().then((bytes) => {
response.writeHead(reply.status, {
"content-type": reply.headers.get("content-type") ?? "application/octet-stream",
});
response.end(Buffer.from(bytes));
}),
() => {
response.writeHead(502);
response.end();
},
);
});
server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server)));
}),
);
const address = server.address();
if (address === null || typeof address === "string")
return yield* Effect.die("The credentialed registry has no port");
const host = `127.0.0.1:${address.port}`;
return {
url: `http://${user}:${password}@${host}/mirror?token=${token}`,
/** The registry's host and path, which a failure may show. */
location: `http://${host}/mirror`,
secrets: [user, password, token],
};
});
(server) =>
Effect.callback<void>((resume) => {
server.close(() => resume(Effect.void));
}),
);
const address = server.address();
if (address === null || typeof address === "string")
return yield* Effect.die("The credentialed registry has no port");
const host = `127.0.0.1:${address.port}`;
return {
url: `http://${user}:${password}@${host}/mirror?token=${token}`,
/** The registry's host and path, which a failure may show. */
location: `http://${host}/mirror`,
secrets: [user, password, token],
};
});
85 changes: 54 additions & 31 deletions e2e/tests/local-registry-credentials.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,16 @@ const BuildFailed = Schema.Struct({
_tag: Schema.Literal("VersionBuildFailed"),
stage: Schema.String,
message: Schema.String,
package: Schema.String,
version: Schema.optionalKey(Schema.String),
registry: Schema.String,
status: Schema.optionalKey(Schema.Int),
});

/** A package the suite's registry does not serve, so installing it fails with the registry's 404. */
const missingPackage = "@executor-fixture/missing-package";
const redirectedPackage = "redirected-missing-package";
const longVersion = `1.0.0+${"a".repeat(195)}`;

layer(TestLive, { excludeTestServices: true })("Local registry credentials", (it) => {
it.effect(
Expand All @@ -30,42 +36,59 @@ layer(TestLive, { excludeTestServices: true })("Local registry credentials", (it
withCase(
context,
Effect.gen(function* () {
const registry = yield* credentialedRegistry;
const registry = yield* credentialedRegistry(`/${redirectedPackage}`);
const local = yield* startLocalProduct({ EXECUTOR_NPM_REGISTRY: registry.url });
const deployed = yield* local.request("POST", "/v1/apps/deploy", {
owner: "registry-credentials-e2e",
name: `Registry credentials ${randomUUID().slice(0, 8)}`,
files: [
{
path: "index.ts",
content: `import { defineApp, query, object, router } from "apps";
import missing from "${missingPackage}";
for (const { name, version, reportedVersion, status } of [
{ name: missingPackage, version: "1.0.0", reportedVersion: "1.0.0", status: 404 },
{
name: "@executor-fixture/_worker",
version: "1.0.0",
reportedVersion: "1.0.0",
status: 404,
},
{ name: "@executor-fixture/-worker", version: longVersion, status: 404 },
{ name: redirectedPackage, version: "1.0.0", reportedVersion: "1.0.0" },
]) {
const deployed = yield* local.request("POST", "/v1/apps/deploy", {
owner: "registry-credentials-e2e",
name: `Registry credentials ${randomUUID().slice(0, 8)}`,
files: [
{
path: "index.ts",
content: `import { defineApp, query, object, router } from "apps";
import missing from "${name}";
export default defineApp({}, { tools: router({
missing: query({ input: object({}) }, async () => String(missing)),
}) });`,
},
{
path: "package.json",
content: JSON.stringify({
type: "module",
dependencies: withApps({ [missingPackage]: "1.0.0" }),
}),
},
],
});
expect(deployed.status, deployed.text).toBe(422);
const failed = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(BuildFailed))(
deployed.text,
);
for (const secret of registry.secrets)
expect(deployed.text, "the failure omits the registry's credentials").not.toContain(
secret,
},
{
path: "package.json",
content: JSON.stringify({
type: "module",
dependencies: withApps({ [name]: version }),
}),
},
],
});
expect(deployed.status, deployed.text).toBe(422);
const failed = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(BuildFailed))(
deployed.text,
);
// The installer's failure reaches the deployer through the bundler's import resolution.
expect(failed.stage).toBe("compile");
// Still useful: it names the package and the registry's host and path.
expect(failed.message).toContain(`Installing ${missingPackage}@1.0.0 failed`);
expect(failed.message).toContain(registry.location);
for (const secret of registry.secrets)
expect(deployed.text, "the failure omits the registry's credentials").not.toContain(
secret,
);
// The installer's failure reaches the deployer through the bundler's import resolution.
expect(failed.stage).toBe("compile");
expect(failed.package).toBe(name);
expect(failed.version).toBe(reportedVersion);
expect(failed.registry).toBe(new URL(registry.url).origin);
expect(failed.status).toBe(status);
// The message still names the dependency, registry path and actual HTTP response.
expect(failed.message).toContain(`Installing ${name}@${version} failed`);
expect(failed.message).toContain(registry.location);
expect(failed.message).toContain("HTTP 404");
}
}),
),
120_000,
Expand Down
43 changes: 24 additions & 19 deletions e2e/tests/self-host-provisioning-failure.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
/**
* A self-host whose npm registry cannot serve the `apps` package keeps failing its default app
* installation. The provisioning log names the failed step by its tagged cause, and never quotes
* the registry's credentials, path or the packages it was asked for.
* installation. The provisioning log names the failed step and package without quoting the
* registry's credentials, path, query or response.
*/
import { randomUUID } from "node:crypto";
import { createServer } from "node:http";
import { expect, layer } from "@effect/vitest";
import { Effect, FileSystem, Layer, Option, Schedule, Schema } from "effect";
import { Api, SessionClients } from "../support/api.ts";
import { appsVersion } from "../support/apps-release.ts";
import { TestLive, withCase } from "../support/case.ts";
import { startLoggedSelfHost } from "../support/managed-server.ts";
import { Target } from "../support/platform.ts";
Expand All @@ -29,21 +30,25 @@ const records = (text: string, message: string) =>
const record = Schema.decodeUnknownOption(LogRecord)(line.slice(at));
if (Option.isNone(record)) return [];
const logged = record.value.message;
return Array.isArray(logged) && logged[0] === message ? [{ line, fields: logged[1] }] : [];
return Array.isArray(logged) && logged[0] === message ? [{ fields: logged[1] }] : [];
});

/** An npm registry answering every request with 404, reached through a credentialed URL. */
const refusingRegistry = Effect.gen(function* () {
const user = `synthetic-user-${randomUUID().slice(0, 8)}`;
const password = `synthetic-password-${randomUUID().slice(0, 8)}`;
const token = `synthetic-token-${randomUUID().slice(0, 8)}`;
const responseMarker = `synthetic-registry-response-${randomUUID()}`;
const paths: string[] = [];
const server = yield* Effect.acquireRelease(
Effect.callback<ReturnType<typeof createServer>>((resume) => {
const server = createServer((request, response) => {
paths.push(request.url ?? "/");
response.writeHead(404, { "content-type": "application/json" });
response.end(JSON.stringify({ error: "not found" }));
response.writeHead(404, {
"content-type": "application/json",
"x-registry-response": responseMarker,
});
response.end(JSON.stringify({ error: responseMarker }));
});
server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server)));
}),
Expand All @@ -58,7 +63,7 @@ const refusingRegistry = Effect.gen(function* () {
return {
url: `http://${user}:${password}@127.0.0.1:${address.port}/mirror?token=${token}`,
paths,
secrets: [user, password, token, "mirror"],
secrets: [user, password, token, "/mirror", "?token=", responseMarker],
};
});

Expand Down Expand Up @@ -95,8 +100,9 @@ layer(TestLive, { excludeTestServices: true })("Self-host provisioning failure",
// The default app pins the `apps` package this host ships; its build asks the registry
// for it, and the refusal fails the team's installation.
const fs = yield* FileSystem.FileSystem;
const { step, attempt } = yield* fs.readFileString(server.log).pipe(
const { text, step, attempt } = yield* fs.readFileString(server.log).pipe(
Effect.map((text) => ({
text,
step: records(text, "Provisioning step failed"),
attempt: records(text, "Provisioning attempt failed"),
})),
Expand All @@ -116,24 +122,23 @@ 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");
// The failed build's stage is a closed name, so the log can say which step broke.
expect(failed.fields["cause"]).toMatchObject({
const cause = {
tag: "VersionBuildFailed",
stage: "dependencies",
});
package: "apps",
version: appsVersion,
registry: new URL(registry.url).origin,
status: 404,
};
expect(failed.fields["cause"]).toEqual(cause);
expect(retried.fields["attempts"]).toBeGreaterThanOrEqual(1);
expect(retried.fields["outcome"]).toBe("requeued");
expect(retried.fields["cause"]).toMatchObject({
tag: "VersionBuildFailed",
stage: "dependencies",
});
expect(retried.fields["cause"]).toEqual(cause);

// The registry's credentials, path and query stay out of both lines.
for (const { line } of [...step, ...attempt])
// The registry's credentials, path, query and response stay out of the server log.
for (const line of text.split("\n"))
for (const secret of registry.secrets)
expect(line, "the failure omits the registry's credentials and path").not.toContain(
secret,
);
expect(line, "the failure omits private registry details").not.toContain(secret);
}),
),
120_000,
Expand Down
Loading
Loading