Skip to content
Open
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
109 changes: 108 additions & 1 deletion src/catalog/no-graphql-leak.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -124,10 +124,117 @@ 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(
DASHBOARD_ERROR_MESSAGES.forbidden,
);
});
});

// 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<string, string> = {}): Set<string> {
const paths = new Set<string>();
const activeFragments = new Set<string>();

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([]);
});
});
Comment on lines +228 to +240

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DOCUMENT_OVERRIDES.teamProjectsV2 is a second copy of the selection that catalog:vendor never refreshes. If the dashboard renames projectsV2/clientId/sandbox, the snapshot updates but the override keeps sending the old name, and since this query backs every env-scoped command the blast radius is the one this PR is shrinking. This test only compares the override to string literals, so CI wouldn't catch that.

Suggest a subset guard next to it. Passes today; fails with expected [ 'bogusField' ] to deeply equal [] when I inject a stray field into the override. loadManagementCatalog is already imported at the top of this file.

Suggested change
});
});
});
// The override is a second copy of the selection that `catalog:vendor` never
// refreshes: every name it sends must still exist in the vendored document.
it('selects only fields the vendored catalog also selects', () => {
const op = getOperation('teamProjectsV2');
const catalog = loadManagementCatalog(undefined, { includeFeatureFlagged: true });
const vendored = [op.document, ...op.fragmentNames.map((name) => catalog.fragments[name])].join('\n');
const vendoredNames = new Set(vendored.match(/\w+/g));
const drift = (resolveExecutableDocument(op).match(/\w+/g) ?? []).filter((name) => !vendoredNames.has(name));
expect(drift).toEqual([]);
});
});

41 changes: 40 additions & 1 deletion src/catalog/operation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand Down Expand Up @@ -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<string, string> = {
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
Expand All @@ -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) => {
Expand Down Expand Up @@ -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_/, '');
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
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
Expand All @@ -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)}.`;
}
}
2 changes: 1 addition & 1 deletion src/lib/command-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.'
);
},
Expand Down
36 changes: 36 additions & 0 deletions src/lib/dashboard-graphql.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 13 additions & 1 deletion src/lib/dashboard-graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -154,7 +156,17 @@ async function sendDashboardRequest<T>(
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) {
Expand Down
36 changes: 36 additions & 0 deletions src/lib/environment-target.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
7 changes: 5 additions & 2 deletions src/lib/environment-target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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()}`,
});
}

Expand Down