Files
plugins/packages/gcp-ai/test/identity.test.mjs
T
拾瑜 c78f965f8d 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.
2026-11-02 03:36:05 +08:00

139 lines
6.9 KiB
JavaScript

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"])
})