From ed892a32bc233c820e75cdb0ce91d0610c475e6f Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian Date: Thu, 26 Nov 2026 07:25:54 +0000 Subject: [PATCH 1/5] fix(spanner): isolate metrics GoogleAuth and handle default endpoints and universeDomain edge cases ## Problem Statement - Passing a shared `GoogleAuth` instance or an unscoped `JWT` `authClient` to `Spanner` could share mutable JWT audience state between Spanner RPCs and built-in Cloud Monitoring metrics, causing `UNAUTHENTICATED` errors. - Explicitly configuring the default Spanner `apiEndpoint`, `servicePath` (`spanner.` with or without `:443`), or `port: 443` caused built-in metrics to be silently disabled. - Conflicting `universeDomain` and `universe_domain` options were not rejected when one value was empty or whitespace, an exported empty `GOOGLE_CLOUD_UNIVERSE_DOMAIN` environment variable caused errors instead of falling back to `googleapis.com`, explicit empty `universeDomain` options were not rejected when built-in metrics were disabled, and direct metrics exporter callers did not forward the normalized environment `universeDomain` into the Cloud Monitoring client options. ## Solution - Isolate the `GoogleAuth` / `JWT` used by built-in Cloud Monitoring metrics when `auth` or an unscoped `JWT` `authClient` is provided, preventing cross-service JWT audience clobbering while keeping built-in metrics credentials resolved from `Spanner` options or Application Default Credentials. - Treat explicit default `apiEndpoint`, `servicePath` (`spanner.` or `spanner.:443`), and `port: 443` as default endpoints so built-in metrics remain enabled unless a non-default endpoint or port is configured. - Reject conflicting `universeDomain`/`universe_domain` values even when one is empty or whitespace, reject explicit empty `universeDomain`/`universe_domain` options consistently regardless of `disableBuiltInMetrics`, treat exported empty or whitespace `GOOGLE_CLOUD_UNIVERSE_DOMAIN` as unset (`googleapis.com`), and forward the normalized `universeDomain` to Cloud Monitoring client options. --- handwritten/spanner/README.md | 2 +- handwritten/spanner/src/index.ts | 170 +++++++++++++-- .../src/metrics/spanner-metrics-exporter.ts | 16 +- handwritten/spanner/test/index.ts | 197 +++++++++++++++++- .../test/metrics/spanner-metrics-exporter.ts | 132 +++++++++++- 5 files changed, 497 insertions(+), 20 deletions(-) diff --git a/handwritten/spanner/README.md b/handwritten/spanner/README.md index 73c9eb9ef5c..f8551805ba5 100644 --- a/handwritten/spanner/README.md +++ b/handwritten/spanner/README.md @@ -97,7 +97,7 @@ const spanner = new Spanner({ You can also disable these metrics by setting `SPANNER_DISABLE_BUILTIN_METRICS` to `true`. -When a custom Spanner `apiEndpoint`, `servicePath`, or `port` is configured, built-in metrics are automatically disabled to avoid sending telemetry or credentials to the default Cloud Monitoring endpoint. To export built-in metrics to a specific Cloud Monitoring endpoint (for example, with a custom endpoint or override), set the `SPANNER_MONITORING_HOST` environment variable using `host`, `host:port`, `[ipv6]`, or `[ipv6]:port` format (without a protocol scheme). Malformed `SPANNER_MONITORING_HOST` values fail closed by throwing an error during `Spanner` client construction when metrics are enabled. +When a non-default Spanner `apiEndpoint`, `servicePath`, or `port` is configured, built-in metrics are automatically disabled to avoid sending telemetry or credentials to the default Cloud Monitoring endpoint. To export built-in metrics to a specific Cloud Monitoring endpoint (for example, with a custom endpoint or override), set the `SPANNER_MONITORING_HOST` environment variable using `host`, `host:port`, `[ipv6]`, or `[ipv6]:port` format (without a protocol scheme). Malformed `SPANNER_MONITORING_HOST` values fail closed by throwing an error during `Spanner` client construction when metrics are enabled. > Note: Client-side metrics needs `monitoring.timeSeries.create` IAM permission to export metrics data. Ask your administrator to grant your service account the [Monitoring Metric Writer](https://cloud.google.com/iam/docs/roles-permissions/monitoring#monitoring.metricWriter) (roles/monitoring.metricWriter) IAM role on the project. diff --git a/handwritten/spanner/src/index.ts b/handwritten/spanner/src/index.ts index 5b63004d19d..0da80a558ac 100644 --- a/handwritten/spanner/src/index.ts +++ b/handwritten/spanner/src/index.ts @@ -117,6 +117,90 @@ import {RequestStreamCoordinator} from './request-stream-coordinator'; // eslint-disable-next-line @typescript-eslint/no-var-requires const gcpApiConfig = require('./spanner_grpc_config.json'); +const METRICS_DEFAULT_SCOPES = [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring.write', +]; + +/** + * Returns whether an auth scopes option contains at least one non-empty scope. + * + * @param scopes Candidate scopes value from options, GoogleAuth, or AuthClient. + * @returns True when explicit scopes are configured. + */ +function hasExplicitScopes(scopes: unknown): boolean { + if (typeof scopes === 'string') { + return scopes.trim().length > 0; + } + if (Array.isArray(scopes)) { + return scopes.some(s => typeof s === 'string' && s.trim().length > 0); + } + return false; +} + +/** + * Checks whether an auth client supports `JWT.createScoped(scopes)` cloning. + * + * @param client Candidate auth client. + * @returns True when `client` is a JWT-like client supporting `createScoped`. + */ +function isJwtLike(client: unknown): client is { + scopes?: string | string[]; + createScoped: (scopes?: string | string[]) => unknown; +} { + return Boolean( + client && + typeof client === 'object' && + typeof (client as {createScoped?: unknown}).createScoped === 'function', + ); +} + +/** + * Checks whether a Spanner endpoint string matches the default endpoint for + * `universeDomain` (`spanner.` with or without `:443`). + * + * @param endpoint Raw `apiEndpoint` or `servicePath` value. + * @param defaultEndpoint Lowercased `spanner.` string. + * @returns True when the endpoint matches the default Spanner host/port. + */ +function isDefaultSpannerEndpoint( + endpoint: string, + defaultEndpoint: string, +): boolean { + const normalized = endpoint.trim().toLowerCase(); + return ( + normalized === defaultEndpoint || normalized === `${defaultEndpoint}:443` + ); +} + +/** + * Determines whether Spanner options configure a non-default endpoint or port. + * + * @param options Resolved Spanner client options. + * @param universeDomain Normalized universe domain for this Spanner client. + * @returns True when `apiEndpoint`, `servicePath`, or `port` overrides the default. + */ +function isCustomSpannerEndpoint( + options: SpannerOptions, + universeDomain: string, +): boolean { + const defaultEndpoint = `spanner.${universeDomain.toLowerCase()}`; + const hasCustomApiEndpoint = + typeof options.apiEndpoint === 'string' && + options.apiEndpoint.trim() !== '' && + !isDefaultSpannerEndpoint(options.apiEndpoint, defaultEndpoint); + const hasCustomServicePath = + typeof options.servicePath === 'string' && + options.servicePath.trim() !== '' && + !isDefaultSpannerEndpoint(options.servicePath, defaultEndpoint); + const hasCustomPort = + options.port !== undefined && + options.port !== null && + String(options.port).trim() !== '' && + Number(options.port) !== 443; + return hasCustomApiEndpoint || hasCustomServicePath || hasCustomPort; +} + export type IOperation = instanceAdmin.longrunning.IOperation; export type GetInstancesOptions = PagedOptionsWithFilter; @@ -271,8 +355,11 @@ export type TranslateEnumKeys< function getUniverseDomain(options: SpannerOptions): string { const universeDomainEnvVar = typeof process === 'object' && typeof process.env === 'object' - ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']?.trim() || undefined : undefined; + const hasExplicitOption = + options?.universeDomain !== undefined || + options?.universe_domain !== undefined; const rawUniverseDomain = options?.universeDomain ?? options?.universe_domain ?? @@ -282,14 +369,16 @@ function getUniverseDomain(options: SpannerOptions): string { typeof rawUniverseDomain === 'string' ? rawUniverseDomain.trim() : rawUniverseDomain; + if ( + hasExplicitOption && + (typeof universeDomain !== 'string' || universeDomain === '') + ) { + throw new Error('universeDomain cannot be empty.'); + } // Sync the trimmed universe domain onto options whenever configured explicitly // (via universeDomain, universe_domain, or GOOGLE_CLOUD_UNIVERSE_DOMAIN) so // Spanner, GAX clients, and GoogleAuth observe the same normalized value. - if ( - options?.universeDomain !== undefined || - options?.universe_domain !== undefined || - universeDomainEnvVar - ) { + if (hasExplicitOption || universeDomainEnvVar) { options.universeDomain = universeDomain; } if (options?.universe_domain !== undefined) { @@ -481,8 +570,8 @@ class Spanner extends GrpcService { ? options.universeDomain.trim() : options?.universeDomain; if ( - trimmedSnakeUniverse && - trimmedCamelUniverse && + trimmedSnakeUniverse !== undefined && + trimmedCamelUniverse !== undefined && trimmedSnakeUniverse !== trimmedCamelUniverse ) { throw new Error( @@ -1709,10 +1798,9 @@ class Spanner extends GrpcService { process.env.SPANNER_DISABLE_BUILTIN_METRICS === 'true' || !!disableBuiltInMetrics; const spannerOptions = this.options as SpannerOptions; - const hasCustomEndpoint = Boolean( - spannerOptions.apiEndpoint || - spannerOptions.servicePath || - spannerOptions.port, + const hasCustomEndpoint = isCustomSpannerEndpoint( + spannerOptions, + this._universeDomain, ); const monitoringHost = process.env.SPANNER_MONITORING_HOST?.trim() || undefined; @@ -1802,6 +1890,45 @@ class Spanner extends GrpcService { }; } + /** + * Returns a `GoogleAuth` instance safe to pass to `MetricServiceClient` + * without clobbering `defaultServicePath` / `defaultScopes` on a shared + * caller `GoogleAuth` or unscoped `JWT`. + * + * @returns A safe `GoogleAuth` instance for `CloudMonitoringMetricsExporter`. + */ + private _createMetricsAuth(): GoogleAuth { + const opts = this.options as SpannerOptions; + if (opts.auth instanceof GoogleAuth) { + // Dedicated GoogleAuth for MetricServiceClient so it cannot mutate + // defaultServicePath/defaultScopes on the caller's shared instance. + const rest = {...opts}; + delete rest.auth; + return new GoogleAuth({ + ...rest, + universeDomain: this._universeDomain, + scopes: METRICS_DEFAULT_SCOPES, + }); + } + if ( + isJwtLike(opts.authClient) && + !hasExplicitScopes(opts.authClient.scopes) + ) { + const scopes = hasExplicitScopes(opts.scopes) + ? opts.scopes + : METRICS_DEFAULT_SCOPES; + return new GoogleAuth({ + ...opts, + universeDomain: this._universeDomain, + scopes, + authClient: opts.authClient.createScoped( + scopes, + ) as GoogleAuthOptions['authClient'], + }); + } + return this.auth; + } + /** * Attaches the Cloud Monitoring exporter to the `MetricsTracerFactory` * scoped to the resolved `(universeDomain, monitoringTargetKey)`. @@ -1829,12 +1956,27 @@ class Spanner extends GrpcService { } if (!factory.hasMetricReaders()) { + const metricsAuth = this._createMetricsAuth(); + const exporterOptions = + metricsAuth === config.exporterOptions.auth + ? config.exporterOptions + : {...config.exporterOptions, auth: metricsAuth}; + const resolvedConfig = + metricsAuth === config.resolvedConfig.clientOptions.auth + ? config.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/src/metrics/spanner-metrics-exporter.ts b/handwritten/spanner/src/metrics/spanner-metrics-exporter.ts index 41c8849e4ac..8e73184442d 100644 --- a/handwritten/spanner/src/metrics/spanner-metrics-exporter.ts +++ b/handwritten/spanner/src/metrics/spanner-metrics-exporter.ts @@ -234,11 +234,21 @@ export function resolveExporterConfig( monitoringEndpoint = formatMonitoringTargetKey(parsed); } + const rawEnvUniverseDomain = + typeof process === 'object' + ? process.env?.GOOGLE_CLOUD_UNIVERSE_DOMAIN + : undefined; + const trimmedEnvUniverseDomain = rawEnvUniverseDomain?.trim() || undefined; const effectiveUniverseDomain = resolvedUniverseDomain ?? - (typeof process === 'object' - ? process.env?.GOOGLE_CLOUD_UNIVERSE_DOMAIN?.trim() || undefined - : undefined); + trimmedEnvUniverseDomain ?? + // When GOOGLE_CLOUD_UNIVERSE_DOMAIN is exported as empty/whitespace, pin + // the default explicitly so MetricServiceClient's `??` cannot read `""`. + (rawEnvUniverseDomain !== undefined ? 'googleapis.com' : undefined); + + if (effectiveUniverseDomain !== undefined) { + clientOptions.universeDomain = effectiveUniverseDomain; + } return { clientOptions, diff --git a/handwritten/spanner/test/index.ts b/handwritten/spanner/test/index.ts index ce312023d4d..6ae9886e9d7 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} from 'google-auth-library'; import * as sinon from 'sinon'; import * as spnr from '../src'; import { @@ -848,8 +849,9 @@ describe('Spanner', () => { () => new Spanner({universeDomain: ' '}), /universeDomain cannot be empty/, ); - assert.doesNotThrow( + assert.throws( () => new Spanner({universeDomain: ' ', disableBuiltInMetrics: true}), + /universeDomain cannot be empty/, ); let capturedCallback: @@ -1092,6 +1094,199 @@ describe('Spanner', () => { 'monitoring.my-tpc.example:8443', ]); }); + + // Verify caller-supplied GoogleAuth isolation for built-in metrics. + it('should create a dedicated GoogleAuth for metrics when options.auth is provided and reuse this.auth otherwise', async () => { + const callerAuth = Object.create(fakeGoogleAuth.prototype); + callerAuth.getProjectId = cb => cb && cb(null, 'caller-project'); + const client = new Spanner( + asAny({ + projectId: 'caller-project', + universeDomain: 'my-tpc.example', + auth: callerAuth, + }), + ); + + assert.strictEqual(client.auth, callerAuth); + assert.strictEqual(recordedExporterCalls.length, 1); + const metricsAuth = recordedExporterCalls[0].options.auth; + assert.notStrictEqual(metricsAuth, callerAuth); + const metricsAuthOpts = getFake(metricsAuth).calledWith_[0]; + assert.strictEqual(metricsAuthOpts.auth, undefined); + assert.strictEqual(metricsAuthOpts.universeDomain, 'my-tpc.example'); + assert.deepStrictEqual(metricsAuthOpts.scopes, [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring.write', + ]); + + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + + const defaultClient = new Spanner({projectId: 'default-project'}); + assert.strictEqual(recordedExporterCalls.length, 1); + assert.strictEqual( + recordedExporterCalls[0].options.auth, + defaultClient.auth, + ); + }); + + it('should keep built-in metrics enabled for explicit default Spanner endpoints and port 443, and disable for non-default endpoints or ports', async () => { + const enabledConfigs = [ + {projectId: 'p', apiEndpoint: 'spanner.googleapis.com'}, + {projectId: 'p', apiEndpoint: 'spanner.googleapis.com:443'}, + {projectId: 'p', apiEndpoint: ' SPANNER.GOOGLEAPIS.COM:443 '}, + {projectId: 'p', servicePath: 'spanner.googleapis.com'}, + {projectId: 'p', servicePath: 'spanner.googleapis.com:443'}, + {projectId: 'p', port: 443}, + {projectId: 'p', port: asAny('443')}, + { + projectId: 'p', + universeDomain: 'my-tpc.example', + apiEndpoint: 'spanner.my-tpc.example', + }, + { + projectId: 'p', + universeDomain: 'my-tpc.example', + apiEndpoint: 'spanner.my-tpc.example:443', + port: 443, + }, + {projectId: 'p', apiEndpoint: ''}, + {projectId: 'p', servicePath: ''}, + {projectId: 'p', port: asAny('')}, + ]; + for (const cfg of enabledConfigs) { + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const client = new Spanner(cfg); + assert.strictEqual( + asAny(client)._metricsEnabled, + true, + `Expected metrics enabled for ${JSON.stringify(cfg)}`, + ); + } + + const disabledConfigs = [ + {projectId: 'p', port: 9010}, + {projectId: 'p', port: 0}, + {projectId: 'p', port: asAny('abc')}, + {projectId: 'p', apiEndpoint: 'spanner.googleapis.com:8443'}, + { + projectId: 'p', + universeDomain: 'my-tpc.example', + apiEndpoint: 'spanner.googleapis.com', + }, + ]; + for (const cfg of disabledConfigs) { + await MetricsTracerFactory.resetInstance(); + recordedExporterCalls = []; + const client = new Spanner(cfg); + assert.strictEqual( + asAny(client)._metricsEnabled, + false, + `Expected metrics disabled for ${JSON.stringify(cfg)}`, + ); + assert.strictEqual(recordedExporterCalls.length, 0); + } + }); + + it('should throw conflict error when universeDomain and universe_domain conflict with empty or whitespace values', () => { + const conflictCases = [ + {universeDomain: '', universe_domain: 'my-tpc.example'}, + {universeDomain: ' ', universe_domain: 'my-tpc.example'}, + {universeDomain: 'my-tpc.example', universe_domain: ''}, + {universeDomain: 'my-tpc.example', universe_domain: ' '}, + ]; + for (const cfg of conflictCases) { + assert.throws( + () => new Spanner(cfg), + /Please set either universe_domain or universeDomain, but not both\./, + `Expected conflict error for ${JSON.stringify(cfg)}`, + ); + } + assert.throws( + () => new Spanner({universeDomain: '', universe_domain: ''}), + /universeDomain cannot be empty/, + ); + }); + + it('should treat exported empty or whitespace GOOGLE_CLOUD_UNIVERSE_DOMAIN as unset and fail closed on explicit empty options regardless of metrics flag', () => { + const prevEnv = process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + try { + for (const envVal of ['', ' ']) { + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = envVal; + const client = new Spanner({projectId: 'env-empty-proj'}); + assert.strictEqual(client.universeDomain, 'googleapis.com'); + assert.strictEqual(client.options.universeDomain, undefined); + assert.strictEqual(asAny(client)._metricsEnabled, true); + } + } finally { + if (prevEnv === undefined) { + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + } else { + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = prevEnv; + } + } + + assert.throws( + () => new Spanner({universeDomain: '', disableBuiltInMetrics: true}), + /universeDomain cannot be empty/, + ); + assert.throws( + () => + new Spanner({universe_domain: ' ', disableBuiltInMetrics: true}), + /universeDomain cannot be empty/, + ); + }); + + it('should isolate an unscoped JWT passed via opts.authClient using createScoped', () => { + const unscopedJwt = new JWT({ + email: 'sa@proj.iam.gserviceaccount.com', + key: 'fake-key', + }); + new Spanner(asAny({projectId: 'jwt-proj', authClient: unscopedJwt})); + + assert.strictEqual(recordedExporterCalls.length, 1); + const metricsAuthOpts = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0]; + assert.ok(metricsAuthOpts.authClient instanceof JWT); + assert.notStrictEqual(metricsAuthOpts.authClient, unscopedJwt); + assert.strictEqual(unscopedJwt.defaultServicePath, undefined); + assert.deepStrictEqual(metricsAuthOpts.authClient.scopes, [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring.write', + ]); + }); + + it('should preserve keyFile, subject, additionalClaims, and quotaProjectId via JWT.createScoped', async () => { + const keyFileJwt = new JWT({keyFile: '/tmp/sa.json'}); + new Spanner(asAny({projectId: 'jwt-keyfile', authClient: keyFileJwt})); + assert.strictEqual(recordedExporterCalls.length, 1); + const keyFileMetricsJwt = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0].authClient as JWT; + assert.notStrictEqual(keyFileMetricsJwt, keyFileJwt); + assert.strictEqual(keyFileMetricsJwt.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})); + assert.strictEqual(recordedExporterCalls.length, 1); + const richMetricsJwt = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0].authClient as JWT; + assert.notStrictEqual(richMetricsJwt, richJwt); + assert.strictEqual(richMetricsJwt.subject, 'delegated@example.com'); + assert.deepStrictEqual(richMetricsJwt.additionalClaims, { + custom: 'claim', + }); + assert.strictEqual(richMetricsJwt.quotaProjectId, 'billing-proj'); + }); }); describe('date', () => { diff --git a/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts b/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts index 4f60181c283..0896adcda75 100644 --- a/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts +++ b/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts @@ -15,12 +15,15 @@ import * as assert from 'assert'; 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 { CloudMonitoringMetricsExporter, MAX_BATCH_EXPORT_SIZE, parseMonitoringEndpoint, + resolveExporterConfig, } from '../../src/metrics/spanner-metrics-exporter'; +import {Spanner} from '../../src'; +import {MetricsTracerFactory} from '../../src/metrics/metrics-tracer-factory'; import * as transform from '../../src/metrics/transform'; import {status} from '@grpc/grpc-js'; import { @@ -285,6 +288,133 @@ describe('CustomExporter', () => { } } }); + + it('should write trimmed effectiveUniverseDomain to clientOptions and handle empty GOOGLE_CLOUD_UNIVERSE_DOMAIN', () => { + const prevEnv = process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + try { + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = ' env-tpc.example '; + const trimmedResolved = resolveExporterConfig({auth: new GoogleAuth()}); + assert.strictEqual(trimmedResolved.universeDomain, 'env-tpc.example'); + assert.strictEqual( + trimmedResolved.clientOptions.universeDomain, + 'env-tpc.example', + ); + const trimmedExporter = new CloudMonitoringMetricsExporter( + {auth: new GoogleAuth()}, + PROJECT_ID, + ); + assert.strictEqual( + (trimmedExporter as any)._client._universeDomain, + 'env-tpc.example', + ); + assert.strictEqual( + (trimmedExporter as any)._client._servicePath, + 'monitoring.env-tpc.example', + ); + + for (const emptyEnv of ['', ' ']) { + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = emptyEnv; + const emptyResolved = resolveExporterConfig({auth: new GoogleAuth()}); + assert.strictEqual(emptyResolved.universeDomain, 'googleapis.com'); + assert.strictEqual( + emptyResolved.clientOptions.universeDomain, + 'googleapis.com', + ); + const emptyExporter = new CloudMonitoringMetricsExporter( + {auth: new GoogleAuth()}, + PROJECT_ID, + ); + assert.strictEqual( + (emptyExporter as any)._client._universeDomain, + 'googleapis.com', + ); + assert.strictEqual( + (emptyExporter as any)._client._servicePath, + 'monitoring.googleapis.com', + ); + } + } finally { + if (prevEnv === undefined) { + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + } else { + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = prevEnv; + } + } + }); + + it('should not clobber caller GoogleAuth or JWT defaultServicePath end-to-end through Spanner and MetricServiceClient', async () => { + const prevDisable = process.env.SPANNER_DISABLE_BUILTIN_METRICS; + const prevEmulator = process.env.SPANNER_EMULATOR_HOST; + const prevMonitoring = process.env.SPANNER_MONITORING_HOST; + try { + process.env.SPANNER_DISABLE_BUILTIN_METRICS = 'false'; + delete process.env.SPANNER_EMULATOR_HOST; + delete process.env.SPANNER_MONITORING_HOST; + await MetricsTracerFactory.resetInstance(); + + // T7a: opts.authClient (unscoped JWT) clones via createScoped without ADC. + const callerJwt = new JWT({ + email: 'sa@proj.iam.gserviceaccount.com', + key: 'fake-key', + }); + const jwtSpanner = new Spanner({ + projectId: PROJECT_ID, + authClient: callerJwt, + }); + + const jwtFactory = MetricsTracerFactory.getInstance( + PROJECT_ID, + 'googleapis.com', + ); + assert.ok(jwtFactory); + const jwtReaders = (jwtFactory as any)._metricReaders; + assert.strictEqual(jwtReaders.length, 1); + const jwtExporter = jwtReaders[0] + ._exporter as CloudMonitoringMetricsExporter; + const jwtMetricsClient = (jwtExporter as any)._client; + assert.notStrictEqual(jwtMetricsClient.auth, jwtSpanner.auth); + const resolvedMetricsClient = await jwtMetricsClient.auth.getClient(); + assert.ok(resolvedMetricsClient instanceof JWT); + assert.notStrictEqual(resolvedMetricsClient, callerJwt); + assert.strictEqual(callerJwt.defaultServicePath, undefined); + + // T7b: opts.auth (shared GoogleAuth) isolates metrics auth without calling + // getClient() (which would hit ADC on CI runners without credentials). + await MetricsTracerFactory.resetInstance(); + const callerAuth = new GoogleAuth({authClient: callerJwt}); + new Spanner({projectId: PROJECT_ID, auth: callerAuth}); + + const authFactory = MetricsTracerFactory.getInstance( + PROJECT_ID, + 'googleapis.com', + ); + assert.ok(authFactory); + const authReaders = (authFactory as any)._metricReaders; + assert.strictEqual(authReaders.length, 1); + const authExporter = authReaders[0] + ._exporter as CloudMonitoringMetricsExporter; + const authMetricsClient = (authExporter as any)._client; + assert.notStrictEqual(authMetricsClient.auth, callerAuth); + assert.strictEqual(callerAuth.defaultServicePath, undefined); + } finally { + await MetricsTracerFactory.resetInstance(); + if (prevDisable === undefined) { + delete process.env.SPANNER_DISABLE_BUILTIN_METRICS; + } else { + process.env.SPANNER_DISABLE_BUILTIN_METRICS = prevDisable; + } + if (prevEmulator === undefined) { + delete process.env.SPANNER_EMULATOR_HOST; + } else { + process.env.SPANNER_EMULATOR_HOST = prevEmulator; + } + if (prevMonitoring === undefined) { + delete process.env.SPANNER_MONITORING_HOST; + } else { + process.env.SPANNER_MONITORING_HOST = prevMonitoring; + } + } + }); }); // Verify that the export call will convert and send the requests out. From 7a6b842f83e091cd83af86974ceac20545e08f33 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian Date: Thu, 26 Nov 2026 07:59:15 +0000 Subject: [PATCH 2/5] Addressed comments --- handwritten/spanner/src/index.ts | 9 +++------ handwritten/spanner/test/index.ts | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/handwritten/spanner/src/index.ts b/handwritten/spanner/src/index.ts index 0da80a558ac..8ec08a7d4f2 100644 --- a/handwritten/spanner/src/index.ts +++ b/handwritten/spanner/src/index.ts @@ -378,7 +378,7 @@ function getUniverseDomain(options: SpannerOptions): string { // Sync the trimmed universe domain onto options whenever configured explicitly // (via universeDomain, universe_domain, or GOOGLE_CLOUD_UNIVERSE_DOMAIN) so // Spanner, GAX clients, and GoogleAuth observe the same normalized value. - if (hasExplicitOption || universeDomainEnvVar) { + if (options && (hasExplicitOption || universeDomainEnvVar)) { options.universeDomain = universeDomain; } if (options?.universe_domain !== undefined) { @@ -1914,15 +1914,12 @@ class Spanner extends GrpcService { isJwtLike(opts.authClient) && !hasExplicitScopes(opts.authClient.scopes) ) { - const scopes = hasExplicitScopes(opts.scopes) - ? opts.scopes - : METRICS_DEFAULT_SCOPES; return new GoogleAuth({ ...opts, universeDomain: this._universeDomain, - scopes, + scopes: METRICS_DEFAULT_SCOPES, authClient: opts.authClient.createScoped( - scopes, + METRICS_DEFAULT_SCOPES, ) as GoogleAuthOptions['authClient'], }); } diff --git a/handwritten/spanner/test/index.ts b/handwritten/spanner/test/index.ts index 6ae9886e9d7..056b43183a1 100644 --- a/handwritten/spanner/test/index.ts +++ b/handwritten/spanner/test/index.ts @@ -1257,6 +1257,30 @@ describe('Spanner', () => { ]); }); + it('should always scope an isolated opts.authClient JWT with metrics scopes even when Spanner-only scopes are configured', () => { + const unscopedJwt = new JWT({ + email: 'sa@proj.iam.gserviceaccount.com', + key: 'fake-key', + }); + new Spanner( + asAny({ + projectId: 'jwt-spanner-scopes', + authClient: unscopedJwt, + scopes: ['https://www.googleapis.com/auth/spanner.data'], + }), + ); + assert.strictEqual(recordedExporterCalls.length, 1); + const metricsAuthOpts = getFake(recordedExporterCalls[0].options.auth) + .calledWith_[0]; + const expectedScopes = [ + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/monitoring.write', + ]; + assert.deepStrictEqual(metricsAuthOpts.scopes, expectedScopes); + assert.deepStrictEqual(metricsAuthOpts.authClient.scopes, expectedScopes); + assert.notStrictEqual(metricsAuthOpts.authClient, unscopedJwt); + }); + it('should preserve keyFile, subject, additionalClaims, and quotaProjectId via JWT.createScoped', async () => { const keyFileJwt = new JWT({keyFile: '/tmp/sa.json'}); new Spanner(asAny({projectId: 'jwt-keyfile', authClient: keyFileJwt})); From e0d2a70e1940fbb0e482b50024a9944c3718f898 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian Date: Thu, 26 Nov 2026 14:35:37 +0000 Subject: [PATCH 3/5] Addressed comments --- .../src/metrics/spanner-metrics-exporter.ts | 21 +++++-------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/handwritten/spanner/src/metrics/spanner-metrics-exporter.ts b/handwritten/spanner/src/metrics/spanner-metrics-exporter.ts index 8e73184442d..d71e2243b0a 100644 --- a/handwritten/spanner/src/metrics/spanner-metrics-exporter.ts +++ b/handwritten/spanner/src/metrics/spanner-metrics-exporter.ts @@ -208,9 +208,6 @@ export function resolveExporterConfig( } const clientOptions: Record = {auth}; - if (resolvedUniverseDomain !== undefined) { - clientOptions.universeDomain = resolvedUniverseDomain; - } // Only fall back to SPANNER_MONITORING_HOST when apiEndpoint was omitted; // explicit `apiEndpoint: undefined` keeps the caller's synchronous snapshot. @@ -234,21 +231,13 @@ export function resolveExporterConfig( monitoringEndpoint = formatMonitoringTargetKey(parsed); } - const rawEnvUniverseDomain = - typeof process === 'object' - ? process.env?.GOOGLE_CLOUD_UNIVERSE_DOMAIN - : undefined; - const trimmedEnvUniverseDomain = rawEnvUniverseDomain?.trim() || undefined; const effectiveUniverseDomain = resolvedUniverseDomain ?? - trimmedEnvUniverseDomain ?? - // When GOOGLE_CLOUD_UNIVERSE_DOMAIN is exported as empty/whitespace, pin - // the default explicitly so MetricServiceClient's `??` cannot read `""`. - (rawEnvUniverseDomain !== undefined ? 'googleapis.com' : undefined); - - if (effectiveUniverseDomain !== undefined) { - clientOptions.universeDomain = effectiveUniverseDomain; - } + (typeof process === 'object' + ? process.env?.GOOGLE_CLOUD_UNIVERSE_DOMAIN?.trim() || undefined + : undefined) ?? + 'googleapis.com'; + clientOptions.universeDomain = effectiveUniverseDomain; return { clientOptions, From c058148adb1ac08b8455996d554286de4352d8a5 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian Date: Thu, 26 Nov 2026 14:45:48 +0000 Subject: [PATCH 4/5] Addressed comments --- handwritten/spanner/src/index.ts | 49 ++++++++++++------------------- handwritten/spanner/test/index.ts | 17 +++++++++++ 2 files changed, 35 insertions(+), 31 deletions(-) diff --git a/handwritten/spanner/src/index.ts b/handwritten/spanner/src/index.ts index 8ec08a7d4f2..3090915b334 100644 --- a/handwritten/spanner/src/index.ts +++ b/handwritten/spanner/src/index.ts @@ -106,6 +106,7 @@ import {PeriodicExportingMetricReader} from '@opentelemetry/sdk-metrics'; import {MetricInterceptor} from './metrics/interceptor'; import { CloudMonitoringMetricsExporter, + normalizeUniverseDomain, ResolvedExporterConfig, resolveExporterConfig, } from './metrics/spanner-metrics-exporter'; @@ -353,38 +354,24 @@ export type TranslateEnumKeys< * @returns {string} The universe domain. */ function getUniverseDomain(options: SpannerOptions): string { - const universeDomainEnvVar = - typeof process === 'object' && typeof process.env === 'object' - ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']?.trim() || undefined - : undefined; - const hasExplicitOption = - options?.universeDomain !== undefined || - options?.universe_domain !== undefined; - const rawUniverseDomain = - options?.universeDomain ?? - options?.universe_domain ?? - universeDomainEnvVar ?? - 'googleapis.com'; - const universeDomain = - typeof rawUniverseDomain === 'string' - ? rawUniverseDomain.trim() - : rawUniverseDomain; - if ( - hasExplicitOption && - (typeof universeDomain !== 'string' || universeDomain === '') - ) { - throw new Error('universeDomain cannot be empty.'); - } - // Sync the trimmed universe domain onto options whenever configured explicitly - // (via universeDomain, universe_domain, or GOOGLE_CLOUD_UNIVERSE_DOMAIN) so - // Spanner, GAX clients, and GoogleAuth observe the same normalized value. - if (options && (hasExplicitOption || universeDomainEnvVar)) { - options.universeDomain = universeDomain; - } - if (options?.universe_domain !== undefined) { - options.universe_domain = universeDomain; + const explicitOption = options?.universeDomain ?? options?.universe_domain; + const configured = + explicitOption !== undefined && explicitOption !== null + ? normalizeUniverseDomain(explicitOption) + : typeof process === 'object' + ? process.env?.GOOGLE_CLOUD_UNIVERSE_DOMAIN?.trim() || undefined + : undefined; + + if (configured !== undefined) { + if (options) { + options.universeDomain = configured; + if (options.universe_domain !== undefined) { + options.universe_domain = configured; + } + } + return configured; } - return universeDomain; + return 'googleapis.com'; } /** diff --git a/handwritten/spanner/test/index.ts b/handwritten/spanner/test/index.ts index 056b43183a1..37099d2fb91 100644 --- a/handwritten/spanner/test/index.ts +++ b/handwritten/spanner/test/index.ts @@ -1238,6 +1238,23 @@ describe('Spanner', () => { ); }); + it('should treat a null universeDomain option as unset and fall back to googleapis.com', () => { + const prevEnv = process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + try { + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + const client = new Spanner( + asAny({projectId: 'null-universe', universeDomain: null}), + ); + assert.strictEqual(client.universeDomain, 'googleapis.com'); + } finally { + if (prevEnv === undefined) { + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + } else { + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = prevEnv; + } + } + }); + it('should isolate an unscoped JWT passed via opts.authClient using createScoped', () => { const unscopedJwt = new JWT({ email: 'sa@proj.iam.gserviceaccount.com', From 42b6d74965a39414d225178c81bd57b68693ff12 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian Date: Tue, 1 Dec 2026 15:04:30 +0000 Subject: [PATCH 5/5] Addressed comments --- handwritten/spanner/src/index.ts | 90 +++++++-- handwritten/spanner/test/index.ts | 122 ++++++++++++ .../test/metrics/spanner-metrics-exporter.ts | 174 ++++++++++++++++++ 3 files changed, 370 insertions(+), 16 deletions(-) diff --git a/handwritten/spanner/src/index.ts b/handwritten/spanner/src/index.ts index ad0cdc6987b..ef52abd16d9 100644 --- a/handwritten/spanner/src/index.ts +++ b/handwritten/spanner/src/index.ts @@ -272,6 +272,31 @@ function isJwtLike(client: unknown): client is JwtLikeClient { ); } +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. * @@ -545,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(); @@ -1827,6 +1851,10 @@ 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 @@ -1838,18 +1866,48 @@ class Spanner extends GrpcService { */ private _createMetricsAuth(): GoogleAuth { const opts = this.options as SpannerOptions; - const jwtClient = isJwtLike(opts.authClient) ? opts.authClient : undefined; - return new GoogleAuth({ - ...opts, - scopes: METRICS_SCOPES, - ...(jwtClient - ? { - authClient: jwtClient.createScoped( - jwtClient.scopes, - ) as GoogleAuthOptions['authClient'], - } - : {}), - }); + 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); } /** diff --git a/handwritten/spanner/test/index.ts b/handwritten/spanner/test/index.ts index d6497073cae..8e6bc413439 100644 --- a/handwritten/spanner/test/index.ts +++ b/handwritten/spanner/test/index.ts @@ -1196,6 +1196,128 @@ describe('Spanner', () => { ); }); + 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 156b49cbb7d..ac5c01b35e1 100644 --- a/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts +++ b/handwritten/spanner/test/metrics/spanner-metrics-exporter.ts @@ -472,6 +472,180 @@ describe('CustomExporter', () => { }); }); + 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({