gcp-ai 0.1.2: accounts follow the Google subject, so a renamed email keeps its sign-in (#606)

An account is now identified by its Google subject (OIDC `sub`), not its email. When the email on a Google account changes, its saved ADC and Console credit cache stay matched to that account, and usage shows the current email. A sign-in for another subject that uses the same email gets a key of its own (email#hash). A new sign-in is staged in a `.adc-pending-` dir, and a lock across every managed ADC checks the subject is not registered already. Console identity is read from the page's own JSON (`extractConsoleIdentity`). No new host: userinfo was already called before.

By NGshiyu (#606), reviewed at b344aa1.

Run on the Mac mini with Bun 1.4.2, node 22 and HOME=$(mktemp -d), on b344aa1 merged with main 1a05a77:
- `node --test test/*.test.mjs` in packages/gcp-ai (with VERTEX_CHROME_PATH set to Playwright's Chromium): 75 tests. 72 pass, 0 fail, 3 skipped (Linux/Windows only).
- Whole repo `bun test` (with #599 and #596 merged in too): 4592 pass, 11 skip, 0 fail. `bun scripts/check.mjs`: exit 0.
- Broken by hand: turning off the subject branch in confirmAccount turns "Console subject matching accepts renamed emails" red (71/1).

Not tried: a real Google account whose email changed.
This commit is contained in:
拾瑜
2026-11-02 03:36:05 +08:00
committed by GitHub
parent 684e4757ad
commit c78f965f8d
16 changed files with 929 additions and 149 deletions
+19 -3
View File
@@ -46,7 +46,7 @@ One Chrome window opens. Approve the consent page there and the plugin closes th
- The first account goes straight to Google's consent page. Adding a second one starts on Google's account picker instead, in the same window.
- Add another account by clicking sign in again with a different Google account.
- The project is picked for you: the first of the account's projects with the Vertex AI API enabled.
- If the account already has an ADC here, nothing is added and your existing sign-in is left alone.
- If the account already has an ADC here, nothing is added and your existing sign-in is left alone. "Already here" is decided by Google's stable account ID (`sub`), not by email: after consent the new ADC's `sub` is compared with every ADC the plugin manages, so the same Google account under a changed email is still recognised. If an existing ADC's `sub` cannot be confirmed, the sign-in stops rather than guess.
## Credits
@@ -55,7 +55,7 @@ Google has no API for promotional credits, so the balance is read from the Cloud
## What it keeps where
- **Credentials**: never held by the plugin. gcloud writes them and prints tokens on demand.
- **ADC directories**: `<config>/gcp-ai/adc-<account>`, one per Google account. The plugin never writes gcloud's own directory. Two addresses that differ only in punctuation would share a directory name, so the second one gets a short hash of its address appended.
- **ADC directories**: `<config>/gcp-ai/adc-<account>`, one per Google account. The plugin never writes gcloud's own directory. Two addresses that differ only in punctuation would share a directory name, so the second one gets a short hash of its address appended (then a hash of its `sub`). Consent is first written to a private `adc-pending-*` directory and moved into place only after its `sub` is checked; that check and the move share a cross-process lock. A directory's name is storage only, never proof of whose account it is.
- **Chrome profile**: `<config>/gcp-auto-profile`.
- **Cache**: `<cache>/magpie/gcp-ai`.
@@ -68,7 +68,23 @@ Google has no API for promotional credits, so the balance is read from the Cloud
**"This browser or app may not be secure"?** Start the sign-in again from the row and use the window that opens. Nothing in it is automated.
**"That account was already signed in"?** Signing in adds an account; it does not refresh one. Use a different Google account.
**"Already signed in (same Google subject)"?** Signing in adds an account; it does not refresh one. The new consent and an existing ADC belong to the same Google account, even if the emails differ; the new credentials are removed and the original kept.
**"An existing ADC's Google subject could not be confirmed"?** One of the ADCs already here could not tell Google's `sub` (its token failed, or userinfo did not answer), so a duplicate cannot be ruled out and nothing is added. Restore that credential, or remove the stale account, and retry.
**Changed your Google account's email?** Nothing needs to be done. The account stays the same account in Magpie, under the address it was signed in with; its credits are read for the new address and the new address is shown beside it.
- Each usage refresh asks Google's userinfo endpoint, with the account's own token, for its current email and `sub`. Google: `sub` is "unique among all Google Accounts and never reused", and "a Google Account can have multiple email addresses at different points in time, but the `sub` value is never changed".
- The credits page is opened for the current email and the plugin checks the Google ID in Console's own page data against `sub`. A matching ID accepts the new email even while userinfo still returns the old one; a different ID is refused even when the emails match. Without IDs on the page the shown email must match.
- A refresh whose token answers with a different (or no) `sub` than the one saved is refused: that is another Google account.
- Saved per account: `googleSubject`, `consoleAccount` and `consoleSubject` (the confirmed current email and the `sub` it was confirmed for) and `credentialAccount` (the address gcloud keeps the credentials under, which does not follow a rename). `accountId` is not changed: it is the account's key in Magpie, which keeps the account's name, proxy, gateway key and quota history under it. The current email reaches Magpie as `usage().user`, which Magpie shows where it differs from the key.
- Console's ID fields are private page data, not a documented API; a page that names conflicting IDs is refused.
If Console's ID cannot be read and the shown email differs, you can map the saved address to the current one in the `gcp-ai` provider's `options` (or the plugin's options; the provider's win). Confirm first that both addresses are the same Google account: the map only picks the Console session, and cannot override a `sub` mismatch.
```json
{ "consoleAccountAliases": { "old@example.com": "new@example.com" } }
```
**Wrong account on the consent page?** Sign in again and pick the right one. Nothing that was already here is removed.
+63 -26
View File
@@ -1,7 +1,7 @@
import { readFile } from "node:fs/promises"
import { defaultProfile, validateProject } from "./lib/browser.mjs"
import { resolveIdentity, startLogin, tokenProvider, accountOf } from "./lib/credentials.mjs"
import { fetchCredits, usageOf } from "./lib/credits.mjs"
import { resolveIdentity, startLogin, tokenProvider, identityOf } from "./lib/credentials.mjs"
import { consoleAccountFor, fetchCredits, usageOf } from "./lib/credits.mjs"
import { testEndpoint } from "./lib/endpoint.mjs"
import { providerModels, seedModels } from "./lib/models.mjs"
@@ -29,7 +29,16 @@ function settings(provider = {}, auth = {}) {
location: auth.location || options.location || env.GOOGLE_VERTEX_LOCATION || "global",
billingAccount: auth.billingAccount || options.billingAccount || env.VERTEX_BILLING_ACCOUNT,
profile: auth.profile || options.profile || env.VERTEX_CHROME_PROFILE || defaultProfile(),
account: auth.accountId || auth.account || options.account || env.VERTEX_GCLOUD_ACCOUNT,
// The credential selector: gcloud keeps an account's credentials under the
// address it was signed in with, so it must not follow an email rename.
account: auth.credentialAccount || auth.accountId || auth.account || options.account || env.VERTEX_GCLOUD_ACCOUNT,
// The current Console address, which may differ from `account` after a
// rename; credits are read for it, verified by googleSubject.
consoleAccount: auth.consoleAccount,
googleSubject: auth.googleSubject,
// Explicit aliases: a fallback for a Console session whose email cannot be
// confirmed by subject (saved address -> current Console address).
consoleAccountAliases: options.consoleAccountAliases,
authMode: auth.authMode || options.authMode || env.VERTEX_GCLOUD_AUTH_MODE,
// Only the directory this plugin filed for an account, never a machine-wide
// CLOUDSDK_CONFIG: one variable would point every account at one ADC, and a
@@ -64,11 +73,6 @@ function geminiRoute(pathname, base) {
return GEMINI_ROUTE.test(pathname.slice(base.length))
}
// ADC records a project and a quota project, not who signed in, so a sign-in
// made in ADC mode is saved without an account id and the row reads "Signed
// in". The token can tell the host that account once; it is written back so
// later reads of the sign-in are labelled without asking Google again.
const named = new Set()
// One probe per project and location per process: the answer cannot change
// between two model calls in the same run, and the same run's later loads
// should not ask Google again.
@@ -84,15 +88,7 @@ async function endorse(identity, location, owner) {
tested.add(key)
}
async function label(client, auth, account) {
if (!account || auth.accountId === account) return
const key = `${auth.authMode ?? ""}/${account}`
if (named.has(key)) return
named.add(key)
try { await client?.auth?.set?.({ path: { id: ID }, body: { ...auth, accountId: account } }) } catch { named.delete(key) }
}
export const GoogleVertexAuthPlugin = async (input = {}) => {
export const GoogleVertexAuthPlugin = async (input = {}, pluginOptions = {}) => {
const client = input.client
let configured = {}
return {
@@ -147,7 +143,7 @@ export const GoogleVertexAuthPlugin = async (input = {}) => {
const login = await startLogin(options)
return {
url: "", method: "auto",
instructions: `A Chrome window opens on Google's consent page and you approve it there; when the plugin already has an account, it opens Google's add-account page first so you can pick which account this is. The plugin closes the window itself when gcloud finishes, so leave it open. An addition counts only when the account approved in the window and the account the new ADC belongs to are the same, and neither was here before; anything else is an overwrite and is removed again. The project is the first of the account's projects that already has the Vertex AI API enabled, chosen automatically; with no such project the sign-in fails instead, so create one and enable the API before trying again. The sign-in expires after ten minutes.`,
instructions: `A Chrome window opens on Google's consent page and you approve it there; when the plugin already has an account, it opens Google's add-account page first so you can pick which account this is. The plugin closes the window itself when gcloud finishes, so leave it open. Google must confirm the new ADC's email and stable subject (sub). A subject already present in a managed ADC is the same Google account even after an email change, so the new credentials are removed and the original ones are kept; if an existing ADC's subject cannot be confirmed, nothing is added. The project is the first of the account's projects that already has the Vertex AI API enabled, chosen automatically; with no such project the sign-in fails instead, so create one and enable the API before trying again. The sign-in expires after ten minutes.`,
async callback() {
try {
const identity = await login.result
@@ -165,7 +161,10 @@ export const GoogleVertexAuthPlugin = async (input = {}) => {
if (identity.cloudsdkConfig) record.cloudsdkConfig = identity.cloudsdkConfig
// startLogin names an ADC sign-in from its token; when even
// that fails the record still succeeds, just unnamed.
if (identity.account) record.accountId = identity.account
if (identity.accountId || identity.account) record.accountId = identity.accountId || identity.account
// Google's stable account ID, saved at sign-in so a later email
// change can be told apart from a different account.
if (identity.subject) record.googleSubject = identity.subject
return { ...record, ...(identity.warning ? { warning: identity.warning } : {}) }
} catch (error) {
return { type: "failed", error: error.message }
@@ -210,14 +209,52 @@ export const GoogleVertexAuthPlugin = async (input = {}) => {
const auth = await getAuth()
if (!auth) return { error: "GCP AI is not signed in", signIn: "kept" }
const options = settings(provider, auth)
// The row is named after this read as well, so a sign-in made before
// this naming existed is fixed on its next usage refresh.
if (!auth.accountId && auth.authMode === "adc" && auth.project) {
void tokenProvider(options)()
.then((token) => accountOf(token))
.then((account) => label(client, auth, account)).catch(() => {})
options.consoleAccountAliases ??= pluginOptions.consoleAccountAliases
// Validated even when Google can confirm the email by subject.
const mapped = consoleAccountFor(options.account, options.consoleAccountAliases)
const aliased = mapped?.toLowerCase() !== options.account?.toLowerCase()
const snapshot = JSON.stringify(auth)
// userinfo: the token's current email and its stable `sub`. A failed
// lookup only leaves the identity unconfirmed for this read.
const current = options.account || auth.authMode === "adc"
? await tokenProvider(options)().then(identityOf).catch(() => undefined) : undefined
// A different (or missing) subject is another Google account, never
// this one under a new email.
if (auth.googleSubject && current && current.subject !== auth.googleSubject) {
throw new Error("Google credentials no longer identify the saved account; remove it and sign in again")
}
return usageOf(await fetchCredits(options))
const saved = auth
if (current?.subject) {
// Console may know a newer email than userinfo: keep an address
// already confirmed for this same subject. The usage hook does not
// persist this derived label: client.auth.set is not a conditional
// write, so persisting here could resurrect a sign-out that races
// the refresh. Login already stores the stable subject and key.
options.consoleAccount = auth.consoleSubject === current.subject
? auth.consoleAccount || current.account : current.account
options.googleSubject = current.subject
// A sign-out or replacement while userinfo was pending wins.
if (JSON.stringify(await getAuth()) !== snapshot) {
return { error: "The GCP AI sign-in changed during the refresh; retry", signIn: "kept" }
}
}
if (aliased) options.consoleAccount = mapped
const credits = await fetchCredits(options)
// A browser read can outlive a sign-out or replacement: its result
// is dropped before any label is updated or balance returned.
if (JSON.stringify(await getAuth()) !== JSON.stringify(saved)) {
return { error: "The GCP AI sign-in changed during the refresh; retry", signIn: "kept" }
}
let user = saved.consoleAccount || current?.account || saved.accountId
// The Console page named its own subject: when it is this account's,
// the address it shows is this account's current email. Keep it in
// this usage result only; the host has no conditional auth.set API.
if (credits.consoleAccount && options.googleSubject && credits.googleSubject === options.googleSubject) {
user = credits.consoleAccount
}
// usage().user is how Magpie shows the account where it differs from
// the account's key; the key itself stays accountId.
return { ...usageOf(credits), ...(user ? { user } : {}) }
} catch (error) { return { error: error.message, signIn: "kept" } }
},
},
+32 -1
View File
@@ -484,7 +484,7 @@ function projectInConsole(waitForConsole = false) {
// page without the key has no answer at all and none is invented.
function accountInPage() {
const text = document.documentElement?.innerHTML ?? ""
const keyed = text.match(/"oPEP7c":"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})"/)?.[1]
const keyed = text.match(/"oPEP7c"\s*:\s*"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})"/)?.[1]
if (keyed && !/(\.gserviceaccount\.com|@system\.|noreply|no-reply)/i.test(keyed)) return keyed
return null
}
@@ -494,6 +494,37 @@ export async function extractAccount(page, { timeout = 20000 } = {}) {
try { return found ? await found.jsonValue() : undefined } finally { await found?.dispose().catch(() => {}) }
}
// Console's current-session JSON contains both its display email and Gaia ID.
// These are private page fields, not an OAuth API: accept only top-level
// identity records with corroborating IDs, never IDs in account-picker arrays
// or arbitrary text. Conflicting records fail closed if the page changes.
export async function extractConsoleIdentity(page, { timeout = 20000 } = {}) {
const account = await extractAccount(page, { timeout })
return page.evaluate((account) => {
if (location.origin !== "https://console.cloud.google.com") return { conflict: true }
const identities = []
for (const script of document.querySelectorAll('script[type="application/json"]')) {
let data
try { data = JSON.parse(script.textContent) } catch { continue }
if (!data || Array.isArray(data) || typeof data.oPEP7c !== "string") continue
if (!/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(data.oPEP7c)) continue
const ids = [data.W3Yyqf, data.S06Grb, data.qDCSke]
if (ids.every((id) => id === undefined)) continue
if (!ids.every((id) => typeof id === "string" && /^[0-9]{10,255}$/.test(id))) return { account, conflict: true }
if (new Set(ids).size !== 1) return { account, conflict: true }
identities.push({ account: data.oPEP7c, subject: ids[0] })
}
if (!identities.length) return { account }
const first = identities[0]
if ((account && first.account.toLowerCase() !== account.toLowerCase())
|| identities.some((identity) => identity.subject !== first.subject
|| identity.account.toLowerCase() !== first.account.toLowerCase())) {
return { account, conflict: true }
}
return first
}, account)
}
// One page visit answers both questions, so this waits for either signal and
// reads both from the same DOM rather than loading the Console a second time.
export async function readConsole(page, { timeout = 30000 } = {}) {
+137 -90
View File
@@ -1,11 +1,12 @@
import { execFile, spawn } from "node:child_process"
import { createHash } from "node:crypto"
import { existsSync } from "node:fs"
import { mkdir, mkdtemp, readFile, readdir, rename, rm, stat } from "node:fs/promises"
import { lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat } from "node:fs/promises"
import { homedir } from "node:os"
import { delimiter, dirname, join } from "node:path"
import { promisify } from "node:util"
import { configRoot, expandPath, home, openSignInWindow, validateProject } from "./browser.mjs"
import { take } from "./lock.mjs"
const execute = promisify(execFile)
const loginTimeout = 10 * 60 * 1000
@@ -205,17 +206,31 @@ export async function resolveIdentity(options = {}, run = runGcloud) {
// identity has no email. The token it prints can ask Google that question
// directly; the answer is the same account the token bills to. A failure here
// is not a credential failure: it only leaves the account unnamed.
export async function accountOf(token, request = fetch) {
export async function identityOf(token, request = fetch) {
try {
const response = await request("https://openidconnect.googleapis.com/v1/userinfo", {
headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(10000),
})
if (!response.ok) return undefined
const body = await response.json()
return typeof body.email === "string" ? validateAccount(body.email) : undefined
// `email` is the display label; `sub` is the stable identity used to
// reject a different Google account after an email rename or replacement.
// Keep a valid subject even when Google's response has no usable email:
// a successful response that names another account must not look offline.
const subject = typeof body?.sub === "string" && body.sub ? body.sub : undefined
if (typeof body?.email !== "string") return subject ? { subject } : {}
try {
return { account: validateAccount(body.email), ...(subject ? { subject } : {}) }
} catch {
return subject ? { subject } : {}
}
} catch { return undefined }
}
export async function accountOf(token, request = fetch) {
return (await identityOf(token, request))?.account
}
// Which projects the signed-in account could actually serve. Cloud Resource
// Manager lists the projects that are alive; Service Usage says whether Vertex
// AI is turned on in each. Billing is deliberately not consulted: whether a
@@ -411,6 +426,8 @@ export function adcDirectoryFor(account, root = adcRoot()) {
// already owns gets a short hash of the full address appended; the first
// account keeps the readable name.
const disambiguated = (account, root) => join(root, `adc-${adcSlug(account)}-${createHash("sha256").update(account.toLowerCase()).digest("hex").slice(0, 6)}`)
const subjectDirectory = (account, subject, root) => join(root, `adc-${adcSlug(account)}-sub-${createHash("sha256").update(subject).digest("hex")}`)
const accountKeyFor = (account, subject) => `${account}#${createHash("sha256").update(subject).digest("hex").slice(0, 12)}`
// Where this account's own ADC lives, whether or not it exists yet. The
// readable directory is read first, so the check costs nothing for the usual
@@ -453,11 +470,9 @@ export const isGcloudDefault = (directory) => expandPath(directory) === expandPa
const ADC_DIRS = "adc-"
// The Google accounts this plugin has already filed an ADC for, as the
// directories under its own root name them. A sign-in compares the account its
// new ADC belongs to against this: an account already here is an overwrite and
// is not recorded again. A directory that exists without an ADC file is not one
// of them — an interrupted run must not make its account look signed in.
// Inventory of managed ADC directories, used to choose the first/add-account
// consent page. These directory labels are NOT Google account identities.
// Duplicate detection resolves each credential's current subject separately.
//
// The machine's own gcloud ADC is deliberately not part of this set. It is a
// different credential in a different place, read by every other Google client
@@ -466,13 +481,19 @@ const ADC_DIRS = "adc-"
export async function knownAccounts(options = {}) {
const root = options.adcRoot ? expandPath(options.adcRoot) : adcRoot()
const known = new Set()
for (const name of await readdir(root).catch(() => [])) {
const names = await readdir(root).catch((error) => {
if (error.code === "ENOENT") return []
throw error
})
for (const name of names) {
if (!name.startsWith(ADC_DIRS)) continue
// A staging directory is one a sign-in made before it knew whose ADC it
// was writing. Its suffix is random, not an account, so counting it would
// add a name nobody can sign in as and let a later sign-in match it.
if (name.startsWith(`${ADC_DIRS}pending-`)) continue
if (await hasAdc({ cloudsdkConfig: join(root, name) })) known.add(name.slice(ADC_DIRS.length))
// Staging directories use a separate hidden prefix, so a legitimate
// account whose email starts with "pending-" remains discoverable.
const present = await lstat(join(root, name, "application_default_credentials.json")).then(() => true, (error) => {
if (error.code === "ENOENT" || error.code === "ENOTDIR") return false
throw error
})
if (present) known.add(name.slice(ADC_DIRS.length))
}
return known
}
@@ -485,6 +506,50 @@ async function adcOwner(options = {}) {
} catch { return undefined }
}
// Legacy directories keep their old email names after a rename. Resolve every
// managed ADC rather than deriving its location from the current email.
// An unreadable identity is unknown, never proof of a distinct account.
async function registeredSubject(subject, root) {
let unknown = false
for (const name of await knownAccounts({ adcRoot: root })) {
const directory = join(root, `${ADC_DIRS}${name}`)
const entry = await lstat(directory).catch(() => undefined)
if (!entry?.isDirectory() || entry.isSymbolicLink()
|| dirname(await realpath(directory)) !== await realpath(root)) {
unknown = true
continue
}
const owner = await tokenProvider({ authMode: "adc", cloudsdkConfig: directory })()
.then(identityOf).catch(() => undefined)
if (owner?.subject === subject) return directory
if (!owner?.subject) unknown = true
}
if (unknown) throw stopped("An existing ADC's Google subject could not be confirmed; no new account was added. Restore access to that credential or remove the stale account explicitly, then retry")
}
async function registeredEmail(account, root) {
for (const name of await knownAccounts({ adcRoot: root })) {
const directory = join(root, `${ADC_DIRS}${name}`)
const owner = await tokenProvider({ authMode: "adc", cloudsdkConfig: directory })()
.then(identityOf).catch(() => undefined)
if (owner?.account?.toLowerCase() === account.toLowerCase()) return true
}
return false
}
// Names only allocate storage. A collision does not mean the same account:
// the subject comparison must have finished before choosing a free directory.
async function availableAdcDirectory(account, subject, root) {
for (const directory of [adcDirectoryFor(account, root), disambiguated(account, root), subjectDirectory(account, subject, root)]) {
const occupied = await lstat(directory).then(() => true, (error) => {
if (error.code === "ENOENT") return false
throw error
})
if (!occupied) return directory
}
throw stopped("The ADC storage paths are occupied; existing files were kept and no new account was added")
}
// Google's own "add another account" page. Console is the fallback destination
// for a session without ADC consent; signInUrl replaces that destination with
// gcloud's consent URL whenever this run is creating credentials.
@@ -599,6 +664,9 @@ export async function startLogin(options = {}, openWindow = openSignInWindow) {
let createdDirectory = false
let chromeError
let adcEmail
let accountId
let googleIdentity
let releaseRegistration
// An existing directory is never removed, even if this run made its ADC.
// Conversely, an unnamed sign-in gets a unique directory that this run can
// safely remove or rename without touching another sign-in's files.
@@ -613,40 +681,21 @@ export async function startLogin(options = {}, openWindow = openSignInWindow) {
// window; the host can save its project once the caller supplies it.
if (pinned && wanted !== "gcloud") {
const found = await resolveIdentity({ ...options, authMode: "adc" })
const owner = await accountOf(await tokenProvider(found)())
if (!owner) throw stopped("The existing ADC was kept, but its Google account could not be confirmed; no account was recorded")
return { ...found, account: owner, creditsSession: "unavailable", warning: "Existing ADC imported; the Chrome Console session was not checked" }
const owner = await identityOf(await tokenProvider(found)())
if (!owner?.subject) throw stopped("The existing ADC was kept, but its Google subject could not be confirmed; no account was recorded")
return { ...found, ...owner, creditsSession: "unavailable", warning: "Existing ADC imported; the Chrome Console session was not checked" }
}
// Saving and reading ADC happens while the window is still open. A failure
// here leaves through the block below, whose finally closes it.
try {
if (creating) {
if (account) {
// Login writes one directory and it is always this plugin's own, named
// for the account. A directory the plugin didn't create — a
// CLOUDSDK_CONFIG the user set, gcloud's default — is read at most:
// pointing gcloud's consent flow at it overwrote another account's ADC
// while the sign-in said nothing had been added.
directory = await adcDirectoryToCreate(account, root)
if (isGcloudDefault(directory)) throw stopped("Cannot create sign-in credentials in the machine's default gcloud directory")
// An ADC this plugin already filed for the account is an overwrite
// rather than a new account: refusing here means no window opens and
// the file is never written a second time. The machine's own ADC does
// not count — it belongs to gcloud, is only ever read, and signing in
// adds this plugin's own credential beside it.
if (await hasAdc({ cloudsdkConfig: directory })) {
throw stopped("That account was already signed in and its ADC already existed, so no new account or ADC was added. Sign in again with a different Google account")
}
await mkdir(dirname(directory), { recursive: true, mode: 0o700 })
try {
await mkdir(directory, { mode: 0o700 })
createdDirectory = true
} catch (error) { if (error.code !== "EEXIST") throw error }
} else {
await mkdir(root, { recursive: true, mode: 0o700 })
directory = await mkdtemp(join(root, "adc-pending-"))
createdDirectory = true
}
// OAuth must identify the account before duplicate detection. Always
// stage consent in a fresh directory, even when an email was supplied.
// An existing email-named directory is never overwritten or treated as
// proof that this is the same Google account.
await mkdir(root, { recursive: true, mode: 0o700 })
directory = await mkdtemp(join(root, ".adc-pending-"))
createdDirectory = true
login = await beginAdcLogin({ ...options, cloudsdkConfig: directory })
}
const consentUrl = login ? await login.url : undefined
@@ -684,59 +733,38 @@ export async function startLogin(options = {}, openWindow = openSignInWindow) {
// ADC must not turn an overwrite into a new account record.
if (!login.file) {
await discard()
throw stopped("That account was already signed in and its ADC already existed, so no new account or ADC was added. Sign in again with a different Google account")
throw stopped("The staging ADC already existed; refusing to replace credentials, so no new account was added")
}
if (!(await hasAdc({ cloudsdkConfig: directory }))) {
await discard()
throw stopped("Google sign-in created no readable ADC, so no new account was added. Start the sign-in again")
}
adcEmail = await tokenProvider({ authMode: "adc", cloudsdkConfig: directory })()
.then((token) => accountOf(token)).then((email) => email?.toLowerCase()).catch(() => undefined)
if (!adcEmail) {
// An unnamed sign-in staged its ADC in a directory with a random
// suffix; keeping it would leave a refresh token on disk that nothing
// ever names again. A named sign-in's directory is the account's own,
// so its ADC is kept and only the row is left unwritten.
if (createdDirectory && !account) {
await discard()
throw stopped("The Google account identity could not be confirmed after consent, so the credentials this run wrote were removed; no new account was recorded. Start the sign-in again")
}
throw stopped("The ADC was kept, but the Google account identity could not be confirmed; no new account was recorded. Check the credentials before signing in again")
}
// Only accounts already filed under the plugin's own root count here.
// The machine's default ADC is independent: this sign-in may create the
// plugin's first ADC for that same email without touching the default.
// The account's own directory is asked rather than the snapshot's slug,
// which two different addresses can share. A named sign-in just wrote
// that directory itself, so only another directory can be a duplicate.
const existing = await adcDirectoryOwnedBy(adcEmail, root)
if (existing !== directory && await hasAdc({ cloudsdkConfig: existing })) {
await discard()
throw stopped(`${adcEmail} was already signed in, so no new ADC was added. Sign in again with a different Google account`)
// Keep Google's stable subject from the first login, before an email
// can change. Email alone cannot establish continuity across a rename.
googleIdentity = await tokenProvider({ authMode: "adc", cloudsdkConfig: directory })()
.then(identityOf).catch(() => undefined)
adcEmail = googleIdentity?.account.toLowerCase()
if (!adcEmail || !googleIdentity.subject) {
throw stopped("The Google account email and subject could not be confirmed after consent; no new account was recorded")
}
// Serialize subject comparison AND registration across processes. Two
// simultaneous logins with different email labels must not both add
// the same subject. Staging directories are excluded from the scan.
releaseRegistration = await take(`${root}.registration`, { timeout: limit })
const existing = await registeredSubject(googleIdentity.subject, root)
if (existing) throw stopped(`${adcEmail} was already signed in (same Google subject), so no new ADC was added. The existing credentials were kept`)
// Magpie also keys the host record by accountId. If another managed
// ADC currently owns this email under a different subject, keep both
// accounts distinct with a stable subject-derived suffix.
accountId = await registeredEmail(adcEmail, root)
? accountKeyFor(adcEmail, googleIdentity.subject) : adcEmail
if (cancelled) throw stopped("Google sign-in was stopped; no new account was saved")
// An explicit email is a user-selection constraint, not a dedup key.
// Without a verified subject for that hint, do not silently approve a
// different account on the person's behalf.
if (account && adcEmail !== account.toLowerCase()) {
await discard()
throw stopped(`The consent page approved ${adcEmail}, not ${account}; no new account or ADC was saved. Sign in again and choose ${account} on Google's consent page.`)
}
if (!account && createdDirectory) {
// The readable directory unless another account already owns it, in
// which case this one gets its own hashed name beside it.
const own = await adcDirectoryToCreate(adcEmail, root)
if (isGcloudDefault(own)) {
await discard()
throw stopped("Cannot move sign-in credentials into the machine's default gcloud directory")
}
// A concurrent sign-in may have registered the account since the
// snapshot. Even an empty existing folder belongs to an earlier run
// and is never replaced by this run's staging directory.
const exists = await stat(own).then(() => true, (error) => { if (error.code === "ENOENT") return false; throw error })
if (exists) {
await discard()
throw stopped(`${adcEmail} was already signed in or its ADC directory already exists, so no new account or ADC was added. Sign in again with a different Google account`)
}
await rename(directory, own)
directory = own
}
}
// A new ADC arrives with no project to serve yet. The one it is filed
// with is the first of the account's projects with Vertex AI already
@@ -769,6 +797,12 @@ export async function startLogin(options = {}, openWindow = openSignInWindow) {
}
}
let found
if (creating) {
if (cancelled) throw stopped("Google sign-in was stopped; no new account was saved")
const own = await availableAdcDirectory(adcEmail, googleIdentity.subject, root)
await rename(directory, own)
directory = own
}
try {
found = await resolveIdentity({
...options,
@@ -785,6 +819,7 @@ export async function startLogin(options = {}, openWindow = openSignInWindow) {
// repeating OAuth would only hit the duplicate-account guard next time.
return {
account: adcEmail, authMode: "adc", cloudsdkConfig: directory, creditsSession: "ready",
...(googleIdentity?.subject ? { subject: googleIdentity.subject } : {}),
warning: `ADC for ${adcEmail} was saved in ${directory}, but no Google Cloud project was selected. To finish registration without signing in again, set project to the project ID selected in Console, set cloudsdkConfig to this directory, and leave account unset.`,
}
}
@@ -794,11 +829,23 @@ export async function startLogin(options = {}, openWindow = openSignInWindow) {
let owner = found.account
if (!creating) {
const token = await tokenProvider(found)()
owner ??= found.authMode === "adc" ? await accountOf(token) : undefined
googleIdentity = await identityOf(token)
if (!googleIdentity?.subject) throw stopped("The Google subject could not be confirmed; no account was recorded")
owner ??= found.authMode === "adc" ? googleIdentity?.account : undefined
}
const identity = {
...found,
...(owner ? { account: owner } : {}),
...(accountId ? { accountId } : {}),
...(googleIdentity?.subject ? { subject: googleIdentity.subject } : {}),
}
const identity = owner ? { ...found, account: owner } : found
if (chromeError) return { ...identity, creditsSession: "unavailable", warning: chromeError.message }
return { ...identity, creditsSession: "ready" }
} catch (error) {
// This run owns only its staged/new ADC. Every identity, duplicate,
// cancellation or storage failure leaves pre-existing ADCs untouched.
if (creating) await discard()
throw error
} finally {
// The sign-in's window, whatever the outcome, is closed here: one window,
// opened once, and the person never has to close it. A gcloud still
@@ -808,7 +855,7 @@ export async function startLogin(options = {}, openWindow = openSignInWindow) {
login.child.kill("SIGKILL")
await login.done.catch(() => {})
}
await close()
try { await close() } finally { await releaseRegistration?.() }
}
})()
// The host may await the callback later. Retain failures as a result without
+67 -17
View File
@@ -1,7 +1,7 @@
import { createHash } from "node:crypto"
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"
import { dirname, join } from "node:path"
import { assertConsoleSession, cacheRoot, defaultProfile, expandPath, extractAccount, safeGoto, validateBillingAccount, validateProject, withPage } from "./browser.mjs"
import { assertConsoleSession, cacheRoot, defaultProfile, expandPath, extractConsoleIdentity, safeGoto, validateBillingAccount, validateProject, withPage } from "./browser.mjs"
import { take } from "./lock.mjs"
import { effectiveAuthMode, resolveProject, validateAccount } from "./credentials.mjs"
@@ -114,16 +114,45 @@ async function nextPage(page) {
// the wrong person is worse than no balance: it is a plausible wrong number on
// someone else's row. So every read that names an account checks that the page
// agrees, and refuses rather than report another account's credits.
async function confirmAccount(page, account) {
if (!account) return
const shown = await extractAccount(page, { timeout: 8000 })
async function confirmAccount(page, account, subject) {
if (!account && !subject) return
const identity = await extractConsoleIdentity(page, { timeout: 8000 })
const shown = identity.account
if (identity.conflict) throw new Error("Cloud Console returned conflicting account identity fields; refusing to report credits")
// Google userinfo can retain the old email while Console shows the renamed
// address. A matching page subject establishes identity despite that label.
// A different subject must be rejected even when the emails happen to match.
if (subject && identity.subject) {
if (identity.subject !== subject) throw new Error("Cloud Console is signed in to a different Google account (subject mismatch); refusing to report credits")
return identity
}
// A page that never named an account is not evidence that it named this one.
// A fallback to another authuser is exactly what the check is for, and it is
// silent: the URL still says this account while the page is another person's.
if (!shown) throw new Error(`Cloud Console did not show which account the credits belong to; refusing to report a balance that may be another account's. Sign in as ${account} in the Chrome profile and retry`)
if (!shown || !account) throw new Error("Cloud Console did not show which account the credits belong to with a verifiable identity; refusing to report a balance that may be another account's")
if (shown.toLowerCase() !== account.toLowerCase()) {
throw new Error(`Cloud Console is signed in as ${shown}, not ${account}; sign in as ${account} in the Chrome profile and retry`)
}
return { account: shown }
}
export function consoleAccountFor(account, aliases) {
if (aliases === undefined) return account
if (!aliases || typeof aliases !== "object" || Array.isArray(aliases)) {
throw new Error("consoleAccountAliases must be an object mapping saved account emails to current Console emails")
}
// Normalize both sides once so renamed emails and case differences select
// the same Console session without changing the saved credential account.
const normalized = new Map()
for (const [saved, current] of Object.entries(aliases)) {
const key = validateAccount(saved).toLowerCase()
const value = validateAccount(current).toLowerCase()
if (normalized.has(key)) throw new Error(`Duplicate consoleAccountAliases entry for ${key}`)
normalized.set(key, value)
}
if (!normalized.size) return account
if (!account) throw new Error("consoleAccountAliases requires a saved account email")
return normalized.get(validateAccount(account).toLowerCase()) ?? account
}
async function readPage(page, options) {
@@ -132,8 +161,9 @@ async function readPage(page, options) {
// assertConsoleSession below (which says a lapsed session is a lapsed
// session) and the table's own wait, whose timeout is the failure to report.
const wait = (fallback) => (Number(options.scrapeTimeout) > 0 ? Math.min(Number(options.scrapeTimeout), fallback) : fallback)
const account = options.billingAccount ? validateBillingAccount(options.billingAccount) : await discoverBillingAccount(page, options.project, options.account)
const source = `https://console.cloud.google.com/billing/${account}/credits/all?hl=en${options.account ? `&authuser=${encodeURIComponent(options.account)}` : ""}`
const consoleAccount = options.consoleAccount
const account = options.billingAccount ? validateBillingAccount(options.billingAccount) : await discoverBillingAccount(page, options.project, consoleAccount)
const source = `https://console.cloud.google.com/billing/${account}/credits/all?hl=en${consoleAccount ? `&authuser=${encodeURIComponent(consoleAccount)}` : ""}`
await safeGoto(page, source)
await page.waitForFunction(() => location.hostname === "accounts.google.com" || [...document.querySelectorAll("th, [role='columnheader']")].some((cell) => cell.innerText.trim() === "Remaining value"), undefined, { timeout: wait(45000) }).catch(() => {})
await assertConsoleSession(page, { timeout: wait(20000) })
@@ -141,7 +171,7 @@ async function readPage(page, options) {
// the error says which of the two waits ran out.
await page.waitForFunction(() => [...document.querySelectorAll("tbody tr, [role='row']")].some((row) => /\$\s*\d/.test(row.innerText)), undefined, { timeout: wait(30000) })
.catch(() => { throw new Error("Google Cloud Credits table was not found or is empty; the session may be expired, the page may still be loading, or its layout changed") })
await confirmAccount(page, options.account)
const confirmed = await confirmAccount(page, consoleAccount, options.googleSubject)
const tables = []
const seen = new Set()
for (let index = 0; index < 100; index++) {
@@ -150,7 +180,10 @@ async function readPage(page, options) {
if (seen.has(signature)) throw new Error("Credits pagination did not advance; refusing an incomplete balance")
seen.add(signature)
tables.push(...next)
if (!(await nextPage(page))) return { ...parseCreditTables(tables), billingAccount: account, source }
if (!(await nextPage(page))) return {
...parseCreditTables(tables), billingAccount: account, source,
...(confirmed?.subject ? { googleSubject: confirmed.subject, consoleAccount: confirmed.account } : {}),
}
await page.waitForFunction((before) => {
const tables = [...document.querySelectorAll("table, [role='grid'], [role='table']")].map((table) => ({
headers: [...table.querySelectorAll("thead th, [role='columnheader']")].map((cell) => cell.innerText),
@@ -185,10 +218,21 @@ export async function fetchCredits(options = {}) {
else settings.project = await resolveProject(settings, undefined, await effectiveAuthMode(settings))
if (settings.project) validateProject(settings.project)
if (settings.account) validateAccount(settings.account)
const mapped = consoleAccountFor(settings.account, settings.consoleAccountAliases)
settings.consoleAccount = mapped?.toLowerCase() !== settings.account?.toLowerCase()
? mapped : settings.consoleAccount || mapped
if (settings.consoleAccount) validateAccount(settings.consoleAccount)
// The Chrome profile alone does not tell two Google accounts apart: one
// profile can hold both, so each read also names the account whose cookies
// it used (and, when it has one, that account's own ADC directory).
const identity = JSON.stringify([expandPath(settings.profile), settings.project ?? "", settings.billingAccount ?? "", settings.account ?? "", settings.cloudsdkConfig ?? ""])
const identityParts = [expandPath(settings.profile), settings.project ?? "", settings.billingAccount ?? "", settings.account ?? "", settings.cloudsdkConfig ?? ""]
// Preserve existing caches unless an alias changes the selected Console
// session; an old email-mismatch error must not block the renamed account.
if (settings.consoleAccount?.toLowerCase() !== settings.account?.toLowerCase()) identityParts.push(settings.consoleAccount)
// A subject-verified request must not reuse legacy email-only balances or
// mismatch failures. Include the subject and validation version in its key.
if (settings.googleSubject) identityParts.push({ googleSubject: settings.googleSubject, identityVersion: 2 })
const identity = JSON.stringify(identityParts)
const digest = createHash("sha256").update(identity).digest("hex").slice(0, 24)
const file = join(cacheRoot(), "magpie", "gcp-ai", `credits-${digest}.json`)
// The cache is what keeps this from opening a browser on every poll, so both
@@ -200,14 +244,20 @@ export async function fetchCredits(options = {}) {
const ttl = Number(options.ttl ?? process.env.VERTEX_CREDITS_CACHE_TTL ?? 300)
if (!Number.isFinite(ttl) || ttl < 0) throw new Error("VERTEX_CREDITS_CACHE_TTL must be a nonnegative number of seconds")
const cached = async () => {
let data
try {
const data = JSON.parse(await readFile(file, "utf8"))
const age = Date.now() - Date.parse(data.failedAt ?? data.fetchedAt)
if (settings.force || !(age >= 0)) return undefined
if (data.failedAt) return age < (transient(data) ? transientTtl : failureTtl) * 1000 ? { ...data, cached: false } : undefined
const futureExpiry = !data.runsOutAt || Date.parse(data.runsOutAt) > Date.now()
if (age < ttl * 1000 && futureExpiry && data.currency === "USD" && Number.isFinite(data.remaining) && Number.isFinite(data.original) && Number.isFinite(data.usedPercent)) return { ...data, cached: true }
} catch {}
data = JSON.parse(await readFile(file, "utf8"))
} catch {
return undefined
}
if (data.googleSubject && data.googleSubject !== settings.googleSubject) {
throw new Error("Cached Google Cloud credits identify a different Google account; refusing to report that balance")
}
const age = Date.now() - Date.parse(data.failedAt ?? data.fetchedAt)
if (settings.force || !(age >= 0)) return undefined
if (data.failedAt) return age < (transient(data) ? transientTtl : failureTtl) * 1000 ? { ...data, cached: false } : undefined
const futureExpiry = !data.runsOutAt || Date.parse(data.runsOutAt) > Date.now()
if (age < ttl * 1000 && futureExpiry && data.currency === "USD" && Number.isFinite(data.remaining) && Number.isFinite(data.original) && Number.isFinite(data.usedPercent)) return { ...data, cached: true }
}
const failureTtl = Number(options.failureTtl ?? process.env.VERTEX_CREDITS_FAILURE_TTL ?? 1200)
if (!Number.isFinite(failureTtl) || failureTtl < 0) throw new Error("VERTEX_CREDITS_FAILURE_TTL must be a nonnegative number of seconds")
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-gcp-ai-auth",
"version": "0.1.1",
"version": "0.1.2",
"description": "Vertex AI models and Google Cloud promotional credits, signed with your own gcloud / ADC login",
"type": "module",
"main": "./index.mjs",
+277
View File
@@ -0,0 +1,277 @@
import "./network.mjs"
import assert from "node:assert/strict"
import { createHash } from "node:crypto"
import { mkdir, writeFile } from "node:fs/promises"
import { join } from "node:path"
import test from "node:test"
import plugin from "../index.mjs"
import { adcDirectoryFor, identityOf } from "../lib/credentials.mjs"
import { fakeGcloud } from "./gcloud.mjs"
// A Google Account whose email changed keeps its `sub`: Google documents `sub`
// as "unique among all Google Accounts and never reused" and says "a Google
// Account can have multiple email addresses at different points in time, but
// the sub value is never changed" (OpenID Connect, ID token claims). These
// tests pin how usage() reads quota for such an account.
const billingAccount = "AAAAAA-BBBBBB-CCCCCC"
async function fixture(t, mode = "adc") {
const gcloud = await fakeGcloud()
const originalFetch = globalThis.fetch
const cache = process.env.XDG_CACHE_HOME
process.env.XDG_CACHE_HOME = join(gcloud.directory, "cache")
t.after(async () => {
globalThis.fetch = originalFetch
if (cache === undefined) delete process.env.XDG_CACHE_HOME
else process.env.XDG_CACHE_HOME = cache
await gcloud.close()
})
const directory = adcDirectoryFor("old@example.com")
await mkdir(directory, { recursive: true })
await writeFile(join(directory, "application_default_credentials.json"), "{}")
const profile = join(gcloud.directory, "profile")
const saved = {
type: "oauth", authMode: mode, accountId: "old@example.com", project: "example-project",
cloudsdkConfig: directory, profile, billingAccount, access: "", refresh: "", expires: 0,
}
let auth = saved
const writes = []
const hooks = await plugin({ client: { auth: { set: async (value) => {
writes.push(value)
auth = value.body
} } } })
// A cached balance proves which Console identity and ADC directory the
// public usage hook selected, without starting Chrome or contacting Google.
// credentialAccount is the account the read is made with (the record's
// credentialAccount or accountId); the cache key names it.
async function balance(account, remaining = 7, failed = false, subject = "google-user-1", identity = {}, credentialAccount = saved.accountId, original = 10) {
// null: a record with no credential account yet (an unnamed sign-in).
const parts = [profile, saved.project, billingAccount, credentialAccount ?? "", directory]
if (account !== (credentialAccount ?? undefined)) parts.push(account)
if (subject) parts.push({ googleSubject: subject, identityVersion: 2 })
const digest = createHash("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 24)
const file = join(process.env.XDG_CACHE_HOME, "magpie", "gcp-ai", `credits-${digest}.json`)
await mkdir(join(process.env.XDG_CACHE_HOME, "magpie", "gcp-ai"), { recursive: true })
await writeFile(file, JSON.stringify(failed
? { error: "old cached email mismatch", failedAt: new Date().toISOString() }
: { currency: "USD", remaining, original, used: original - remaining, usedPercent: ((original - remaining) * 100) / original, fetchedAt: new Date().toISOString(), ...identity }))
}
return { gcloud, hooks, writes, saved, directory, balance, getAuth: async () => auth, replace: (value) => { auth = value } }
}
const userinfo = (body) => async () => ({ ok: true, json: async () => body })
test("a renamed account exposes its promotional-credit window to the host", async (t) => {
const f = await fixture(t)
f.replace({ ...f.saved, googleSubject: "google-user-1", credentialAccount: "old@example.com", consoleAccount: "old@example.com" })
globalThis.fetch = userinfo({ sub: "google-user-1", email: "old@example.com" })
await f.balance("old@example.com", 85.43, false, "google-user-1", {
googleSubject: "google-user-1", consoleAccount: "new@example.com",
}, f.saved.accountId, 100)
const usage = await f.hooks.auth.usage(f.getAuth)
assert.equal(usage.error, undefined)
assert.equal(usage.user, "new@example.com")
assert.equal(usage.balance, "$85.43 USD")
const window = usage.windows[0]
assert.equal(window.name, "Promotional Credits")
assert.ok(Math.abs(window.used - 14.57) < 0.001)
assert.match(window.display, /^\$85\.43 remaining \/ \$100\.00 USD(?: \(cached\))?$/)
assert.ok(Math.abs(window.amount - 14.57) < 0.001)
assert.equal(window.limit, 100)
assert.equal(window.unit, "USD")
})
test("userinfo keeps stable identity claims from successful responses", async () => {
assert.deepEqual(await identityOf("test-token", userinfo({ sub: "google-user-1", email: "new@example.com" })),
{ subject: "google-user-1", account: "new@example.com" })
assert.deepEqual(await identityOf("test-token", userinfo({ sub: "google-user-1" })), { subject: "google-user-1" })
assert.deepEqual(await identityOf("test-token", userinfo({})), {})
assert.equal(await identityOf("test-token", async () => ({ ok: false })), undefined)
})
test("login callback saves the Google subject before the first quota refresh", async (t) => {
const f = await fixture(t)
globalThis.fetch = userinfo({ sub: "google-user-1", email: "new@example.com" })
// Pinned ADC exercises the real authorize/callback path without opening
// Chrome or creating another credential for the fixture account.
await f.hooks.config({ provider: { "gcp-ai": { options: {
authMode: "adc", cloudsdkConfig: f.directory, project: f.saved.project,
} } } })
const authorization = await f.hooks.auth.methods[0].authorize()
const result = await authorization.callback()
assert.equal(result.type, "success")
assert.equal(result.accountId, "new@example.com")
assert.equal(result.googleSubject, "google-user-1")
assert.equal(result.cloudsdkConfig, f.directory)
assert.equal(f.writes.length, 0, "login returns a record for the host; it does not refresh quota")
f.replace({ ...result, type: "oauth" })
globalThis.fetch = userinfo({ sub: "another-google-user", email: "new@example.com" })
const usage = await f.hooks.auth.usage(f.getAuth)
assert.match(usage.error, /no longer identify the saved account/)
assert.equal(f.writes.length, 0, "even the first quota refresh must reject another subject")
})
for (const mode of ["adc", "gcloud"]) {
test(`${mode}: after a rename, quota is read for the new email under the unchanged Magpie account`, async (t) => {
const f = await fixture(t, mode)
const asked = []
globalThis.fetch = async (url, init) => {
asked.push([url, init.headers.authorization])
return { ok: true, json: async () => ({ sub: "google-user-1", email: "new@example.com" }) }
}
// An email-only failure cached for the old address must not block the
// renamed account; the subject-keyed read for the new address is used.
await f.balance("old@example.com", 1, true, null)
await f.balance("new@example.com")
const usage = await f.hooks.auth.usage(f.getAuth)
assert.equal(usage.error, undefined)
assert.equal(usage.balance, "$7.00 USD")
assert.equal(usage.user, "new@example.com", "the new email is shown through usage().user")
assert.equal(f.writes.length, 0, "usage must not persist a derived identity through a non-conditional host write")
assert.deepEqual(await f.getAuth(), f.saved, "the Magpie account key and auth record remain unchanged")
assert.equal((await f.hooks.auth.usage(f.getAuth)).balance, "$7.00 USD")
assert.equal(f.writes.length, 0, "repeated usage reads must not rewrite host authentication")
assert.equal(asked.length, 2)
assert.ok(asked.every(([url]) => url === "https://openidconnect.googleapis.com/v1/userinfo"))
// gcloud keeps a renamed account's credentials under the address it was
// signed in with, so the credential selector never follows the rename.
const calls = (await f.gcloud.calls()).filter((args) => args.includes("print-access-token"))
assert.ok(calls.every((args) => mode === "adc" ? args.includes("application-default") : args.includes("--account=old@example.com")))
})
}
test("an unnamed sign-in remains readable without a non-conditional auth write", async (t) => {
const f = await fixture(t)
f.replace({ ...f.saved, accountId: undefined })
globalThis.fetch = userinfo({ sub: "google-user-1", email: "old@example.com" })
// This first read has no credential account yet: the cache key says so.
await f.balance("old@example.com", 7, false, "google-user-1", {}, null)
const usage = await f.hooks.auth.usage(f.getAuth)
assert.equal(usage.error, undefined)
assert.equal((await f.getAuth()).accountId, undefined)
assert.equal((await f.hooks.auth.usage(f.getAuth)).user, "old@example.com")
assert.equal(f.writes.length, 0)
})
test("an unavailable userinfo service keeps the last confirmed Console email", async (t) => {
const f = await fixture(t)
f.replace({ ...f.saved, googleSubject: "google-user-1", consoleAccount: "new@example.com" })
globalThis.fetch = async () => { throw new Error("offline") }
await f.balance("new@example.com")
const usage = await f.hooks.auth.usage(f.getAuth)
assert.equal(usage.balance, "$7.00 USD")
assert.equal(usage.user, "new@example.com")
assert.equal(f.writes.length, 0)
})
test("Console can confirm a new email by subject while userinfo keeps returning the old one", async (t) => {
const f = await fixture(t)
const initial = { ...f.saved, googleSubject: "google-user-1", credentialAccount: "old@example.com", consoleAccount: "old@example.com" }
f.replace(initial)
globalThis.fetch = userinfo({ sub: "google-user-1", email: "old@example.com" })
const identity = { googleSubject: "google-user-1", consoleAccount: "new@example.com" }
await f.balance("old@example.com", 7, false, "google-user-1", identity)
const usage = await f.hooks.auth.usage(f.getAuth)
assert.equal(usage.error, undefined)
assert.equal(usage.user, "new@example.com")
assert.equal(usage.balance, "$7.00 USD")
assert.deepEqual(await f.getAuth(), initial, "Console display identity is returned without rewriting the host auth record")
// Later polls select the verified Console address; userinfo's older email
// does not overwrite it, and nothing is rewritten again.
await f.balance("new@example.com", 7, false, "google-user-1", identity)
assert.equal((await f.hooks.auth.usage(f.getAuth)).user, "new@example.com")
assert.equal(f.writes.length, 0)
globalThis.fetch = async () => { throw new Error("offline") }
assert.equal((await f.hooks.auth.usage(f.getAuth)).user, "new@example.com")
assert.equal(f.writes.length, 0)
})
test("a Console page of another subject is never taken as this account's new email", async (t) => {
const f = await fixture(t)
f.replace({ ...f.saved, googleSubject: "google-user-1", credentialAccount: "old@example.com", consoleAccount: "old@example.com" })
globalThis.fetch = userinfo({ sub: "google-user-1", email: "old@example.com" })
await f.balance("old@example.com", 7, false, "google-user-1", { googleSubject: "google-user-2", consoleAccount: "other@example.com" })
const usage = await f.hooks.auth.usage(f.getAuth)
assert.match(usage.error, /Cached Google Cloud credits identify a different Google account/)
assert.equal(usage.balance, undefined)
assert.equal(usage.windows, undefined)
assert.notEqual(usage.user, "other@example.com")
assert.equal((await f.getAuth()).consoleAccount, "old@example.com")
assert.equal(f.writes.length, 0)
})
test("a replacement during credits retrieval cannot inherit the old account's label or balance", async (t) => {
const f = await fixture(t)
f.replace({ ...f.saved, googleSubject: "google-user-1", credentialAccount: "old@example.com", consoleAccount: "old@example.com" })
globalThis.fetch = userinfo({ sub: "google-user-1", email: "old@example.com" })
await f.balance("old@example.com", 7, false, "google-user-1", {
googleSubject: "google-user-1", consoleAccount: "new@example.com",
})
// Read 1 is the hook's start (the record is complete, so nothing is written
// and not read again); read 2 is the check after the credits read.
let reads = 0
const usage = await f.hooks.auth.usage(async () => {
if (++reads === 2) f.replace(undefined)
return f.getAuth()
})
assert.match(usage.error, /sign-in changed/)
assert.equal(usage.balance, undefined)
assert.equal(f.writes.length, 0)
assert.equal(await f.getAuth(), undefined)
})
test("a different or missing Google subject cannot replace an established identity", async (t) => {
const f = await fixture(t)
f.replace({ ...f.saved, googleSubject: "google-user-1" })
await f.balance("new@example.com")
for (const body of [
{ sub: "another-google-user", email: "new@example.com" },
{ sub: "another-google-user" },
{ sub: "another-google-user", email: "not-an-email" },
{},
]) {
globalThis.fetch = userinfo(body)
const usage = await f.hooks.auth.usage(f.getAuth)
assert.match(usage.error, /no longer identify the saved account/)
assert.equal(usage.balance, undefined)
assert.equal(usage.windows, undefined)
assert.equal(f.writes.length, 0)
}
})
test("sign-out during identity lookup cannot recreate the account", async (t) => {
const f = await fixture(t)
globalThis.fetch = async () => {
f.replace(undefined)
return { ok: true, json: async () => ({ sub: "google-user-1", email: "new@example.com" }) }
}
assert.match((await f.hooks.auth.usage(f.getAuth)).error, /sign-in changed/)
assert.equal(f.writes.length, 0)
assert.equal(await f.getAuth(), undefined)
})
test("explicit Console aliases remain scoped to the original credential account", async (t) => {
const f = await fixture(t)
globalThis.fetch = userinfo({ sub: "google-user-1", email: "new@example.com" })
await f.balance("console@example.com", 4)
const provider = { options: { consoleAccountAliases: { "old@example.com": "console@example.com" } } }
assert.equal((await f.hooks.auth.usage(f.getAuth, provider)).balance, "$4.00 USD")
assert.equal((await f.hooks.auth.usage(f.getAuth, provider)).balance, "$4.00 USD")
})
test("a record renamed by an earlier plugin version keeps reading with its credential account", async (t) => {
// Shape of a record the previous implementation wrote: accountId moved to
// the new email, credentialAccount kept the original sign-in address.
const f = await fixture(t)
f.replace({ ...f.saved, accountId: "new@example.com", credentialAccount: "old@example.com",
consoleAccount: "new@example.com", consoleSubject: "google-user-1", googleSubject: "google-user-1" })
globalThis.fetch = userinfo({ sub: "google-user-1", email: "new@example.com" })
await f.balance("new@example.com")
const usage = await f.hooks.auth.usage(f.getAuth)
assert.equal(usage.error, undefined)
assert.equal(usage.balance, "$7.00 USD")
assert.equal((await f.getAuth()).accountId, "new@example.com", "an existing key is left as it is, never moved again")
assert.equal(f.writes.length, 0)
})
+136 -1
View File
@@ -4,7 +4,7 @@ import { mkdtemp, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import test from "node:test"
import { assertConsoleSession, chromeExecutable, closeKeptBrowsers as endKeptBrowsers, extractProjectId, extractAccount, openBrowser, routeAll, withPage } from "../lib/browser.mjs"
import { assertConsoleSession, chromeExecutable, closeKeptBrowsers as endKeptBrowsers, extractProjectId, extractAccount, extractConsoleIdentity, openBrowser, routeAll, withPage } from "../lib/browser.mjs"
// A kept browser is meant to outlive one read; a test that opens several must
// not leave them running behind it.
@@ -121,6 +121,67 @@ test("the signed-in account is only read from the Console's own keyed field", {
}
})
test("Console subject matching accepts renamed emails but rejects other accounts and ambiguous page data", { timeout: 40000, ...needsBrowser }, async (t) => {
const directory = await mkdtemp(join(tmpdir(), "vertex-console-subject-"))
const previousCache = process.env.XDG_CACHE_HOME
process.env.XDG_CACHE_HOME = directory
const browser = await openBrowser({ launchArgs, profile: join(directory, "profile"), headless: true })
t.after(async () => {
await browser.close()
if (previousCache === undefined) delete process.env.XDG_CACHE_HOME
else process.env.XDG_CACHE_HOME = previousCache
await rm(directory, { recursive: true, force: true })
})
const subject = "111000000000000000001"
const other = "111000000000000000002"
const record = (email, id) => ({ oPEP7c: email, W3Yyqf: id, S06Grb: id, qDCSke: id })
const json = (value) => `<script type="application/json">${JSON.stringify(value, null, 2)}</script>`
let identity = json(record("new@example.com", subject))
const table = '<table><thead><tr><th>Credit name</th><th>Status</th><th>Remaining value</th><th>Original value</th><th>Credit ID</th></tr></thead><tbody><tr><td>Benefit</td><td>Available</td><td>$12.00</td><td>$20.00</td><td>one</td></tr></tbody></table>'
await routeAll(browser.page, pageFor(() => identity + table))
const options = {
browser, profile: join(directory, "profile"), account: "old@example.com",
billingAccount: "AAAAAA-BBBBBB-CCCCCC",
}
// This is the old bug, including its cached failure. Adding the verified
// subject must bypass that failure without erasing any production cache.
await assert.rejects(fetchCredits(options), /signed in as new@example.com, not old@example.com/)
const verified = { ...options, googleSubject: subject }
const credits = await fetchCredits(verified)
assert.equal(credits.remaining, 12)
assert.equal(credits.googleSubject, subject)
assert.equal(credits["consoleAccount"], "new@example.com")
assert.deepEqual(await extractConsoleIdentity(browser.page), { account: "new@example.com", subject })
assert.equal((await fetchCredits(verified)).cached, true)
await assert.rejects(fetchCredits({ ...verified, googleSubject: other }), /subject mismatch/)
// Same email is insufficient when the page positively names another subject.
identity = json(record("old@example.com", other))
await assert.rejects(fetchCredits({ ...verified, force: true }), /subject mismatch/)
for (const ambiguous of [
json({ ...record("old@example.com", subject), S06Grb: other }),
json({ ...record("old@example.com", subject), qDCSke: undefined }),
json(record("old@example.com", subject)) + json(record("old@example.com", other)),
]) {
identity = ambiguous
await assert.rejects(fetchCredits({ ...verified, force: true }), /conflicting account identity/)
}
// Account chooser arrays and nested objects never prove the active identity.
for (const unrelated of [
[record("new@example.com", subject)],
{ accounts: [record("new@example.com", subject)] },
]) {
identity = json(unrelated)
await assert.rejects(fetchCredits({ ...verified, force: true }), /signed in as new@example.com, not old@example.com/)
}
identity = json({ oPEP7c: "new@example.com" })
await assert.rejects(fetchCredits({ ...verified, force: true }), /signed in as/)
identity = json({ oPEP7c: "old@example.com" })
const fallback = await fetchCredits({ ...verified, force: true })
assert.equal(fallback.remaining, 12)
assert.equal(fallback.googleSubject, undefined, "email fallback must not invent subject verification")
})
// Two accounts are two tabs of one Chrome, not two Chromes: the second read
// must land in the browser the first one left open.
test("a second read on one profile is a tab of the browser the first left open", { timeout: 60000, ...needsBrowser }, async () => {
@@ -208,6 +269,80 @@ test("Chrome credits scrape handles pagination, keeps cache isolated, and force
}
})
test("renamed Console emails use a resolved identity or explicit alias and keep cache isolation", { timeout: 30000, ...needsBrowser }, async () => {
const directory = await mkdtemp(join(tmpdir(), "vertex-browser-alias-"))
const previousCache = process.env.XDG_CACHE_HOME
let browser
try {
process.env.XDG_CACHE_HOME = directory
browser = await openBrowser({ profile: join(directory, "profile"), launchArgs })
let shown = "new@example.com"
let requests = 0
const selected = []
await routeAll(browser.page, async (request) => {
const url = new URL(request.url())
assert.equal(url.origin, "https://console.cloud.google.com")
if (!url.pathname.startsWith("/billing/")) return request.abort()
selected.push(url.searchParams.get("authuser"))
requests++
if (url.pathname === "/billing/linkedaccount") {
return request.fulfill({ body: '<a href="/billing/AAAAAA-BBBBBB-CCCCCC">Billing</a>' })
}
return request.fulfill({ body: `<!doctype html><script>var a={"oPEP7c":${JSON.stringify(shown)}}</script>
<table><thead><tr><th>Credit name</th><th>Status</th><th>Remaining value</th><th>Original value</th><th>Credit ID</th></tr></thead>
<tbody><tr><td>Benefit</td><td>Available</td><td>$12.00</td><td>$20.00</td><td>one</td></tr></tbody></table>` })
})
const options = {
browser, profile: join(directory, "profile"), project: "example-project",
authMode: "adc", account: "old@example.com", cloudsdkConfig: join(directory, "original-adc"),
}
await assert.rejects(fetchCredits(options), /signed in as new@example.com, not old@example.com/)
const afterFailure = requests
await assert.rejects(fetchCredits(options), /signed in as/)
assert.equal(requests, afterFailure)
const resolved = { ...options, consoleAccount: "new@example.com" }
selected.length = 0
assert.equal((await fetchCredits(resolved)).remaining, 12)
assert.deepEqual(selected, ["new@example.com", "new@example.com"])
const mapped = { ...options, consoleAccountAliases: { "old@example.com": "new@example.com" } }
selected.length = 0
const result = await fetchCredits({ ...mapped, force: true })
assert.equal(result.remaining, 12)
assert.equal(result.cached, false)
assert.deepEqual(selected, ["new@example.com", "new@example.com"])
assert.equal((await fetchCredits(mapped)).cached, true)
assert.equal(options.account, "old@example.com")
assert.equal(options.cloudsdkConfig, join(directory, "original-adc"))
assert.equal((await fetchCredits({ ...mapped, cloudsdkConfig: join(directory, "other-adc") })).cached, false)
assert.equal((await fetchCredits({
...mapped, account: "another-saved@example.com",
consoleAccountAliases: { "another-saved@example.com": "new@example.com" },
})).cached, false)
// An alias does not authorize a fallback to an unrelated browser account.
shown = "other@example.com"
await assert.rejects(fetchCredits({ ...mapped, force: true }), /signed in as other@example.com, not new@example.com/)
await assert.rejects(fetchCredits({ ...resolved, force: true }), /signed in as other@example.com, not new@example.com/)
shown = null
await assert.rejects(fetchCredits({ ...mapped, force: true }), /did not show which account/)
// Another credential account cannot inherit the first account's mapping.
shown = "new@example.com"
await assert.rejects(fetchCredits({ ...mapped, account: "second@example.com" }), /not second@example.com/)
// Changing the alias must not reuse either success or failure for the old one.
shown = "renamed-again@example.com"
const changed = await fetchCredits({ ...mapped, consoleAccountAliases: { "old@example.com": shown } })
assert.equal(changed.cached, false)
assert.equal(changed.remaining, 12)
// Removing the alias restores the original check, even with a cached success.
await assert.rejects(fetchCredits({ ...options, force: true }), /not old@example.com/)
} finally {
if (browser) await browser.close()
if (previousCache === undefined) delete process.env.XDG_CACHE_HOME
else process.env.XDG_CACHE_HOME = previousCache
await rm(directory, { recursive: true, force: true })
}
})
// A failed read is remembered, so a project that cannot read its credits does
// not open a browser on every usage poll: the cache is what stands in for a
// switch here, since asking again would cost a browser for the same answer.
Binary file not shown.

After

Width:  |  Height:  |  Size: 325 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 268 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

+138
View File
@@ -0,0 +1,138 @@
import "./network.mjs"
import assert from "node:assert/strict"
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"
import { join } from "node:path"
import test from "node:test"
import { adcDirectoryFor, startLogin } from "../lib/credentials.mjs"
import { fakeGcloud } from "./gcloud.mjs"
async function fixture(t) {
const gcloud = await fakeGcloud()
const root = join(gcloud.directory, ".config", "gcp-ai")
const originalFetch = globalThis.fetch
const identities = new Map()
const logins = []
globalThis.fetch = async (url, init) => {
assert.equal(url, "https://openidconnect.googleapis.com/v1/userinfo")
const identity = identities.get(init.headers.authorization.replace(/^Bearer /, ""))
return { ok: Boolean(identity), json: async () => identity }
}
t.after(async () => {
await Promise.all(logins.map((login) => login.close()))
globalThis.fetch = originalFetch
await gcloud.close()
})
const seed = async (email, token) => {
const directory = adcDirectoryFor(email, root)
await mkdir(directory, { recursive: true })
await writeFile(join(directory, "application_default_credentials.json"), "{}")
await writeFile(join(directory, ".fixture-account"), token)
return directory
}
const start = async (options = {}) => {
const login = await startLogin({ adcRoot: root, project: "example-project", ...options }, async () => ({
ended: new Promise(() => {}), close: async () => {},
}))
logins.push(login)
return login
}
const signIn = async (token, options = {}) => {
await gcloud.set({ approved: token })
return (await start(options)).result
}
const directories = async () => (await readdir(root)).filter((name) => name.startsWith("adc-")).sort()
return { gcloud, root, identities, seed, start, signIn, directories }
}
for (const existingEmail of ["old@example.com", "new@example.com"]) {
test(`same subject rejects a renamed login when the old ADC returns ${existingEmail}`, async (t) => {
const f = await fixture(t)
const oldDirectory = await f.seed("old@example.com", "old-token")
f.identities.set("old-token", { email: existingEmail, sub: "stable-subject" })
f.identities.set("new-token", { email: "new@example.com", sub: "stable-subject" })
const result = await f.signIn("new-token", { account: "new@example.com" })
assert.equal(result.project, undefined)
assert.match(result.warning, /already signed in \(same Google subject\)/)
assert.equal(await readFile(join(oldDirectory, "application_default_credentials.json"), "utf8"), "{}")
assert.deepEqual(await f.directories(), ["adc-old-example-com"])
})
}
test("same email with distinct subjects creates separate ADCs", async (t) => {
const f = await fixture(t)
const accounts = []
for (const subject of ["Subject", "subject", "third-subject"]) {
f.identities.set(subject, { email: "same@example.com", sub: subject })
const result = await f.signIn(subject)
assert.equal(result.project, "example-project")
assert.equal(result.subject, subject)
accounts.push(result)
}
// `sub` identifies the Google Account, compared exactly: three subjects are
// three accounts even though they share one email label. The host account
// key must be distinct too, or a later callback could overwrite the first.
assert.equal(new Set(accounts.map((a) => a.cloudsdkConfig)).size, 3)
assert.equal(new Set(accounts.map((a) => a.accountId)).size, 3)
assert.equal(accounts[0].accountId, "same@example.com")
assert.match(accounts[1].accountId, /^same@example\.com#[a-f0-9]{12}$/)
assert.match(accounts[2].accountId, /^same@example\.com#[a-f0-9]{12}$/)
for (const account of accounts) {
assert.ok(await readFile(join(account.cloudsdkConfig, "application_default_credentials.json")))
}
})
test("missing subject on a new login cannot register an email-only account", async (t) => {
const f = await fixture(t)
f.identities.set("new-token", { email: "new@example.com" })
const result = await f.signIn("new-token", { account: "new@example.com" })
assert.match(result.warning, /subject could not be confirmed/)
assert.deepEqual(await f.directories(), [])
})
for (const unavailable of [true, false]) {
test(`an existing ADC with ${unavailable ? "unavailable identity" : "missing subject"} blocks unverified registration`, async (t) => {
const f = await fixture(t)
const oldDirectory = await f.seed("old@example.com", "old-token")
if (!unavailable) f.identities.set("old-token", { email: "old@example.com" })
f.identities.set("new-token", { email: "new@example.com", sub: "new-subject" })
const result = await f.signIn("new-token")
assert.match(result.warning, /existing ADC's Google subject could not be confirmed/)
assert.doesNotMatch(result.warning, /already signed in/)
assert.equal(await readFile(join(oldDirectory, "application_default_credentials.json"), "utf8"), "{}")
assert.deepEqual(await f.directories(), ["adc-old-example-com"])
})
}
test("an email beginning with pending- remains discoverable for duplicate detection", async (t) => {
const f = await fixture(t)
const oldDirectory = await f.seed("pending-user@example.com", "old-token")
f.identities.set("old-token", { email: "pending-user@example.com", sub: "stable-subject" })
f.identities.set("new-token", { email: "renamed@example.com", sub: "stable-subject" })
const result = await f.signIn("new-token", { account: "renamed@example.com" })
assert.match(result.warning, /already signed in \(same Google subject\)/)
assert.equal((await readFile(join(oldDirectory, "application_default_credentials.json"))).toString(), "{}")
assert.deepEqual(await f.directories(), ["adc-pending-user-example-com"])
})
test("an empty email-named directory is a storage collision, not a duplicate identity", async (t) => {
const f = await fixture(t)
const oldDirectory = adcDirectoryFor("same@example.com", f.root)
await mkdir(oldDirectory, { recursive: true })
await writeFile(join(oldDirectory, "keep"), "not-an-account")
f.identities.set("new-token", { email: "same@example.com", sub: "new-subject" })
const result = await f.signIn("new-token")
assert.equal(result.project, "example-project")
assert.notEqual(result.cloudsdkConfig, oldDirectory)
assert.equal(await readFile(join(oldDirectory, "keep"), "utf8"), "not-an-account")
})
test("concurrent sign-ins register a subject only once", { timeout: 30000 }, async (t) => {
const f = await fixture(t)
f.identities.set("new-token", { email: "new@example.com", sub: "same-subject" })
await f.gcloud.set({ approved: "new-token" })
const logins = await Promise.all([f.start(), f.start()])
const results = await Promise.all(logins.map((login) => login.result))
assert.equal(results.filter((result) => result.project).length, 1)
assert.match(results.find((result) => !result.project).warning, /same Google subject/)
assert.deepEqual(await f.directories(), ["adc-new-example-com"])
})
+59 -10
View File
@@ -11,7 +11,7 @@ import { EventEmitter } from "node:events"
import { promisify } from "node:util"
import { accountOf, adcDirectoryFor, adcDirectoryOwnedBy, adcDirectoryToCreate, adcFile, adcSlug, beginAdcLogin, command, effectiveAuthMode, gcloudProgram, hasAdc, resolveAccount, resolveIdentity, resolveProject, runGcloud, startLogin, tokenProvider, windowsCommand } from "../lib/credentials.mjs"
import { fakeGcloud } from "./gcloud.mjs"
import { parseCreditTables, usageOf } from "../lib/credits.mjs"
import { consoleAccountFor, parseCreditTables, usageOf } from "../lib/credits.mjs"
import { availableModels, toProviderModels } from "../lib/models.mjs"
import { assertConsoleSession } from "../lib/browser.mjs"
import { main } from "../lib/fetch_credits.mjs"
@@ -20,6 +20,32 @@ const headers = ["Credit name", "Status", "Percent remaining", "Remaining value"
const row = (id, remaining, original = "$10.00", status = "Available", start = "July 15, 2026", end = "July 1, 2027") => ["Example benefit", status, "100%", remaining, original, "One-time", id, "All Google Cloud services", start, end]
const now = Date.parse("2026-10-18T12:00:00Z")
test("Console aliases are explicit, case-insensitive and scoped to the credential account", () => {
const aliases = { "OLD@example.com": "New@example.com" }
assert.equal(consoleAccountFor("old@example.com", aliases), "new@example.com")
assert.equal(consoleAccountFor("other@example.com", aliases), "other@example.com")
assert.equal(consoleAccountFor("old@example.com"), "old@example.com")
assert.equal(consoleAccountFor(undefined, {}), undefined)
assert.equal(consoleAccountFor("old@example.com", { ...aliases, "new@example.com": "third@example.com" }), "new@example.com")
for (const invalid of [null, [], "new@example.com", { "old@example.com": 42 }, { bad: "new@example.com" }]) {
assert.throws(() => consoleAccountFor("old@example.com", invalid))
}
assert.throws(() => consoleAccountFor(undefined, aliases), /requires a saved account/)
assert.throws(() => consoleAccountFor("old@example.com", { ...aliases, "old@example.com": "other@example.com" }), /Duplicate/)
})
test("the usage hook forwards Console aliases from provider options without rewriting authentication", async () => {
const hooks = await plugin()
const auth = { accountId: "old@example.com", authMode: "adc", cloudsdkConfig: "/original-adc" }
const before = { ...auth }
const usage = await hooks.auth.usage(async () => auth, {
options: { billingAccount: "AAAAAA-BBBBBB-CCCCCC", consoleAccountAliases: "invalid" },
})
assert.match(usage.error, /consoleAccountAliases must be an object/)
assert.equal(usage.signIn, "kept")
assert.deepEqual(auth, before)
})
test("credits sum active rows, deduplicate IDs, reject future/expired rows, and count exhausted grants", () => {
const tables = [{ headers, rows: [row("a", "$10.00"), row("b", "$2.07"), row("b", "$2.07"), row("expired", "$262.09", "$300.00", "Expired"), row("future", "$10.00", "$10.00", "Available", "January 1, 2027"), row("used", "$0.00", "$10.00", "Exhausted")] }]
const result = parseCreditTables(tables, { now })
@@ -303,6 +329,11 @@ test("ADC setup reads gcloud's complete consent URL and distinguishes saved ADC
test("ADC uses only its own token command, never assumes the active gcloud account, and adds ADC only when there is none", { timeout: 30000 }, async () => {
const fixture = await fakeGcloud()
let login
const originalFetch = globalThis.fetch
globalThis.fetch = async (url) => {
assert.equal(url, "https://openidconnect.googleapis.com/v1/userinfo")
return { ok: true, json: async () => ({ email: "user@example.com", sub: "google-user-1" }) }
}
try {
await fixture.setAdc({})
const identity = await resolveIdentity({ authMode: "adc" })
@@ -324,9 +355,10 @@ test("ADC uses only its own token command, never assumes the active gcloud accou
// read for the gcloud identity, and no ADC login was run for them.
assert.equal(result.project, "example-project")
assert.equal(result.creditsSession, "ready")
assert.equal(result.subject, "google-user-1")
assert.ok(!(await fixture.calls()).some((args) => args.includes("login")))
await assert.rejects(tokenProvider({ authMode: "unknown" })(), /must be auto, gcloud or adc/)
} finally { await login?.close(); await fixture.close() }
} finally { await login?.close(); globalThis.fetch = originalFetch; await fixture.close() }
})
test("auto mode prefers ADC like official Vertex clients, takes its quota project, and falls back to gcloud", { timeout: 30000 }, async () => {
@@ -354,13 +386,14 @@ test("auto mode prefers ADC like official Vertex clients, takes its quota projec
} finally { await fixture.close() }
})
test("a sign-in with an ADC the plugin already filed counts as an overwrite and fails", { timeout: 30000 }, async () => {
test("a sign-in resolves the Google subject before rejecting an existing ADC account", { timeout: 30000 }, async () => {
const fixture = await fakeGcloud()
let login
const original = globalThis.fetch
globalThis.fetch = mockFetch()
const root = join(fixture.directory, "plugin")
try {
await fixture.set({ token: "user@example.com", pendingToken: "user@example.com" })
// The plugin's own ADC for this account is the overwrite. gcloud's
// machine-wide one is not: it belongs to gcloud, is only ever read, and a
// sign-in writes this plugin's credential beside it.
@@ -380,8 +413,9 @@ test("a sign-in with an ADC the plugin already filed counts as an overwrite and
const result = await login.result
assert.equal(result.creditsSession, "unavailable")
assert.match(result.warning, /already signed in|ADC already existed/i)
// Refused before anything opened: no window, and the ADC is as it was.
assert.deepEqual(visited, [])
// Consent identifies the subject in a staging directory. The original ADC
// is never overwritten, even though another consent window was opened.
assert.equal(visited.length, 1)
assert.equal(await readFile(join(own, "application_default_credentials.json"), "utf8").then((text) => JSON.parse(text).refresh_token), "refresh")
} finally { await login?.close(); globalThis.fetch = original; await fixture.close() }
})
@@ -470,12 +504,15 @@ function profileOf(accounts, project = "adc-project", added = accounts.at(-1)) {
}
// Routes fetch requests by URL host for testing sign-in and project listing.
const mockFetch = (projects = [{ projectId: "example-project", name: "Example Project", lifecycleState: "ACTIVE" }]) => async (url, init) => {
const mockFetch = (projects = [{ projectId: "example-project", name: "Example Project", lifecycleState: "ACTIVE" }], subject) => async (url, init) => {
const parsed = new URL(url)
if (parsed.host === "openidconnect.googleapis.com") {
return {
ok: true,
json: async () => ({ email: String(init.headers.authorization).replace(/^Bearer /, "") }),
json: async () => ({
email: String(init.headers.authorization).replace(/^Bearer /, ""),
sub: subject ?? `subject-${createHash("sha256").update(init.headers.authorization).digest("hex")}`,
}),
}
}
if (parsed.host === "cloudresourcemanager.googleapis.com") {
@@ -502,7 +539,7 @@ test("a named sign-in saves its own ADC and refuses a later duplicate", { timeou
let login
let duplicate
const original = globalThis.fetch
globalThis.fetch = mockFetch()
globalThis.fetch = mockFetch(undefined, "google-user-1")
try {
const account = "me@example.com"
const root = join(fixture.directory, "plugin")
@@ -511,7 +548,7 @@ test("a named sign-in saves its own ADC and refuses a later duplicate", { timeou
const visited = []
login = await startLogin({ adcRoot: root, account }, signInWindowOf(visited))
assert.deepEqual(await login.result, {
project: "example-project", account, source: "gcloud", authMode: "adc", cloudsdkConfig: own, creditsSession: "ready",
project: "example-project", account, accountId: account, subject: "google-user-1", source: "gcloud", authMode: "adc", cloudsdkConfig: own, creditsSession: "ready",
})
assert.equal(visited.length, 1)
const file = join(own, "application_default_credentials.json")
@@ -520,7 +557,7 @@ test("a named sign-in saves its own ADC and refuses a later duplicate", { timeou
assert.equal(await adcDirectoryOwnedBy(account, root), own)
duplicate = await startLogin({ adcRoot: root, account }, signInWindowOf(visited))
assert.match((await duplicate.result).warning, /already signed in/)
assert.equal(visited.length, 1)
assert.equal(visited.length, 2)
assert.equal(await readFile(file, "utf8"), saved)
assert.deepEqual(await readdir(root), ["adc-me-example-com"])
} finally { await login?.close(); await duplicate?.close(); globalThis.fetch = original; await fixture.close() }
@@ -1069,3 +1106,15 @@ test("account settings beat the row, and row settings beat environment defaults"
await fixture.close()
}
})
test("usage accepts plugin-level aliases while provider options take precedence", async () => {
const hooks = await plugin({}, { consoleAccountAliases: "invalid-plugin-aliases" })
const auth = { accountId: "old@example.com" }
const provider = { options: { billingAccount: "AAAAAA-BBBBBB-CCCCCC" } }
const usage = await hooks.auth.usage(async () => auth, provider)
assert.match(usage.error, /consoleAccountAliases must be an object/)
const override = await hooks.auth.usage(async () => auth, {
options: { ...provider.options, consoleAccountAliases: { "old@example.com": "invalid-email" } },
})
assert.match(override.error, /intended Google account email/)
})