Skip to content

Commit 97a2142

Browse files
authored
fix(gateway): explain why Vertex needs another sign-in (#7680)
* fix(gateway): explain why Vertex needs another sign-in Signed-off-by: Jalil <reachjalil@gmail.com> * test(gateway): keep Vertex connected through transient renewal failures Signed-off-by: Jalil <reachjalil@gmail.com> --------- Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent 4df2fa9 commit 97a2142

4 files changed

Lines changed: 57 additions & 8 deletions

File tree

‎ee/apps/gateway/src/credentials/oauth-refresh.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,17 @@ export type OauthRefreshStore = {
3434
recordRefreshFailure(input: { lock: RefreshLock; error: string | null; permanent: boolean; now: Date }): Promise<boolean>
3535
}
3636

37+
export type GoogleRenewalReason = "invalid_rapt" | "invalid_grant"
38+
39+
export function googleRenewalReason(row: Pick<CredentialRow, "kind" | "status"> & { last_error?: string | null }): { googleReason?: GoogleRenewalReason } {
40+
if (row.kind === "oauth_google" && row.status === "refresh_failed"
41+
&& (row.last_error === "invalid_rapt" || row.last_error === "invalid_grant")) return { googleReason: row.last_error }
42+
return {}
43+
}
44+
3745
export type OauthRefreshOutcome =
3846
| { kind: "refreshed"; credential: OauthCredentialRow }
39-
| { kind: "auth_required" }
47+
| { kind: "auth_required"; googleReason?: GoogleRenewalReason }
4048
| { kind: "configuration_required" }
4149
| { kind: "retry"; reason: "refresh_busy" | "refresh_unavailable" | "credential_changed" }
4250

@@ -220,13 +228,13 @@ export function createOauthRefresher(deps: {
220228
const clock = input.clock ?? (() => new Date(input.now.getTime() + Math.floor(performance.now() - started)))
221229
const scope = { credentialId: input.credential.id, provider: input.provider, subject: input.subject, authorization: input.authorization }
222230
const row = await deps.store.reloadCredential(scope)
223-
if (!row || row.status !== "active") return { kind: "auth_required" }
231+
if (!row || row.status !== "active") return { kind: "auth_required", ...(row && googleRenewalReason(row)) }
224232
if (isAdminRepairableKind(row.kind) && row.last_error === "invalid_client") return { kind: "configuration_required" }
225233
if (!row.expires_at || !Number.isFinite(row.expires_at.getTime())) return { kind: "auth_required" }
226234
if (canReuseOauthToken(row, clock())) return { kind: "refreshed", credential: row }
227235
const latest = async (reason: "refresh_busy" | "refresh_unavailable" | "credential_changed"): Promise<OauthRefreshOutcome> => {
228236
const winner = await deps.store.reloadCredential(scope)
229-
if (!winner || winner.status !== "active") return { kind: "auth_required" }
237+
if (!winner || winner.status !== "active") return { kind: "auth_required", ...(winner && googleRenewalReason(winner)) }
230238
if (isAdminRepairableKind(winner.kind) && winner.last_error === "invalid_client") return { kind: "configuration_required" }
231239
if (!winner.expires_at || !Number.isFinite(winner.expires_at.getTime())) return { kind: "auth_required" }
232240
const now = clock()

‎ee/apps/gateway/src/gateway.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -874,11 +874,13 @@ export function registerGatewayRoutes(api: Hono<GatewayEnv>, input: GatewayRoute
874874
const response = gatewayError(
875875
401,
876876
"openwork_auth_required",
877-
`Connect your ${provider.provider_id} account in OpenWork to use this provider (${credential.reason === "missing" ? "no credential" : `credential ${credential.reason}`}).`,
877+
credential.googleReason === "invalid_rapt" ? "Google requires you to sign in again. Reconnect your Vertex account in My Library."
878+
: credential.googleReason === "invalid_grant" ? "Google no longer accepts this sign-in. Reconnect your Vertex account in My Library."
879+
: `Connect your ${provider.provider_id} account in OpenWork to use this provider (${credential.reason === "missing" ? "no credential" : `credential ${credential.reason}`}).`,
878880
{ provider_id: provider.id, credential_set_id: selection.row.credentialSet.id },
879881
)
880882
response.headers.set("x-openwork-auth-required", "1")
881-
return reject(response, "member_auth_required", "Member credential required")
883+
return reject(response, "member_auth_required", `Member credential required (${credential.googleReason ?? credential.reason})`)
882884
}
883885
case "configuration_required": {
884886
const client = resolved.family === "microsoft_foundry" || liteLlmEntraScope(provider) !== null ? "Microsoft Entra ID app registration (check that its client secret has not expired)" : "Google OAuth client"

‎ee/apps/gateway/src/provider-credentials.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ export { pickInferenceApiKeyFromMap as pickApiKeyFromMap } from "@openwork-ee/ga
55
import { parseGatewayProviderSecret } from "@openwork/types/den/gateway"
66
import type { GatewayAwsKeysSecret, GatewayProviderCredentialKind } from "@openwork/types/den/gateway"
77
import type { MintAwsRoleCredentials, MintGcpAccessToken } from "@openwork-ee/gateway-upstreams"
8-
import { hasRefreshToken, isAdminRepairableKind, isRefreshableCredentialKind, needsOauthRefresh } from "./credentials/oauth-refresh.js"
8+
import { googleRenewalReason, type GoogleRenewalReason, hasRefreshToken, isAdminRepairableKind, isRefreshableCredentialKind, needsOauthRefresh } from "./credentials/oauth-refresh.js"
99
import type { RefreshMemberToken } from "./credentials/oauth-refresh.js"
1010
import { loadGatewayAccessFromDb, sameGatewaySelection, selectGatewayGrant } from "./provider-access.js"
1111
import type { GatewayAccessScope, GatewayGrantSelection } from "./provider-access.js"
@@ -34,7 +34,7 @@ type MaterializedCredential =
3434
| { kind: "feature_disabled" }
3535
| { kind: "secret"; credentialId: CredentialId; credentialKind: GatewayProviderCredentialKind; secret: string }
3636
| { kind: "aws_keys"; credentialId: CredentialId; credentialKind: "aws_keys" | "aws_sso"; awsKeys: GatewayAwsKeysSecret }
37-
| { kind: "auth_required"; credentialId: CredentialId | null; reason: "missing" | "expired" | "inactive" | "refresh_failed" }
37+
| { kind: "auth_required"; credentialId: CredentialId | null; reason: "missing" | "expired" | "inactive" | "refresh_failed"; googleReason?: GoogleRenewalReason }
3838
| { kind: "configuration_required"; credentialId: CredentialId }
3939
| { kind: "org_credential_missing" }
4040
| { kind: "org_credential_expired"; credentialId: CredentialId }
@@ -147,6 +147,9 @@ export async function resolveUpstreamCredential(input: {
147147
consistency: liteLlmEntraScope(input.provider) !== null ? "primary" : undefined }
148148
let credential = await input.loadProviderCredential(lookup)
149149
if (!credential) return set.credential_mode === "member" ? { kind: "auth_required", credentialId: null, reason: "missing" } : { kind: "org_credential_missing" }
150+
if (set.credential_mode === "member" && credential.kind === "oauth_google" && credential.status === "refresh_failed") {
151+
return { kind: "auth_required", credentialId: credential.id, reason: "refresh_failed", ...googleRenewalReason(credential) }
152+
}
150153
if (credential.status !== "active") return inactive(credential.id)
151154
if (isAdminRepairableKind(credential.kind) && credential.last_error === "invalid_client") return { kind: "configuration_required", credentialId: credential.id }
152155
let parsed = parseSecret(credential)
@@ -168,7 +171,7 @@ export async function resolveUpstreamCredential(input: {
168171
if (set.credential_mode === "member" && isRefreshableCredentialKind(refreshKind) && parsed.kind === refreshKind && input.refreshMemberToken
169172
&& needsOauthRefresh(credential, hasRefreshToken(parsed), clock())) {
170173
const outcome = await input.refreshMemberToken({ credential: { ...credential, kind: refreshKind }, provider: { ...set, api_scope: apiScope }, authorization: lookup, subject, now: clock(), clock })
171-
if (outcome.kind === "auth_required") return { kind: "auth_required", credentialId: credential.id, reason: "refresh_failed" }
174+
if (outcome.kind === "auth_required") return { ...outcome, credentialId: credential.id, reason: "refresh_failed" }
172175
if (outcome.kind === "refreshed") {
173176
credential = outcome.credential
174177
parsed = parseSecret(credential)

‎ee/apps/gateway/test/litellm-entra-sign-in.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import type { OrganizationVariables } from "../src/middleware/org-context.js"
2222
// env.ts validates at import; nothing here touches a database.
2323
process.env.DATABASE_URL ??= "mysql://fixture:fixture@127.0.0.1:1/fixture"
2424
process.env.DEN_DB_ENCRYPTION_KEY ??= "fixture-encryption-key-0000000000000000"
25+
const { resolveUpstreamCredential } = await import("../src/provider-credentials.js")
2526
const { registerGatewayRoutes, gatewayPathPrefix, gatewayModelsPath } = await import("../src/gateway.js")
2627
const { createProviderCatalog } = await import("@openwork-ee/gateway-catalog")
2728

@@ -213,6 +214,41 @@ async function refresh(input: { secret: string; configuredScope: string | null;
213214
return { outcome, requests, current }
214215
}
215216

217+
test("Vertex keeps Google's sign-in reason across the first failed renewal and later model requests", async () => {
218+
for (const reason of ["invalid_rapt", "invalid_grant"] as const) {
219+
const secret = JSON.stringify({ accessToken: "old-google-access", refreshToken: "old-google-refresh" })
220+
const input = refreshInput(secret)
221+
const initial = { ...input.credential, kind: "oauth_google" as const }
222+
const memory = memoryStore(initial)
223+
const refresh = createOauthRefresher({ store: memory.store, tokenFetch: async () => Response.json({
224+
error: "invalid_grant", error_subtype: reason, error_description: "private provider text",
225+
}, { status: 400 }) })
226+
const resolve = () => resolveUpstreamCredential({
227+
provider: { id: providerId, organization_id: organizationId, provider_id: "google-vertex", status: "active", settings: {}, provider_config: {} },
228+
scope: input.authorization.scope, selection: input.authorization.selection, envNames: [], clock: () => now,
229+
loadProviderCredential: async () => memory.current(), refreshMemberToken: refresh,
230+
})
231+
const expected = { kind: "auth_required", credentialId, reason: "refresh_failed", googleReason: reason }
232+
assert.deepEqual(await resolve(), expected)
233+
assert.deepEqual(await resolve(), expected)
234+
}
235+
})
236+
237+
test("Vertex keeps a working grant during a temporary outage and renews it on the next request", async () => {
238+
const secret = JSON.stringify({ accessToken: "old-google-access", refreshToken: "old-google-refresh" })
239+
const input = refreshInput(secret)
240+
const credential = { ...input.credential, kind: "oauth_google" as const }
241+
const memory = memoryStore(credential)
242+
let calls = 0
243+
const renew = createOauthRefresher({ store: memory.store, tokenFetch: async () => ++calls === 1
244+
? Response.json({ error: "invalid_grant" }, { status: 503 })
245+
: Response.json({ access_token: "new-google-access", token_type: "Bearer", expires_in: 3600 }) })
246+
assert.deepEqual(await renew({ ...input, credential }), { kind: "retry", reason: "refresh_unavailable" })
247+
assert.equal(memory.current().status, "active")
248+
assert.equal((await renew({ ...input, credential })).kind, "refreshed")
249+
assert.equal(JSON.parse(memory.current().secret).refreshToken, "old-google-refresh")
250+
})
251+
216252
test("a LiteLLM member's token is renewed with the provider's configured API scope", async () => {
217253
const { outcome, requests, current } = await refresh({ secret: memberSecret(apiScope), configuredScope: apiScope, granted: apiScope })
218254
assert.equal(outcome.kind, "refreshed")

0 commit comments

Comments
 (0)