From e63417cd63cc529b9a32c4c616448d99873ff1cf Mon Sep 17 00:00:00 2001 From: Daniel Bruce Date: Mon, 30 Nov 2026 21:15:02 +0000 Subject: [PATCH] test: fix c1 --- .../src/constructor/auth-configuration.ts | 99 +++ .../datastore/src/constructor/constants.ts | 24 + .../datastore/src/constructor/options.ts | 79 +++ handwritten/datastore/src/index.ts | 53 +- handwritten/datastore/test/index.ts | 23 +- handwritten/datastore/test/universe-domain.ts | 608 ++++++++++++++++++ 6 files changed, 868 insertions(+), 18 deletions(-) create mode 100644 handwritten/datastore/src/constructor/auth-configuration.ts create mode 100644 handwritten/datastore/src/constructor/constants.ts create mode 100644 handwritten/datastore/src/constructor/options.ts create mode 100644 handwritten/datastore/test/universe-domain.ts diff --git a/handwritten/datastore/src/constructor/auth-configuration.ts b/handwritten/datastore/src/constructor/auth-configuration.ts new file mode 100644 index 00000000000..cf5d2d6bbf2 --- /dev/null +++ b/handwritten/datastore/src/constructor/auth-configuration.ts @@ -0,0 +1,99 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {GoogleAuth} from 'google-gax'; +import {InternalDatastoreOptions} from './constants'; + +interface AuthClientOptionsShape { + universeDomain?: string; + universe_domain?: string; + apiKey?: string; + credentials?: unknown; +} + +function createDatastoreAuth(options: InternalDatastoreOptions): GoogleAuth { + const authOptions: InternalDatastoreOptions = {...options}; + if (options.clientOptions) { + authOptions.clientOptions = {...options.clientOptions}; + } + const clientOpts = authOptions.clientOptions as + AuthClientOptionsShape | undefined; + const hasExplicitClientUniverse = Boolean( + clientOpts?.universeDomain || clientOpts?.universe_domain, + ); + const isApiKeyOnly = Boolean( + (authOptions.apiKey || clientOpts?.apiKey) && + !authOptions.credentials && + !authOptions.keyFilename && + !authOptions.keyFile && + !authOptions.authClient && + !clientOpts?.credentials, + ); + if (!isApiKeyOnly || hasExplicitClientUniverse) { + delete authOptions.universeDomain; + } + delete authOptions.auth; + + return new GoogleAuth(authOptions); +} + +function isInsecureGrpcWithoutCredentials( + options: InternalDatastoreOptions, + usedDefaultInsecureCreds = false, +): boolean { + const sslCreds = options.sslCreds as {_isSecure?: () => boolean} | undefined; + const clientOpts = options.clientOptions as + AuthClientOptionsShape | undefined; + const hasInsecureSslCreds = + usedDefaultInsecureCreds || sslCreds?._isSecure?.() === false; + return Boolean( + hasInsecureSslCreds && + !options.fallback && + !options.credentials && + !options.keyFilename && + !options.keyFile && + !options.authClient && + !options.apiKey && + !clientOpts?.apiKey && + !clientOpts?.credentials, + ); +} + +export function configureDatastoreAuth( + options: InternalDatastoreOptions, + universeDomain: string, + usedDefaultInsecureCreds = false, + defaultScopes?: string[], +): GoogleAuth { + const callerAuth = options.auth; + const gapicAuth = callerAuth || createDatastoreAuth(options); + if (!callerAuth && gapicAuth && typeof gapicAuth === 'object') { + // Pre-populate GAPIC JWT settings before getProjectId() can lazily load + // and cache a JWT credential prior to GAPIC client construction. + const defaultServicePath = `datastore.${universeDomain}`; + gapicAuth.useJWTAccessWithScope = true; + gapicAuth.defaultServicePath = defaultServicePath; + if ( + (options.servicePath || options.apiEndpoint || defaultServicePath) === + defaultServicePath + ) { + gapicAuth.defaultScopes = defaultScopes ?? options.scopes; + } + if (isInsecureGrpcWithoutCredentials(options, usedDefaultInsecureCreds)) { + gapicAuth.getUniverseDomain = async () => universeDomain; + } + } + options.auth = gapicAuth; + return gapicAuth; +} diff --git a/handwritten/datastore/src/constructor/constants.ts b/handwritten/datastore/src/constructor/constants.ts new file mode 100644 index 00000000000..7287c759b85 --- /dev/null +++ b/handwritten/datastore/src/constructor/constants.ts @@ -0,0 +1,24 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import type {GoogleAuth} from 'google-gax'; +import type {DatastoreOptions} from '../index'; + +export const DEFAULT_UNIVERSE_DOMAIN = 'googleapis.com'; + +export interface InternalDatastoreOptions extends DatastoreOptions { + servicePath?: string; + port?: number; + auth?: GoogleAuth; +} diff --git a/handwritten/datastore/src/constructor/options.ts b/handwritten/datastore/src/constructor/options.ts new file mode 100644 index 00000000000..f19f376eb01 --- /dev/null +++ b/handwritten/datastore/src/constructor/options.ts @@ -0,0 +1,79 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import {DEFAULT_UNIVERSE_DOMAIN, InternalDatastoreOptions} from './constants'; + +export function resolveUniverseDomain( + options: InternalDatastoreOptions, +): string { + const camel = options.universeDomain?.trim(); + const snake = options.universe_domain?.trim(); + if (camel === '' || snake === '') { + throw new Error('The universe domain cannot be an empty string.'); + } + if (camel && snake && camel !== snake) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.', + ); + } + const env = + typeof process === 'object' && process !== null + ? process.env?.GOOGLE_CLOUD_UNIVERSE_DOMAIN?.trim() + : undefined; + return camel || snake || env || DEFAULT_UNIVERSE_DOMAIN; +} + +export function buildClientOptions( + options: InternalDatastoreOptions, + scopes: string[], + universeDomain: string, + customEndpoint?: boolean, + baseUrl?: string, + detectedPort?: number, +): InternalDatastoreOptions { + const defaultPort = typeof detectedPort === 'number' ? detectedPort : 443; + const mergedOptions: InternalDatastoreOptions = Object.assign( + { + libName: 'gccl', + libVersion: require('../../../package.json').version, + scopes, + port: defaultPort, + }, + options, + {universeDomain}, + ); + if (mergedOptions.apiEndpoint !== undefined) { + const trimmedApiEndpoint = mergedOptions.apiEndpoint.trim(); + if (trimmedApiEndpoint) { + mergedOptions.apiEndpoint = trimmedApiEndpoint; + } else { + delete mergedOptions.apiEndpoint; + } + } + const servicePath = mergedOptions.servicePath?.trim(); + if (servicePath) { + mergedOptions.servicePath = servicePath; + } else if (customEndpoint && baseUrl?.trim()) { + mergedOptions.servicePath = baseUrl.trim(); + } else { + delete mergedOptions.servicePath; + } + mergedOptions.port ||= defaultPort; + mergedOptions.scopes ??= scopes; + if (mergedOptions.fallback === undefined) { + delete mergedOptions.fallback; + } + delete mergedOptions.universe_domain; + return mergedOptions; +} diff --git a/handwritten/datastore/src/index.ts b/handwritten/datastore/src/index.ts index 1fe0b0f31dc..12cc6d3de52 100644 --- a/handwritten/datastore/src/index.ts +++ b/handwritten/datastore/src/index.ts @@ -81,6 +81,8 @@ import IValue = google.datastore.v1.IValue; import IEntity = google.datastore.v1.IEntity; import ServerValue = google.datastore.v1.PropertyTransform.ServerValue; import {buildPropertyTransforms} from './utils/entity/buildPropertyTransforms'; +import {configureDatastoreAuth} from './constructor/auth-configuration'; +import {buildClientOptions, resolveUniverseDomain} from './constructor/options'; const {grpc} = new GrpcClient(); @@ -113,16 +115,20 @@ export interface LongRunningCallback { export type LongRunningResponse = [Operation, google.longrunning.IOperation]; export type Fallback = boolean | 'rest' | 'proto'; -export interface ExportEntitiesConfig - extends Omit { +export interface ExportEntitiesConfig extends Omit< + google.datastore.admin.v1.IExportEntitiesRequest, + 'projectId' +> { bucket?: string | {name: string}; kinds?: string[]; namespaces?: string[]; gaxOptions?: CallOptions; } -export interface ImportEntitiesConfig - extends Omit { +export interface ImportEntitiesConfig extends Omit< + google.datastore.admin.v1.IImportEntitiesRequest, + 'projectId' +> { file?: string | {bucket: {name: string}; name: string}; kinds?: string[]; namespaces?: string[]; @@ -178,6 +184,8 @@ const urlSafeKey = new entity.URLSafeKey(); * to reach Datastore. This is useful for connecting to your local Datastore * server (usually "http://localhost:8080"). * @param {string} [options.namespace] Namespace to isolate transactions to. + * @param {string} [options.universeDomain] The default service domain for a + * given Cloud universe (defaults to "googleapis.com"). * * @example Import the client library * ``` @@ -498,8 +506,9 @@ class Datastore extends DatastoreRequest { options.projectId = options.projectId || process.env.DATASTORE_PROJECT_ID; - this.defaultBaseUrl_ = 'datastore.googleapis.com'; - this.determineBaseUrl_(options.apiEndpoint); + const universeDomain = resolveUniverseDomain(options); + this.defaultBaseUrl_ = `datastore.${universeDomain}`; + this.determineBaseUrl_(options.apiEndpoint?.trim()); const scopes: string[] = Array.from( new Set([ @@ -508,15 +517,13 @@ class Datastore extends DatastoreRequest { ]), ); - this.options = Object.assign( - { - libName: 'gccl', - libVersion: require('../../package.json').version, - scopes, - servicePath: this.baseUrl_, - port: typeof this.port_ === 'number' ? this.port_ : 443, - }, + this.options = buildClientOptions( options, + scopes, + universeDomain, + this.customEndpoint_, + this.baseUrl_, + this.port_, ); const isUsingLocalhost = this.baseUrl_ && @@ -525,11 +532,22 @@ class Datastore extends DatastoreRequest { this.baseUrl_.includes('::1')); const isEmulatorVariableSet = process.env.DATASTORE_EMULATOR_HOST?.trim(); const isUsingEmulator = isUsingLocalhost || isEmulatorVariableSet; - if (this.customEndpoint_ && isUsingEmulator) { - this.options.sslCreds ??= grpc.credentials.createInsecure(); + let usedDefaultInsecureCreds = false; + if ( + this.customEndpoint_ && + isUsingEmulator && + (this.options.sslCreds === undefined || this.options.sslCreds === null) + ) { + this.options.sslCreds = grpc.credentials.createInsecure(); + usedDefaultInsecureCreds = true; } - this.auth = new GoogleAuth(this.options); + this.auth = configureDatastoreAuth( + this.options, + universeDomain, + usedDefaultInsecureCreds, + scopes, + ); } /** @@ -1939,6 +1957,7 @@ export interface DatastoreOptions extends GoogleAuthOptions { sslCreds?: ChannelCredentials; databaseId?: string; fallback?: Fallback; + universe_domain?: string; } export interface KeyToLegacyUrlSafeCallback { diff --git a/handwritten/datastore/test/index.ts b/handwritten/datastore/test/index.ts index 753b1b79841..743164cbf64 100644 --- a/handwritten/datastore/test/index.ts +++ b/handwritten/datastore/test/index.ts @@ -170,6 +170,8 @@ async.each( const NAMESPACE = 'namespace'; const DATASTORE_PROJECT_ID_CACHED = process.env.DATASTORE_PROJECT_ID; + const GOOGLE_CLOUD_UNIVERSE_DOMAIN_CACHED = + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; const DEFAULT_OPTIONS = { projectId: PROJECT_ID, @@ -190,6 +192,12 @@ async.each( '../../entity.js': {entity: fakeEntity}, }, ); + const authConfigModule = proxyquire( + '../src/constructor/auth-configuration.js', + { + 'google-gax': fakeGoogleGax, + }, + ); Datastore = proxyquire('../src', { './entity.js': {entity: fakeEntity}, './index-class.js': {Index: FakeIndex}, @@ -201,12 +209,15 @@ async.each( }, 'google-gax': fakeGoogleGax, './utils/entity/buildEntityProto': buildEntityProtoModule, + './constructor/auth-configuration': authConfigModule, }).Datastore; }); beforeEach(() => { Object.assign(fakeEntity, fakeEntityInit); + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + createInsecureOverride = null; googleAuthOverride = null; @@ -222,6 +233,12 @@ async.each( } else { delete process.env.DATASTORE_PROJECT_ID; } + if (typeof GOOGLE_CLOUD_UNIVERSE_DOMAIN_CACHED === 'string') { + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = + GOOGLE_CLOUD_UNIVERSE_DOMAIN_CACHED; + } else { + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + } }); after(() => { @@ -292,8 +309,11 @@ async.each( } as DatastoreOptions; const datastore = new Datastore(options); + const clientOpts = datastore.options as gax.ClientOptions; assert.notStrictEqual(datastore.options, options); + assert.strictEqual('servicePath' in datastore.options, false); + assert.strictEqual(clientOpts.auth, datastore.auth); assert.deepStrictEqual( datastore.options, @@ -302,9 +322,10 @@ async.each( libName: 'gccl', libVersion: require('../../package.json').version, scopes: v1.DatastoreClient.scopes, - servicePath: datastore.baseUrl_, port: 443, projectId: undefined, + universeDomain: 'googleapis.com', + auth: datastore.auth, }, options, ), diff --git a/handwritten/datastore/test/universe-domain.ts b/handwritten/datastore/test/universe-domain.ts new file mode 100644 index 00000000000..11f8dcc2da1 --- /dev/null +++ b/handwritten/datastore/test/universe-domain.ts @@ -0,0 +1,608 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as assert from 'assert'; +import * as crypto from 'crypto'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import {afterEach, before, beforeEach, describe, it} from 'mocha'; +import * as gax from 'google-gax'; +import * as sinon from 'sinon'; + +import { + Datastore, + DatastoreAdminClient, + DatastoreClient, + DatastoreOptions, +} from '../src'; + +interface ExtendedDatastoreOptions extends DatastoreOptions { + servicePath?: string; + auth?: gax.GoogleAuth; +} + +const ENV_VARS = [ + 'GOOGLE_CLOUD_UNIVERSE_DOMAIN', + 'DATASTORE_EMULATOR_HOST', + 'DATASTORE_PROJECT_ID', + 'GCLOUD_PROJECT', + 'GOOGLE_CLOUD_PROJECT', + 'gcloud_project', + 'google_cloud_project', + 'GOOGLE_APPLICATION_CREDENTIALS', + 'google_application_credentials', + 'GOOGLE_API_USE_CLIENT_CERTIFICATE', + 'GOOGLE_API_USE_MTLS_ENDPOINT', + 'CLOUDSDK_CONFIG', + 'http_proxy', + 'https_proxy', + 'HTTP_PROXY', + 'HTTPS_PROXY', + 'grpc_proxy', + 'GRPC_PROXY', +] as const; + +const PROJECT_ID = 'test-project'; +const CUSTOM_UNIVERSE = 'my-tpc.example.com'; +const OTHER_UNIVERSE = 'other-tpc.example.com'; + +function makeCredentials( + privateKey: string, + universeDomain?: string, + projectId = PROJECT_ID, +) { + return { + type: 'service_account', + project_id: projectId, + client_email: `sa@${projectId}.iam.gserviceaccount.com`, + private_key: privateKey, + ...(universeDomain ? {universe_domain: universeDomain} : {}), + }; +} + +function assertGrpcTarget(stub: unknown, expectedHostPort: string) { + const channel = (stub as {getChannel(): {getTarget(): string}}).getChannel(); + const target = channel.getTarget().replace(/^dns:(\/\/\/)?/, ''); + assert.strictEqual(target, expectedHostPort); +} + +describe('Datastore universeDomain', () => { + let sandbox: sinon.SinonSandbox; + let savedEnv: Record; + let syntheticPrivateKey: string; + let gduCreds: ReturnType; + let tpcCreds: ReturnType; + let otherTpcCreds: ReturnType; + let clientsToClose: Array<{close(): Promise}>; + let tempDirs: string[]; + + before(() => { + const {privateKey} = crypto.generateKeyPairSync('rsa', { + modulusLength: 2048, + }); + syntheticPrivateKey = privateKey + .export({type: 'pkcs8', format: 'pem'}) + .toString(); + gduCreds = makeCredentials(syntheticPrivateKey); + tpcCreds = makeCredentials(syntheticPrivateKey, CUSTOM_UNIVERSE); + otherTpcCreds = makeCredentials(syntheticPrivateKey, OTHER_UNIVERSE); + }); + + beforeEach(() => { + sandbox = sinon.createSandbox(); + clientsToClose = []; + tempDirs = []; + savedEnv = {}; + for (const key of ENV_VARS) { + savedEnv[key] = process.env[key]; + delete process.env[key]; + } + const emptyConfigDir = fs.mkdtempSync( + path.join(os.tmpdir(), 'datastore-gcloud-'), + ); + tempDirs.push(emptyConfigDir); + process.env.CLOUDSDK_CONFIG = emptyConfigDir; + }); + + afterEach(async () => { + sandbox.restore(); + for (const client of clientsToClose) { + await client.close().catch(() => {}); + } + for (const dir of tempDirs) { + fs.rmSync(dir, {recursive: true, force: true}); + } + for (const key of ENV_VARS) { + if (savedEnv[key] === undefined) { + delete process.env[key]; + } else { + process.env[key] = savedEnv[key]; + } + } + }); + + function createDataClient(datastore: Datastore): DatastoreClient { + const client = new DatastoreClient( + datastore.options as unknown as gax.ClientOptions, + ); + clientsToClose.push(client); + return client; + } + + function createAdminClient(datastore: Datastore): DatastoreAdminClient { + const client = new DatastoreAdminClient( + datastore.options as unknown as gax.ClientOptions, + ); + clientsToClose.push(client); + return client; + } + + async function prepareClient( + datastore: Datastore, + clientName: 'DatastoreClient' | 'DatastoreAdminClient', + method: string, + ): Promise { + await new Promise((resolve, reject) => { + datastore.prepareGaxRequest_( + {client: clientName, method, reqOpts: {}, gaxOpts: {}}, + (err: Error | null) => (err ? reject(err) : resolve()), + ); + }); + const client = datastore.clients_.get(clientName) as unknown as + DatastoreClient | DatastoreAdminClient; + assert.ok(client); + clientsToClose.push(client); + return client; + } + + function writeTempFile(filename: string, contents: string): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'datastore-universe-')); + tempDirs.push(dir); + const filePath = path.join(dir, filename); + fs.writeFileSync(filePath, contents, 'utf8'); + return filePath; + } + + it('routes DatastoreClient and DatastoreAdminClient to the configured universeDomain', async () => { + const defaultDs = new Datastore({ + projectId: PROJECT_ID, + credentials: gduCreds, + }); + assert.strictEqual('servicePath' in defaultDs.options, false); + assert.strictEqual(defaultDs.options.universeDomain, 'googleapis.com'); + assertGrpcTarget( + await ( + await prepareClient(defaultDs, 'DatastoreClient', 'lookup') + ).initialize(), + 'datastore.googleapis.com:443', + ); + + const cases: Array<{ + env?: string; + opts: ExtendedDatastoreOptions; + }> = [ + { + env: OTHER_UNIVERSE, + opts: { + projectId: PROJECT_ID, + universeDomain: ` ${CUSTOM_UNIVERSE} `, + credentials: tpcCreds, + }, + }, + { + opts: { + projectId: PROJECT_ID, + universe_domain: CUSTOM_UNIVERSE, + credentials: tpcCreds, + }, + }, + { + env: CUSTOM_UNIVERSE, + opts: {projectId: PROJECT_ID, credentials: tpcCreds}, + }, + ]; + + for (const {env, opts} of cases) { + if (env) { + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = env; + } else { + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + } + const ds = new Datastore(opts); + assert.strictEqual('servicePath' in ds.options, false); + assert.strictEqual(ds.options.universeDomain, CUSTOM_UNIVERSE); + assert.strictEqual( + 'universe_domain' in (ds.options as ExtendedDatastoreOptions), + false, + ); + + const dataClient = (await prepareClient( + ds, + 'DatastoreClient', + 'lookup', + )) as DatastoreClient; + assert.strictEqual(dataClient.auth, ds.auth); + assertGrpcTarget( + await dataClient.initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + + const adminClient = (await prepareClient( + ds, + 'DatastoreAdminClient', + 'listIndexes', + )) as DatastoreAdminClient; + assert.strictEqual(adminClient.auth, ds.auth); + assertGrpcTarget( + await adminClient.initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + assertGrpcTarget( + await adminClient.operationsClient.operationsStub, + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + } + + for (const emptyEnv of ['', ' ']) { + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = emptyEnv; + const fallbackDefaultDs = new Datastore({ + projectId: PROJECT_ID, + credentials: gduCreds, + }); + assert.strictEqual( + fallbackDefaultDs.options.universeDomain, + 'googleapis.com', + ); + assertGrpcTarget( + await createDataClient(fallbackDefaultDs).initialize(), + 'datastore.googleapis.com:443', + ); + } + + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + const restDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + credentials: tpcCreds, + fallback: true, + }); + const capturedUrls: string[] = []; + sandbox.stub(restDs.auth, 'fetch').callsFake((async (url: string | URL) => { + capturedUrls.push(String(url)); + throw new Error('intercepted-rest-fetch'); + }) as typeof restDs.auth.fetch); + const restStub = await createDataClient(restDs).initialize(); + await new Promise(resolve => + restStub.lookup({projectId: PROJECT_ID, keys: []}, {}, {}, () => + resolve(), + ), + ); + assert.strictEqual(capturedUrls.length, 1); + assert.ok( + capturedUrls[0].startsWith(`https://datastore.${CUSTOM_UNIVERSE}:443/`), + ); + }); + + it('validates conflicting or empty universeDomain options and rejects mismatched credentials', async () => { + assert.throws( + () => new Datastore({universeDomain: ''}), + /cannot be an empty string/, + ); + assert.throws( + () => new Datastore({universe_domain: ' '} as ExtendedDatastoreOptions), + /cannot be an empty string/, + ); + assert.throws( + () => + new Datastore({ + universeDomain: CUSTOM_UNIVERSE, + universe_domain: OTHER_UNIVERSE, + } as ExtendedDatastoreOptions), + /Please set either universe_domain or universeDomain/, + ); + + for (const fallback of [false, true]) { + const tpcWithGdu = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + credentials: gduCreds, + fallback, + }); + await assert.rejects( + () => createDataClient(tpcWithGdu).initialize(), + /does not match the universe domain found in the credentials/, + ); + } + + for (const fallback of [false, true]) { + const gduWithTpc = new Datastore({ + projectId: PROJECT_ID, + credentials: tpcCreds, + fallback, + }); + await assert.rejects( + () => createDataClient(gduWithTpc).initialize(), + /does not match the universe domain found in the credentials/, + ); + } + + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = CUSTOM_UNIVERSE; + const envMismatch = new Datastore({ + projectId: PROJECT_ID, + credentials: otherTpcCreds, + }); + await assert.rejects( + () => createAdminClient(envMismatch).initialize(), + /does not match the universe domain found in the credentials/, + ); + + process.env.GOOGLE_API_USE_CLIENT_CERTIFICATE = 'true'; + const mtlsTpc = new Datastore({ + projectId: PROJECT_ID, + credentials: tpcCreds, + }); + await assert.rejects( + () => createDataClient(mtlsTpc).initialize(), + /mTLS is not supported outside of googleapis\.com/, + ); + }); + + it('preserves custom apiEndpoint, explicit servicePath, blank servicePath, and emulator', async () => { + const customDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + apiEndpoint: 'https://regional.example.com:8443', + credentials: tpcCreds, + }); + assertGrpcTarget( + await createDataClient(customDs).initialize(), + 'regional.example.com:8443', + ); + + const customMismatchDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + apiEndpoint: 'https://regional.example.com:8443', + credentials: gduCreds, + }); + await assert.rejects( + () => createDataClient(customMismatchDs).initialize(), + /does not match the universe domain found in the credentials/, + ); + + const explicitServicePathDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + servicePath: 'explicit.example.com', + credentials: tpcCreds, + } as ExtendedDatastoreOptions); + assertGrpcTarget( + await createDataClient(explicitServicePathDs).initialize(), + 'explicit.example.com:443', + ); + + const blankServicePathDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + servicePath: ' ', + credentials: tpcCreds, + } as ExtendedDatastoreOptions); + assert.strictEqual('servicePath' in blankServicePathDs.options, false); + assertGrpcTarget( + await createDataClient(blankServicePathDs).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + + process.env.DATASTORE_EMULATOR_HOST = 'localhost:8081'; + const emulatorDs = new Datastore({projectId: PROJECT_ID}); + assert.ok(emulatorDs.options.sslCreds); + const emulatorMetaStub = sandbox + .stub(emulatorDs.auth, 'getUniverseDomainFromMetadataServer') + .rejects(new Error('metadata unreachable')); + assert.strictEqual( + await emulatorDs.auth.getUniverseDomain(), + 'googleapis.com', + ); + assertGrpcTarget( + await createDataClient(emulatorDs).initialize(), + 'localhost:8081', + ); + assert.strictEqual(emulatorMetaStub.callCount, 0); + + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = CUSTOM_UNIVERSE; + const emulatorWithTpcEnv = new Datastore({projectId: PROJECT_ID}); + assert.strictEqual( + await emulatorWithTpcEnv.auth.getUniverseDomain(), + CUSTOM_UNIVERSE, + ); + assertGrpcTarget( + await createDataClient(emulatorWithTpcEnv).initialize(), + 'localhost:8081', + ); + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + + process.env.GOOGLE_APPLICATION_CREDENTIALS = writeTempFile( + 'tpc.json', + JSON.stringify(tpcCreds), + ); + const emulatorWithAmbientTpc = new Datastore({projectId: PROJECT_ID}); + assert.strictEqual( + await emulatorWithAmbientTpc.auth.getUniverseDomain(), + 'googleapis.com', + ); + assertGrpcTarget( + await createDataClient(emulatorWithAmbientTpc).initialize(), + 'localhost:8081', + ); + delete process.env.GOOGLE_APPLICATION_CREDENTIALS; + + const paddedCustomDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + apiEndpoint: ' https://regional.example.com:8443 ', + credentials: tpcCreds, + }); + assert.strictEqual( + paddedCustomDs.options.apiEndpoint, + 'https://regional.example.com:8443', + ); + assertGrpcTarget( + await createDataClient(paddedCustomDs).initialize(), + 'regional.example.com:8443', + ); + + process.env.DATASTORE_EMULATOR_HOST = ' '; + const blankEmulatorDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + credentials: gduCreds, + }); + assert.strictEqual(blankEmulatorDs.customEndpoint_, undefined); + assert.strictEqual(blankEmulatorDs.options.sslCreds, undefined); + assert.strictEqual('servicePath' in blankEmulatorDs.options, false); + await assert.rejects( + () => createDataClient(blankEmulatorDs).initialize(), + /does not match the universe domain found in the credentials/, + ); + + delete process.env.DATASTORE_EMULATOR_HOST; + const blankApiEndpointDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + apiEndpoint: ' ', + credentials: tpcCreds, + }); + assert.strictEqual('apiEndpoint' in blankApiEndpointDs.options, false); + assertGrpcTarget( + await createDataClient(blankApiEndpointDs).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + }); + + it('handles apiKey, JSON keyfiles, explicit clientOptions/auth, and self-signed JWTs', async () => { + const apiKeyDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + apiKey: 'synthetic-api-key', + }); + assert.strictEqual( + await apiKeyDs.auth.getUniverseDomain(), + CUSTOM_UNIVERSE, + ); + assertGrpcTarget( + await createDataClient(apiKeyDs).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + + const apiKeyMismatchDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + apiKey: 'synthetic-api-key', + clientOptions: {universeDomain: OTHER_UNIVERSE}, + }); + await assert.rejects( + () => createDataClient(apiKeyMismatchDs).initialize(), + /does not match the universe domain found in the credentials/, + ); + + const gduJsonPath = writeTempFile('gdu.json', JSON.stringify(gduCreds)); + const mismatchedJsonDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + keyFilename: gduJsonPath, + }); + await assert.rejects( + () => createDataClient(mismatchedJsonDs).initialize(), + /does not match the universe domain found in the credentials/, + ); + + const callerClientOptions = {universeDomain: CUSTOM_UNIVERSE}; + const overrideDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + clientOptions: callerClientOptions, + credentials: gduCreds, + }); + assertGrpcTarget( + await createDataClient(overrideDs).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + assert.deepStrictEqual(callerClientOptions, { + universeDomain: CUSTOM_UNIVERSE, + }); + + const callerAuth = new gax.GoogleAuth({ + projectId: PROJECT_ID, + credentials: tpcCreds, + }); + const callerAuthDs = new Datastore({ + universeDomain: CUSTOM_UNIVERSE, + auth: callerAuth, + } as ExtendedDatastoreOptions); + assert.strictEqual(callerAuthDs.auth, callerAuth); + assert.strictEqual(await callerAuthDs.getProjectId(), PROJECT_ID); + const callerAuthClient = await prepareClient( + callerAuthDs, + 'DatastoreClient', + 'lookup', + ); + assert.strictEqual(callerAuthClient.auth, callerAuth); + assert.strictEqual( + await callerAuthClient.auth.getClient(), + await callerAuth.getClient(), + ); + assertGrpcTarget( + await callerAuthClient.initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + + const callerApiKeyClientOpts = {apiKey: 'synthetic-api-key'}; + const clientOptsApiKeyDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + clientOptions: callerApiKeyClientOpts, + }); + assertGrpcTarget( + await createDataClient(clientOptsApiKeyDs).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + assert.deepStrictEqual(callerApiKeyClientOpts, { + apiKey: 'synthetic-api-key', + }); + + const keyfileDs = new Datastore({keyFilename: gduJsonPath}); + const keyfileClient = await prepareClient( + keyfileDs, + 'DatastoreClient', + 'lookup', + ); + assert.strictEqual(keyfileClient.auth, keyfileDs.auth); + await keyfileClient.initialize(); + const jwtClient = (await keyfileClient.auth.getClient()) as unknown as { + useJWTAccessWithScope?: boolean; + transporter: {request: Function}; + getRequestHeaders(url?: string): Promise; + }; + assert.strictEqual(jwtClient.useJWTAccessWithScope, true); + const tokenStub = sandbox + .stub(jwtClient.transporter, 'request') + .throws(new Error('Unexpected token HTTP request')); + const headers = await jwtClient.getRequestHeaders( + 'https://datastore.googleapis.com/google.datastore.v1.Datastore', + ); + assert.ok(headers.get('authorization')?.startsWith('Bearer ')); + assert.strictEqual(tokenStub.callCount, 0); + }); +});