Skip to content

Commit 6fe4e11

Browse files
authored
fix(gateway): reuse verified GitHub profiles during outages (#128833)
1 parent e1a7008 commit 6fe4e11

3 files changed

Lines changed: 194 additions & 37 deletions

File tree

‎src/gateway/github-user-identity.test.ts‎

Lines changed: 131 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js
33
import {
44
ensureProfileForTailscaleIdentity,
55
getUserProfileListItem,
6+
syncGitHubIdentity,
67
} from "../state/user-profiles.js";
78
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
89
import { ControlUiGitHubError } from "./control-ui-github-api.js";
@@ -15,6 +16,17 @@ function githubResponse(body: unknown, status = 200, headers: Record<string, str
1516
});
1617
}
1718

19+
function githubBodyReadFailure() {
20+
return new Response(
21+
new ReadableStream({
22+
start(controller) {
23+
controller.error(new Error("body read failed"));
24+
},
25+
}),
26+
{ status: 200 },
27+
);
28+
}
29+
1830
function accessAssertion(issuer: unknown): string {
1931
const payload = Buffer.from(JSON.stringify({ iss: issuer })).toString("base64url");
2032
return `header.${payload}.signature`;
@@ -250,6 +262,23 @@ describe("authenticated GitHub identity sync", () => {
250262
emails: ["[email protected]"],
251263
githubIdentity: { login: "steipete" },
252264
});
265+
266+
fetchMock
267+
.mockResolvedValueOnce(
268+
githubResponse({
269+
id: 58493,
270+
271+
idp: { type: "github" },
272+
}),
273+
)
274+
.mockResolvedValueOnce(githubResponse({ id: 58493, login: "steipete-renamed" }));
275+
await expect(cloudflareSync({})?.()).resolves.toMatchObject({
276+
profileId: result!.profileId,
277+
});
278+
expect(getUserProfileListItem(result!.profileId).githubIdentity).toMatchObject({
279+
login: "steipete-renamed",
280+
});
281+
expect(fetchMock).toHaveBeenCalledTimes(4);
253282
});
254283
});
255284

@@ -352,39 +381,116 @@ describe("authenticated GitHub identity sync", () => {
352381
"x-ratelimit-remaining": "0",
353382
}),
354383
},
384+
{ name: "GitHub upstream failure", githubResult: githubResponse({}, 503) },
355385
{ name: "GitHub network failure", githubError: new Error("network unavailable") },
356-
])("preserves prior identity after a $name", async ({ githubResult, githubError }) => {
357-
await withOpenClawTestState({ scenario: "minimal" }, async () => {
358-
const fetchMock = vi
359-
.spyOn(globalThis, "fetch")
360-
.mockResolvedValueOnce(
386+
])(
387+
"reattaches the exact cached verified identity after a $name",
388+
async ({ githubResult, githubError }) => {
389+
await withOpenClawTestState({ scenario: "minimal" }, async () => {
390+
const fetchMock = vi
391+
.spyOn(globalThis, "fetch")
392+
.mockResolvedValueOnce(
393+
githubResponse({
394+
id: 58493,
395+
396+
idp: { type: "github" },
397+
}),
398+
)
399+
.mockResolvedValueOnce(githubResponse({ id: 58493, login: "steipete" }));
400+
const first = await cloudflareSync({})?.();
401+
fetchMock.mockResolvedValueOnce(
361402
githubResponse({
362403
id: 58493,
363404
364405
idp: { type: "github" },
365406
}),
366-
)
367-
.mockResolvedValueOnce(githubResponse({ id: 58493, login: "steipete" }));
368-
const first = await cloudflareSync({})?.();
369-
fetchMock.mockResolvedValueOnce(
370-
githubResponse({
371-
id: 58493,
372-
373-
idp: { type: "github" },
374-
}),
375-
);
376-
if (githubError) {
377-
fetchMock.mockRejectedValueOnce(githubError);
378-
} else {
379-
fetchMock.mockResolvedValueOnce(githubResult!);
380-
}
407+
);
408+
if (githubError) {
409+
fetchMock.mockRejectedValueOnce(githubError);
410+
} else {
411+
fetchMock.mockResolvedValueOnce(githubResult!);
412+
}
381413

382-
await expect(cloudflareSync({})?.()).rejects.toThrow();
383-
expect(getUserProfileListItem(first!.profileId).githubIdentity).toMatchObject({
384-
login: "steipete",
414+
await expect(cloudflareSync({ principal: "[email protected]" })?.()).resolves.toEqual(first);
415+
expect(getUserProfileListItem(first!.profileId).githubIdentity).toMatchObject({
416+
login: "steipete",
417+
});
418+
expect(fetchMock).toHaveBeenCalledTimes(4);
385419
});
386-
});
387-
});
420+
},
421+
);
422+
423+
it.each([
424+
{ name: "malformed GitHub response", githubStatus: 200, expectedStatus: 502, malformed: true },
425+
{
426+
name: "GitHub body read failure",
427+
githubStatus: 200,
428+
expectedStatus: 502,
429+
bodyReadFailure: true,
430+
},
431+
{ name: "non-retryable GitHub request", githubStatus: 400, expectedStatus: 502 },
432+
{ name: "unauthorized GitHub account", githubStatus: 401 },
433+
{ name: "GitHub permission denial", githubStatus: 403 },
434+
{ name: "deleted GitHub account", githubStatus: 404 },
435+
{ name: "different cached account", githubStatus: 429, accessAccountId: 99999 },
436+
{ name: "different cached email", githubStatus: 429, principal: "[email protected]" },
437+
{
438+
name: "email and account on different profiles",
439+
githubStatus: 429,
440+
accessAccountId: 99999,
441+
otherProfile: true,
442+
},
443+
{ name: "missing cached identity", githubStatus: 429, seedCache: false },
444+
])(
445+
"fails closed for a $name",
446+
async ({
447+
githubStatus,
448+
expectedStatus,
449+
malformed,
450+
bodyReadFailure,
451+
accessAccountId,
452+
principal,
453+
otherProfile,
454+
seedCache,
455+
}) => {
456+
await withOpenClawTestState({ scenario: "minimal" }, async () => {
457+
if (seedCache !== false) {
458+
syncGitHubIdentity({
459+
identity: { accountId: 58493, login: "steipete" },
460+
authenticationAlias: { kind: "email", email: "[email protected]" },
461+
});
462+
}
463+
if (otherProfile) {
464+
syncGitHubIdentity({
465+
identity: { accountId: 99999, login: "mallory" },
466+
authenticationAlias: { kind: "email", email: "[email protected]" },
467+
});
468+
}
469+
const authenticatedEmail = principal ?? "[email protected]";
470+
const fetchMock = vi
471+
.spyOn(globalThis, "fetch")
472+
.mockResolvedValueOnce(
473+
githubResponse({
474+
id: accessAccountId ?? 58493,
475+
email: authenticatedEmail,
476+
idp: { type: "github" },
477+
}),
478+
)
479+
.mockResolvedValueOnce(
480+
bodyReadFailure
481+
? githubBodyReadFailure()
482+
: malformed
483+
? new Response("{", { status: githubStatus })
484+
: githubResponse({}, githubStatus),
485+
);
486+
487+
await expect(cloudflareSync({ principal: authenticatedEmail })?.()).rejects.toMatchObject({
488+
statusCode: expectedStatus ?? githubStatus,
489+
} satisfies Partial<ControlUiGitHubError>);
490+
expect(fetchMock).toHaveBeenCalledTimes(2);
491+
});
492+
},
493+
);
388494

389495
it("redacts the Access assertion from network failures and retries on the same connection", async () => {
390496
await withOpenClawTestState({ scenario: "minimal" }, async () => {

‎src/gateway/github-user-identity.ts‎

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,19 @@ import type { IncomingHttpHeaders } from "node:http";
22
import { isRecord } from "@openclaw/normalization-core/record-coerce";
33
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
44
import type { GatewayAuthConfig } from "../config/types.gateway.js";
5+
import { resolveCachedGitHubIdentity } from "../state/user-profile-github-identity.js";
56
import { classifyTailscaleLogin } from "../state/user-profiles-tailscale-login.js";
67
import { syncGitHubIdentity } from "../state/user-profiles.js";
78
import { normalizeGitHubLogin } from "../utils/github-login.js";
89
import type { GatewayAuthResult } from "./auth.js";
910
import {
1011
ControlUiGitHubError,
12+
fetchGitHubApi,
1113
fetchGitHubJson,
1214
GITHUB_API_ORIGIN,
1315
GITHUB_REQUEST_TIMEOUT_MS,
1416
readBoundedResponse,
17+
readGitHubJsonResponse,
1518
} from "./control-ui-github-api.js";
1619

1720
const CLOUDFLARE_ACCESS_USER_HEADER = "cf-access-authenticated-user-email";
@@ -142,18 +145,10 @@ async function resolveGitHubUserIdentityByLogin(
142145
return { accountId, login };
143146
}
144147

145-
async function resolveGitHubUserIdentityById(
148+
function resolveGitHubUserIdentityById(
146149
accountId: number,
147-
): Promise<ResolvedGitHubUserIdentity> {
148-
let payload: unknown;
149-
try {
150-
payload = await fetchGitHubJson(`${GITHUB_API_ORIGIN}/user/${accountId}`, fetch, undefined);
151-
} catch (error) {
152-
if (error instanceof ControlUiGitHubError) {
153-
throw error;
154-
}
155-
throw new ControlUiGitHubError(502, "GitHub request failed");
156-
}
150+
payload: unknown,
151+
): ResolvedGitHubUserIdentity {
157152
if (!isRecord(payload) || payload.id !== accountId) {
158153
throw new ControlUiGitHubError(502, "GitHub account id did not match");
159154
}
@@ -246,7 +241,35 @@ export function createAuthenticatedGitHubIdentitySync(params: {
246241
access.assertion,
247242
access.principal,
248243
);
249-
const identity = await resolveGitHubUserIdentityById(accessIdentity.accountId);
244+
let response: Response | undefined;
245+
let payload: unknown;
246+
try {
247+
response = await fetchGitHubApi(
248+
`${GITHUB_API_ORIGIN}/user/${accessIdentity.accountId}`,
249+
fetch,
250+
);
251+
payload = await readGitHubJsonResponse(response);
252+
} catch (error) {
253+
const retryable = response
254+
? response.status === 429 ||
255+
response.status >= 500 ||
256+
(error instanceof ControlUiGitHubError && error.statusCode === 429)
257+
: !(error instanceof ControlUiGitHubError);
258+
if (retryable) {
259+
// Retry failures may reuse only the exact verified email + immutable-account binding.
260+
const cached = resolveCachedGitHubIdentity({
261+
accountId: accessIdentity.accountId,
262+
email: access.principal,
263+
});
264+
if (cached) {
265+
return cached;
266+
}
267+
}
268+
throw error instanceof ControlUiGitHubError
269+
? error
270+
: new ControlUiGitHubError(502, "GitHub request failed");
271+
}
272+
const identity = resolveGitHubUserIdentityById(accessIdentity.accountId, payload);
250273
const profile = syncGitHubIdentity({
251274
identity,
252275
authenticationAlias: { kind: "email", email: access.principal },

‎src/state/user-profile-github-identity.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,34 @@ function selectStoredGitHubIdentities(
6060
);
6161
}
6262

63+
export function resolveCachedGitHubIdentity(
64+
params: { accountId: number; email: string },
65+
options: OpenClawStateDatabaseOptions = {},
66+
): { profileId: string; updatedAt: number } | undefined {
67+
const email = params.email.trim().toLowerCase();
68+
if (!email || !Number.isSafeInteger(params.accountId) || params.accountId <= 0) {
69+
return undefined;
70+
}
71+
const database = openOpenClawStateDatabase(options);
72+
ensureUserProfilesSchema(options, database);
73+
const { db } = database;
74+
const alias = executeSqliteQueryTakeFirstSync(
75+
db,
76+
userProfilesDb(db)
77+
.selectFrom("user_profile_emails")
78+
.select("profile_id")
79+
.where("email", "=", email),
80+
);
81+
const profile = alias ? selectResolvedUserProfileById(db, alias.profile_id) : undefined;
82+
if (!profile) {
83+
return undefined;
84+
}
85+
const identity = selectStoredGitHubIdentities(db, [profile.id]).get(profile.id);
86+
return identity?.accountId === params.accountId
87+
? { profileId: profile.id, updatedAt: profile.updated_at }
88+
: undefined;
89+
}
90+
6391
function deleteProfileGitHubIdentities(
6492
db: DatabaseSync,
6593
profileIds: readonly string[],

0 commit comments

Comments
 (0)