gcp-ai: a sign-in without an email stops with a clear error, and a 0.1.1 staging dir is not an account (NGshiyu, #723)

Follow-up to #606's post-merge notes (c78f965):

- startLogin: a userinfo reply with a sub but no (or an invalid) email, or
  an empty one, now stops with "The Google account email and subject could
  not be confirmed after consent; no new account was recorded" instead of a
  TypeError from googleIdentity?.account.toLowerCase().
- knownAccounts skips a leftover 0.1.1 staging dir (adc-pending- plus
  mkdtemp's six alphanumerics, no "-"), so it is never read as an account;
  an address starting with pending- (adc-pending-user-example-com) is still
  found for the same-sub check.
- README: staging is .adc-pending-*, and only googleSubject and accountId
  are saved at sign-in; consoleAccount, consoleSubject and
  credentialAccount are read when an older record has them.

Not done: the six PNGs under test/evidence stay. The PR description says
they were removed, but the commit doesn't delete them; removing them at the
tip wouldn't shrink a clone, since history keeps them.

Run at the reviewed head fa173ba (main f9b7a1a plus this PR, Bun 1.4.4
38afee6c8, CI's version):
- Linux (WSL magpie-desktop), fresh HOME: bun test 5483 pass, 18 skip,
  0 fail across 406 files; bun scripts/check.mjs ok; no bun/node process
  left behind.
- macOS (mote): bun test packages/gcp-ai 70 pass, 14 skip, 0 fail; node
  --test packages/gcp-ai/test/*.test.mjs 70 pass, 0 fail.
- Broken by hand: without the LEGACY_PENDING_ADC skip, the pending- test
  goes red; with .account.toLowerCase() back, the missing-email test goes
  red (Bun and Node both).
- Bun 1.4.4's and Node's mkdtemp(".../adc-pending-") names all match
  /^adc-pending-[0-9A-Za-z]{6}$/ (200 each).

Not tried: a real Google sign-in.
This commit is contained in:
拾瑜
2026-11-04 18:43:51 +08:00
committed by GitHub
parent f9b7a1ab24
commit a4fbe854be
3 changed files with 28 additions and 13 deletions
+2 -2
View File
@@ -55,7 +55,7 @@ Google has no API for promotional credits, so the balance is read from the Cloud
## What it keeps where ## What it keeps where
- **Credentials**: never held by the plugin. gcloud writes them and prints tokens on demand. - **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 (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. - **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`. - **Chrome profile**: `<config>/gcp-auto-profile`.
- **Cache**: `<cache>/magpie/gcp-ai`. - **Cache**: `<cache>/magpie/gcp-ai`.
@@ -77,7 +77,7 @@ Google has no API for promotional credits, so the balance is read from the Cloud
- 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". - 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. - 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. - 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. - Saved per account at sign-in: `googleSubject` and `accountId` (with a `#<hash>` suffix when two Google accounts share one email). `accountId` is not changed after a rename: it is the account's key in Magpie, which keeps the account's name, proxy, gateway key and quota history under it, and gcloud keeps the credentials under the original sign-in address (`credentialAccount`, `consoleAccount` and `consoleSubject` on older records are still read if present, while `usage()` never writes back to the host auth record). The current email is cached with the credits and 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. - 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. 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.
+7 -3
View File
@@ -469,6 +469,10 @@ export function gcloudDefaultDirectory() {
export const isGcloudDefault = (directory) => expandPath(directory) === expandPath(gcloudDefaultDirectory()) export const isGcloudDefault = (directory) => expandPath(directory) === expandPath(gcloudDefaultDirectory())
const ADC_DIRS = "adc-" const ADC_DIRS = "adc-"
// 0.1.1 staged unnamed sign-ins in mkdtemp(join(root, "adc-pending-")), which
// appends six alphanumeric characters with no "-". Every validated email has
// "@" and therefore produces a "-" after the local-part in adcSlug(account).
const LEGACY_PENDING_ADC = /^adc-pending-[0-9A-Za-z]{6}$/
// Inventory of managed ADC directories, used to choose the first/add-account // Inventory of managed ADC directories, used to choose the first/add-account
// consent page. These directory labels are NOT Google account identities. // consent page. These directory labels are NOT Google account identities.
@@ -486,7 +490,7 @@ export async function knownAccounts(options = {}) {
throw error throw error
}) })
for (const name of names) { for (const name of names) {
if (!name.startsWith(ADC_DIRS)) continue if (!name.startsWith(ADC_DIRS) || LEGACY_PENDING_ADC.test(name)) continue
// Staging directories use a separate hidden prefix, so a legitimate // Staging directories use a separate hidden prefix, so a legitimate
// account whose email starts with "pending-" remains discoverable. // account whose email starts with "pending-" remains discoverable.
const present = await lstat(join(root, name, "application_default_credentials.json")).then(() => true, (error) => { const present = await lstat(join(root, name, "application_default_credentials.json")).then(() => true, (error) => {
@@ -743,8 +747,8 @@ export async function startLogin(options = {}, openWindow = openSignInWindow) {
// can change. Email alone cannot establish continuity across a rename. // can change. Email alone cannot establish continuity across a rename.
googleIdentity = await tokenProvider({ authMode: "adc", cloudsdkConfig: directory })() googleIdentity = await tokenProvider({ authMode: "adc", cloudsdkConfig: directory })()
.then(identityOf).catch(() => undefined) .then(identityOf).catch(() => undefined)
adcEmail = googleIdentity?.account.toLowerCase() adcEmail = googleIdentity?.account?.toLowerCase()
if (!adcEmail || !googleIdentity.subject) { if (!adcEmail || !googleIdentity?.subject) {
throw stopped("The Google account email and subject could not be confirmed after consent; no new account was recorded") 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 // Serialize subject comparison AND registration across processes. Two
+19 -8
View File
@@ -3,7 +3,7 @@ import assert from "node:assert/strict"
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises" import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"
import { join } from "node:path" import { join } from "node:path"
import test from "node:test" import test from "node:test"
import { adcDirectoryFor, startLogin } from "../lib/credentials.mjs" import { adcDirectoryFor, knownAccounts, startLogin } from "../lib/credentials.mjs"
import { fakeGcloud } from "./gcloud.mjs" import { fakeGcloud } from "./gcloud.mjs"
async function fixture(t) { async function fixture(t) {
@@ -81,12 +81,19 @@ test("same email with distinct subjects creates separate ADCs", async (t) => {
} }
}) })
test("missing subject on a new login cannot register an email-only account", async (t) => { test("missing email or subject on a new login cannot register an incomplete account", async (t) => {
const f = await fixture(t) const f = await fixture(t)
f.identities.set("new-token", { email: "new@example.com" }) for (const [token, identity] of Object.entries({
const result = await f.signIn("new-token", { account: "new@example.com" }) "missing-sub": { email: "new@example.com" },
assert.match(result.warning, /subject could not be confirmed/) "missing-email": { sub: "stable-subject" },
assert.deepEqual(await f.directories(), []) "invalid-email": { sub: "stable-subject", email: "not-an-email" },
"empty-userinfo": {},
})) {
f.identities.set(token, identity)
const result = await f.signIn(token, { account: "new@example.com" })
assert.match(result.warning, /email and subject could not be confirmed/)
assert.deepEqual(await f.directories(), [])
}
}) })
for (const unavailable of [true, false]) { for (const unavailable of [true, false]) {
@@ -103,15 +110,19 @@ for (const unavailable of [true, false]) {
}) })
} }
test("an email beginning with pending- remains discoverable for duplicate detection", async (t) => { test("an email beginning with pending- remains discoverable while 0.1.1 adc-pending-* temp dirs are ignored", async (t) => {
const f = await fixture(t) const f = await fixture(t)
const legacyPending = join(f.root, "adc-pending-Ab12Cd")
await mkdir(legacyPending, { recursive: true })
await writeFile(join(legacyPending, "application_default_credentials.json"), "{}")
const oldDirectory = await f.seed("pending-user@example.com", "old-token") 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("old-token", { email: "pending-user@example.com", sub: "stable-subject" })
assert.deepEqual([...await knownAccounts({ adcRoot: f.root })], ["pending-user-example-com"])
f.identities.set("new-token", { email: "renamed@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" }) const result = await f.signIn("new-token", { account: "renamed@example.com" })
assert.match(result.warning, /already signed in \(same Google subject\)/) assert.match(result.warning, /already signed in \(same Google subject\)/)
assert.equal((await readFile(join(oldDirectory, "application_default_credentials.json"))).toString(), "{}") assert.equal((await readFile(join(oldDirectory, "application_default_credentials.json"))).toString(), "{}")
assert.deepEqual(await f.directories(), ["adc-pending-user-example-com"]) assert.deepEqual(await f.directories(), ["adc-pending-Ab12Cd", "adc-pending-user-example-com"])
}) })
test("an empty email-named directory is a storage collision, not a duplicate identity", async (t) => { test("an empty email-named directory is a storage collision, not a duplicate identity", async (t) => {