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
12 changes: 11 additions & 1 deletion packages/cli/src/commands/cli/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import {
warmCachesAfterLogin,
} from "../../lib/completion-warmup.js";
import { CLI_VERSION } from "../../lib/constants.js";
import { getAuthConfig } from "../../lib/db/auth.js";
import { getAuthConfig, hasStoredAuthCredentials } from "../../lib/db/auth.js";
import {
getOnOffPreference,
setOnOffPreference,
Expand All @@ -55,6 +55,7 @@ import { CommandOutput } from "../../lib/formatters/output.js";
import { runInteractiveLogin } from "../../lib/interactive-login.js";
import { interactivePromptsAllowed } from "../../lib/interactive-prompts.js";
import { logger } from "../../lib/logger.js";
import { bootstrapAuthentication } from "../../lib/setup-code.js";
Comment thread
evanpurkhiser marked this conversation as resolved.
Resolved
Comment thread
evanpurkhiser marked this conversation as resolved.
Resolved
import {
addToFpath,
addToGitHubPath,
Expand Down Expand Up @@ -789,6 +790,14 @@ export const setupCommand = buildCommand({
warn,
});

if (getEnv().SENTRY_SETUP_CODE && !hasStoredAuthCredentials()) {
await bootstrapAuthentication();
emit("Authenticated with Sentry using the setup code.");
if (!flags["no-completions"]) {
await warmCachesAfterLogin();
}
}

if (flags["ensure-auth-scopes"]) {
await bestEffort(
"Authorization",
Expand Down Expand Up @@ -830,6 +839,7 @@ export const setupCommand = buildCommand({
flags.quiet ||
flags["ensure-auth-scopes"] ||
getEnv().SENTRY_INIT === "1" ||
Boolean(getEnv().SENTRY_SETUP_CODE) ||
!(interactivePromptsAllowed() && isatty(0) && isatty(1) && isatty(2))
) {
return;
Expand Down
136 changes: 134 additions & 2 deletions packages/cli/test/commands/cli/setup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ vi.mock("../../../src/lib/windows-path.js", async (importOriginal) => ({
import { app } from "../../../src/app.js";
import { warmCachesAfterLogin } from "../../../src/lib/completion-warmup.js";
import type { SentryContext } from "../../../src/context.js";
import { getAccountRow } from "../../../src/lib/db/accounts.js";
import { EXIT } from "../../../src/lib/errors.js";
import { getAuthConfig, setAuthToken } from "../../../src/lib/db/auth.js";
import {
getOnOffPreference,
Expand Down Expand Up @@ -139,7 +141,10 @@ function createMockContext(
}),
},
stderr: {
write: vi.fn((_s: string) => true),
write: vi.fn((s: string) => {
stderrChunks.push(String(s));
return true;
}),
},
stdin: process.stdin,
env,
Expand All @@ -161,7 +166,10 @@ function createMockContext(
}),
},
stderr: {
write: vi.fn((_s: string) => true),
write: vi.fn((s: string) => {
stderrChunks.push(String(s));
return true;
}),
},
stdin: process.stdin,
setFlags: () => {
Expand Down Expand Up @@ -1022,6 +1030,130 @@ describe("sentry cli setup", () => {
};
}

test.each([true, false])(
"redeems a setup code with completions=%s without opening a browser",
async (completions) => {
vi.mocked(warmCachesAfterLogin).mockClear();

const claim = Buffer.from(
JSON.stringify({ url: "https://sentry.io", iat: 1 }),
).toString("base64");
const code = "sntryc_" + claim + "_" + "a".repeat(43);
const fixture = createInstall({
completions,
env: { SENTRY_SETUP_CODE: code },
});
const fetch = vi.fn().mockResolvedValue(
Response.json({
access_token: "setup-token",
refresh_token: "refresh-token",
expires_in: 3600,
token_type: "bearer",
}),
);
vi.stubGlobal("fetch", fetch);
try {
await fixture.run();
expect(readFileSync(fixture.binaryPath, "utf8")).toBe(
"fixture-binary",
);
expect(fetch).toHaveBeenCalledTimes(1);
expect(getAuthConfig()?.token).toBe("setup-token");
expect(warmCachesAfterLogin).toHaveBeenCalledTimes(
completions ? 1 : 0,
);
expect(fixture.getOutput()).toContain(
Comment thread
evanpurkhiser marked this conversation as resolved.
Resolved
"Authenticated with Sentry using the setup code",
);
expect(fixture.getOutput()).not.toContain(code);
expect(interactiveLogin.runInteractiveLogin).not.toHaveBeenCalled();
expect(fixture.context.process.exitCode).toBe(0);
} finally {
vi.unstubAllGlobals();
}
},
);

test("finishes installation configuration when setup-code redemption fails", async () => {
const claim = Buffer.from(
JSON.stringify({ url: "https://sentry.io" }),
).toString("base64");
const code = "sntryc_" + claim + "_" + "a".repeat(43);
const fixture = createInstall({ env: { SENTRY_SETUP_CODE: code } });
const fetch = vi
.fn()
.mockResolvedValue(
Response.json({ error: "invalid_grant" }, { status: 400 }),
);
vi.stubGlobal("fetch", fetch);

try {
await fixture.run();

expect(fetch).toHaveBeenCalledOnce();
expect(getInstallInfo()?.path).toBe(fixture.binaryPath);
expect(getOnOffPreference("agent-skills")).toBe(false);
expect(readFileSync(fixture.binaryPath, "utf8")).toBe("fixture-binary");
expect(fixture.context.process.exitCode).toBeGreaterThan(0);
expect(fixture.getOutput()).not.toContain(code);
expect(interactiveLogin.runInteractiveLogin).not.toHaveBeenCalled();
} finally {
vi.unstubAllGlobals();
}
});

test.each([true, false])(
"keeps stored authentication with a retained code when install=%s",
async (install) => {
setAuthToken("existing-token");
const fixture = createInstall({
install,
env: { SENTRY_SETUP_CODE: "consumed-code" },
});
const fetch = vi.fn();
vi.stubGlobal("fetch", fetch);
try {
await fixture.run();
expect(getAuthConfig()?.token).toBe("existing-token");
expect(fetch).not.toHaveBeenCalled();
expect(fixture.context.process.exitCode).toBe(0);
} finally {
vi.unstubAllGlobals();
}
},
);

test.each([true, false])(
"shows a bootstrap recovery command for an expired login when install=%s",
async (install) => {
const account = setAuthToken("expired-token", -1, undefined, {
host: "https://sentry.io",
});
const claim = Buffer.from(
JSON.stringify({ url: "https://sentry.io" }),
).toString("base64");
const code = "sntryc_" + claim + "_" + "a".repeat(43);
const fixture = createInstall({
install,
env: { SENTRY_SETUP_CODE: code },
});
const fetch = vi.fn();
vi.stubGlobal("fetch", fetch);
try {
await fixture.run();
expect(fixture.context.process.exitCode).toBe(EXIT.VALIDATION);
expect(fixture.getOutput()).toContain(
"sentry auth bootstrap --force",
);
expect(fixture.getOutput()).not.toContain(code);
expect(fetch).not.toHaveBeenCalled();
expect(getAccountRow(account)?.token).toBe("expired-token");
} finally {
vi.unstubAllGlobals();
}
},
);

test("starts OAuth only after installing the binary and displaying success", async () => {
const fixture = createInstall();
vi.mocked(interactiveLogin.runInteractiveLogin).mockImplementation(
Expand Down
Loading