Skip to content

Commit 85c0c09

Browse files
authored
Merge pull request #4178 from github/mbg/use-api-error-classification-more
Use `wrapApiConfigurationError` more for `init-action-post`
2 parents 7b6a151 + 503e2f6 commit 85c0c09

4 files changed

Lines changed: 149 additions & 119 deletions

File tree

‎lib/entry-points.js‎

Lines changed: 15 additions & 11 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/api-client.test.ts‎

Lines changed: 98 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -111,103 +111,115 @@ test.serial("getGitHubVersion for GHEC-DR", async (t) => {
111111
t.deepEqual({ type: util.GitHubVariant.GHEC_DR }, gheDotcom);
112112
});
113113

114-
test.serial(
115-
"wrapApiConfigurationError correctly wraps specific configuration errors",
116-
(t) => {
114+
test("wrapApiConfigurationError doesn't wrap errors it isn't supposed to", (t) => {
115+
const unwrappedErrors = [
117116
// We don't reclassify arbitrary errors
118-
const arbitraryError = new Error("arbitrary error");
119-
let res = api.wrapApiConfigurationError(arbitraryError);
120-
t.is(res, arbitraryError);
117+
new Error("arbitrary error"),
118+
// Same goes for arbitrary strings
119+
"arbitrary error",
120+
// If an HTTP error doesn't contain a specific error message, we don't wrap it.
121+
new util.HTTPError("arbitrary HTTP error", 456),
122+
];
121123

122-
// Same goes for arbitrary errors
123-
const configError = new util.ConfigurationError("arbitrary error");
124-
res = api.wrapApiConfigurationError(configError);
125-
t.is(res, configError);
126-
127-
// If an HTTP error doesn't contain a specific error message, we don't
128-
// wrap is an an API error.
129-
const httpError = new util.HTTPError("arbitrary HTTP error", 456);
130-
res = api.wrapApiConfigurationError(httpError);
131-
t.is(res, httpError);
132-
133-
// For other HTTP errors, we wrap them as Configuration errors if they contain
134-
// specific error messages.
135-
const httpNotFoundError = new util.HTTPError("commit not found", 404);
136-
res = api.wrapApiConfigurationError(httpNotFoundError);
137-
t.deepEqual(res, new util.ConfigurationError("commit not found"));
138-
139-
const refNotFoundError = new util.HTTPError(
140-
"ref 'refs/heads/jitsi' not found in this repository - https://docs.github.com/rest",
141-
404,
142-
);
143-
res = api.wrapApiConfigurationError(refNotFoundError);
144-
t.deepEqual(
124+
for (const unwrappedError of unwrappedErrors) {
125+
const res = api.wrapApiConfigurationError(unwrappedError);
126+
t.is(
145127
res,
146-
new util.ConfigurationError(
147-
"ref 'refs/heads/jitsi' not found in this repository - https://docs.github.com/rest",
148-
),
128+
unwrappedError,
129+
`${util.getErrorMessage(unwrappedError)} should not be wrapped by wrapApiConfigurationError`,
149130
);
131+
}
132+
});
150133

151-
const apiRateLimitError = new util.HTTPError(
152-
"API rate limit exceeded for installation",
153-
403,
154-
);
155-
res = api.wrapApiConfigurationError(apiRateLimitError);
156-
t.deepEqual(
157-
res,
158-
new util.ConfigurationError("API rate limit exceeded for installation"),
159-
);
134+
test("wrapApiConfigurationError correctly wraps specific configuration errors", (t) => {
135+
// For other HTTP errors, we wrap them as Configuration errors if they contain
136+
// specific error messages.
137+
const httpNotFoundError = new util.HTTPError("commit not found", 404);
138+
const refNotFoundError = new util.HTTPError(
139+
"ref 'refs/heads/jitsi' not found in this repository - https://docs.github.com/rest",
140+
404,
141+
);
142+
const apiRateLimitError = new util.HTTPError(
143+
"API rate limit exceeded for installation",
144+
403,
145+
);
146+
const resourceNotAccessibleError = new util.HTTPError(
147+
"Resource not accessible by integration",
148+
403,
149+
);
150+
const errorsToWrap = [
151+
httpNotFoundError,
152+
refNotFoundError,
153+
apiRateLimitError,
154+
resourceNotAccessibleError,
155+
];
160156

161-
const tokenSuggestionMessage =
162-
"Please check that your token is valid and has the required permissions: contents: read, security-events: write";
163-
const badCredentialsError = new util.HTTPError("Bad credentials", 401);
164-
res = api.wrapApiConfigurationError(badCredentialsError);
165-
t.deepEqual(res, new util.ConfigurationError(tokenSuggestionMessage));
157+
for (const errorToWrap of errorsToWrap) {
158+
const res = api.wrapApiConfigurationError(errorToWrap);
159+
t.deepEqual(res, new util.ConfigurationError(errorToWrap.message));
160+
}
161+
});
166162

167-
const notFoundError = new util.HTTPError("Not Found", 404);
168-
res = api.wrapApiConfigurationError(notFoundError);
169-
t.deepEqual(res, new util.ConfigurationError(tokenSuggestionMessage));
163+
test("wrapApiConfigurationError wraps token errors", async (t) => {
164+
const tokenSuggestionMessage =
165+
"Please check that your token is valid and has the required permissions: contents: read, security-events: write";
166+
const badCredentialsError = new util.HTTPError("Bad credentials", 401);
167+
const notFoundError = new util.HTTPError("Not Found", 404);
168+
const errorsToWrap = [badCredentialsError, notFoundError];
170169

171-
const resourceNotAccessibleError = new util.HTTPError(
172-
"Resource not accessible by integration",
173-
403,
174-
);
175-
res = api.wrapApiConfigurationError(resourceNotAccessibleError);
176-
t.deepEqual(
177-
res,
178-
new util.ConfigurationError("Resource not accessible by integration"),
179-
);
170+
for (const errorToWrap of errorsToWrap) {
171+
const res = api.wrapApiConfigurationError(errorToWrap);
172+
t.deepEqual(res, new util.ConfigurationError(tokenSuggestionMessage));
173+
}
174+
});
180175

181-
// Enablement errors.
182-
const enablementErrorMessages = [
183-
"Code Security must be enabled for this repository to use code scanning",
184-
"Advanced Security must be enabled for this repository to use code scanning",
185-
"Code Scanning is not enabled for this repository. Please enable code scanning in the repository settings.",
186-
"Code quality is not enabled for this repository. Please enable code quality in the repository settings.",
187-
];
188-
const transforms = [
189-
(msg: string) => msg,
190-
(msg: string) => msg.toLowerCase(),
191-
(msg: string) => msg.toLocaleUpperCase(),
192-
];
176+
test("wrapApiConfigurationError wraps enablement errors", async (t) => {
177+
// Enablement errors.
178+
const enablementErrorMessages = [
179+
"Code Security must be enabled for this repository to use code scanning",
180+
"Advanced Security must be enabled for this repository to use code scanning",
181+
"Code Scanning is not enabled for this repository. Please enable code scanning in the repository settings.",
182+
"Code quality is not enabled for this repository. Please enable code quality in the repository settings.",
183+
];
184+
const transforms = [
185+
(msg: string) => msg,
186+
(msg: string) => msg.toLowerCase(),
187+
(msg: string) => msg.toLocaleUpperCase(),
188+
];
193189

194-
for (const enablementErrorMessage of enablementErrorMessages) {
195-
for (const transform of transforms) {
196-
const enablementError = new util.HTTPError(
197-
transform(enablementErrorMessage),
198-
403,
199-
);
200-
res = api.wrapApiConfigurationError(enablementError);
201-
t.deepEqual(
202-
res,
203-
new util.ConfigurationError(
204-
api.getFeatureEnablementError(enablementError.message),
205-
),
206-
);
207-
}
190+
for (const enablementErrorMessage of enablementErrorMessages) {
191+
for (const transform of transforms) {
192+
const enablementError = new util.HTTPError(
193+
transform(enablementErrorMessage),
194+
403,
195+
);
196+
const res = api.wrapApiConfigurationError(enablementError);
197+
t.deepEqual(
198+
res,
199+
new util.ConfigurationError(
200+
api.getFeatureEnablementError(enablementError.message),
201+
),
202+
);
208203
}
209-
},
210-
);
204+
}
205+
});
206+
207+
test("wrapApiConfigurationError doesn't double-wrap errors", async (t) => {
208+
// This test checks that errors don't get wrapped a second time if `wrapApiConfigurationError`
209+
// is called on an error that was already wrapped by a previous call to `wrapApiConfigurationError`.
210+
// Start by calling `wrapApiConfigurationError` on an unwrapped error that should be wrapped:
211+
const unwrappedError = new util.HTTPError("commit not found", 404);
212+
const wrappedError = api.wrapApiConfigurationError(unwrappedError);
213+
214+
// Sanity-check that it was wrapped, as expected.
215+
t.deepEqual(
216+
wrappedError,
217+
new util.ConfigurationError(unwrappedError.message),
218+
);
219+
220+
// The result of the second call should be exactly `wrappedError`:
221+
t.is(api.wrapApiConfigurationError(wrappedError), wrappedError);
222+
});
211223

212224
test("getRegistryProxy - returns undefined if the proxy is not configured", async (t) => {
213225
const target = callee(api.getRegistryProxy).withArgs();

‎src/api-client.ts‎

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -219,25 +219,31 @@ export async function getGitHubVersionFromApi(
219219
return { type: GitHubVariant.DOTCOM };
220220
}
221221

222-
// Doesn't strictly have to be the meta endpoint as we're only
223-
// using the response headers which are available on every request.
224-
//
225-
// See https://docs.github.com/en/rest/meta/meta#get-github-meta-information.
226-
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
227-
const response = await apiClient.rest.meta.get();
228-
229-
// This happens on dotcom, although we expect to have already returned in that
230-
// case. This can also serve as a fallback in cases we haven't foreseen.
231-
if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === undefined) {
232-
return { type: GitHubVariant.DOTCOM };
233-
}
222+
try {
223+
// Doesn't strictly have to be the meta endpoint as we're only
224+
// using the response headers which are available on every request.
225+
//
226+
// See https://docs.github.com/en/rest/meta/meta#get-github-meta-information.
227+
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
228+
const response = await apiClient.rest.meta.get();
229+
230+
// This happens on dotcom, although we expect to have already returned in that
231+
// case. This can also serve as a fallback in cases we haven't foreseen.
232+
if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === undefined) {
233+
return { type: GitHubVariant.DOTCOM };
234+
}
234235

235-
if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === "ghe.com") {
236-
return { type: GitHubVariant.GHEC_DR };
237-
}
236+
if (response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] === "ghe.com") {
237+
return { type: GitHubVariant.GHEC_DR };
238+
}
238239

239-
const version = response.headers[GITHUB_ENTERPRISE_VERSION_HEADER] as string;
240-
return { type: GitHubVariant.GHES, version };
240+
const version = response.headers[
241+
GITHUB_ENTERPRISE_VERSION_HEADER
242+
] as string;
243+
return { type: GitHubVariant.GHES, version };
244+
} catch (err) {
245+
throw wrapApiConfigurationError(err);
246+
}
241247
}
242248

243249
/**
@@ -415,7 +421,14 @@ export function getFeatureEnablementError(message: string): string {
415421
return `Please verify that the necessary features are enabled: ${message}`;
416422
}
417423

418-
export function wrapApiConfigurationError(e: unknown) {
424+
/**
425+
* Decides whether `e` is a known error returned by the GitHub API that we should
426+
* classify as a `ConfigurationError`.
427+
*
428+
* @param e The error to classify.
429+
* @returns Either `e` or a corresponding `ConfigurationError`.
430+
*/
431+
export function wrapApiConfigurationError<T>(e: T): T | ConfigurationError {
419432
const httpError = asHTTPError(e);
420433
if (httpError !== undefined) {
421434
if (

‎src/init-action-post.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
getTemporaryDirectory,
1313
printDebugLogs,
1414
} from "./actions-util";
15-
import { getGitHubVersion } from "./api-client";
15+
import { getGitHubVersion, wrapApiConfigurationError } from "./api-client";
1616
import { CachingKind } from "./caching-utils";
1717
import { getCodeQL } from "./codeql";
1818
import { type Config, getConfig } from "./config-utils";
@@ -64,7 +64,9 @@ async function run(startedAt: Date) {
6464
// Restore inputs from `init` Action.
6565
restoreInputs(logger);
6666

67-
const gitHubVersion = await getGitHubVersion();
67+
config = await getConfig(getTemporaryDirectory(), logger);
68+
69+
const gitHubVersion = config?.gitHubVersion ?? (await getGitHubVersion());
6870
checkGitHubVersionInRange(gitHubVersion, logger);
6971

7072
const repositoryNwo = getRepositoryNwo();
@@ -75,7 +77,6 @@ async function run(startedAt: Date) {
7577
logger,
7678
);
7779

78-
config = await getConfig(getTemporaryDirectory(), logger);
7980
if (config === undefined) {
8081
logger.warning(
8182
"Debugging artifacts are unavailable since the 'init' Action failed before it could produce any.",
@@ -107,7 +108,7 @@ async function run(startedAt: Date) {
107108
}
108109
}
109110
} catch (unwrappedError) {
110-
const error = wrapError(unwrappedError);
111+
const error = wrapApiConfigurationError(wrapError(unwrappedError));
111112
core.setFailed(error.message);
112113

113114
const statusReportBase = await createStatusReportBase(

0 commit comments

Comments
 (0)