diff --git a/handwritten/spanner/src/index.ts b/handwritten/spanner/src/index.ts index 5b63004d19d..ef52abd16d9 100644 --- a/handwritten/spanner/src/index.ts +++ b/handwritten/spanner/src/index.ts @@ -251,6 +251,52 @@ export type TranslateEnumKeys< [P in keyof T]: P extends U ? EnumKey | null | undefined : T[P]; }; +const METRICS_SCOPES = ['https://www.googleapis.com/auth/monitoring.write']; + +interface JwtLikeClient { + scopes?: string | string[]; + createScoped(scopes?: string | string[]): unknown; +} + +/** + * Structural check for a `google-auth-library` `JWT` client supporting + * `createScoped()`, avoiding `instanceof` fragility across duplicate installs. + * + * @param client Candidate auth client. + */ +function isJwtLike(client: unknown): client is JwtLikeClient { + return ( + typeof client === 'object' && + client !== null && + typeof (client as JwtLikeClient).createScoped === 'function' + ); +} + +interface GoogleAuthCredentialSource { + jsonContent?: GoogleAuthOptions['credentials'] | null; + keyFilename?: string | null; + cachedCredential?: unknown; + clientOptions?: GoogleAuthOptions['clientOptions']; +} + +/** + * Structural check for a `google-auth-library` `GoogleAuth` instance, avoiding + * `instanceof` fragility across duplicate installs or realms. + * + * @param value Candidate auth object. + */ +function isGoogleAuthLike(value: unknown): value is GoogleAuth { + if (value instanceof GoogleAuth) { + return true; + } + return ( + typeof value === 'object' && + value !== null && + typeof (value as {getClient?: unknown}).getClient === 'function' && + typeof (value as {getProjectId?: unknown}).getProjectId === 'function' + ); +} + /** * Retrieves the universe domain. * @@ -524,10 +570,9 @@ class Spanner extends GrpcService { this._isInSecureCredentials = options.sslCreds?._isSecure() === false; this.options = options; - this.auth = - options.auth instanceof GoogleAuth - ? options.auth - : new GoogleAuth(this.options); + this.auth = isGoogleAuthLike(options.auth) + ? options.auth + : new GoogleAuth(this.options); this.clients_ = new Map(); this.instances_ = new Map(); this.instanceConfigs_ = new Map(); @@ -1802,6 +1847,69 @@ class Spanner extends GrpcService { }; } + /** + * Returns a dedicated `GoogleAuth` instance for `CloudMonitoringMetricsExporter`: + * - Scoped strictly to `METRICS_SCOPES` (`monitoring.write`) instead of + * inheriting Spanner scopes from `this.options.scopes`. + * - When `options.auth` is a `GoogleAuth` instance, derives a fresh `GoogleAuth` + * from its credential source (`jsonContent`, `keyFilename`, cloned `JWT` + * `cachedCredential`, and `clientOptions`) without sharing or mutating the + * caller's `GoogleAuth` instance. + * - Clones a caller-provided `options.authClient` `JWT` with its own + * `scopes` (`createScoped(jwt.scopes)`) so `google-auth-library >= 11.3.2` + * cannot latch `defaultServicePath` on the caller's instance while keeping + * unscoped JWTs in local self-signed mode (zero OAuth2 token exchanges). + * - Leaves `universeDomain` untouched unless explicitly configured so TPC + * credential universe-domain mismatch validation remains active. + * + * @returns A `GoogleAuth` instance suitable for built-in metrics export. + */ + private _createMetricsAuth(): GoogleAuth { + const opts = this.options as SpannerOptions; + const metricsOpts: SpannerOptions = {...opts, scopes: METRICS_SCOPES}; + delete metricsOpts.auth; + + const callerAuth = isGoogleAuthLike(opts.auth) + ? (opts.auth as unknown as GoogleAuthCredentialSource) + : undefined; + if (callerAuth) { + // Strip top-level credential fields up front so an ADC-only callerAuth + // never falls back to competing SpannerOptions credentials or an uncloned + // top-level authClient. + delete metricsOpts.credentials; + delete metricsOpts.keyFilename; + delete metricsOpts.keyFile; + delete metricsOpts.authClient; + delete (metricsOpts as Record).apiKey; + + if ( + callerAuth.clientOptions && + Object.keys(callerAuth.clientOptions).length > 0 + ) { + metricsOpts.clientOptions = { + ...callerAuth.clientOptions, + ...metricsOpts.clientOptions, + }; + } + if (callerAuth.jsonContent) { + metricsOpts.credentials = callerAuth.jsonContent; + } else if (callerAuth.keyFilename) { + metricsOpts.keyFilename = callerAuth.keyFilename; + } else if (callerAuth.cachedCredential) { + const cached = callerAuth.cachedCredential; + metricsOpts.authClient = ( + isJwtLike(cached) ? cached.createScoped(cached.scopes) : cached + ) as GoogleAuthOptions['authClient']; + } + } else if (isJwtLike(opts.authClient)) { + metricsOpts.authClient = opts.authClient.createScoped( + opts.authClient.scopes, + ) as GoogleAuthOptions['authClient']; + } + + return new GoogleAuth(metricsOpts); + } + /** * Attaches the Cloud Monitoring exporter to the `MetricsTracerFactory` * scoped to the resolved `(universeDomain, monitoringTargetKey)`. @@ -1829,12 +1937,21 @@ class Spanner extends GrpcService { } if (!factory.hasMetricReaders()) { + const metricsAuth = this._createMetricsAuth(); + const exporterOptions = {...config.exporterOptions, auth: metricsAuth}; + const resolvedConfig = { + ...config.resolvedConfig, + clientOptions: { + ...config.resolvedConfig.clientOptions, + auth: metricsAuth, + }, + }; context.with(ROOT_CONTEXT, () => { const periodicReader = new PeriodicExportingMetricReader({ exporter: new CloudMonitoringMetricsExporter( - config.exporterOptions, + exporterOptions, projectId, - config.resolvedConfig, + resolvedConfig, ), exportIntervalMillis: 60000, }); diff --git a/handwritten/spanner/test/index.ts b/handwritten/spanner/test/index.ts index 974fcd6cf82..8e6bc413439 100644 --- a/handwritten/spanner/test/index.ts +++ b/handwritten/spanner/test/index.ts @@ -27,6 +27,7 @@ import {PreciseDate} from '@google-cloud/precise-date'; import {hasProjectIdToken, replaceProjectIdToken} from '../src/helper'; import * as pfy from '@google-cloud/promisify'; import {grpc} from 'google-gax'; +import {JWT, OAuth2Client} from 'google-auth-library'; import * as sinon from 'sinon'; import * as spnr from '../src'; import { @@ -1100,6 +1101,223 @@ describe('Spanner', () => { assert.strictEqual(recordedExporterCalls.length, 0); }); + it('should always scope metrics auth strictly to monitoring.write without forcing universeDomain, and allocate lazily', async () => { + for (const scopes of [ + undefined, + ['https://www.googleapis.com/auth/cloud-platform'], + ['https://www.googleapis.com/auth/spanner.data'], + 'https://www.googleapis.com/auth/spanner.data', + [], + ]) { + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const spanner = new Spanner( + asAny({projectId: 'metrics-scopes', scopes}), + ); + assert.strictEqual(recordedExporterCalls.length, 1); + const metricsAuth = recordedExporterCalls[0].options.auth; + assert.notStrictEqual(metricsAuth, spanner.auth); + const metricsAuthOpts = getFake(metricsAuth).calledWith_[0]; + assert.deepStrictEqual(metricsAuthOpts.scopes, [ + 'https://www.googleapis.com/auth/monitoring.write', + ]); + assert.strictEqual(metricsAuthOpts.universeDomain, undefined); + } + + // Second client sharing the same factory reuses the existing reader. + const secondClient = new Spanner({projectId: 'metrics-scopes'}); + assert.strictEqual(asAny(secondClient)._metricsEnabled, true); + assert.strictEqual(recordedExporterCalls.length, 1); + }); + + it('should clone JWT authClient preserving scopes and metadata, and pass through non-JWT authClient unchanged', async () => { + for (const jwtScopes of [ + ['https://www.googleapis.com/auth/cloud-platform'], + 'https://www.googleapis.com/auth/spanner.data', + ]) { + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const scopedJwt = new JWT({ + email: 'sa@proj.iam.gserviceaccount.com', + key: 'fake-key', + scopes: jwtScopes, + }); + new Spanner(asAny({projectId: 'scoped-jwt', authClient: scopedJwt})); + const cloned = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0].authClient as JWT; + assert.ok(cloned instanceof JWT); + assert.notStrictEqual(cloned, scopedJwt); + assert.deepStrictEqual(cloned.scopes, jwtScopes); + } + + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const keyFileJwt = new JWT({keyFile: '/tmp/sa.json'}); + new Spanner(asAny({projectId: 'jwt-keyfile', authClient: keyFileJwt})); + const clonedKeyFile = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0].authClient as JWT; + assert.notStrictEqual(clonedKeyFile, keyFileJwt); + assert.strictEqual(clonedKeyFile.keyFile, '/tmp/sa.json'); + + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const richJwt = new JWT({ + email: 'sa@proj.iam.gserviceaccount.com', + key: 'fake-key', + subject: 'delegated@example.com', + additionalClaims: {custom: 'claim'}, + quotaProjectId: 'billing-proj', + }); + new Spanner(asAny({projectId: 'jwt-rich', authClient: richJwt})); + const clonedRich = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0].authClient as JWT; + assert.notStrictEqual(clonedRich, richJwt); + assert.strictEqual(clonedRich.subject, 'delegated@example.com'); + assert.deepStrictEqual(clonedRich.additionalClaims, {custom: 'claim'}); + assert.strictEqual(clonedRich.quotaProjectId, 'billing-proj'); + + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const oauthClient = new OAuth2Client(); + new Spanner(asAny({projectId: 'non-jwt', authClient: oauthClient})); + assert.strictEqual( + getFake(recordedExporterCalls[0].options.auth).calledWith_[0] + .authClient, + oauthClient, + ); + + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + new Spanner(asAny({projectId: 'null-auth-client', authClient: null})); + assert.strictEqual( + getFake(recordedExporterCalls[0].options.auth).calledWith_[0] + .authClient, + null, + ); + }); + + it('should accept structural GoogleAuth on options.auth and derive isolated metrics auth from its credential source', async () => { + // Non-auth object falls back to new GoogleAuth(this.options). + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const badAuth = {notAnAuth: true}; + const fallbackSpanner = new Spanner( + asAny({projectId: 'bad-auth', auth: badAuth}), + ); + assert.notStrictEqual(fallbackSpanner.auth, badAuth); + + // Structural GoogleAuth-like with jsonContent and clientOptions. + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const jsonCreds = {client_email: 'sa@p.iam', private_key: 'k'}; + const structuralJsonAuth = { + getClient: async () => ({}), + getProjectId: (cb?: (err: Error | null, id?: string) => void) => + cb ? cb(null, 'struct-json') : Promise.resolve('struct-json'), + jsonContent: jsonCreds, + clientOptions: {quotaProjectId: 'qp-1'}, + }; + const jsonSpanner = new Spanner( + asAny({ + projectId: 'struct-json', + auth: structuralJsonAuth, + keyFilename: '/ignored.json', + }), + ); + assert.strictEqual(jsonSpanner.auth, structuralJsonAuth); + const jsonMetricsOpts = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0]; + assert.strictEqual(jsonMetricsOpts.auth, undefined); + assert.strictEqual(jsonMetricsOpts.credentials, jsonCreds); + assert.strictEqual(jsonMetricsOpts.keyFilename, undefined); + assert.deepStrictEqual(jsonMetricsOpts.clientOptions, { + quotaProjectId: 'qp-1', + }); + assert.deepStrictEqual(jsonMetricsOpts.scopes, [ + 'https://www.googleapis.com/auth/monitoring.write', + ]); + + // Structural GoogleAuth-like with keyFilename. + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const structuralKeyFileAuth = { + getClient: async () => ({}), + getProjectId: () => Promise.resolve('struct-kf'), + keyFilename: '/tmp/from-auth.json', + }; + new Spanner( + asAny({ + projectId: 'struct-kf', + auth: structuralKeyFileAuth, + credentials: jsonCreds, + }), + ); + const kfMetricsOpts = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0]; + assert.strictEqual(kfMetricsOpts.keyFilename, '/tmp/from-auth.json'); + assert.strictEqual(kfMetricsOpts.credentials, undefined); + + // Structural GoogleAuth-like with non-JWT cachedCredential. + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const oauthClient = new OAuth2Client(); + const structuralOAuth = { + getClient: async () => oauthClient, + getProjectId: () => Promise.resolve('struct-oauth'), + cachedCredential: oauthClient, + }; + new Spanner(asAny({projectId: 'struct-oauth', auth: structuralOAuth})); + const oauthMetricsOpts = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0]; + assert.strictEqual(oauthMetricsOpts.authClient, oauthClient); + + // Structural GoogleAuth-like with no explicit credential source (ADC). + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const structuralAdcAuth = { + getClient: async () => ({}), + getProjectId: () => Promise.resolve('struct-adc'), + clientOptions: {}, + }; + new Spanner(asAny({projectId: 'struct-adc', auth: structuralAdcAuth})); + const adcMetricsOpts = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0]; + assert.strictEqual(adcMetricsOpts.auth, undefined); + assert.strictEqual(adcMetricsOpts.credentials, undefined); + assert.strictEqual(adcMetricsOpts.keyFilename, undefined); + assert.strictEqual(adcMetricsOpts.authClient, undefined); + assert.strictEqual(adcMetricsOpts.clientOptions, undefined); + }); + + it('should not mix top-level Spanner credential options into metrics auth derived from an ADC-only caller GoogleAuth', () => { + const callerAuth = Object.create(fakeGoogleAuth.prototype); + callerAuth.getProjectId = cb => cb && cb(null, 'caller-project'); + const topLevelJwt = new JWT({ + email: 'other@proj.iam.gserviceaccount.com', + key: 'fake-key', + }); + new Spanner( + asAny({ + projectId: 'caller-project', + auth: callerAuth, + keyFilename: '/tmp/spanner-level-option.json', + authClient: topLevelJwt, + apiKey: 'top-level-key', + }), + ); + assert.strictEqual(recordedExporterCalls.length, 1); + const metricsOpts = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0]; + assert.strictEqual(metricsOpts.auth, undefined); + assert.strictEqual(metricsOpts.keyFilename, undefined); + assert.strictEqual(metricsOpts.credentials, undefined); + assert.strictEqual(metricsOpts.authClient, undefined); + assert.strictEqual(metricsOpts.apiKey, undefined); + assert.deepStrictEqual(metricsOpts.scopes, [ + 'https://www.googleapis.com/auth/monitoring.write', + ]); + }); + it('should trim universeDomain consistently on Spanner and exporter options', () => { const client = new Spanner({ projectId: 'tpc-project', diff --git a/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts b/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts index 85e2f8915af..ac5c01b35e1 100644 --- a/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts +++ b/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts @@ -13,9 +13,12 @@ // limitations under the License. import * as assert from 'assert'; +import * as crypto from 'crypto'; import * as sinon from 'sinon'; import {MeterProvider, MetricReader} from '@opentelemetry/sdk-metrics'; -import {GoogleAuth} from 'google-auth-library'; +import {GoogleAuth, JWT} from 'google-auth-library'; +import {Spanner, v1} from '../../src'; +import {MetricsTracerFactory} from '../../src/metrics/metrics-tracer-factory'; import { CloudMonitoringMetricsExporter, MAX_BATCH_EXPORT_SIZE, @@ -309,6 +312,405 @@ describe('CustomExporter', () => { } }); + async function withMetricsEnv(fn: () => Promise): Promise { + const prev = { + GOOGLE_CLOUD_UNIVERSE_DOMAIN: process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN, + SPANNER_DISABLE_BUILTIN_METRICS: + process.env.SPANNER_DISABLE_BUILTIN_METRICS, + SPANNER_EMULATOR_HOST: process.env.SPANNER_EMULATOR_HOST, + SPANNER_MONITORING_HOST: process.env.SPANNER_MONITORING_HOST, + }; + try { + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + process.env.SPANNER_DISABLE_BUILTIN_METRICS = 'false'; + delete process.env.SPANNER_EMULATOR_HOST; + delete process.env.SPANNER_MONITORING_HOST; + await MetricsTracerFactory.resetInstance(); + return await fn(); + } finally { + await MetricsTracerFactory.resetInstance(); + for (const [key, value] of Object.entries(prev)) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } + } + } + + it('should scope built-in metrics auth to monitoring.write with self-signed JWTs while keeping Spanner scopes on SpannerClient', async () => { + await withMetricsEnv(async () => { + const {privateKey} = crypto.generateKeyPairSync('rsa', { + modulusLength: 2048, + }); + const pem = privateKey.export({type: 'pkcs8', format: 'pem'}) as string; + const credentials = { + type: 'service_account', + client_email: 'sa@proj.iam.gserviceaccount.com', + private_key: pem, + }; + + for (const extraOpts of [ + {}, + {scopes: ['https://www.googleapis.com/auth/spanner.data']}, + ]) { + await MetricsTracerFactory.resetInstance(); + let spannerClient: v1.SpannerClient | undefined; + let metricsClient: any; + try { + const spanner = new Spanner({ + projectId: PROJECT_ID, + credentials, + ...extraOpts, + }); + spannerClient = new v1.SpannerClient(spanner.options as any); + const factory = MetricsTracerFactory.getInstance( + PROJECT_ID, + 'googleapis.com', + ); + assert.ok(factory); + metricsClient = (factory as any)._metricReaders[0]._exporter._client; + + const spannerAuthClient = + (await spannerClient.auth.getClient()) as JWT; + const metricsAuthClient = + (await metricsClient.auth.getClient()) as JWT; + assert.strictEqual( + spannerAuthClient.email, + 'sa@proj.iam.gserviceaccount.com', + ); + assert.strictEqual( + metricsAuthClient.email, + 'sa@proj.iam.gserviceaccount.com', + ); + assert.deepStrictEqual(metricsAuthClient.scopes, [ + 'https://www.googleapis.com/auth/monitoring.write', + ]); + if (extraOpts.scopes) { + assert.deepStrictEqual(spannerAuthClient.scopes, extraOpts.scopes); + } + + let tokenExchangeCalls = 0; + metricsAuthClient.transporter.request = async () => { + tokenExchangeCalls++; + throw new Error('Unexpected OAuth2 token exchange'); + }; + const headers = await metricsAuthClient.getRequestHeaders( + 'https://monitoring.googleapis.com/google.monitoring.v3.MetricService', + ); + const authHeader = headers.get('authorization'); + assert.ok(authHeader?.startsWith('Bearer ')); + assert.strictEqual(tokenExchangeCalls, 0); + const payload = JSON.parse( + Buffer.from( + authHeader!.slice('Bearer '.length).split('.')[1], + 'base64url', + ).toString('utf8'), + ); + assert.strictEqual( + payload.scope, + 'https://www.googleapis.com/auth/monitoring.write', + ); + } finally { + await spannerClient?.close().catch(() => {}); + await metricsClient?.close().catch(() => {}); + } + } + }); + }); + + it('should isolate caller authClient JWT instance and keep self-signed JWT signing without calling oauth2.googleapis.com', async () => { + await withMetricsEnv(async () => { + const {privateKey} = crypto.generateKeyPairSync('rsa', { + modulusLength: 2048, + }); + const pem = privateKey.export({type: 'pkcs8', format: 'pem'}) as string; + + for (const extraOpts of [ + {}, + {scopes: ['https://www.googleapis.com/auth/spanner.data']}, + ]) { + await MetricsTracerFactory.resetInstance(); + let metricsClient: any; + try { + const unscopedJwt = new JWT({ + email: 'sa@proj.iam.gserviceaccount.com', + key: pem, + }); + new Spanner({ + projectId: PROJECT_ID, + authClient: unscopedJwt, + ...extraOpts, + }); + const factory = MetricsTracerFactory.getInstance( + PROJECT_ID, + 'googleapis.com', + ); + assert.ok(factory); + metricsClient = (factory as any)._metricReaders[0]._exporter._client; + const metricsAuthClient = + (await metricsClient.auth.getClient()) as JWT; + assert.notStrictEqual(metricsAuthClient, unscopedJwt); + assert.strictEqual(metricsAuthClient.scopes, undefined); + + let tokenExchangeCalls = 0; + metricsAuthClient.transporter.request = async () => { + tokenExchangeCalls++; + throw new Error('Unexpected OAuth2 token exchange'); + }; + const headers = await metricsAuthClient.getRequestHeaders( + 'https://monitoring.googleapis.com/google.monitoring.v3.MetricService', + ); + assert.ok(headers.get('authorization')?.startsWith('Bearer ')); + assert.strictEqual(tokenExchangeCalls, 0); + assert.strictEqual(unscopedJwt.defaultServicePath, undefined); + } finally { + await metricsClient?.close().catch(() => {}); + } + } + }); + }); + + it('should derive isolated monitoring.write-scoped metrics auth from caller GoogleAuth across jsonContent, keyFilename, authClient, and clientOptions', async () => { + await withMetricsEnv(async () => { + const {privateKey} = crypto.generateKeyPairSync('rsa', { + modulusLength: 2048, + }); + const pem = privateKey.export({type: 'pkcs8', format: 'pem'}) as string; + const saCredentials = { + type: 'service_account', + client_email: 'sa@proj.iam.gserviceaccount.com', + private_key: pem, + }; + + // 1. Caller GoogleAuth with jsonContent + clientOptions (even when cachedCredential is already populated with Spanner scopes). + await MetricsTracerFactory.resetInstance(); + let metricsClient: any; + try { + const callerAuth = new GoogleAuth({ + credentials: saCredentials, + scopes: ['https://www.googleapis.com/auth/spanner.data'], + clientOptions: {quotaProjectId: 'caller-quota-proj'}, + }); + await callerAuth.getClient(); + const spanner = new Spanner({ + projectId: PROJECT_ID, + auth: callerAuth, + }); + assert.strictEqual(spanner.auth, callerAuth); + const factory = MetricsTracerFactory.getInstance( + PROJECT_ID, + 'googleapis.com', + ); + assert.ok(factory); + metricsClient = (factory as any)._metricReaders[0]._exporter._client; + assert.notStrictEqual(metricsClient.auth, callerAuth); + assert.strictEqual( + metricsClient.auth.clientOptions?.quotaProjectId, + 'caller-quota-proj', + ); + const metricsAuthClient = (await metricsClient.auth.getClient()) as JWT; + assert.ok(metricsAuthClient instanceof JWT); + assert.strictEqual( + metricsAuthClient.email, + 'sa@proj.iam.gserviceaccount.com', + ); + assert.deepStrictEqual(metricsAuthClient.scopes, [ + 'https://www.googleapis.com/auth/monitoring.write', + ]); + let tokenExchangeCalls = 0; + metricsAuthClient.transporter.request = async () => { + tokenExchangeCalls++; + throw new Error('Unexpected OAuth2 token exchange'); + }; + const headers = await metricsAuthClient.getRequestHeaders( + 'https://monitoring.googleapis.com/google.monitoring.v3.MetricService', + ); + const authHeader = headers.get('authorization'); + assert.ok(authHeader?.startsWith('Bearer ')); + assert.strictEqual(tokenExchangeCalls, 0); + const payload = JSON.parse( + Buffer.from( + authHeader!.slice('Bearer '.length).split('.')[1], + 'base64url', + ).toString('utf8'), + ); + assert.strictEqual( + payload.scope, + 'https://www.googleapis.com/auth/monitoring.write', + ); + assert.notStrictEqual( + callerAuth.defaultServicePath, + 'monitoring.googleapis.com', + ); + } finally { + await metricsClient?.close().catch(() => {}); + metricsClient = undefined; + } + + // 2. Caller GoogleAuth wrapping an unscoped JWT authClient. + await MetricsTracerFactory.resetInstance(); + try { + const callerJwt = new JWT({ + email: 'sa@proj.iam.gserviceaccount.com', + key: pem, + }); + const callerAuth = new GoogleAuth({authClient: callerJwt}); + const spanner = new Spanner({ + projectId: PROJECT_ID, + auth: callerAuth, + }); + assert.strictEqual(spanner.auth, callerAuth); + const factory = MetricsTracerFactory.getInstance( + PROJECT_ID, + 'googleapis.com', + ); + assert.ok(factory); + metricsClient = (factory as any)._metricReaders[0]._exporter._client; + assert.notStrictEqual(metricsClient.auth, callerAuth); + const resolvedClient = (await metricsClient.auth.getClient()) as JWT; + assert.ok(resolvedClient instanceof JWT); + assert.notStrictEqual(resolvedClient, callerJwt); + assert.strictEqual( + resolvedClient.email, + 'sa@proj.iam.gserviceaccount.com', + ); + assert.strictEqual(resolvedClient.scopes, undefined); + assert.strictEqual(callerJwt.defaultServicePath, undefined); + } finally { + await metricsClient?.close().catch(() => {}); + metricsClient = undefined; + } + + // 3. Caller GoogleAuth configured with keyFilename. + await MetricsTracerFactory.resetInstance(); + try { + const callerAuth = new GoogleAuth({ + keyFilename: '/tmp/caller-sa.json', + }); + new Spanner({projectId: PROJECT_ID, auth: callerAuth}); + const factory = MetricsTracerFactory.getInstance( + PROJECT_ID, + 'googleapis.com', + ); + assert.ok(factory); + metricsClient = (factory as any)._metricReaders[0]._exporter._client; + assert.notStrictEqual(metricsClient.auth, callerAuth); + assert.strictEqual( + metricsClient.auth.keyFilename, + '/tmp/caller-sa.json', + ); + assert.deepStrictEqual(metricsClient.auth.scopes, [ + 'https://www.googleapis.com/auth/monitoring.write', + ]); + } finally { + await metricsClient?.close().catch(() => {}); + metricsClient = undefined; + } + + // 4. Structural GoogleAuth-like object (not instanceof GoogleAuth). + await MetricsTracerFactory.resetInstance(); + try { + const callerJwt = new JWT({ + email: 'sa@proj.iam.gserviceaccount.com', + key: pem, + }); + const structuralAuth = { + getClient: async () => callerJwt, + getProjectId: () => Promise.resolve(PROJECT_ID), + cachedCredential: callerJwt, + }; + const spanner = new Spanner({ + projectId: PROJECT_ID, + auth: structuralAuth as unknown as GoogleAuth, + }); + assert.strictEqual(spanner.auth, structuralAuth); + const factory = MetricsTracerFactory.getInstance( + PROJECT_ID, + 'googleapis.com', + ); + assert.ok(factory); + metricsClient = (factory as any)._metricReaders[0]._exporter._client; + assert.notStrictEqual(metricsClient.auth, structuralAuth); + const resolvedClient = (await metricsClient.auth.getClient()) as JWT; + assert.ok(resolvedClient instanceof JWT); + assert.notStrictEqual(resolvedClient, callerJwt); + assert.strictEqual( + resolvedClient.email, + 'sa@proj.iam.gserviceaccount.com', + ); + } finally { + await metricsClient?.close().catch(() => {}); + } + }); + }); + + it('should reject TPC credentials when universeDomain is omitted and forward explicit universeDomain', async () => { + await withMetricsEnv(async () => { + const tpcJwt = new JWT({ + email: 'sa@tpc.iam.gserviceaccount.com', + key: 'fake-key', + universeDomain: 'tpc.example', + }); + + let spannerClient: v1.SpannerClient | undefined; + let metricsClient: any; + try { + const spanner = new Spanner({ + projectId: PROJECT_ID, + authClient: tpcJwt, + scopes: ['https://www.googleapis.com/auth/spanner.data'], + }); + spannerClient = new v1.SpannerClient(spanner.options as any); + await assert.rejects( + () => spannerClient!.initialize(), + /does not match the universe domain found in the credentials \(tpc\.example\)/, + ); + const factory = MetricsTracerFactory.getInstance( + PROJECT_ID, + 'googleapis.com', + ); + assert.ok(factory); + metricsClient = (factory as any)._metricReaders[0]._exporter._client; + await assert.rejects( + () => metricsClient.initialize(), + /does not match the universe domain found in the credentials \(tpc\.example\)/, + ); + } finally { + await spannerClient?.close().catch(() => {}); + await metricsClient?.close().catch(() => {}); + } + + await MetricsTracerFactory.resetInstance(); + let tpcMetricsClient: any; + try { + new Spanner({ + projectId: PROJECT_ID, + authClient: tpcJwt, + universeDomain: 'tpc.example', + }); + const tpcFactory = MetricsTracerFactory.getInstance( + PROJECT_ID, + 'tpc.example', + ); + assert.ok(tpcFactory); + tpcMetricsClient = (tpcFactory as any)._metricReaders[0]._exporter + ._client; + const resolvedJwt = (await tpcMetricsClient.auth.getClient()) as JWT; + assert.notStrictEqual(resolvedJwt, tpcJwt); + assert.strictEqual(resolvedJwt.universeDomain, 'tpc.example'); + assert.strictEqual( + await tpcMetricsClient.auth.getUniverseDomain(), + 'tpc.example', + ); + await assert.doesNotReject(() => tpcMetricsClient.initialize()); + } finally { + await tpcMetricsClient?.close().catch(() => {}); + } + }); + }); + it('should normalize https:// monitoring endpoints for MetricServiceClient', () => { assert.deepStrictEqual( parseMonitoringEndpoint('https://monitoring.custom-universe.example'),