Skip to content
TypeScript

fix(server): Pull Requests says which GitHub credential cannot see a repository (#24350)

shivam33d27e999a07
diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
index 6c675219dc9..02e8b516dec 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
@@ -11,6 +11,7 @@ import { useAtomValue } from "@effect/atom-react";
import {
Keyboard,
Platform,
+ Pressable,
RefreshControl,
ScrollView,
View,
@@ -20,6 +21,7 @@ import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeS
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/ui/AppText";
+import { SymbolView } from "../../components/ui/AppSymbol";
import { EmptyState } from "../../components/ui/EmptyState";
import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
@@ -32,7 +34,6 @@ import {
usePullRequestListFilters,
type PullRequestFilterMenu,
} from "./PullRequestListFilters";
-import { PullRequestCardRow } from "./PullRequestControls";
import { usePullRequestList } from "./usePullRequestList";
import { usePullRequestListControls } from "./usePullRequestListControls";
import { usePullRequestListActions } from "./usePullRequestListActions";
@@ -58,26 +59,38 @@ function PullRequestScrollView(props: ScrollViewProps) {
);
}
-function PullRequestListErrors(props: { readonly messages: readonly string[] }) {
+function PullRequestListError(props: { readonly message: string }) {
const [expanded, setExpanded] = useState(false);
- const title = `${props.messages.length} ${props.messages.length === 1 ? "error" : "errors"} loading pull requests`;
return (
- <View>
- <PullRequestCardRow
- title={title}
- icon="exclamationmark.triangle"
- compact
- last
- expanded={expanded}
- accessibilityLabel={`${title}. ${expanded ? "Hide" : "Show"} details`}
- onPress={() => setExpanded((value) => !value)}
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={props.message}
+ accessibilityState={{ expanded }}
+ onPress={() => setExpanded((value) => !value)}
+ // A long press selects the text; collapsing under that selection crashes Android's
+ // smart-select animation, so it must not also count as a press.
+ onLongPress={() => undefined}
+ className="min-h-11 flex-row items-center gap-3 px-4 py-2.5 active:opacity-70"
+ >
+ <SymbolView
+ name="exclamationmark.triangle"
+ size={18}
+ tintColorClassName="accent-icon-muted"
/>
- {expanded ? (
- <Text selectable className="px-4 pb-3 text-sm text-foreground-muted">
- {props.messages.join("\n")}
- </Text>
- ) : null}
- </View>
+ <Text
+ selectable={expanded}
+ numberOfLines={expanded ? undefined : 1}
+ ellipsizeMode="tail"
+ className="min-w-0 flex-1 text-sm text-foreground-muted"
+ >
+ {props.message}
+ </Text>
+ <SymbolView
+ name={expanded ? "chevron.up" : "chevron.down"}
+ size={11}
+ tintColorClassName="accent-icon-muted"
+ />
+ </Pressable>
);
}
@@ -334,13 +347,14 @@ export function PullRequestsScreen(
<>
<PullRequestListFilters sidebar={sidebar} filters={filters} />
{result.data?.errors.length ? (
- <PullRequestListErrors
- key={JSON.stringify(targets)}
- messages={result.data.errors.map(
- (error) =>
- `${error.projectTitle || environments.find((environment) => environment.environmentId === error.environmentId)?.environmentLabel || "Environment"}: ${error.message}`,
- )}
- />
+ <View key={JSON.stringify(targets)}>
+ {result.data.errors.map((error) => (
+ <PullRequestListError
+ key={`${error.environmentId} ${error.projectTitle} ${error.message}`}
+ message={`${error.projectTitle || environments.find((environment) => environment.environmentId === error.environmentId)?.environmentLabel || "Environment"}: ${error.message}`}
+ />
+ ))}
+ </View>
) : null}
</>
}
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index 9f18426be19..e1f0f6525fb 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -1359,19 +1359,24 @@ export const make = Effect.gen(function* () {
: null,
};
}),
- Effect.orElseSucceed((): RepositoryBatch => ({
- key,
- entries: [],
- errors: [
- {
- projectId: project.project.id,
- projectTitle: project.project.title,
- message: `${project.repository} could not be read.`,
- },
- ],
- truncated: false,
- nextCursor: null,
- })),
+ Effect.catch((error): Effect.Effect<RepositoryBatch> =>
+ Effect.succeed({
+ key,
+ entries: [],
+ errors: [
+ {
+ projectId: project.project.id,
+ projectTitle: project.project.title,
+ message:
+ error.accessHint === undefined
+ ? `${project.repository} could not be read.`
+ : `${project.repository} could not be read. ${error.accessHint}`,
+ },
+ ],
+ truncated: false,
+ nextCursor: null,
+ }),
+ ),
);
}
};
diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts
index 63dfe8db7a8..4aa0c06cb8e 100644
--- a/packages/source-control-core/src/server/PullRequestProvider.ts
+++ b/packages/source-control-core/src/server/PullRequestProvider.ts
@@ -53,6 +53,11 @@ export class PullRequestProviderError extends Schema.TaggedError<PullRequestProv
]),
detail: Schema.String,
retryAt: Schema.optional(Schema.Number),
+ /**
+ * Why the host would not return a repository and what to change, in the reader's terms.
+ * Shown beside that repository in the list; `detail` is about the failed call instead.
+ */
+ accessHint: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
},
) {
@@ -69,6 +74,7 @@ export interface ProviderChangeRequestWatchFingerprint {
export interface PullRequestProviderFailure {
readonly reason: PullRequestProviderError["reason"];
readonly retryAt?: number | undefined;
+ readonly accessHint?: string | undefined;
}
export interface ProviderChangeRequest {
diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
index a4b5eb8da4c..78deffdfaeb 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
@@ -29,6 +30,9 @@ const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
token: () => Effect.succeedNone,
invalidate: () => Effect.void,
});
+const mockedAppToken = vi.fn<(host: string) => Effect.Effect<Option.Option<string>>>(
+ () => Effect.succeedNone,
+);
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
@@ -111,7 +115,12 @@ type ApiAnswer = Effect.Effect<GitHubRest.GitHubRestResponse, GitHubRequestPolic
const mockedExecute = vi.fn<(call: ApiCall) => ApiAnswer>();
const defaultCredential = (host: string) =>
Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:token` });
-const mockedCredential = vi.fn(defaultCredential);
+const mockedCredential =
+ vi.fn<
+ (
+ host: string,
+ ) => Effect.Effect<GitHubRequestPolicy.GitHubHeldCredential, GitHubRequestPolicy.GitHubApiError>
+ >(defaultCredential);
const mockedStackMemberships = vi.fn<(call: ApiCall) => ApiAnswer>(() =>
Effect.succeed(output('{"data":{}}')),
);
@@ -180,14 +189,23 @@ const layer = it.layer(
Layer.provideMerge(GitHubAppAccess.layer),
Layer.provideMerge(mockApi),
Layer.provideMerge(GitHubRequestPolicy.layer),
- Layer.provideMerge(appSignedOut),
+ Layer.provideMerge(
+ Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
+ enabled: false,
+ token: (host) => mockedAppToken(host),
+ invalidate: () => Effect.void,
+ }),
+ ),
Layer.provideMerge(GitHubQuota.layer),
Layer.provideMerge(SourceControlRateLimit.layer),
Layer.provideMerge(mockHttp),
Layer.provideMerge(
Layer.succeed(GitHubCredentials.GitHubCredentials, {
get: (host) =>
- Effect.map(mockedCredential(host), (held) => ({ ...held, host, source: "gh" as const })),
+ mockedCredential(host).pipe(
+ Effect.map((held) => ({ source: "gh" as const, ...held, host })),
+ Effect.mapError(() => new GitHubCredentials.GitHubCliMissingError({ host })),
+ ),
saved: () => Effect.succeedNone,
fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
invalidate: () => Effect.void,
@@ -617,6 +635,7 @@ afterEach(() => {
mockedExecute.mockReset();
mockedStackMemberships.mockReset();
mockedCredential.mockReset();
+ mockedAppToken.mockReset();
mockedCredential.mockImplementation(defaultCredential);
});
@@ -1276,6 +1295,101 @@ layer("GitHubPullRequestApi.layer", (it) => {
}),
);
+ /**
+ * Lists a repository GitHub will not return, answering credential lookups in turn (the last
+ * answer repeats; `undefined` is no credential), and returns the error with the tokens sent.
+ */
+ const listUnreadableRepository = (
+ ...lookups: ReadonlyArray<
+ | { readonly token: string; readonly source: GitHubCredentials.GitHubCredentialSource }
+ | undefined
+ >
+ ) => {
+ mockedExecute.mockClear();
+ let lookup = 0;
+ mockedCredential.mockImplementation((host) =>
+ Effect.suspend(() => {
+ const held = lookups[Math.min(lookup++, lookups.length - 1)];
+ return held === undefined
+ ? Effect.fail(
+ new GitHubRequestPolicy.GitHubApiAuthenticationError({
+ host,
+ operation: "credential",
+ }),
+ )
+ : Effect.succeed({
+ token: Redacted.make(held.token),
+ fingerprint: `${host}:${held.token}`,
+ source: held.source,
+ });
+ }),
+ );
+ route(
+ ["PullRequestSearch", { data: { search: { pageInfo: lastPage, nodes: [] } } }],
+ [
+ "PullRequestList",
+ {
+ data: { repository: null },
+ errors: [
+ {
+ type: "NOT_FOUND",
+ path: ["repository"],
+ message: "Could not resolve to a Repository with the name 'acme/private'.",
+ },
+ ],
+ },
+ ],
+ );
+ return GitHubPullRequestProvider.make.pipe(
+ Effect.flatMap((provider) =>
+ Effect.flip(
+ provider.listChangeRequests({
+ cwd: "/w",
+ repository: "acme/private",
+ host: "github.com",
+ state: "open",
+ involvement: "all",
+ viewer: "bilal",
+ limit: 10,
+ }),
+ ),
+ ),
+ Effect.map((error) => ({
+ error,
+ sentWith: mockedExecute.mock.calls.map(([call]) =>
+ call.kind === "graphql" ? call.authorization : undefined,
+ ),
+ })),
+ );
+ };
+
+ it.effect("names the credential GitHub would not return a repository to", () =>
+ Effect.gen(function* () {
+ // The saved token is replaced mid-read; every request still goes out with the one named.
+ const saved = yield* listUnreadableRepository(
+ { token: "first", source: "settings" },
+ { token: "replaced", source: "settings" },
+ );
+ expect(saved.error.accessHint).toContain("saved GitHub token");
+ assert.isAbove(saved.sentWith.length, 1);
+ for (const authorization of saved.sentWith) expect(authorization).toContain("first");
+
+ // The policy hands what the app cannot see to the gh login, which GitHub refuses too.
+ mockedAppToken.mockReturnValue(Effect.succeedSome("app"));
+ const app = { token: "app", source: "app" } as const;
+ const gh = { token: "personal", source: "gh" } as const;
+ const retried = yield* listUnreadableRepository(app, gh);
+ expect(retried.error.accessHint).toContain("gh login");
+ expect(retried.sentWith).toEqual(["Bearer app", "Bearer app", "Bearer personal"]);
+
+ // With no gh login when the app is refused, the app made the last request; a login that
+ // turns up afterwards is not named.
+ const appOnly = yield* listUnreadableRepository(app, undefined, gh);
+ assert.isUndefined(appOnly.error.accessHint);
+ expect(appOnly.sentWith).toEqual(["Bearer app", "Bearer app"]);
+ }),
+ );
+
it.effect("carries every repository and every qualifier into one search", () =>
Effect.gen(function* () {
mockedExecute.mockReturnValue(Effect.succeed(searchPage([])));
diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts
index 16a7a1df18c..b812fd7682e 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts
@@ -1816,7 +1816,7 @@ export const make = Effect.gen(function* () {
);
// Unindexed repositories silently return no search rows; fall back to the repository listing.
const hasQuery = (input.query?.trim().length ?? 0) > 0;
- return read(true).pipe(
+ const listed = read(true).pipe(
Effect.filterOrElse(
(batch) => batch.items.length > 0 || input.cursor !== undefined || hasQuery,
() => read(false),
@@ -1857,6 +1857,24 @@ export const make = Effect.gen(function* () {
),
),
);
+ // GitHub answers a private repository the token cannot see as missing, and its error names
+ // the credential that request carried. A personal credential is pinned for the whole
+ // read, so a token changed mid-read does not split it; the app keeps the policy's fallback.
+ const host = normalizeHost(input.host);
+ return api.credential(host).pipe(
+ Effect.flatMap(({ token, fingerprint, source }) =>
+ source === undefined || source === "app"
+ ? listed
+ : listed.pipe(
+ Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
+ host,
+ token,
+ credentialFingerprint: fingerprint,
+ source,
+ }),
+ ),
+ ),
+ );
}),
searchPullRequests: Effect.fn("GitHubPullRequestApi.searchPullRequests")(function* (input) {
diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
index 4f3490eec97..a99aa87c965 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
@@ -24,6 +24,7 @@ import {
type PullRequestProviderApi,
type ProviderRepositoryRef,
} from "@t3tools/source-control-core/server/PullRequestProvider";
+import type { GitHubCredentialSource } from "./GitHubCredentials.ts";
import type {
GitHubRepositoryAccess,
GitHubViewerAccess,
@@ -120,12 +121,21 @@ function gitHubProviderFailure(
case "SourceControlRateLimitPausedError":
return { reason: "rate-limited", retryAt: error.retryAt };
case "GitHubApiNotFoundError":
- return { reason: "not-found" };
+ return error.credential === undefined || error.credential === "app"
+ ? { reason: "not-found" }
+ : { reason: "not-found", accessHint: REPOSITORY_ACCESS_HINTS[error.credential] };
default:
return { reason: "failed" };
}
}
+const REPOSITORY_ACCESS_HINTS: Record<Exclude<GitHubCredentialSource, "app">, string> = {
+ settings:
+ "Your saved GitHub token can't see it. Give it access, or change it in Settings → Source Control.",
+ env: "The server's environment token can't see it. Give it access, or unset it.",
+ gh: "Your gh login can't see it. Give it access, or save a token in Settings → Source Control.",
+};
+
function withAvatar(
actor: PullRequestActor | null,
avatarsByLogin: ReadonlyMap<string, string>,
diff --git a/packages/source-control-github/src/server/GitHubRequestPolicy.ts b/packages/source-control-github/src/server/GitHubRequestPolicy.ts
index 2c2935bd1fb..158a0982d96 100644
--- a/packages/source-control-github/src/server/GitHubRequestPolicy.ts
+++ b/packages/source-control-github/src/server/GitHubRequestPolicy.ts
@@ -28,6 +28,7 @@ export const PinnedGitHubCredential = Context.Reference<{
readonly host: string;
readonly token: Redacted.Redacted<string>;
readonly credentialFingerprint: string;
+ readonly source?: GitHubCredentials.GitHubCredentialSource;
} | null>("@t3tools/source-control-github/server/GitHubRequestPolicy/PinnedGitHubCredential", {
defaultValue: () => null,
});
@@ -65,7 +66,12 @@ export class GitHubApiRateLimitError extends Schema.TaggedError<GitHubApiRateLim
export class GitHubApiNotFoundError extends Schema.TaggedError<GitHubApiNotFoundError>()(
"GitHubApiNotFoundError",
- { host: Schema.String, operation: Schema.String },
+ {
+ host: Schema.String,
+ operation: Schema.String,
+ /** The source of the credential the refused request carried, when known. */
+ credential: Schema.optionalKey(GitHubCredentials.GitHubCredentialSource),
+ },
) {
override get message(): string {
return "GitHub could not find the requested resource, or the credential cannot see it.";
@@ -193,10 +199,16 @@ export interface GitHubRequest {
export class GitHubRequestPolicy extends Context.Service<
GitHubRequestPolicy,
{
- /** send receives auth/version headers; its failures pass through unchanged. */
+ /**
+ * send receives auth/version headers and the source of the credential they carry; its
+ * failures pass through unchanged.
+ */
readonly request: <A, E, R>(
input: GitHubRequest,
- send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
+ send: (
+ headers: Readonly<Record<string, string>>,
+ source: GitHubCredentials.GitHubCredentialSource | undefined,
+ ) => Effect.Effect<GitHubAnswer<A>, E, R>,
) => Effect.Effect<A, E | GitHubApiError, R>;
/**
* The credential requests to `host` use: a token saved in Settings, else the app sign-in,
@@ -214,6 +226,7 @@ export class GitHubRequestPolicy extends Context.Service<
>()("@t3tools/source-control-github/server/GitHubRequestPolicy") {}
export interface GitHubHeldCredential {
+ readonly source?: GitHubCredentials.GitHubCredentialSource;
readonly token: Redacted.Redacted<string>;
readonly fingerprint: string;
}
@@ -255,6 +268,7 @@ export const make = Effect.gen(function* () {
Effect.map((held): ChosenCredential => ({
token: held.token,
fingerprint: held.fingerprint,
+ source: held.source,
fromApp: false,
})),
);
@@ -265,6 +279,7 @@ export const make = Effect.gen(function* () {
const token = yield* appSignIn.token(normalizeHost(host));
if (Option.isNone(token)) return Option.none();
return Option.some({
+ source: "app" as const,
token: Redacted.make(token.value),
fingerprint: yield* credentials.fingerprint(normalizeHost(host), token.value),
});
@@ -279,12 +294,18 @@ export const make = Effect.gen(function* () {
return {
token: pinned.token,
fingerprint: pinned.credentialFingerprint,
+ ...(pinned.source === undefined ? {} : { source: pinned.source }),
fromApp: false,
} satisfies ChosenCredential;
}
const saved = yield* credentials.saved(host);
if (Option.isSome(saved)) {
- return { token: saved.value.token, fingerprint: saved.value.fingerprint, fromApp: false };
+ return {
+ token: saved.value.token,
+ fingerprint: saved.value.fingerprint,
+ source: saved.value.source,
+ fromApp: false,
+ };
}
if (personal) return yield* personalCredential(host);
const app = yield* Effect.result(appCredential(host));
@@ -298,13 +319,20 @@ export const make = Effect.gen(function* () {
const credential: GitHubRequestPolicy["Service"]["credential"] = (host, options) =>
choose(normalizeHost(host), options?.personal === true).pipe(
- Effect.map(({ token, fingerprint }) => ({ token, fingerprint })),
+ Effect.map(({ token, fingerprint, source }) => ({
+ token,
+ fingerprint,
+ ...(source === undefined ? {} : { source }),
+ })),
);
// The REST/GraphQL transport span owns request and quota metadata.
const request: GitHubRequestPolicy["Service"]["request"] = Effect.fnUntraced(function* <A, E, R>(
input: GitHubRequest,
- send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
+ send: (
+ headers: Readonly<Record<string, string>>,
+ source: GitHubCredentials.GitHubCredentialSource | undefined,
+ ) => Effect.Effect<GitHubAnswer<A>, E, R>,
) {
const host = normalizeHost(input.host);
const context = { host, operation: input.operation };
@@ -321,7 +349,7 @@ export const make = Effect.gen(function* () {
const settle = Effect.fnUntraced(function* (
lease: number,
answer: GitHubAnswer<A>,
- token: Redacted.Redacted<string>,
+ held: ChosenCredential,
) {
yield* quota.observe(host, answer.headers);
yield* Effect.annotateCurrentSpan({
@@ -346,11 +374,14 @@ export const make = Effect.gen(function* () {
}
case "Unauthorized":
// The source may hold a newer token than the one that was refused.
- yield* appSignIn.invalidate(host, Redacted.value(token));
+ yield* appSignIn.invalidate(host, Redacted.value(held.token));
yield* credentials.invalidate(host);
return yield* new GitHubApiAuthenticationError(context);
case "NotFound":
- return yield* new GitHubApiNotFoundError(context);
+ return yield* new GitHubApiNotFoundError({
+ ...context,
+ ...(held.source === undefined ? {} : { credential: held.source }),
+ });
case "Failed":
return yield* new GitHubApiResponseError({
...context,
@@ -380,10 +411,10 @@ export const make = Effect.gen(function* () {
);
// One deadline covers the headers and the body: a host that answers headers and then
// stalls must not hold a shared slot for undici's own five-minute body timeout.
- const answer = yield* send({
- ...REQUEST_HEADERS,
- authorization: `Bearer ${Redacted.value(held.token)}`,
- }).pipe(
+ const answer = yield* send(
+ { ...REQUEST_HEADERS, authorization: `Bearer ${Redacted.value(held.token)}` },
+ held.source,
+ ).pipe(
Effect.timeoutOrElse({
duration: input.timeout ?? DEFAULT_TIMEOUT,
orElse: () =>
@@ -401,7 +432,7 @@ export const make = Effect.gen(function* () {
return { _tag: "Retry", with: personal.value } as const;
}
}
- return { _tag: "Done", value: yield* settle(lease, answer, held.token) } as const;
+ return { _tag: "Done", value: yield* settle(lease, answer, held) } as const;
}),
)
// The rate-limit scope follows the credential, so a pause on one account never blocks another.
diff --git a/packages/source-control-github/src/server/gitHubGraphQlClient.ts b/packages/source-control-github/src/server/gitHubGraphQlClient.ts
index 32198ad0b02..7030abb1742 100644
--- a/packages/source-control-github/src/server/gitHubGraphQlClient.ts
+++ b/packages/source-control-github/src/server/gitHubGraphQlClient.ts
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
import { dual } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
import * as Headers from "effect/http/Headers";
@@ -11,9 +12,13 @@ import { GraphQLClientError, GraphQLMiddleware, GraphQLProtocol } from "effect/g
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
+import * as GitHubCredentials from "./GitHubCredentials.ts";
import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
+/** Added to the answer, never sent: names the credential an errored answer was given to. */
+const CREDENTIAL_SOURCE_HEADER = "x-t3code-credential-source";
+const isCredentialSource = Schema.is(GitHubCredentials.GitHubCredentialSource);
/** One client serves all hosts; each call must supply its target. */
export class GitHubGraphQlTarget extends Context.Service<
@@ -67,7 +72,7 @@ export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<
resource: "graphql",
allowReserve: target.allowReserve ?? (yield* SourceControlRateLimit.Interactive),
},
- (headers) =>
+ (headers, source) =>
next({ ...request, headers: Headers.setAll(request.headers, headers) }).pipe(
Effect.map((answer) => {
const status = answer.status;
@@ -84,7 +89,14 @@ export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<
? { _tag: "RateLimited" as const, status, headers: responseHeaders }
: {
_tag: "Ok" as const,
- value: answer,
+ // The source is local; never trust one GitHub's answer carries.
+ value: {
+ ...answer,
+ headers:
+ source === undefined
+ ? Headers.remove(responseHeaders, CREDENTIAL_SOURCE_HEADER)
+ : Headers.set(responseHeaders, CREDENTIAL_SOURCE_HEADER, source),
+ },
withheld,
status,
headers: responseHeaders,
@@ -223,8 +235,15 @@ const fromClientError = (
host: normalizeHost(target.host),
operation: target.operation,
};
+ const credential = Option.filter(
+ Headers.get(reason.headers ?? Headers.empty, CREDENTIAL_SOURCE_HEADER),
+ isCredentialSource,
+ );
return isNotFoundOnly(error)
- ? new GitHubRequestPolicy.GitHubApiNotFoundError(context)
+ ? new GitHubRequestPolicy.GitHubApiNotFoundError({
+ ...context,
+ ...(Option.isSome(credential) ? { credential: credential.value } : {}),
+ })
: new GitHubRequestPolicy.GitHubApiResponseError({
...context,
status: reason.status ?? 200,