Skip to content
Draft
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
123 changes: 98 additions & 25 deletions apps/cli-docs/test/install-handoff.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@ import { buildOutput } from "../vercel/build-output.mjs";
import { createHandler } from "../vercel/install-handoff.mjs";

const code = `sntryh_${"a1_-".repeat(10)}xyz`;
const echoHandoff = createHandler(`#!/bin/bash\nprintf '%s' "\${SENTRY_HANDOFF:-unset}"\n`);
const echoHandoff = createHandler({
install: `#!/bin/bash\nprintf '%s' "\${SENTRY_HANDOFF:-unset}"\n`,
// A failing install must still clear the variable, so this one can throw.
"install.ps1": `[Console]::Out.Write("$env:SENTRY_HANDOFF")\nif ($env:SENTRY_TEST_THROW) { throw 'install failed' }\n`,
});
const hasPwsh =
spawnSync("pwsh", ["-NoProfile", "-Command", "exit 0"], { stdio: "ignore" }).status === 0;

async function pipeToBash(response) {
return spawnSync("bash", [], {
Expand All @@ -19,9 +25,31 @@ async function pipeToBash(response) {
});
}

// Runs the response the way `irm <url> | iex` does, then prints whether
// SENTRY_HANDOFF is still set in the session.
async function pipeToIex(response, env = {}) {
const dir = mkdtempSync(join(tmpdir(), "cli-docs-iex-"));
const script = join(dir, "install.ps1");
writeFileSync(script, await response.text());
try {
return spawnSync(
"pwsh",
[
"-NoProfile",
"-NonInteractive",
"-Command",
`try { Get-Content -Raw -LiteralPath '${script}' | Invoke-Expression } catch { [Console]::Out.Write("|threw") }; [Console]::Out.Write("|after=$env:SENTRY_HANDOFF")`,
],
{ encoding: "utf8", env: { PATH: process.env.PATH, HOME: process.env.HOME, ...env } },
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}

test("piping /install/<code> to bash runs the script with SENTRY_HANDOFF set", async () => {
for (const url of [
`https://cli.sentry.dev/install-handoff?code=${code}`,
`https://cli.sentry.dev/install-handoff?script=install&code=${code}`,
`https://cli.sentry.dev/install/${code}`,
]) {
const response = echoHandoff(new Request(url));
Expand All @@ -33,51 +61,96 @@ test("piping /install/<code> to bash runs the script with SENTRY_HANDOFF set", a
}
});

test("anything but a well-formed handoff code is not found", async () => {
for (const bad of [
"",
"sntryh_short",
`sntryh_${"a".repeat(42)}'`,
`sntryh_${"a".repeat(40)}';id`,
`${code}a`,
`sntryx_${"a".repeat(43)}`,
]) {
test(
"piping /install.ps1/<code> to iex runs the script with SENTRY_HANDOFF set, then clears it",
{ skip: !hasPwsh && "pwsh is not installed" },
async () => {
for (const url of [
`https://cli.sentry.dev/install-handoff?script=install.ps1&code=${code}`,
`https://cli.sentry.dev/install.ps1/${code}`,
]) {
const response = echoHandoff(new Request(url));
assert.equal(response.status, 200);
assert.equal(response.headers.get("cache-control"), "no-store");
const result = await pipeToIex(response);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stdout, `${code}|after=`);
}

const failed = await pipeToIex(
echoHandoff(new Request(`https://cli.sentry.dev/install.ps1/${code}`)),
{ SENTRY_TEST_THROW: "1" },
);
assert.equal(failed.stdout, `${code}|threw|after=`);
},
);

test("anything but a known script and a well-formed handoff code is not found", async () => {
const bad = [
["install", ""],
["install", "sntryh_short"],
["install", `sntryh_${"a".repeat(42)}'`],
["install", `sntryh_${"a".repeat(40)}';id`],
["install.ps1", `sntryh_${"a".repeat(40)}';id`],
["install", `${code}a`],
["install", `sntryx_${"a".repeat(43)}`],
["", code],
["install.sh", code],
["constructor", code],
];
for (const [script, badCode] of bad) {
const response = echoHandoff(
new Request(`https://cli.sentry.dev/install-handoff?code=${encodeURIComponent(bad)}`),
new Request(
`https://cli.sentry.dev/install-handoff?script=${encodeURIComponent(script)}&code=${encodeURIComponent(badCode)}`,
),
);
assert.equal(response.status, 404, bad);
assert.equal(response.status, 404, `${script} ${badCode}`);
assert.equal(await response.text(), "Not found\n");
}
});

test("the packaged site routes /install/<code> to a function serving the install script", async () => {
test("the packaged site routes /install/<code> and /install.ps1/<code> to a function serving the install scripts", async () => {
const dir = mkdtempSync(join(tmpdir(), "cli-docs-vercel-"));
try {
const dist = join(dir, "dist");
const output = join(dir, "output");
const script = readFileSync(new URL("../public/install", import.meta.url), "utf8");
const bash = readFileSync(new URL("../public/install", import.meta.url), "utf8");
const powershell = readFileSync(new URL("../public/install.ps1", import.meta.url), "utf8");
mkdirSync(dist);
writeFileSync(join(dist, "install"), script);
writeFileSync(join(dist, "install"), bash);
writeFileSync(join(dist, "install.ps1"), powershell);
buildOutput(dist, output);

const config = JSON.parse(readFileSync(join(output, "config.json"), "utf8"));
const route = config.routes.find((r) => r.dest?.startsWith("/install-handoff"));
const match = `/install/${code}`.match(new RegExp(route.src));
assert.equal(match?.[1], code);
assert.equal(new RegExp(route.src).test(`/install/${code}x`), false);
assert.equal(readFileSync(join(output, "static", "install"), "utf8"), script);
const src = new RegExp(route.src);
assert.deepEqual(`/install/${code}`.match(src)?.slice(1), ["install", code]);
assert.deepEqual(`/install.ps1/${code}`.match(src)?.slice(1), ["install.ps1", code]);
assert.equal(src.test(`/install/${code}x`), false);
assert.equal(src.test(`/installxps1/${code}`), false);
assert.equal(readFileSync(join(output, "static", "install"), "utf8"), bash);
assert.equal(readFileSync(join(output, "static", "install.ps1"), "utf8"), powershell);

const fn = join(output, "functions", "install-handoff.func");
assert.deepEqual(JSON.parse(readFileSync(join(fn, ".vc-config.json"), "utf8")), {
runtime: "edge",
entrypoint: "index.js",
});
const { default: handler } = await import(pathToFileURL(join(fn, "index.js")).href);
const body = await handler(
new Request(`https://cli.sentry.dev${route.dest.replace("$1", code)}`),
).text();
const [shebang, ...rest] = script.split("\n");
assert.equal(body, [shebang, `export SENTRY_HANDOFF='${code}'`, ...rest].join("\n"));
const serve = (script) =>
handler(
new Request(
`https://cli.sentry.dev${route.dest.replace("$1", script).replace("$2", code)}`,
),
).text();

const [shebang, ...rest] = bash.split("\n");
assert.equal(
await serve("install"),
[shebang, `export SENTRY_HANDOFF='${code}'`, ...rest].join("\n"),
);
const ps1 = await serve("install.ps1");
assert.ok(ps1.startsWith(`$env:SENTRY_HANDOFF = '${code}'\ntry {\n${powershell}`));
} finally {
rmSync(dir, { recursive: true, force: true });
}
Expand Down
16 changes: 10 additions & 6 deletions apps/cli-docs/vercel/build-output.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Packages the built site (apps/cli-docs/dist) as Vercel Build Output API v3:
// the static files, the routes below, and the /install/<handoff code> Edge
// Function. Usage: node build-output.mjs <output dir, e.g. .vercel/output>
// the static files, the routes below, and the Edge Function behind
// /install/<handoff code> and /install.ps1/<handoff code>.
// Usage: node build-output.mjs <output dir, e.g. .vercel/output>
import { cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
Expand All @@ -26,8 +27,8 @@ const routes = [
continue: true,
},
{
src: `^/install/(${HANDOFF_CODE.source.slice(1, -1)})$`,
dest: `/${HANDOFF_FUNCTION}?code=$1`,
src: `^/(install|install\\.ps1)/(${HANDOFF_CODE.source.slice(1, -1)})$`,
dest: `/${HANDOFF_FUNCTION}?script=$1&code=$2`,
},
];

Expand All @@ -46,10 +47,13 @@ export function buildOutput(distDir, outputDir) {
`${JSON.stringify({ runtime: "edge", entrypoint: "index.js" })}\n`,
);
const handler = readFileSync(new URL("./install-handoff.mjs", import.meta.url), "utf8");
const installScript = readFileSync(join(distDir, "install"), "utf8");
const scripts = {
install: readFileSync(join(distDir, "install"), "utf8"),
"install.ps1": readFileSync(join(distDir, "install.ps1"), "utf8"),
};
writeFileSync(
join(functionDir, "index.js"),
`${handler}\nexport default createHandler(${JSON.stringify(installScript)});\n`,
`${handler}\nexport default createHandler(${JSON.stringify(scripts)});\n`,
);
}

Expand Down
61 changes: 40 additions & 21 deletions apps/cli-docs/vercel/install-handoff.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// Serves cli.sentry.dev/install/<handoff code>: the install script with
// SENTRY_HANDOFF set, so `curl -fsSL https://cli.sentry.dev/install/<code> | bash`
// claims the Sentry agent handoff during `sentry cli setup`. build-output.mjs
// bundles this module with the install script as a Vercel Edge Function.
// Serves cli.sentry.dev/install/<handoff code> and /install.ps1/<handoff code>:
// the install script with SENTRY_HANDOFF set, so
// curl -fsSL https://cli.sentry.dev/install/<code> | bash
// irm https://cli.sentry.dev/install.ps1/<code> | iex
// claim the Sentry agent handoff during `sentry cli setup`. build-output.mjs
// bundles this module with both install scripts as a Vercel Edge Function.

// Matches the codes Sentry issues (`sntryh_` + 32 random bytes, base64url).
// The code is written into a shell script, so nothing outside this character
// set may ever reach the response.
// The code is written into a script, so nothing outside this character set
// may ever reach the response.
export const HANDOFF_CODE = /^sntryh_[A-Za-z0-9_-]{43}$/;

const HEADERS = {
Expand All @@ -15,27 +17,44 @@ const HEADERS = {
"X-Robots-Tag": "noindex",
};

export function createHandler(installScript) {
const firstLineEnd = installScript.indexOf("\n") + 1;
if (!installScript.startsWith("#!") || firstLineEnd === 0) {
// bash runs the piped script in its own process, so an export after the
// shebang is enough.
function withBashHandoff(script) {
const firstLineEnd = script.indexOf("\n") + 1;
if (!script.startsWith("#!") || firstLineEnd === 0) {
throw new Error("install script must start with a shebang line");
}
const shebang = installScript.slice(0, firstLineEnd);
const body = installScript.slice(firstLineEnd);
const shebang = script.slice(0, firstLineEnd);
const body = script.slice(firstLineEnd);
return (code) => `${shebang}export SENTRY_HANDOFF='${code}'\n${body}`;
}

// iex runs the script in the caller's session, where $env: changes outlive
// the install. Remove the variable afterwards, even when the install throws,
// so the code does not stay in the user's session.
function withPowerShellHandoff(script) {
return (code) =>
`$env:SENTRY_HANDOFF = '${code}'\ntry {\n${script}\n} finally {\n Remove-Item Env:SENTRY_HANDOFF -ErrorAction SilentlyContinue\n}\n`;
}

// `scripts` holds the raw `install` (bash) and `install.ps1` scripts.
export function createHandler(scripts) {
const render = {
install: withBashHandoff(scripts.install),
"install.ps1": withPowerShellHandoff(scripts["install.ps1"]),
};

return function handler(request) {
const url = new URL(request.url);
// The route rewrites /install/<code> to ?code=<code>. Read the original
// path too, in case the function sees the URL before the rewrite.
const code =
url.searchParams.get("code") ??
url.pathname.match(/^\/install\/([^/]+)$/)?.[1] ??
"";
if (!HANDOFF_CODE.test(code)) {
// The route rewrites /<script>/<code> to ?script=<script>&code=<code>.
// Read the original path too, in case the function sees the URL before
// the rewrite.
const path = url.pathname.match(/^\/(install(?:\.ps1)?)\/([^/]+)$/);
const script = url.searchParams.get("script") ?? path?.[1] ?? "";
const code = url.searchParams.get("code") ?? path?.[2] ?? "";
if (!Object.hasOwn(render, script) || !HANDOFF_CODE.test(code)) {
return new Response("Not found\n", { status: 404, headers: HEADERS });
}
return new Response(`${shebang}export SENTRY_HANDOFF='${code}'\n${body}`, {
headers: HEADERS,
});
return new Response(render[script](code), { headers: HEADERS });
};
}
5 changes: 3 additions & 2 deletions docs/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ CLI releases build it from that workspace. Start here for repository guides:
[release configuration](../../.craft.yml) — binaries, npm packaging, and
release-gated website artifacts.
- [Website packaging](../../apps/cli-docs/vercel/build-output.mjs) — the
Vercel routes for `/install`, and the `/install/<handoff code>` function that
serves the install script with `SENTRY_HANDOFF` set.
Vercel routes for `/install`, and the function behind
`/install/<handoff code>` and `/install.ps1/<handoff code>` that serves the
install script with `SENTRY_HANDOFF` set.
- [CLI nightly watchdog](../../.github/workflows/cli-nightly-watchdog.yml) —
hourly and after each main Build, checks for stuck or failed Build runs and a
GHCR `nightly` that lags main. It keeps one open alert issue while unhealthy,
Expand Down
Loading