Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 123 additions & 6 deletions handwritten/spanner/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@
>;
observabilityOptions?: ObservabilityOptions;
disableBuiltInMetrics?: boolean;
interceptors?: any[];

Check warning on line 184 in handwritten/spanner/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
sessionLabels?: {[key: string]: string};
/**
* The Trusted Cloud Domain (TPC) DNS of the service used to make requests.
Expand Down Expand Up @@ -251,6 +251,52 @@
[P in keyof T]: P extends U ? EnumKey<E> | 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.
*
Expand Down Expand Up @@ -524,10 +570,9 @@

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();
Expand Down Expand Up @@ -653,8 +698,8 @@
if (callback) {
// process.nextTick prevents Unhandled Promise Rejections if callback throws
res
.then(() => process.nextTick(() => callback(null)))

Check warning on line 701 in handwritten/spanner/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

Avoid calling back inside of a promise
.catch(err => process.nextTick(() => callback(err)));

Check warning on line 702 in handwritten/spanner/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

Avoid calling back inside of a promise
return;
}
return res;
Expand Down Expand Up @@ -1802,6 +1847,69 @@
};
}

/**
* 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<string, unknown>).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)`.
Expand Down Expand Up @@ -1829,12 +1937,21 @@
}

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,
});
Expand Down Expand Up @@ -1926,7 +2043,7 @@
if (!this.clients_.has(clientName)) {
this.clients_.set(
clientName,
new (v1 as Record<string, any>)[clientName](this.options),

Check warning on line 2046 in handwritten/spanner/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
);
}
const gaxClient = this.clients_.get(clientName)!;
Expand Down Expand Up @@ -2224,7 +2341,7 @@
try {
const result = requestFn();
if (result && typeof result.then === 'function') {
result

Check warning on line 2344 in handwritten/spanner/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

Avoid using promises inside of callbacks

Check warning on line 2344 in handwritten/spanner/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

Avoid using promises inside of callbacks
.then(val => {
metricsTracer?.recordOperationCompletion();
resolve(val);
Expand Down
218 changes: 218 additions & 0 deletions handwritten/spanner/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
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 {
Expand Down Expand Up @@ -348,7 +349,7 @@
it('should disable channelz by default and allow overriding it', () => {
const spannerDefault = new Spanner(OPTIONS);
assert.strictEqual(
(spannerDefault.options as any)['grpc.enable_channelz'],

Check warning on line 352 in handwritten/spanner/test/index.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
0,
);

Expand All @@ -356,7 +357,7 @@
Object.assign({}, OPTIONS, {'grpc.enable_channelz': 1}),
);
assert.strictEqual(
(spannerEnabled.options as any)['grpc.enable_channelz'],

Check warning on line 360 in handwritten/spanner/test/index.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
1,
);
});
Expand Down Expand Up @@ -399,7 +400,7 @@

it('should configure metrics if project Id is not passed', async () => {
await enableMetrics(sandbox);
const spanner = new Spanner();

Check warning on line 403 in handwritten/spanner/test/index.ts

View workflow job for this annotation

GitHub Actions / lint

'spanner' is assigned a value but never used
assert.strictEqual(MetricsTracerFactory.enabled, true);
await disableMetrics(sandbox);
});
Expand Down Expand Up @@ -624,7 +625,7 @@
);

try {
const spanner = new Spanner(fakeOption);

Check warning on line 628 in handwritten/spanner/test/index.ts

View workflow job for this annotation

GitHub Actions / lint

'spanner' is assigned a value but never used
// this line should never reach client must throw an error.
throw new Error('should never reach this line');
} catch (err) {
Expand Down Expand Up @@ -1100,6 +1101,223 @@
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',
Expand Down
Loading
Loading