import "./network.mjs"
import assert from "node:assert/strict"
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, 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.
process.env.VERTEX_CHROME_IDLE = "0"
import { discoverBillingAccount, fetchCredits, usageOf } from "../lib/credits.mjs"
// Chrome's services run outside routeAll. Deny external name resolution at
// launch, as one argv value (no shell quotes), for every test browser.
const launchArgs = [
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1",
// Any request not served by routeAll is sent to a closed loopback port.
// Chrome may still perform its own numeric IPv6 reachability probe.
"--proxy-server=http://127.0.0.1:9",
"--proxy-bypass-list=<-loopback>",
]
// These tests drive the machine's own Chrome, which the plugin starts and
// speaks to over its pipe transport. A machine with no Chrome can still load
// the plugin and its hooks; it just cannot open a browser, and says so here
// rather than failing as a broken test.
const chrome = await chromeExecutable().then(() => true, () => false)
const needsBrowser = { skip: chrome ? false : "Chrome is not installed; set VERTEX_CHROME_PATH to run the browser tests" }
// A stand-in for Google, served from inside the test: every request the page
// makes is answered here, so nothing leaves the machine.
function pageFor(answers) {
return async (request) => {
const url = new URL(request.url())
if (url.hostname === "console.cloud.google.com") {
const html = answers(url) ?? "
Google Cloud Console
"
return request.fulfill({ body: `${html}` })
}
if (url.hostname === "accounts.google.com") {
const html = answers(url) ?? '
Sign in with your Google Account
'
return request.fulfill({ body: `${html}` })
}
return request.abort()
}
}
// The timeout is stated because this test waits out a real passive sign-in
// redirect: two seconds beyond the default a runner like Bun gives a test.
test("Console session waits for passive sign-in, rejects persistent forms, and handles a closed page", { timeout: 40000, ...needsBrowser }, async () => {
const directory = await mkdtemp(join(tmpdir(), "vertex-browser-session-"))
let browser
try {
browser = await openBrowser({ launchArgs, profile: join(directory, "profile") })
const hosts = new Set()
await routeAll(browser.page, pageFor((url) => {
hosts.add(url.hostname)
if (url.hostname === "accounts.google.com") {
if (url.searchParams.has("passive")) return '
Sign in with your Google Account
'
if (url.searchParams.has("project")) return '
Sign in with your Google Account
'
if (url.searchParams.has("billing")) return '
Sign in with your Google Account
'
return '
Sign in with your Google Account
'
}
if (url.pathname === "/billing/linkedaccount") {
return url.searchParams.has("returned")
? ''
: ''
}
if (url.pathname === "/signin") return '
Sign in with your Google Account
'
if (url.pathname === "/denied") return "
You need additional access
"
return undefined
}))
await browser.page.goto("https://accounts.google.com/v3/signin/identifier?passive=true")
const start = Date.now()
await assertConsoleSession(browser.page)
assert.ok(Date.now() - start >= 8000)
assert.equal(new URL(await browser.page.url()).hostname, "console.cloud.google.com")
await browser.page.goto("https://accounts.google.com/v3/signin/identifier?project=true")
assert.equal(await extractProjectId(browser.page), "example-project")
assert.equal(await discoverBillingAccount(browser.page, "example-project"), "AAAAAA-BBBBBB-CCCCCC")
for (const url of ["https://accounts.google.com/v3/signin/identifier", "https://console.cloud.google.com/signin", "https://accounts.google.com/v3/signin/identifier?continue=https://console.cloud.google.com"]) {
await browser.page.goto(url)
await assert.rejects(assertConsoleSession(browser.page, { timeout: 150 }), /Google session expired/)
}
await browser.page.goto("https://console.cloud.google.com/denied")
await assert.rejects(assertConsoleSession(browser.page), /permission denied/)
await assert.rejects(assertConsoleSession(browser.page, { timeout: 0 }), /positive number/)
// Nothing reached a host this test did not answer.
assert.deepEqual([...hosts].sort(), ["accounts.google.com", "console.cloud.google.com"])
await browser.page.goto("https://accounts.google.com/v3/signin/identifier")
const closed = assert.rejects(assertConsoleSession(browser.page), /page closed/)
await browser.page.close()
await closed
} finally {
if (browser) await browser.close()
await rm(directory, { recursive: true, force: true })
}
})
// The Console names the signed-in account under an obfuscated key. A page that
// has an address but not that key has no answer: another address on it could be
// a project member, a billing contact, or a notification.
test("the signed-in account is only read from the Console's own keyed field", { timeout: 40000, ...needsBrowser }, async () => {
const directory = await mkdtemp(join(tmpdir(), "vertex-browser-account-"))
let browser
try {
browser = await openBrowser({ launchArgs, profile: join(directory, "profile"), headless: true })
await routeAll(browser.page, async (request) => request.fulfill({ body: '
Contact billing@example.com or owner@example.com
' }))
await browser.page.goto("https://console.cloud.google.com/")
assert.equal(await extractAccount(browser.page, { timeout: 1000 }), undefined)
// The keyed field arrives with the Console's own payload, a moment after
// the document it is in.
await routeAll(browser.page, async (request) => request.fulfill({
body: '
'
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 () => {
const directory = await mkdtemp(join(tmpdir(), "vertex-browser-reuse-"))
const previousIdle = process.env.VERTEX_CHROME_IDLE
try {
process.env.VERTEX_CHROME_IDLE = "60000"
const profile = join(directory, "profile")
const seen = []
const read = (label) => withPage({ profile, launchArgs }, async (page) => {
seen.push({ label, connection: page.connection, pid: page.connection.child.pid, targetId: page.targetId })
await routeAll(page, pageFor(() => "
Google Cloud Console
"))
await page.goto("https://console.cloud.google.com/")
return label
})
assert.equal(await read("first"), "first")
assert.equal(await read("second"), "second")
assert.equal(seen.length, 2)
// Same Chrome process, so the second read paid for a tab and nothing else.
assert.equal(seen[0].pid, seen[1].pid)
assert.equal(seen[0].connection, seen[1].connection)
assert.equal(seen[0].connection.closed, false)
// Each read got its own target, and the first one's is gone: what was kept
// is the browser, never the tab a read used.
assert.notEqual(seen[0].targetId, seen[1].targetId)
let open = []
for (let i = 0; i < 50; i++) {
open = (await seen[0].connection.send("Target.getTargets")).targetInfos
if (!open.some((target) => target.targetId === seen[0].targetId)) break
await new Promise((resolve) => setTimeout(resolve, 100))
}
assert.ok(!open.some((target) => target.targetId === seen[0].targetId), "the first read's tab is still open")
} finally {
if (previousIdle === undefined) delete process.env.VERTEX_CHROME_IDLE
else process.env.VERTEX_CHROME_IDLE = previousIdle
await endKeptBrowsers()
await rm(directory, { recursive: true, force: true })
}
})
test("Chrome credits scrape handles pagination, keeps cache isolated, and force refresh bypasses it", { timeout: 60000, ...needsBrowser }, async () => {
const directory = await mkdtemp(join(tmpdir(), "vertex-browser-credits-"))
const previousCache = process.env.XDG_CACHE_HOME
let browser
try {
process.env.XDG_CACHE_HOME = directory
const profile = join(directory, "profile")
browser = await openBrowser({ profile, launchArgs })
let requests = 0
await routeAll(browser.page, async (request) => {
const url = new URL(request.url())
assert.equal(url.origin, "https://console.cloud.google.com")
assert.match(url.pathname, /^\/billing\//)
assert.ok(url.searchParams.get("authuser").endsWith("@example.com"))
requests++
// The Console names the account it rendered for under its own obfuscated
// key, which is what a credits read is checked against.
const shown = url.searchParams.get("authuser")
return request.fulfill({ body: `
` })
})
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.
test("a failed credit read is cached instead of opening a browser each poll", { timeout: 30000, ...needsBrowser }, async () => {
const directory = await mkdtemp(join(tmpdir(), "vertex-browser-failure-"))
const previousCache = process.env.XDG_CACHE_HOME
let browser
try {
process.env.XDG_CACHE_HOME = directory
const profile = join(directory, "profile")
let requests = 0
browser = await openBrowser({ profile, launchArgs })
await routeAll(browser.page, async (request) => {
requests++
return request.fulfill({ body: "
No credits table here
" })
})
// The scrape gives up on a Console page that has no table rather than
// waiting out the page's whole patience.
const options = { profile, browser, billingAccount: "AAAAAA-BBBBBB-CCCCCC", scrapeTimeout: 3000 }
await assert.rejects(fetchCredits(options), /Credits table was not found/)
const afterFirst = requests
assert.ok(afterFirst > 0)
// The second poll answers from the remembered failure without a browser.
await assert.rejects(fetchCredits(options), /Credits table was not found/)
assert.equal(requests, afterFirst)
// Asking again on purpose does try again.
await assert.rejects(fetchCredits({ ...options, force: true }), /Credits table was not found/)
assert.ok(requests > afterFirst)
} 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 })
}
})