Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(google): probe Contacts with people/me/connections, which contacts.readonly covers (#7490)
garrytan1d370b7e9fdd
diff --git a/docs/architecture/key-files/google-api-access.md b/docs/architecture/key-files/google-api-access.mdindex 8ce949aede..45dc0f8e05 100644--- a/docs/architecture/key-files/google-api-access.md+++ b/docs/architecture/key-files/google-api-access.md@@ -2,7 +2,7 @@[Subsystem index](../KEY_FILES.md) · [Google connector + open-loop engine](google-and-loops.md).-- `src/core/google/api-access.ts` — #7004/#7073 account identity and API reachability. `probeGoogleAccount(clients, services, { every })` asks Gmail profile, Calendar primary and People `me` in order (stopping at the first address unless `every`), then OAuth userinfo when none named the account, and records each failure per attempt. `resolveGoogleAccount` (`persistence/connector-account.ts`) is the managed sync's stop-at-first use: when nothing names the account it rethrows `api_not_enabled` first, then another credential error, then the first other failure (a network error stays transient), so `connector_account_changed` means a resolved account that differs from the pin. `probeGoogleApiAccess` probes every service of a setup or status run (an ungranted scope is `scope_missing` with no request) and returns `{ resolved_account, resolved_via, services, problems, fix }`; `googleApiProblem` maps `GoogleApiDisabledError` and `scope_missing` to a `GoogleApiProblem`; `googleApiAccessFix` is one Action naming every problem (`ask_user` with each enable link when an API is disabled, else the user's `gbrain google connect --reauth` command), verified by `gbrain google status --json`.+- `src/core/google/api-access.ts` — #7004/#7073 account identity and API reachability. `probeGoogleAccount(clients, services, { every })` asks Gmail profile and Calendar primary in order (stopping at the first address unless `every`), checks People by listing one connection (#7490: `people/me` needs the `profile` scope connect never requests; the probe names no account), then OAuth userinfo when none named the account, and records each failure per attempt. `resolveGoogleAccount` (`persistence/connector-account.ts`) is the managed sync's stop-at-first use: when nothing names the account it rethrows `api_not_enabled` first, then another credential error, then the first other failure (a network error stays transient), so `connector_account_changed` means a resolved account that differs from the pin. `probeGoogleApiAccess` probes every service of a setup or status run (an ungranted scope is `scope_missing` with no request) and returns `{ resolved_account, resolved_via, services, problems, fix }`; `googleApiProblem` maps `GoogleApiDisabledError` and `scope_missing` to a `GoogleApiProblem`; `googleApiAccessFix` is one Action naming every problem (`ask_user` with each enable link when an API is disabled, else the user's `gbrain google connect --reauth` command), verified by `gbrain google status --json`.- The clients (`google-clients.ts`) throw `GoogleApiDisabledError` (`api_not_enabled`) for a 403 with reason `accessNotConfigured`, ErrorInfo `SERVICE_DISABLED` or the disabled-API message, carrying the API, its title, the project and the enable link from the error body (ErrorInfo `activationUrl`, then the Help link, then the message; only console.cloud.google.com and console.developers.google.com links are relayed, otherwise the client id's project number builds it). A 403 for insufficient authentication scopes (`insufficientPermissions`, ErrorInfo `ACCESS_TOKEN_SCOPE_INSUFFICIENT`) is `scope_missing`, never `GoogleForbiddenError`, so a calendar read never names it `calendar_unreadable`.- The sweep (`google-source.ts`) records each `api_not_enabled` / `scope_missing` failure, plus an unmanaged source's ungranted services, as `api_access: { problems, at }` in source state; a service leaves it when its sweep reaches the API again, `at` changes only when the problems do, and a partial managed run publishes it with the loop recovery state.- `gbrain google status` (with a probe) runs `probeGoogleApiAccess` per refreshed account over its linked sources' services (every granted service when none is linked) and reports `accounts[].api_access`; a problem makes `ok: false` and exit 1. `gbrain google setup` probes every requested service (`--services`, default all) before registering anything; a problem stops it with one report (`status: api_access_blocked`, exit 2, the rendered fix and the narrower `--services` command for the reachable services).diff --git a/src/core/google/api-access.ts b/src/core/google/api-access.tsindex 705351680b..a00f9cf9f5 100644--- a/src/core/google/api-access.ts+++ b/src/core/google/api-access.ts@@ -3,8 +3,10 @@* Gmail, Calendar and People APIs it can reach.** `probeGoogleAccount` asks each enabled service to name the account (Gmail- * profile, Calendar primary calendar, People `me`) and, when none can, the- * OAuth userinfo endpoint (the `email` scope is always requested). Every+ * profile, Calendar primary calendar) and, when none can, the OAuth userinfo+ * endpoint (the `email` scope is always requested). People only proves the+ * token reaches the API by listing one connection (#7490): `people/me`+ * needs the `profile` scope, which connect never requests. Every* per-service failure stays in the result: the managed sync uses the first* address it finds, while `gbrain google setup` and `gbrain google status`* probe every service and name each disabled API or missing scope at once.@@ -54,9 +56,8 @@ export async function probeGoogleAccount(clients: GoogleIdentityClients, service['gmail', async () => (await clients.gmail.getProfile(request)).emailAddress],['calendar', async () => (await clients.calendar.fetchJSON<{ id?: string }>('https://www.googleapis.com/calendar/v3/calendars/primary', 'calendar-json', request)).id],['contacts', async () => {- const me = await clients.people.fetchJSON<{ emailAddresses?: Array<{ value?: string; metadata?: { primary?: boolean } }> }>(- 'https://people.googleapis.com/v1/people/me?personFields=emailAddresses', 'people', request);- return (me.emailAddresses?.find(address => address.metadata?.primary) ?? me.emailAddresses?.[0])?.value;+ await clients.people.fetchJSON('https://people.googleapis.com/v1/people/me/connections?pageSize=1&personFields=emailAddresses', 'people', request);+ return undefined;}],['userinfo', clients.userinfo],];diff --git a/test/connector-checkpoint-identity.test.ts b/test/connector-checkpoint-identity.test.tsindex b2367b2645..c0a66c8f7a 100644--- a/test/connector-checkpoint-identity.test.ts+++ b/test/connector-checkpoint-identity.test.ts@@ -15,7 +15,7 @@ import { resumeCheckpoint } from '../src/core/persistence/connector-sync.ts';import { connectorCheckpointsRepair, ORPHAN_CHECKPOINT_MIN_AGE_DAYS } from '../src/core/repair/connector-checkpoints.ts';import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';import { withEnv } from './helpers/with-env.ts';-import { createConnectorFixture, options, json, googleConfig, contact, withPausedOwnerBudget } from './helpers/connector-fixture.ts';+import { createConnectorFixture, options, json, googleConfig, contact, withPausedOwnerBudget, isPeopleAccessProbe } from './helpers/connector-fixture.ts';const { engines, env, source, boundSource, setup, teardown } = createConnectorFixture();beforeAll(setup, 120_000);@@ -46,6 +46,8 @@ function peopleFetcher(opts: { rotate?: boolean; rewalk?: boolean; onList?: () =const u = new URL(url);if (url.includes('/settings/sendAs')) return json({ sendAs: [] });if (u.pathname.endsWith('/people/me')) return json({ resourceName: 'people/me', emailAddresses: [{ value: googleConfig.g_account, metadata: { primary: true } }] });+ if (isPeopleAccessProbe(url)) return json({ connections: [] });+ if (u.pathname.endsWith('/v1/userinfo')) return json({ email: googleConfig.g_account });if (u.pathname.endsWith('/people/me/connections')) {await opts.onList?.();const token = opts.rotate ? `contacts-${++sweep}` : 'contacts-stable';diff --git a/test/google-api-access-7073.test.ts b/test/google-api-access-7073.test.tsindex 822a9180c0..8725c48ae3 100644--- a/test/google-api-access-7073.test.ts+++ b/test/google-api-access-7073.test.ts@@ -48,6 +48,7 @@ function clientsFor(routes: Routes): { clients: GoogleIdentityClients; calls: stif (path.endsWith('/users/me/profile')) return routes.gmail?.() ?? json({ emailAddress: OWNER, historyId: '1' });if (path.endsWith('/calendars/primary')) return routes.calendar?.() ?? json({ id: OWNER });if (path.endsWith('/people/me')) return routes.people?.() ?? json({ emailAddresses: [{ value: OWNER, metadata: { primary: true } }] });+ if (path.endsWith('/people/me/connections')) return routes.people?.() ?? json({ connections: [] });if (path.endsWith('/userinfo')) return routes.userinfo?.() ?? json({ email: OWNER });throw new Error(`unexpected route ${url}`);};diff --git a/test/google-api-access-cmd-7073.serial.test.ts b/test/google-api-access-cmd-7073.serial.test.tsindex 0caa81a6dd..df11ead7f8 100644--- a/test/google-api-access-cmd-7073.serial.test.ts+++ b/test/google-api-access-cmd-7073.serial.test.ts@@ -42,6 +42,7 @@ const mockFetch = (async (input: string | URL | Request) => {if (url.pathname.endsWith('/users/me/profile')) return disabledApis.has('gmail') ? disabled('gmail.googleapis.com', 'Gmail API') : json({ emailAddress: ACCOUNT, historyId: '1' });if (url.pathname.endsWith('/calendars/primary')) return disabledApis.has('calendar') ? disabled('calendar-json.googleapis.com', 'Google Calendar API') : json({ id: ACCOUNT });if (url.pathname.endsWith('/people/me')) return disabledApis.has('people') ? disabled('people.googleapis.com', 'People API') : json({ emailAddresses: [{ value: ACCOUNT, metadata: { primary: true } }] });+ if (url.pathname.endsWith('/people/me/connections')) return disabledApis.has('people') ? disabled('people.googleapis.com', 'People API') : json({ connections: [] });throw new Error(`unexpected fetch in test: ${url}`);}) as typeof fetch;diff --git a/test/google-status-contacts-probe-7490.test.ts b/test/google-status-contacts-probe-7490.test.tsnew file mode 100644index 0000000000..c0e407cbd0--- /dev/null+++ b/test/google-status-contacts-probe-7490.test.ts@@ -0,0 +1,70 @@+/**+ * #7490: `gbrain google status` probes Contacts with a People request that+ * `contacts.readonly` covers. `people/me` now needs the `profile` scope,+ * which `gbrain google connect` never requests, so probing it reported a 403+ * error on a healthy, fully consented account. The probe lists one connection+ * instead, the request the contacts sweep itself makes.+ *+ * Synthetic responses only: example.invalid addresses, no network.+ */+import { describe, expect, test } from 'bun:test';+import { CalendarClient, GmailClient, PeopleClient, type FetchImpl } from '../src/core/google/google-clients.ts';+import { probeGoogleApiAccess, type GoogleIdentityClients } from '../src/core/google/api-access.ts';+import { resolveGoogleAccount } from '../src/core/persistence/connector-account.ts';++const OWNER = '[email protected]';+const CLIENT_ID = '123-abc.apps.googleusercontent.com';+const GRANTED = ['openid', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/gmail.readonly',+ 'https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/contacts.readonly'];+const tokens = { getAccessToken: async () => 'token', forceRefresh: async () => 'token' };+const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });++/** Google's current answer to people/me for a token without the profile scope. */+const profileScopeRequired = () => json({ error: { code: 403, status: 'PERMISSION_DENIED',+ message: 'The caller does not have permission to request "people/me". Request requires one of the following scopes: [profile].' } }, 403);++function clients(): { clients: GoogleIdentityClients; calls: string[] } {+ const calls: string[] = [];+ const fetchImpl: FetchImpl = async (url) => {+ calls.push(url);+ const path = new URL(url).pathname;+ if (path.endsWith('/users/me/profile')) return json({ emailAddress: OWNER, historyId: '1' });+ if (path.endsWith('/calendars/primary')) return json({ id: OWNER });+ if (path.endsWith('/people/me')) return profileScopeRequired();+ if (path.endsWith('/people/me/connections')) return json({ connections: [{ resourceName: 'people/c1', emailAddresses: [{ value: '[email protected]' }] }], totalPeople: 1 });+ if (path.endsWith('/userinfo')) return json({ email: OWNER });+ throw new Error(`unexpected route ${url}`);+ };+ const args = [tokens, fetchImpl, () => {}, CLIENT_ID] as const;+ return { calls, clients: { gmail: new GmailClient(...args), calendar: new CalendarClient(...args), people: new PeopleClient(...args),+ userinfo: async () => ((await (await fetchImpl('https://openidconnect.googleapis.com/v1/userinfo')).json()) as { email?: string }).email } };+}++describe('#7490 the Contacts probe needs only contacts.readonly', () => {+ test('a granted contacts.readonly reports Contacts ok while people/me demands the profile scope', async () => {+ const { clients: c, calls } = clients();+ const report = await probeGoogleApiAccess(c, OWNER, ['gmail', 'calendar', 'contacts'], GRANTED);+ expect(report.services.contacts).toEqual({ status: 'ok' });+ expect(report.problems).toEqual([]);+ expect(report.fix).toBeUndefined();+ const people = calls.filter(url => url.includes('people.googleapis.com'));+ expect(people.map(url => new URL(url).pathname)).toEqual(['/v1/people/me/connections']);+ const params = new URL(people[0]!).searchParams;+ expect([params.get('pageSize'), params.get('personFields')]).toEqual(['1', 'emailAddresses']);+ });++ test('Contacts alone resolves the account through userinfo, never from a contact\'s address', async () => {+ const { clients: c } = clients();+ const report = await probeGoogleApiAccess(c, OWNER, ['contacts'], GRANTED);+ expect(report).toMatchObject({ resolved_account: OWNER, resolved_via: 'userinfo', problems: [] });+ expect(report.services).toEqual({ contacts: { status: 'ok' } });+ });++ test('a Contacts-only managed sync pins the same account, through userinfo', async () => {+ const { clients: c, calls } = clients();+ const resolution = await resolveGoogleAccount(c, ['contacts']);+ expect(resolution).toMatchObject({ email: OWNER, via: 'userinfo' });+ expect(resolution.errors).toEqual({});+ expect(calls.some(url => new URL(url).pathname === '/v1/people/me')).toBe(false);+ });+});diff --git a/test/helpers/connector-fixture.ts b/test/helpers/connector-fixture.tsindex 6073b95bde..6f4e6b9202 100644--- a/test/helpers/connector-fixture.ts+++ b/test/helpers/connector-fixture.ts@@ -138,15 +138,24 @@ export function createConnectorFixture() {return { home, engines, env, backends, setup, teardown, source, boundSource, standaloneConnector };}+/** #7490: the People reachability probe (one connection, email addresses only), told apart from a contacts sweep page. */+export function isPeopleAccessProbe(url: string): boolean {+ const u = new URL(url);+ return u.pathname.endsWith('/people/me/connections') && u.searchParams.get('pageSize') === '1' && u.searchParams.get('personFields') === 'emailAddresses';+}+/**- * #5686: a managed Google run resolves the credential's account (People `me`,- * Calendar primary, Gmail profile) before any service runs. Fixture fetchers- * that only model sweep routes get those identity routes answered here.+ * #5686: a managed Google run resolves the credential's account (People+ * reachability, Calendar primary, Gmail profile, then OAuth userinfo) before+ * any service runs. Fixture fetchers that only model sweep routes get those+ * identity routes answered here.*/export function withGoogleAccount(fetcher: ((url: string, init?: RequestInit) => Promise<Response>) | undefined, account = googleConfig.g_account) {return async (url: string, init?: RequestInit) => {const path = new URL(url).pathname;if (path.endsWith('/people/me')) return json({ resourceName: 'people/me', emailAddresses: [{ value: account, metadata: { primary: true } }] });+ if (isPeopleAccessProbe(url)) return json({ connections: [] });+ if (path.endsWith('/v1/userinfo')) return json({ email: account });if (path.endsWith('/calendars/primary')) return json({ id: account });if (!fetcher) throw new Error('Unexpected external fixture route');return fetcher(url, init);diff --git a/test/managed-connector-routing.serial.test.ts b/test/managed-connector-routing.serial.test.tsindex 77c65a228e..fc992ba8d2 100644--- a/test/managed-connector-routing.serial.test.ts+++ b/test/managed-connector-routing.serial.test.ts@@ -112,6 +112,7 @@ test('deliberate activation and public sync route unbound API sources without crif (url.pathname.endsWith('/settings/sendAs')) return json({ sendAs: [] });// #5686: the managed Google run resolves the credential's account before sweeping.if (url.pathname.endsWith('/people/me')) return json({ emailAddresses: [{ value: googleConfig.g_account, metadata: { primary: true } }] });+ if (url.pathname.endsWith('/v1/userinfo')) return json({ email: googleConfig.g_account });if (url.pathname.endsWith('/people/me/connections')) return json({ connections: [{ resourceName: 'people/routing', names: [{ displayName: 'Connector Example' }], emailAddresses: [{ value: '[email protected]' }] }], nextSyncToken: 'routing-contacts' });if (url.pathname.endsWith('/issues')) return json([issue]);if (url.pathname.endsWith('/pulls') || url.pathname.endsWith('/comments')) return json([]);