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
6 changes: 5 additions & 1 deletion src/commands/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { defineCommand } from 'citty';

import { apiFlags } from '../config/flags/api.flags.js';
import { resolveFrontendUrl } from '../config/environments.js';
import { ApiGateway } from '../gateways/api-gateway.js';
import { ApiError, ApiGateway } from '../gateways/api-gateway.js';
import { formatDurationSeconds } from '../methods.js';
import { resolveAuth } from '../utils/auth.js';
import { CliError, logger } from '../utils/cli.js';
Expand Down Expand Up @@ -42,6 +42,10 @@ type StatusResponse = {
/** Errors the API gateway surfaces for 4xx-class failures — retrying is pointless. */
function isClientApiError(error: Error | null): boolean {
if (!error) return false;
if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
return true;
}

return (
error.message.includes('Invalid request:') ||
error.message.includes('Resource not found') ||
Expand Down
50 changes: 42 additions & 8 deletions src/gateways/api-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,29 @@ import { components, paths } from '../types/generated/schema.types.js';
*/
export class ApiError extends Error {
status: number;
/** The API's machine-readable error code, such as `API_KEY_SCOPE`, when it sent one. */
code?: string;

constructor(message: string, status: number) {
constructor(message: string, status: number, code?: string) {
super(message);
this.name = 'ApiError';
this.status = status;
this.code = code;
}
}

/**
* API errors no retry can clear: an API key whose access doesn't cover the
* call (`API_KEY_SCOPE`), or an upload the key can't see (`UPLOAD_NOT_FOUND`).
* A key's access is fixed when it is created.
*/
export function isPermanentApiError(error: unknown): error is ApiError {
return (
error instanceof ApiError &&
(error.code === 'API_KEY_SCOPE' || error.code === 'UPLOAD_NOT_FOUND')
);
}

/**
* Parses a successful response body as JSON, wrapping parse failures in a
* descriptive error (a 200 with an HTML body otherwise surfaces as a bare
Expand Down Expand Up @@ -104,19 +119,25 @@ export const ApiGateway = {
async handleApiError(res: Response, operation: string): Promise<never> {
const errorText = await res.text();
let userMessage: string;
let code: string | undefined;

// Parse common API error formats
try {
const errorData = JSON.parse(errorText);
userMessage = errorData.message || errorData.error || errorText;
// The API's own codes are UPPER_SNAKE_CASE. Its framework fills `error`
// with the HTTP reason ("Forbidden") otherwise, which is not a code.
if (typeof errorData.error === 'string' && /^[A-Z][A-Z0-9_]+$/.test(errorData.error)) {
code = errorData.error;
}
} catch {
userMessage = errorText;
}

// Add context and improve readability
switch (res.status) {
case 400: {
throw new ApiError(`Invalid request: ${userMessage}`, 400);
throw new ApiError(`Invalid request: ${userMessage}`, 400, code);
}

case 401: {
Expand All @@ -129,10 +150,22 @@ export const ApiGateway = {
message += `\nServer response: ${userMessage}`;
}

throw new ApiError(message, 401);
throw new ApiError(message, 401, code);
}

case 403: {
// A valid key whose access is limited, such as a CI-only key. The
// revoked-key advice below would send the user looking in the wrong
// place, and the server's message already names what to use instead.
if (code === 'API_KEY_SCOPE') {
throw new ApiError(
`Access denied. ${userMessage}\n` +
`An API key's access is chosen when the key is created, under Settings → API keys in the console.`,
403,
code,
);
}

// For 403, use the server's error message directly as it's now detailed
// If the message suggests an API key issue, provide additional guidance
if (userMessage.toLowerCase().includes('api key')) {
Expand All @@ -143,28 +176,29 @@ export const ApiGateway = {
` 3. Ensure the API key hasn't been deleted or revoked\n` +
` 4. Confirm you're connecting to the correct API URL`,
403,
code,
);
}

throw new ApiError(`Access denied. ${userMessage}`, 403);
throw new ApiError(`Access denied. ${userMessage}`, 403, code);
}

case 404: {
throw new ApiError(`Resource not found. ${userMessage}`, 404);
throw new ApiError(`Resource not found. ${userMessage}`, 404, code);
}

case 429: {
throw new ApiError(`Rate limit exceeded. Please try again later. (${operation})`, 429);
throw new ApiError(`Rate limit exceeded. Please try again later. (${operation})`, 429, code);
}

case 500: {
throw new ApiError(`Server error occurred. Please try again or contact support. (${operation})`, 500);
throw new ApiError(`Server error occurred. Please try again or contact support. (${operation})`, 500, code);
}

default: {
// `operation` is already phrased as "Failed to …", so don't append
// another "failed" here (avoids "Failed to execute test failed: …").
throw new ApiError(`${operation}: ${userMessage} (HTTP ${res.status})`, res.status);
throw new ApiError(`${operation}: ${userMessage} (HTTP ${res.status})`, res.status, code);
}
}
},
Expand Down
15 changes: 12 additions & 3 deletions src/services/results-polling.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import * as path from 'node:path';

import { ApiGateway, type ResultsPollCache } from '../gateways/api-gateway.js';
import {
ApiGateway,
isPermanentApiError,
type ResultsPollCache,
} from '../gateways/api-gateway.js';
import { formatDurationSeconds } from '../methods.js';
import type { AuthContext } from '../types/domain/auth.types.js';
import { paths } from '../types/generated/schema.types.js';
Expand Down Expand Up @@ -295,8 +299,13 @@ export class ResultsPollingService {
await this.sleep(pollIntervalMs);
} catch (error) {
// Re-throw RunFailedError immediately (test failures, not polling
// errors), and an expired login no retry can fix.
if (error instanceof RunFailedError || error instanceof PollingAuthError) {
// errors), and an expired login or a key without access to this run,
// which no retry can fix.
if (
error instanceof RunFailedError ||
error instanceof PollingAuthError ||
isPermanentApiError(error)
) {
throw error;
}

Expand Down
5 changes: 4 additions & 1 deletion src/utils/compatibility.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ApiGateway } from '../gateways/api-gateway.js';
import type { AuthContext } from '../types/domain/auth.types.js';
import type { Notice } from '../services/notices.service.js';

Expand Down Expand Up @@ -43,7 +44,9 @@ export async function fetchCompatibilityData(
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
// Says why, such as a key whose access doesn't cover running tests,
// rather than only the status code.
await ApiGateway.handleApiError(response, 'Failed to fetch compatibility data');
}

const result = await response.json() as { data?: CompatibilityData; message?: string; statusCode: number };
Expand Down
161 changes: 161 additions & 0 deletions test/unit/api-key-access-errors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import { expect } from 'chai';
import * as http from 'node:http';
import type { AddressInfo } from 'node:net';

import { ApiError, ApiGateway, isPermanentApiError } from '../../src/gateways/api-gateway.js';
import { ResultsPollingService } from '../../src/services/results-polling.service.js';
import type { AuthContext } from '../../src/types/domain/auth.types.js';
import { clearCompatibilityCache, fetchCompatibilityData } from '../../src/utils/compatibility.js';

/**
* An API key's access can be limited when it is created (for example a key
* that may only start test runs and read the runs it started). A call
* outside that access is a 403 `API_KEY_SCOPE`, and a run the key didn't
* start is a 404 `UPLOAD_NOT_FOUND`. Neither clears on retry, and neither
* means the key is invalid.
*/

const AUTH: AuthContext = { mode: 'apiKey', headers: { 'x-app-api-key': 'k' } };

const SCOPE_BODY = {
statusCode: 403,
message:
"This API key is limited to CI (run tests only) and can't reach /uploads/list. Use a key with full access for this.",
error: 'API_KEY_SCOPE',
};

const reply = (status: number, body: unknown) =>
new Response(JSON.stringify(body), {
status,
headers: { 'content-type': 'application/json' },
});

const thrownBy = async (promise: Promise<unknown>): Promise<unknown> => {
try {
await promise;
} catch (error) {
return error;
}

throw new Error('expected a rejection');
};

describe('API key access errors', () => {
describe('handleApiError', () => {
it('explains a scope denial without the invalid-key advice', async () => {
const error = await thrownBy(ApiGateway.handleApiError(reply(403, SCOPE_BODY), 'Failed to list uploads'));

expect(error).to.be.instanceOf(ApiError);
const apiError = error as ApiError;
expect(apiError.status).to.equal(403);
expect(apiError.code).to.equal('API_KEY_SCOPE');
expect(apiError.message).to.include('limited to CI (run tests only)');
expect(apiError.message).to.include('Settings → API keys');
expect(apiError.message).not.to.include('revoked');
});

it('keeps the invalid-key advice for a key the API rejected', async () => {
const error = (await thrownBy(
ApiGateway.handleApiError(
reply(403, {
statusCode: 403,
message: 'Invalid API key. Please check your API key and ensure it is valid for this environment.',
error: 'Forbidden',
}),
'Failed to list uploads',
),
)) as ApiError;

// "Forbidden" is the HTTP reason, not one of the API's codes.
expect(error.code).to.equal(undefined);
expect(error.message).to.include('Troubleshooting steps');
});

it('carries the code of a run the key cannot see', async () => {
const error = (await thrownBy(
ApiGateway.handleApiError(
reply(404, { message: 'Upload not found', error: 'UPLOAD_NOT_FOUND' }),
'Failed to get results',
),
)) as ApiError;

expect(error.code).to.equal('UPLOAD_NOT_FOUND');
expect(isPermanentApiError(error)).to.equal(true);
});

it('treats only those two codes as permanent', () => {
expect(isPermanentApiError(new ApiError('x', 403, 'API_KEY_SCOPE'))).to.equal(true);
expect(isPermanentApiError(new ApiError('x', 404))).to.equal(false);
expect(isPermanentApiError(new ApiError('x', 503))).to.equal(false);
expect(isPermanentApiError(new Error('fetch failed'))).to.equal(false);
});
});

describe('dcd cloud polling', () => {
const realGetResults = ApiGateway.getResultsForUpload;
afterEach(() => {
ApiGateway.getResultsForUpload = realGetResults;
});

for (const [label, error] of [
['a scope denial', new ApiError('Access denied.', 403, 'API_KEY_SCOPE')],
['a run the key cannot see', new ApiError('Resource not found.', 404, 'UPLOAD_NOT_FOUND')],
] as const) {
it(`stops at once on ${label}, rather than retrying 30 times`, async () => {
let polls = 0;
ApiGateway.getResultsForUpload = (async () => {
polls++;
throw error;
}) as unknown as typeof ApiGateway.getResultsForUpload;
const service = new ResultsPollingService();
// Would skip the backoff if it retried; it must not get that far.
(service as unknown as { sleep: () => Promise<void> }).sleep = async () => {};

const caught = await thrownBy(
service.pollUntilComplete({
auth: AUTH,
apiUrl: 'https://api.example.com',
consoleUrl: 'https://console.example.com/results?upload=u1',
json: true,
uploadId: 'u1',
}),
);

expect(caught).to.equal(error);
expect(polls).to.equal(1);
});
}
});

describe('compatibility data', () => {
let server: http.Server;
let baseUrl: string;

before(async () => {
server = http.createServer((_req, res) => {
res.writeHead(403, { 'content-type': 'application/json' });
res.end(JSON.stringify({ ...SCOPE_BODY, message: SCOPE_BODY.message.replace('CI (run tests only)', 'device sessions') }));
});
await new Promise<void>((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});

after(async () => {
await new Promise((resolve) => {
server.close(resolve);
});
});

beforeEach(() => clearCompatibilityCache());

it('says why the API refused, not only the status code', async () => {
const error = (await thrownBy(fetchCompatibilityData(baseUrl, AUTH))) as Error;

expect(error.message).to.include('limited to device sessions');
expect(error.message).not.to.include('HTTP error! status: 403');
expect(error.cause).to.be.instanceOf(ApiError);
});
});
});
Loading