diff --git a/src/catalog/no-graphql-leak.spec.ts b/src/catalog/no-graphql-leak.spec.ts index fb54526b..62d2efca 100644 --- a/src/catalog/no-graphql-leak.spec.ts +++ b/src/catalog/no-graphql-leak.spec.ts @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'; import { loadManagementCatalog } from './loader.js'; import { getManifest } from './manifest.js'; import { OVERRIDES, resolveCommandMeta, findLeaks, LEAK_PATTERN } from './curation.js'; -import { dashboardErrorMessage } from './operation.js'; +import { dashboardErrorMessage, getOperation, resolveExecutableDocument } from './operation.js'; import { DASHBOARD_ERROR_MESSAGES } from '../lib/command-auth.js'; import { DashboardGraphqlError, type DashboardGraphqlErrorCode } from '../lib/dashboard-graphql.js'; import { buildCommandTree, type CommandSchema, type HelpOutput } from '../utils/help-json.js'; @@ -124,6 +124,19 @@ describe('no GraphQL/userland leak in dashboard-plane error copy', () => { } }); + it('appends a clean server error code to graphql_error copy, never the server message', () => { + const msg = (serverCode?: string) => + dashboardErrorMessage(new DashboardGraphqlError('private details', 'graphql_error', undefined, serverCode)); + expect(msg('INTERNAL_SERVER_ERROR')).toBe( + 'The WorkOS account plane could not complete this request (INTERNAL_SERVER_ERROR).', + ); + expect(msg('GRAPHQL_VALIDATION_FAILED')).toContain('(VALIDATION_FAILED)'); + expect(msg(undefined)).toBe('The WorkOS account plane could not complete this request.'); + expect(msg('not a code; private')).toBe('The WorkOS account plane could not complete this request.'); + expect(msg('USERLAND_THING')).toBe('The WorkOS account plane could not complete this request.'); + expect(msg('INTERNAL_SERVER_ERROR')).not.toContain('private details'); + }); + it('forbidden copy no longer claims the capability is staging-gated', () => { expect(DASHBOARD_ERROR_MESSAGES.forbidden).not.toMatch(/staging/i); expect(dashboardErrorMessage(new DashboardGraphqlError('x', 'forbidden', 403))).toBe( @@ -131,3 +144,97 @@ describe('no GraphQL/userland leak in dashboard-plane error copy', () => { ); }); }); + +// Only the selection syntax used by this query and its fragments is needed. +// Reject arguments and directives rather than mistaking their names for fields. +function selectedFieldPaths(document: string, fragments: Record = {}): Set { + const paths = new Set(); + const activeFragments = new Set(); + + function visitDefinition(source: string, prefix: string) { + const tokens = source.replace(/#[^\r\n]*/g, '').match(/\.\.\.|[_A-Za-z][_0-9A-Za-z]*|[^\s,]/g) ?? []; + let index = 0; + + function consume(expected: string) { + const token = tokens[index++]; + if (token !== expected) throw new Error(`Expected "${expected}", got ${token ?? 'end of document'}`); + } + + function readName(): string { + const token = tokens[index++]; + if (!token || !/^[_A-Za-z]/.test(token)) throw new Error(`Expected a name, got ${token ?? 'end of document'}`); + return token; + } + + function visitSelection(parent: string) { + consume('{'); + while (tokens[index] !== '}') { + if (tokens[index] === '...') { + index++; + const name = readName(); + if (name === 'on') { + readName(); // Inline fragment type condition, not a field. + visitSelection(parent); + } else { + const fragment = fragments[name]; + if (typeof fragment !== 'string') throw new Error(`Missing fragment "${name}"`); + if (activeFragments.has(name)) throw new Error(`Cyclic fragment "${name}"`); + activeFragments.add(name); + visitDefinition(fragment, parent); + activeFragments.delete(name); + } + continue; + } + let field = readName(); + if (tokens[index] === ':') { + index++; + field = readName(); // Use the schema field name, not the alias. + } + const path = parent ? `${parent}.${field}` : field; + paths.add(path); + if (tokens[index] === '{') visitSelection(path); + } + consume('}'); + } + + if (tokens[index] === 'fragment') { + consume('fragment'); + readName(); + consume('on'); + readName(); + } else { + consume('query'); + readName(); + } + visitSelection(prefix); + if (index !== tokens.length) throw new Error(`Unexpected token "${tokens[index]}" after selection set`); + } + + visitDefinition(document, ''); + return paths; +} + +describe('teamProjectsV2 wire document', () => { + // Every env-scoped command resolves its target through this query, so it must + // select only what the CLI reads: a failing resolver on an unread field + // (e.g. certificate expiry) must not take down every command for the team. + it('selects only the fields the CLI reads', () => { + const doc = resolveExecutableDocument(getOperation('teamProjectsV2')); + expect(doc).toContain('query teamProjectsV2'); + for (const field of ['projectsV2', 'clientId', 'sandbox']) expect(doc).toContain(field); + for (const field of ['...Environment', 'expiredConnectionCertificates', 'customAuthDomain', 'resourceTypeCount']) { + expect(doc).not.toContain(field); + } + }); + + // `catalog:vendor` never refreshes the override. Compare paths, not names: + // a project may still select `name` after the environment field is renamed. + it('selects only fields the vendored catalog also selects', () => { + const operation = getOperation('teamProjectsV2'); + const fragments = Object.fromEntries(operation.fragmentNames.map((name) => [name, catalog.fragments[name]])); + const vendoredPaths = selectedFieldPaths(operation.document, fragments); + const overridePaths = selectedFieldPaths(resolveExecutableDocument(operation)); + const drift = [...overridePaths].filter((path) => !vendoredPaths.has(path)); + expect(drift).toEqual([]); + }); +}); diff --git a/src/catalog/operation.ts b/src/catalog/operation.ts index 47efb349..afc5a600 100644 --- a/src/catalog/operation.ts +++ b/src/catalog/operation.ts @@ -2,6 +2,7 @@ import { loadManagementCatalog } from './loader.js'; import { DashboardGraphqlError } from '../lib/dashboard-graphql.js'; import { DASHBOARD_ERROR_MESSAGES } from '../lib/command-auth.js'; import { exitWithError } from '../utils/output.js'; +import { LEAK_PATTERN } from './curation.js'; import type { CatalogOperation, ManagementCatalog } from './catalog-types.js'; /** @@ -59,6 +60,32 @@ export function getOperation( return op; } +/** + * Slimmer wire documents for operations whose catalog selection is far wider + * than anything the CLI reads. `teamProjectsV2` backs environment resolution + * for every env-scoped command, and its catalog version pulls the full + * Environment fragment (certificate expiry, custom domains, ...): one of those + * resolvers failing for one environment used to fail the whole team's reads. + * Keep the operation name: specs route on it. + */ +const DOCUMENT_OVERRIDES: Record = { + teamProjectsV2: `query teamProjectsV2 { + currentTeam { + id + projectsV2 { + id + name + environments { + id + name + sandbox + clientId + } + } + } +}`, +}; + /** * Returns the full executable GraphQL document for an operation: its own * `document` text plus the definitions of every fragment it transitively @@ -74,6 +101,8 @@ export function resolveExecutableDocument( op: CatalogOperation, catalog: ManagementCatalog = loadManagementCatalog(undefined, { includeFeatureFlagged: true }), ): string { + const override = DOCUMENT_OVERRIDES[op.name]; + if (override) return override; if (op.fragmentNames.length === 0) return op.document; const fragments = op.fragmentNames.map((fragmentName) => { @@ -111,6 +140,16 @@ export function reportDashboardError(error: unknown): never { throw error; } +/** + * The server's error code (e.g. `INTERNAL_SERVER_ERROR`) is the only server + * detail we echo: messages can carry private data. Codes are uppercase + * identifiers; anything else, or anything naming GraphQL, is dropped. + */ +function serverCodeSuffix(code: string | undefined): string { + const clean = code?.replace(/^GRAPHQL_/, ''); + return clean && /^[A-Z][A-Z0-9_]*$/.test(clean) && !LEAK_PATTERN.test(clean) ? ` (${clean})` : ''; +} + /** * Per-code user-facing copy. Exported so `no-graphql-leak.spec.ts` can run the * leak gate over every branch. `forbidden` (exit 1, not auth-recoverable) is @@ -127,6 +166,6 @@ export function dashboardErrorMessage(error: DashboardGraphqlError): string { return 'Could not reach the WorkOS account plane. Check your connection and try again.'; case 'graphql_error': default: - return 'The WorkOS account plane could not complete this request.'; + return `The WorkOS account plane could not complete this request${serverCodeSuffix(error.serverCode)}.`; } } diff --git a/src/lib/command-auth.ts b/src/lib/command-auth.ts index 7571cd6d..41cde4e6 100644 --- a/src/lib/command-auth.ts +++ b/src/lib/command-auth.ts @@ -84,7 +84,7 @@ export const DASHBOARD_ERROR_MESSAGES: Record< /** 403 from the dashboard plane: capability off for the team, or no team. */ get forbidden() { return ( - 'This account-plane capability is not enabled for this team, ' + + 'This account-plane capability is not enabled for this team, your team role does not allow it, ' + 'or the logged-in account is not backed by a WorkOS dashboard team.' ); }, diff --git a/src/lib/dashboard-graphql.spec.ts b/src/lib/dashboard-graphql.spec.ts index 9507d674..38ee41c8 100644 --- a/src/lib/dashboard-graphql.spec.ts +++ b/src/lib/dashboard-graphql.spec.ts @@ -54,6 +54,42 @@ describe('dashboardGraphqlUpload', () => { }); }); + it('maps an all-FORBIDDEN errors[] payload to forbidden (403)', async () => { + fetchMock.mockResolvedValue( + Response.json({ errors: [{ message: 'private details', extensions: { code: 'FORBIDDEN' } }] }), + ); + await expect(dashboardGraphqlRequest('query {}', { token: 'fake-token' })).rejects.toMatchObject({ + code: 'forbidden', + status: 403, + message: expect.not.stringContaining('private details'), + }); + }); + + it('keeps the server error code on graphql_error', async () => { + fetchMock.mockResolvedValue( + Response.json({ errors: [{ message: 'boom' }, { message: 'x', extensions: { code: 'INTERNAL_SERVER_ERROR' } }] }), + ); + await expect(dashboardGraphqlRequest('query {}', { token: 'fake-token' })).rejects.toMatchObject({ + code: 'graphql_error', + serverCode: 'INTERNAL_SERVER_ERROR', + }); + }); + + it('ignores a non-string server error code', async () => { + fetchMock.mockResolvedValue( + Response.json({ + errors: [ + { message: 'boom', extensions: { code: 500 } }, + { message: 'x', extensions: { code: {} } }, + ], + }), + ); + await expect(dashboardGraphqlRequest('query {}', { token: 'fake-token' })).rejects.toMatchObject({ + code: 'graphql_error', + serverCode: undefined, + }); + }); + /** The FormData handed to fetch on the most recent call. */ function sentForm(): FormData { const init = fetchMock.mock.calls[0]?.[1] as RequestInit; diff --git a/src/lib/dashboard-graphql.ts b/src/lib/dashboard-graphql.ts index 673ee953..b557c5a2 100644 --- a/src/lib/dashboard-graphql.ts +++ b/src/lib/dashboard-graphql.ts @@ -40,6 +40,8 @@ export class DashboardGraphqlError extends Error { message: string, readonly code: DashboardGraphqlErrorCode, readonly status?: number, + /** Server-supplied error code (`errors[].extensions.code`) for `graphql_error`. */ + readonly serverCode?: string, ) { super(message); this.name = 'DashboardGraphqlError'; @@ -154,7 +156,17 @@ async function sendDashboardRequest( if (body.errors.every((error) => error.extensions?.code === 'UNAUTHENTICATED')) { throw new DashboardGraphqlError('The dashboard session was rejected.', 'forbidden', 401); } - throw new DashboardGraphqlError(body.errors.map((e) => e.message).join('; '), 'graphql_error'); + // The capability gate (and role checks) answer HTTP 200 with FORBIDDEN, not a 403. + if (body.errors.every((error) => error.extensions?.code === 'FORBIDDEN')) { + throw new DashboardGraphqlError('The dashboard refused this request.', 'forbidden', 403); + } + throw new DashboardGraphqlError( + body.errors.map((e) => e.message).join('; '), + 'graphql_error', + undefined, + // Untrusted JSON: keep only a string code. + body.errors.map((e) => e.extensions?.code).find((code): code is string => typeof code === 'string'), + ); } if (body.data == null) { diff --git a/src/lib/environment-target.spec.ts b/src/lib/environment-target.spec.ts index 16368ecf..51e90661 100644 --- a/src/lib/environment-target.spec.ts +++ b/src/lib/environment-target.spec.ts @@ -288,6 +288,42 @@ describe('resolveEnvironmentTarget', () => { expect(err).not.toMatch(/graphql/i); }); + it('says try again once on a network error', async () => { + mockGraphqlRequest.mockRejectedValueOnce(new DashboardGraphqlError('connection failed', 'network_error')); + await expect(resolveEnvironmentTarget('tok', { forMutation: false })).rejects.toMatchObject({ + name: 'CliExit', + context: { errorCode: 'environment_unresolved' }, + }); + const networkMessage = errorSpy.mock.lastCall?.map(String).join(' '); + expect(networkMessage?.match(/try again/gi)).toHaveLength(1); + + mockGraphqlRequest.mockRejectedValueOnce( + new DashboardGraphqlError('private details', 'graphql_error', undefined, 'INTERNAL_SERVER_ERROR'), + ); + await expect(resolveEnvironmentTarget('tok', { forMutation: false })).rejects.toMatchObject({ + name: 'CliExit', + context: { errorCode: 'environment_unresolved' }, + }); + const serverMessage = errorSpy.mock.lastCall?.map(String).join(' '); + expect(serverMessage).toContain('Try again.'); + }); + + it('names the server failure instead of blaming the network when the account plane errors', async () => { + seedProfile({ clientId: 'client_abc' }); + mockGraphqlRequest.mockRejectedValue( + new DashboardGraphqlError('private details', 'graphql_error', undefined, 'INTERNAL_SERVER_ERROR'), + ); + await expect(resolveEnvironmentTarget('tok', { forMutation: false })).rejects.toMatchObject({ + name: 'CliExit', + context: { errorCode: 'environment_unresolved' }, + }); + const err = errorSpy.mock.calls.map((c) => c.map(String).join(' ')).join('\n'); + expect(err).toContain('account plane could not complete this request (INTERNAL_SERVER_ERROR)'); + expect(err).not.toMatch(/network or server error/i); + expect(err).not.toContain('private details'); + expect(err).toContain('--environment-id'); + }); + it('surfaces a 403 as forbidden guidance, not a transient retry hint', async () => { seedProfile({ clientId: 'client_abc' }); mockGraphqlRequest.mockRejectedValue(new DashboardGraphqlError('denied', 'forbidden', 403)); diff --git a/src/lib/environment-target.ts b/src/lib/environment-target.ts index 1fb1c827..fcb8fd75 100644 --- a/src/lib/environment-target.ts +++ b/src/lib/environment-target.ts @@ -28,7 +28,7 @@ import ui from '../utils/ui.js'; import { getConfig, getActiveEnvironment, setProfileEnvironmentId, type CliConfig } from './config-store.js'; import { dashboardGraphqlRequest, DashboardGraphqlError } from './dashboard-graphql.js'; -import { getOperation, resolveExecutableDocument } from '../catalog/operation.js'; +import { dashboardErrorMessage, getOperation, resolveExecutableDocument } from '../catalog/operation.js'; import { refreshIfExpired, DASHBOARD_ERROR_MESSAGES } from './command-auth.js'; import { exitWithError } from '../utils/output.js'; import { isPromptAllowed } from '../utils/interaction-mode.js'; @@ -163,9 +163,12 @@ export async function resolveEnvironmentTarget( if (error instanceof DashboardGraphqlError && error.code === 'forbidden') { exitWithError({ code: 'forbidden', message: DASHBOARD_ERROR_MESSAGES.forbidden }); } + const cause = + error instanceof DashboardGraphqlError ? `: ${dashboardErrorMessage(error)}` : ' (network or server error).'; + const retry = cause.toLowerCase().endsWith('try again.') ? '' : ' Try again.'; exitWithError({ code: 'environment_unresolved', - message: `Could not resolve the target WorkOS environment (network or server error). Try again. ${remedies()}`, + message: `Could not resolve the target WorkOS environment${cause}${retry} ${remedies()}`, }); }