From 43c9a6a10fe8f472122453600f42706219b03584 Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Fri, 3 Jul 2026 12:12:33 +0000 Subject: [PATCH] feat(info): add info command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port `sentry info` from the legacy CLI. Prints the resolved Sentry server URL and default org/project, then verifies authentication against `/auth/`. - `--config-status-json` emits the legacy machine-readable status object (`{ config: {org, project, url}, auth: {type, successful}, have_dsn }`) and always exits 0 — a status report, not a check. (`--json` gives the same shape, plus an additive `user`.) - `--no-defaults` verifies only authentication, without requiring a default org/project. - Exits non-zero when auth fails, or (unless --no-defaults) when no default org/project is configured. Composes existing helpers (getDefaultUrl/Organization/Project, isAuthenticated, getCurrentUser). Registered as a top-level route. Tests cover unauthenticated, verified, verification-failure, --config-status-json (forced JSON + exit 0), --no-defaults, and env-var defaults. --- docs/src/content/docs/contributing.md | 1 + docs/src/fragments/commands/info.md | 25 +++ plugins/sentry-cli/skills/sentry-cli/SKILL.md | 8 + .../skills/sentry-cli/references/info.md | 35 ++++ src/app.ts | 2 + src/commands/info.ts | 171 ++++++++++++++++++ test/commands/info.test.ts | 128 +++++++++++++ 7 files changed, 370 insertions(+) create mode 100644 docs/src/fragments/commands/info.md create mode 100644 plugins/sentry-cli/skills/sentry-cli/references/info.md create mode 100644 src/commands/info.ts create mode 100644 test/commands/info.test.ts diff --git a/docs/src/content/docs/contributing.md b/docs/src/content/docs/contributing.md index 6a88bcf06f..b58f8fb946 100644 --- a/docs/src/content/docs/contributing.md +++ b/docs/src/content/docs/contributing.md @@ -80,6 +80,7 @@ cli/ │ │ ├── api.ts # Make an authenticated API request │ │ ├── explore.ts # Query aggregate event data (Explore) │ │ ├── help.ts # Help command +│ │ ├── info.ts # Print configuration and verify authentication │ │ ├── init.ts # Initialize Sentry in your project (experimental) │ │ └── schema.ts # Browse the Sentry API schema │ ├── lib/ # Shared utilities diff --git a/docs/src/fragments/commands/info.md b/docs/src/fragments/commands/info.md new file mode 100644 index 0000000000..de341e2087 --- /dev/null +++ b/docs/src/fragments/commands/info.md @@ -0,0 +1,25 @@ +## Examples + +```bash +# Print the resolved config and verify authentication +sentry info + +# Verify only authentication (don't require a default org/project) +sentry info --no-defaults + +# Machine-readable status for external tooling (always exits 0) +sentry info --config-status-json +``` + +## Important Notes + +- `info` prints the resolved Sentry server URL and the default organization and + project, then verifies your credentials against the server. +- The server URL comes from `SENTRY_URL`, the stored default, or the SaaS + default; org/project come from `SENTRY_ORG`/`SENTRY_PROJECT` or stored + defaults. `have_dsn` reflects whether `SENTRY_DSN` is set. +- Exits non-zero when authentication fails, or (unless `--no-defaults`) when no + default organization/project is configured. +- `--config-status-json` emits a JSON status object (`config`, `auth`, + `have_dsn`) for external tooling and **always exits 0** — it is a status + report, not a check. For general machine-readable output use `--json`. diff --git a/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/plugins/sentry-cli/skills/sentry-cli/SKILL.md index cd4c20e80a..0ebe530300 100644 --- a/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -577,6 +577,14 @@ Initialize Sentry in your project (experimental) → Full flags and examples: `references/init.md` +### Info + +Print configuration and verify authentication + +- `sentry info` — Print configuration and verify authentication + +→ Full flags and examples: `references/info.md` + ### Local Sentry for local development diff --git a/plugins/sentry-cli/skills/sentry-cli/references/info.md b/plugins/sentry-cli/skills/sentry-cli/references/info.md new file mode 100644 index 0000000000..a5f14f692e --- /dev/null +++ b/plugins/sentry-cli/skills/sentry-cli/references/info.md @@ -0,0 +1,35 @@ +--- +name: sentry-cli-info +version: 0.39.0-dev.0 +description: Print configuration and verify authentication +requires: + bins: ["sentry"] + auth: true +--- + +# Info Commands + +Print configuration and verify authentication + +### `sentry info` + +Print configuration and verify authentication + +**Flags:** +- `--config-status-json - Emit configuration + auth status as JSON (for external tooling); always exits 0` +- `--no-defaults - Verify only authentication, without requiring a default org/project` + +**Examples:** + +```bash +# Print the resolved config and verify authentication +sentry info + +# Verify only authentication (don't require a default org/project) +sentry info --no-defaults + +# Machine-readable status for external tooling (always exits 0) +sentry info --config-status-json +``` + +All commands also support `--json`, `--fields`, `--help`, `--log-level`, and `--verbose` flags. diff --git a/src/app.ts b/src/app.ts index 20a5cc419c..c0d3a62220 100644 --- a/src/app.ts +++ b/src/app.ts @@ -21,6 +21,7 @@ import { eventRoute } from "./commands/event/index.js"; import { listCommand as eventListCommand } from "./commands/event/list.js"; import { exploreCommand } from "./commands/explore.js"; import { helpCommand } from "./commands/help.js"; +import { infoCommand } from "./commands/info.js"; import { initCommand } from "./commands/init.js"; import { issueRoute } from "./commands/issue/index.js"; import { listCommand as issueListCommand } from "./commands/issue/list.js"; @@ -125,6 +126,7 @@ export const routes = buildRouteMap({ trace: traceRoute, trial: trialRoute, init: initCommand, + info: infoCommand, local: localRoute, api: apiCommand, schema: schemaCommand, diff --git a/src/commands/info.ts b/src/commands/info.ts new file mode 100644 index 0000000000..a2ff367fbf --- /dev/null +++ b/src/commands/info.ts @@ -0,0 +1,171 @@ +/** + * sentry info + * + * Print the resolved configuration (server URL, default org/project) and verify + * authentication. Mirrors the legacy `sentry-cli info`, including the + * `--config-status-json` machine-readable contract used by external tooling. + */ + +import type { SentryContext } from "../context.js"; +import { getCurrentUser } from "../lib/api/users.js"; +import { buildCommand } from "../lib/command.js"; +import { DEFAULT_SENTRY_URL } from "../lib/constants.js"; +import { isAuthenticated } from "../lib/db/auth.js"; +import { + getDefaultOrganization, + getDefaultProject, + getDefaultUrl, +} from "../lib/db/defaults.js"; +import { colorTag, renderMarkdown } from "../lib/formatters/markdown.js"; +import { CommandOutput } from "../lib/formatters/output.js"; +import { logger } from "../lib/logger.js"; + +const log = logger.withTag("info"); + +/** + * Resolved configuration + auth status. + * + * The `config`/`auth`/`have_dsn` fields match the legacy `--config-status-json` + * contract (snake_case); `user` is an additive convenience for human output. + */ +type InfoStatus = { + config: { + org: string | null; + project: string | null; + url: string; + }; + auth: { + /** Auth method, or `null` when unauthenticated. */ + type: "token" | null; + /** Whether the credentials were verified against the server. */ + successful: boolean; + }; + /** Whether a DSN is configured (via `SENTRY_DSN`). */ + have_dsn: boolean; + /** Identity of the verified user, when available. */ + user?: { email?: string; name?: string }; +}; + +/** Flags accepted by `info`. */ +type InfoFlags = { + "config-status-json"?: boolean; + "no-defaults"?: boolean; + json?: boolean; +}; + +/** Read a non-empty configured value, or `null`. */ +function nonEmpty(value: string | null | undefined): string | null { + const trimmed = value?.trim(); + return trimmed ? trimmed : null; +} + +/** Gather configuration + verify authentication. */ +async function gatherStatus(ctx: SentryContext): Promise { + const url = + nonEmpty(ctx.env.SENTRY_URL) ?? getDefaultUrl() ?? DEFAULT_SENTRY_URL; + const org = nonEmpty(ctx.env.SENTRY_ORG) ?? getDefaultOrganization(); + const project = nonEmpty(ctx.env.SENTRY_PROJECT) ?? getDefaultProject(); + const authenticated = isAuthenticated(); + + let successful = false; + let user: InfoStatus["user"]; + if (authenticated) { + try { + const info = await getCurrentUser(); + successful = true; + user = { + email: info.email ?? undefined, + name: info.name ?? undefined, + }; + } catch (err) { + log.debug("Authentication verification failed", err); + } + } + + return { + config: { org, project, url }, + auth: { type: authenticated ? "token" : null, successful }, + have_dsn: nonEmpty(ctx.env.SENTRY_DSN) !== null, + user, + }; +} + +/** Human-readable rendering of the info status. */ +function formatInfo(data: InfoStatus): string { + const lines: string[] = [ + `${colorTag("muted", "Sentry Server:")} ${data.config.url}`, + `${colorTag("muted", "Default Organization:")} ${data.config.org ?? "-"}`, + `${colorTag("muted", "Default Project:")} ${data.config.project ?? "-"}`, + "", + colorTag("muted", "Authentication Info:"), + ` Method: ${data.auth.type ? "Auth Token" : "Unauthorized"}`, + ` Verified: ${ + data.auth.successful ? colorTag("green", "yes") : colorTag("red", "no") + }`, + ]; + if (data.user?.email) { + lines.push(` User: ${data.user.email}`); + } + return renderMarkdown(lines.join("\n")); +} + +export const infoCommand = buildCommand({ + docs: { + brief: "Print configuration and verify authentication", + fullDescription: + "Print the resolved Sentry server URL and default organization/project, " + + "and verify authentication against the server.\n\n" + + "Use `--config-status-json` for a machine-readable status dump (for " + + "external tooling); it always exits 0. Use `--no-defaults` to verify " + + "only authentication, without requiring a default org/project.", + }, + // Reports auth status (including "Unauthorized") — must run without auth. + auth: false, + output: { + human: formatInfo, + }, + parameters: { + flags: { + "config-status-json": { + kind: "boolean", + brief: + "Emit configuration + auth status as JSON (for external tooling); always exits 0", + optional: true, + }, + "no-defaults": { + kind: "boolean", + brief: + "Verify only authentication, without requiring a default org/project", + optional: true, + }, + }, + }, + async *func(this: SentryContext, flags: InfoFlags) { + const status = await gatherStatus(this); + + // `--config-status-json` is a status *report* for external tools: force + // JSON output and never fail (matching the legacy contract). + if (flags["config-status-json"]) { + flags.json = true; + yield new CommandOutput(status); + return; + } + + yield new CommandOutput(status); + + const missingDefaults = !( + flags["no-defaults"] || + (status.config.org && status.config.project) + ); + const failed = status.auth.type === null || !status.auth.successful; + if (failed || missingDefaults) { + this.process.exitCode = 1; + return { + hint: failed + ? "Not authenticated. Run `sentry auth login`." + : "No default organization/project. Run `sentry init` or set defaults.", + }; + } + return { hint: "Configuration verified." }; + }, +}); diff --git a/test/commands/info.test.ts b/test/commands/info.test.ts new file mode 100644 index 0000000000..51d82bff46 --- /dev/null +++ b/test/commands/info.test.ts @@ -0,0 +1,128 @@ +/** + * Tests for `sentry info`. + * + * Drives the command via its wrapper `loader()`, spying the auth/config getters + * and the `/auth/` verification call so no network or real config is needed. + */ + +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { infoCommand } from "../../src/commands/info.js"; +// biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking +import * as users from "../../src/lib/api/users.js"; +// biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking +import * as auth from "../../src/lib/db/auth.js"; +// biome-ignore lint/performance/noNamespaceImport: needed for spyOn mocking +import * as defaults from "../../src/lib/db/defaults.js"; + +function createContext(env: NodeJS.ProcessEnv = {}) { + const writes: string[] = []; + return { + context: { + stdout: { + write: (data: string | Uint8Array) => { + writes.push( + typeof data === "string" ? data : new TextDecoder().decode(data) + ); + return true; + }, + }, + stderr: { write: () => true }, + cwd: "/tmp", + env, + process: { ...process, exitCode: undefined } as typeof process, + }, + output: () => writes.join(""), + get exitCode() { + return this.context.process.exitCode; + }, + }; +} + +describe("sentry info", () => { + beforeEach(() => { + vi.spyOn(defaults, "getDefaultUrl").mockReturnValue(null); + vi.spyOn(defaults, "getDefaultOrganization").mockReturnValue(null); + vi.spyOn(defaults, "getDefaultProject").mockReturnValue(null); + vi.spyOn(auth, "isAuthenticated").mockReturnValue(false); + vi.spyOn(users, "getCurrentUser").mockRejectedValue(new Error("no auth")); + }); + afterEach(() => vi.restoreAllMocks()); + + test("reports unauthenticated and exits 1", async () => { + const harness = createContext(); + const func = await infoCommand.loader(); + + await func.call(harness.context, {}); + + expect(harness.output()).toContain("Unauthorized"); + expect(harness.exitCode).toBe(1); + }); + + test("verifies auth and shows the user (exit 0)", async () => { + vi.spyOn(auth, "isAuthenticated").mockReturnValue(true); + vi.spyOn(users, "getCurrentUser").mockResolvedValue({ + id: "1", + email: "me@example.com", + name: "Me", + } as Awaited>); + vi.spyOn(defaults, "getDefaultOrganization").mockReturnValue("acme"); + vi.spyOn(defaults, "getDefaultProject").mockReturnValue("web"); + + const harness = createContext(); + const func = await infoCommand.loader(); + await func.call(harness.context, {}); + + expect(harness.output()).toContain("me@example.com"); + expect(harness.exitCode ?? 0).toBe(0); + }); + + test("authenticated but verification fails exits 1", async () => { + vi.spyOn(auth, "isAuthenticated").mockReturnValue(true); + // getCurrentUser rejects (default) → successful false. + const harness = createContext(); + const func = await infoCommand.loader(); + await func.call(harness.context, {}); + expect(harness.exitCode).toBe(1); + }); + + test("--config-status-json emits JSON and always exits 0", async () => { + const harness = createContext(); + const func = await infoCommand.loader(); + + await func.call(harness.context, { "config-status-json": true }); + + const parsed = JSON.parse(harness.output()); + expect(parsed).toHaveProperty("config"); + expect(parsed).toHaveProperty("auth.successful", false); + expect(parsed).toHaveProperty("have_dsn", false); + expect(harness.exitCode ?? 0).toBe(0); + }); + + test("--no-defaults ignores missing org/project (only auth matters)", async () => { + vi.spyOn(auth, "isAuthenticated").mockReturnValue(true); + vi.spyOn(users, "getCurrentUser").mockResolvedValue({ + id: "1", + email: "me@example.com", + } as Awaited>); + + const harness = createContext(); + const func = await infoCommand.loader(); + await func.call(harness.context, { "no-defaults": true }); + expect(harness.exitCode ?? 0).toBe(0); + }); + + test("reads defaults from environment variables", async () => { + const harness = createContext({ + SENTRY_URL: "https://sentry.example.com", + SENTRY_ORG: "envorg", + SENTRY_DSN: "https://k@o.ingest.sentry.io/1", + }); + const func = await infoCommand.loader(); + await func.call(harness.context, { "config-status-json": true }); + + const parsed = JSON.parse(harness.output()); + expect(parsed.config.url).toBe("https://sentry.example.com"); + expect(parsed.config.org).toBe("envorg"); + expect(parsed.have_dsn).toBe(true); + }); +});