diff --git a/handwritten/datastore/src/constructor/auth-client.ts b/handwritten/datastore/src/constructor/auth-client.ts new file mode 100644 index 00000000000..2adad5a9f87 --- /dev/null +++ b/handwritten/datastore/src/constructor/auth-client.ts @@ -0,0 +1,105 @@ +// 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, googleAuthLibrary} from 'google-gax'; +import {DEFAULT_UNIVERSE_DOMAIN} from './constants'; + +const computeUniverseCache = new WeakMap>(); + +export function isComputeClient(client: unknown): boolean { + if (!client || typeof client !== 'object') { + return false; + } + const ComputeCtor = googleAuthLibrary?.Compute; + if (typeof ComputeCtor === 'function' && client instanceof ComputeCtor) { + return true; + } + const candidate = client as { + constructor?: {name?: string}; + serviceAccountEmail?: unknown; + fetchIdToken?: unknown; + }; + return ( + candidate.constructor?.name === 'Compute' && + typeof candidate.serviceAccountEmail === 'string' && + typeof candidate.fetchIdToken === 'function' + ); +} + +export function resolveComputeUniverse(auth: GoogleAuth): Promise { + let promise = computeUniverseCache.get(auth); + if (!promise) { + promise = auth + .getUniverseDomainFromMetadataServer() + .then(domain => domain?.trim() || DEFAULT_UNIVERSE_DOMAIN) + .catch(err => { + computeUniverseCache.delete(auth); + throw err; + }); + computeUniverseCache.set(auth, promise); + } + return promise; +} + +export async function getAuthClientWithRollback( + auth: GoogleAuth, + getClient: () => Promise, + rollbackOnError: boolean, +): Promise { + const authRecord = auth as unknown as { + cachedCredential?: T | null; + jsonContent?: unknown; + }; + const hadCachedCredential = Boolean(authRecord.cachedCredential); + const hadJsonContent = Boolean(authRecord.jsonContent); + try { + return await getClient(); + } catch (err) { + if ( + rollbackOnError && + !hadCachedCredential && + authRecord.cachedCredential + ) { + authRecord.cachedCredential = null; + if (!hadJsonContent) { + authRecord.jsonContent = null; + } + } + throw err; + } +} + +export function wrapAuthClientWithUniverse( + client: T, + resolvedUniverseDomain: string, +): T { + return new Proxy(client, { + get(target, prop) { + if (prop === 'universeDomain') { + return resolvedUniverseDomain; + } + const value = Reflect.get(target, prop, target); + if ( + typeof value === 'function' && + !Object.prototype.hasOwnProperty.call(target, prop) + ) { + return value.bind(target); + } + return value; + }, + set(target, prop, value) { + return Reflect.set(target, prop, value, target); + }, + }); +} diff --git a/handwritten/datastore/src/constructor/auth-configuration.ts b/handwritten/datastore/src/constructor/auth-configuration.ts new file mode 100644 index 00000000000..b63efff470e --- /dev/null +++ b/handwritten/datastore/src/constructor/auth-configuration.ts @@ -0,0 +1,186 @@ +// 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'; +import {buildUniverseAuthMethods} from './universe-auth-methods'; + +interface AuthClientOptionsShape { + universeDomain?: string; + universe_domain?: string; + apiKey?: string; + credentials?: unknown; +} + +function getAuthClientOptions( + auth: unknown, +): AuthClientOptionsShape | undefined { + return (auth as {clientOptions?: AuthClientOptionsShape} | null | undefined) + ?.clientOptions; +} + +function isApiKeyOnlyAuth( + auth: unknown, + clientOpts?: AuthClientOptionsShape, +): boolean { + const authRecord = auth as + | {apiKey?: string | null; jsonContent?: unknown; keyFilename?: string} + | null + | undefined; + return Boolean( + (authRecord?.apiKey || clientOpts?.apiKey) && + !authRecord?.jsonContent && + !authRecord?.keyFilename, + ); +} + +function createDatastoreAuth( + options: InternalDatastoreOptions, + universeDomain: string, +): GoogleAuth { + const authOptions: InternalDatastoreOptions = {...options}; + if (options.clientOptions) { + authOptions.clientOptions = {...options.clientOptions}; + } + delete authOptions.universeDomain; + delete authOptions.auth; + + const auth = new GoogleAuth(authOptions); + const clientOpts = authOptions.clientOptions as + AuthClientOptionsShape | undefined; + const hasExplicitClientUniverse = Boolean( + clientOpts?.universeDomain || clientOpts?.universe_domain, + ); + if ( + hasExplicitClientUniverse || + options.authClient || + typeof auth?.getClient !== 'function' || + typeof auth?.getUniverseDomainFromMetadataServer !== 'function' + ) { + return auth; + } + + const origGetClient = auth.getClient.bind(auth); + const isApiKeyOnly = Boolean( + (authOptions.apiKey || clientOpts?.apiKey) && + !authOptions.credentials && + !authOptions.keyFilename && + !authOptions.keyFile, + ); + const {getClient, getUniverseDomain} = buildUniverseAuthMethods( + auth, + universeDomain, + isApiKeyOnly, + origGetClient, + true, + ); + auth.getClient = getClient; + auth.getUniverseDomain = getUniverseDomain; + return auth; +} + +function wrapCallerAuth( + callerAuth: GoogleAuth, + universeDomain: string, +): GoogleAuth { + const clientOpts = getAuthClientOptions(callerAuth); + const hasExplicitClientUniverse = Boolean( + clientOpts?.universeDomain || clientOpts?.universe_domain, + ); + if ( + hasExplicitClientUniverse || + typeof callerAuth?.getClient !== 'function' || + typeof callerAuth?.getUniverseDomainFromMetadataServer !== 'function' + ) { + return callerAuth; + } + + const isApiKeyOnly = isApiKeyOnlyAuth(callerAuth, clientOpts); + const {getClient, getUniverseDomain} = buildUniverseAuthMethods( + callerAuth, + universeDomain, + isApiKeyOnly, + () => callerAuth.getClient(), + false, + ); + + return new Proxy(callerAuth, { + get(target, prop) { + if (prop === 'getClient') { + return getClient; + } + if (prop === 'getUniverseDomain') { + return Object.prototype.hasOwnProperty.call(target, 'getUniverseDomain') + ? target.getUniverseDomain + : getUniverseDomain; + } + const value = Reflect.get(target, prop, target); + if ( + typeof value === 'function' && + !Object.prototype.hasOwnProperty.call(target, prop) + ) { + return value.bind(target); + } + return value; + }, + set(target, prop, value) { + return Reflect.set(target, prop, value, target); + }, + }); +} + +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, +): GoogleAuth { + const callerAuth = options.auth; + const gapicAuth = callerAuth + ? wrapCallerAuth(callerAuth, universeDomain) + : createDatastoreAuth(options, universeDomain); + const datastoreAuth = + callerAuth || createDatastoreAuth(options, universeDomain); + if ( + !callerAuth && + isInsecureGrpcWithoutCredentials(options, usedDefaultInsecureCreds) && + gapicAuth && + typeof gapicAuth === 'object' + ) { + gapicAuth.getUniverseDomain = async () => universeDomain; + } + options.auth = gapicAuth; + return datastoreAuth; +} 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..1b9d37b54ad --- /dev/null +++ b/handwritten/datastore/src/constructor/options.ts @@ -0,0 +1,91 @@ +// 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 = + typeof options.universeDomain === 'string' + ? options.universeDomain.trim() + : undefined; + const snake = + typeof options.universe_domain === 'string' + ? options.universe_domain.trim() + : undefined; + 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 ('apiEndpoint' in mergedOptions) { + const trimmedApiEndpoint = + typeof mergedOptions.apiEndpoint === 'string' + ? mergedOptions.apiEndpoint.trim() + : ''; + if (trimmedApiEndpoint) { + mergedOptions.apiEndpoint = trimmedApiEndpoint; + } else { + delete mergedOptions.apiEndpoint; + } + } + const servicePath = + typeof mergedOptions.servicePath === 'string' + ? mergedOptions.servicePath.trim() + : undefined; + 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/constructor/universe-auth-methods.ts b/handwritten/datastore/src/constructor/universe-auth-methods.ts new file mode 100644 index 00000000000..af343bbc4fb --- /dev/null +++ b/handwritten/datastore/src/constructor/universe-auth-methods.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 type {GoogleAuth} from 'google-gax'; +import { + getAuthClientWithRollback, + isComputeClient, + resolveComputeUniverse, + wrapAuthClientWithUniverse, +} from './auth-client'; +import {DEFAULT_UNIVERSE_DOMAIN} from './constants'; + +export function buildUniverseAuthMethods( + auth: GoogleAuth, + universeDomain: string, + isApiKeyOnly: boolean, + getRawClient: () => ReturnType, + mutateClient: boolean, +): { + getClient: () => ReturnType; + getUniverseDomain: () => Promise; +} { + const applyClientUniverse = async < + T extends object & {universeDomain?: string}, + >( + client: T, + ): Promise => { + const hasExplicitNonDefaultUniverse = Boolean( + client.universeDomain && + client.universeDomain !== DEFAULT_UNIVERSE_DOMAIN, + ); + if ( + universeDomain !== DEFAULT_UNIVERSE_DOMAIN && + isComputeClient(client) && + !hasExplicitNonDefaultUniverse + ) { + const resolved = await resolveComputeUniverse(auth); + if (mutateClient) { + client.universeDomain = resolved; + return client; + } + return wrapAuthClientWithUniverse(client, resolved); + } + if ( + universeDomain !== DEFAULT_UNIVERSE_DOMAIN && + isApiKeyOnly && + Boolean((client as {apiKey?: string}).apiKey) && + !hasExplicitNonDefaultUniverse + ) { + if (mutateClient) { + client.universeDomain = universeDomain; + return client; + } + return wrapAuthClientWithUniverse(client, universeDomain); + } + return client; + }; + + const getClient = async () => + applyClientUniverse( + await getAuthClientWithRollback(auth, getRawClient, mutateClient), + ); + + const getUniverseDomain = async () => { + let client: Awaited>; + try { + client = await getAuthClientWithRollback( + auth, + getRawClient, + mutateClient, + ); + } catch (err) { + if ( + err instanceof Error && + err.message.startsWith('Could not load the default credentials') + ) { + return DEFAULT_UNIVERSE_DOMAIN; + } + throw err; + } + return ( + (await applyClientUniverse(client)).universeDomain || + DEFAULT_UNIVERSE_DOMAIN + ); + }; + + return {getClient, getUniverseDomain}; +} diff --git a/handwritten/datastore/src/index.ts b/handwritten/datastore/src/index.ts index 1fe0b0f31dc..e17cffa825f 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 * ``` @@ -486,7 +494,7 @@ class Datastore extends DatastoreRequest { auth: GoogleAuth; constructor(options?: DatastoreOptions) { super(); - options = options || {}; + options = {...options}; this.clients_ = new Map(); this.datastore = this; @@ -498,8 +506,13 @@ 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_( + typeof options.apiEndpoint === 'string' + ? options.apiEndpoint.trim() + : undefined, + ); const scopes: string[] = Array.from( new Set([ @@ -508,15 +521,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 +536,21 @@ 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, + ); } /** @@ -1939,6 +1960,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..ff78ae40f25 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,12 @@ async.each( } as DatastoreOptions; const datastore = new Datastore(options); + const clientOpts = datastore.options as gax.ClientOptions; assert.notStrictEqual(datastore.options, options); + assert.deepStrictEqual(options, {a: 'b', c: 'd'}); + assert.strictEqual('servicePath' in datastore.options, false); + assert.notStrictEqual(clientOpts.auth, datastore.auth); assert.deepStrictEqual( datastore.options, @@ -302,15 +323,26 @@ async.each( libName: 'gccl', libVersion: require('../../package.json').version, scopes: v1.DatastoreClient.scopes, - servicePath: datastore.baseUrl_, port: 443, projectId: undefined, + universeDomain: 'googleapis.com', + auth: clientOpts.auth, }, options, ), ); }); + it('should not mutate the passed options object', () => { + process.env.DATASTORE_PROJECT_ID = 'env-project-id'; + const options = Object.freeze({namespace: 'ns'}) as DatastoreOptions; + + const datastore = new Datastore(options); + + assert.deepStrictEqual(options, {namespace: 'ns'}); + assert.strictEqual(datastore.options.projectId, 'env-project-id'); + }); + it('should set port if detected', () => { const determineBaseUrl_ = Datastore.prototype.determineBaseUrl_; const port = 99; diff --git a/handwritten/datastore/test/universe-domain.ts b/handwritten/datastore/test/universe-domain.ts new file mode 100644 index 00000000000..97de17bb6a3 --- /dev/null +++ b/handwritten/datastore/test/universe-domain.ts @@ -0,0 +1,1051 @@ +// 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', + 'GOOGLE_CLOUD_QUOTA_PROJECT', + '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; + } + + function stubComputeMetadata( + auth: gax.GoogleAuth, + resolveMetadata: () => Promise, + ) { + const compute = new gax.googleAuthLibrary.Compute(); + sandbox + .stub( + auth as unknown as {getApplicationDefaultAsync: Function}, + 'getApplicationDefaultAsync', + ) + .resolves({ + credential: compute, + projectId: PROJECT_ID, + }); + return sandbox + .stub(auth, 'getUniverseDomainFromMetadataServer') + .callsFake(resolveMetadata); + } + + 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; + assertGrpcTarget( + await dataClient.initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + + const adminClient = (await prepareClient( + ds, + 'DatastoreAdminClient', + 'listIndexes', + )) as DatastoreAdminClient; + 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 restAuth = (restDs.options as ExtendedDatastoreOptions) + .auth as gax.GoogleAuth; + const capturedUrls: string[] = []; + sandbox.stub(restAuth, 'fetch').callsFake((async (url: string | URL) => { + capturedUrls.push(String(url)); + throw new Error('intercepted-rest-fetch'); + }) as typeof restAuth.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.options as ExtendedDatastoreOptions).auth as gax.GoogleAuth, + 'getUniverseDomainFromMetadataServer', + ) + .rejects(new Error('metadata unreachable')); + 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}); + 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}); + 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; + for (const emptyApiEndpoint of [' ', null as unknown as string]) { + const blankApiEndpointDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + apiEndpoint: emptyApiEndpoint, + credentials: tpcCreds, + }); + assert.strictEqual('apiEndpoint' in blankApiEndpointDs.options, false); + assertGrpcTarget( + await createDataClient(blankApiEndpointDs).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + } + + const frozenOpts = Object.freeze({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + credentials: tpcCreds, + }); + const frozenDs = new Datastore(frozenOpts); + assertGrpcTarget( + await createDataClient(frozenDs).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.ok(callerAuthClient.auth instanceof gax.GoogleAuth); + assert.strictEqual( + await callerAuthClient.auth.getClient(), + await callerAuth.getClient(), + ); + assert.strictEqual( + Object.prototype.hasOwnProperty.call(callerAuth, 'getClient'), + false, + ); + assert.strictEqual( + Object.prototype.hasOwnProperty.call(callerAuth, 'getUniverseDomain'), + false, + ); + 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 keyfileClient = await prepareClient( + new Datastore({keyFilename: gduJsonPath}), + 'DatastoreClient', + 'lookup', + ); + 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); + }); + + it('resolves non-GDU Compute ADC universe from metadata server without probing MDS on GDU', async () => { + for (const opts of [ + {projectId: PROJECT_ID}, + {projectId: PROJECT_ID, universeDomain: 'googleapis.com'}, + ]) { + for (const fallback of [false, true]) { + const gduVmDs = new Datastore({...opts, fallback}); + const gduMetaStub = stubComputeMetadata( + (gduVmDs.options as ExtendedDatastoreOptions).auth as gax.GoogleAuth, + async () => { + throw new Error('GDU must not query MDS universe endpoint'); + }, + ); + const stub = await createDataClient(gduVmDs).initialize(); + if (!fallback) { + assertGrpcTarget(stub, 'datastore.googleapis.com:443'); + } + assert.strictEqual(gduMetaStub.callCount, 0); + } + } + + for (const useEnv of [false, true]) { + if (useEnv) { + process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN = CUSTOM_UNIVERSE; + } else { + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + } + const tpcVmDs = new Datastore( + useEnv + ? {projectId: PROJECT_ID} + : {projectId: PROJECT_ID, universeDomain: CUSTOM_UNIVERSE}, + ); + const tpcMetaStub = stubComputeMetadata( + (tpcVmDs.options as ExtendedDatastoreOptions).auth as gax.GoogleAuth, + async () => CUSTOM_UNIVERSE, + ); + assertGrpcTarget( + await createDataClient(tpcVmDs).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + assert.strictEqual(tpcMetaStub.callCount, 1); + } + delete process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN; + + for (const fallback of [false, true]) { + const tpcOnGduVm = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + fallback, + }); + stubComputeMetadata( + (tpcOnGduVm.options as ExtendedDatastoreOptions).auth as gax.GoogleAuth, + async () => 'googleapis.com', + ); + await assert.rejects( + () => createDataClient(tpcOnGduVm).initialize(), + /does not match the universe domain found in the credentials/, + ); + } + + const tpcOnOtherTpcVm = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + }); + stubComputeMetadata( + (tpcOnOtherTpcVm.options as ExtendedDatastoreOptions) + .auth as gax.GoogleAuth, + async () => OTHER_UNIVERSE, + ); + await assert.rejects( + () => createDataClient(tpcOnOtherTpcVm).initialize(), + /does not match the universe domain found in the credentials/, + ); + + const retryDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + }); + let attempts = 0; + const retryStub = stubComputeMetadata( + (retryDs.options as ExtendedDatastoreOptions).auth as gax.GoogleAuth, + async () => { + attempts++; + if (attempts === 1) { + throw new Error('transient metadata error'); + } + return CUSTOM_UNIVERSE; + }, + ); + await assert.rejects( + () => createDataClient(retryDs).initialize(), + /transient metadata error/, + ); + assertGrpcTarget( + await createDataClient(retryDs).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + assert.strictEqual(retryStub.callCount, 2); + + const explicitCompute = new gax.googleAuthLibrary.Compute(); + const explicitDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + authClient: explicitCompute, + }); + const explicitMetadataStub = sandbox.stub( + (explicitDs.options as ExtendedDatastoreOptions).auth as gax.GoogleAuth, + 'getUniverseDomainFromMetadataServer', + ); + await assert.rejects( + () => createDataClient(explicitDs).initialize(), + /does not match the universe domain found in the credentials/, + ); + assert.strictEqual(explicitMetadataStub.callCount, 0); + }); + + it('rolls back cachedCredential and fails closed on external_account and non-ADC errors', async () => { + const tokenPath = writeTempFile('subject-token.txt', 'synthetic-token'); + const externalAccountPath = writeTempFile( + 'external-account.json', + JSON.stringify({ + type: 'external_account', + universe_domain: CUSTOM_UNIVERSE, + audience: `//iam.${CUSTOM_UNIVERSE}/projects/123/locations/global/workloadIdentityPools/p/providers/pr`, + subject_token_type: 'urn:ietf:params:oauth:token-type:jwt', + token_url: `https://sts.${CUSTOM_UNIVERSE}/v1/token`, + credential_source: {file: tokenPath}, + }), + ); + process.env.GOOGLE_APPLICATION_CREDENTIALS = externalAccountPath; + + for (const fallback of [false, true]) { + const gduExternalWithProjectDs = new Datastore({ + projectId: PROJECT_ID, + fallback, + }); + await assert.rejects( + () => createDataClient(gduExternalWithProjectDs).initialize(), + /does not match the universe domain found in the credentials/, + ); + } + + for (const fallback of [false, true]) { + const gduExternalDs = new Datastore({fallback}); + const gduExternalAuth = ( + gduExternalDs.options as ExtendedDatastoreOptions + ).auth as gax.GoogleAuth; + sandbox + .stub( + gduExternalAuth as unknown as {getProjectIdOptional: Function}, + 'getProjectIdOptional', + ) + .rejects(new Error('CRM project lookup failed')); + await assert.rejects( + () => createDataClient(gduExternalDs).initialize(), + /CRM project lookup failed/, + ); + assert.strictEqual(gduExternalAuth.cachedCredential, null); + await assert.rejects( + () => createDataClient(gduExternalDs).initialize(), + /CRM project lookup failed/, + ); + } + + const tpcExternalDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + }); + assertGrpcTarget( + await createDataClient(tpcExternalDs).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + + const tpcExternalRestDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + fallback: true, + }); + const tpcExternalRestAuth = ( + tpcExternalRestDs.options as ExtendedDatastoreOptions + ).auth as gax.GoogleAuth; + const restExtUrls: string[] = []; + sandbox.stub(tpcExternalRestAuth, 'fetch').callsFake((async ( + url: string | URL, + ) => { + restExtUrls.push(String(url)); + throw new Error('intercepted-rest-fetch'); + }) as typeof tpcExternalRestAuth.fetch); + const tpcExternalRestStub = + await createDataClient(tpcExternalRestDs).initialize(); + await new Promise(resolve => + tpcExternalRestStub.lookup( + {projectId: PROJECT_ID, keys: []}, + {}, + {}, + () => resolve(), + ), + ); + assert.strictEqual(restExtUrls.length, 1); + assert.ok( + restExtUrls[0].startsWith(`https://datastore.${CUSTOM_UNIVERSE}:443/`), + ); + + process.env.GOOGLE_APPLICATION_CREDENTIALS = path.join( + path.dirname(externalAccountPath), + 'does-not-exist.json', + ); + const brokenCredsDs = new Datastore({projectId: PROJECT_ID}); + await assert.rejects( + () => createDataClient(brokenCredsDs).initialize(), + /GOOGLE_APPLICATION_CREDENTIALS/, + ); + }); + + it('enforces non-GDU Compute metadata and fail-closed universe checks for caller-supplied auth', async () => { + for (const fallback of [false, true]) { + const callerAuth = new gax.GoogleAuth(); + const compute = new gax.googleAuthLibrary.Compute(); + sandbox + .stub( + callerAuth as unknown as {getApplicationDefaultAsync: Function}, + 'getApplicationDefaultAsync', + ) + .resolves({credential: compute, projectId: PROJECT_ID}); + const gduMetaStub = sandbox + .stub(callerAuth, 'getUniverseDomainFromMetadataServer') + .rejects(new Error('GDU must not query MDS universe endpoint')); + + const gduCallerAuthDs = new Datastore({ + projectId: PROJECT_ID, + auth: callerAuth, + fallback, + } as ExtendedDatastoreOptions); + assert.strictEqual(gduCallerAuthDs.auth, callerAuth); + const stub = await createDataClient(gduCallerAuthDs).initialize(); + if (!fallback) { + assertGrpcTarget(stub, 'datastore.googleapis.com:443'); + } + assert.strictEqual(gduMetaStub.callCount, 0); + assert.strictEqual(compute.universeDomain, 'googleapis.com'); + assert.strictEqual( + Object.prototype.hasOwnProperty.call(callerAuth, 'getUniverseDomain'), + false, + ); + } + + const explicitUniverseCompute = new gax.googleAuthLibrary.Compute({ + universeDomain: OTHER_UNIVERSE, + }); + const explicitComputeCallerAuth = new gax.GoogleAuth({ + projectId: PROJECT_ID, + authClient: explicitUniverseCompute, + }); + const explicitComputeMetaStub = sandbox + .stub(explicitComputeCallerAuth, 'getUniverseDomainFromMetadataServer') + .resolves(CUSTOM_UNIVERSE); + const explicitComputeMismatchDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + auth: explicitComputeCallerAuth, + } as ExtendedDatastoreOptions); + await assert.rejects( + () => createDataClient(explicitComputeMismatchDs).initialize(), + /does not match the universe domain found in the credentials/, + ); + assert.strictEqual(explicitComputeMetaStub.callCount, 0); + + const tpcCallerAuth = new gax.GoogleAuth(); + const tpcCompute = new gax.googleAuthLibrary.Compute(); + sandbox + .stub( + tpcCallerAuth as unknown as {getApplicationDefaultAsync: Function}, + 'getApplicationDefaultAsync', + ) + .resolves({credential: tpcCompute, projectId: PROJECT_ID}); + const tpcCallerMetaStub = sandbox + .stub(tpcCallerAuth, 'getUniverseDomainFromMetadataServer') + .resolves(CUSTOM_UNIVERSE); + + const tpcCallerAuthDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + auth: tpcCallerAuth, + } as ExtendedDatastoreOptions); + assertGrpcTarget( + await createDataClient(tpcCallerAuthDs).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + assert.strictEqual(tpcCompute.universeDomain, 'googleapis.com'); + + const tpcCallerAuthRestDs = new Datastore({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + auth: tpcCallerAuth, + fallback: true, + } as ExtendedDatastoreOptions); + const capturedRestUrls: string[] = []; + sandbox.stub(tpcCallerAuth, 'fetch').callsFake((async ( + url: string | URL, + ) => { + capturedRestUrls.push(String(url)); + throw new Error('intercepted-rest-fetch'); + }) as typeof tpcCallerAuth.fetch); + const tpcCallerRestStub = + await createDataClient(tpcCallerAuthRestDs).initialize(); + await new Promise(resolve => + tpcCallerRestStub.lookup({projectId: PROJECT_ID, keys: []}, {}, {}, () => + resolve(), + ), + ); + assert.strictEqual(capturedRestUrls.length, 1); + assert.ok( + capturedRestUrls[0].startsWith( + `https://datastore.${CUSTOM_UNIVERSE}:443/`, + ), + ); + assert.strictEqual(tpcCallerMetaStub.callCount, 1); + + const tokenPath = writeTempFile('caller-subject-token.txt', 'token'); + const externalAccountPath = writeTempFile( + 'caller-external-account.json', + JSON.stringify({ + type: 'external_account', + universe_domain: CUSTOM_UNIVERSE, + audience: `//iam.${CUSTOM_UNIVERSE}/projects/123/locations/global/workloadIdentityPools/p/providers/pr`, + subject_token_type: 'urn:ietf:params:oauth:token-type:jwt', + token_url: `https://sts.${CUSTOM_UNIVERSE}/v1/token`, + credential_source: {file: tokenPath}, + }), + ); + process.env.GOOGLE_APPLICATION_CREDENTIALS = externalAccountPath; + for (const fallback of [false, true]) { + const extCallerAuth = new gax.GoogleAuth(); + sandbox + .stub( + extCallerAuth as unknown as {getProjectIdOptional: Function}, + 'getProjectIdOptional', + ) + .rejects(new Error('CRM project lookup failed')); + const gduExtCallerDs = new Datastore({ + auth: extCallerAuth, + fallback, + } as ExtendedDatastoreOptions); + await assert.rejects( + () => createDataClient(gduExtCallerDs).initialize(), + /CRM project lookup failed/, + ); + await assert.rejects( + () => createDataClient(gduExtCallerDs).initialize(), + /does not match the universe domain found in the credentials/, + ); + } + delete process.env.GOOGLE_APPLICATION_CREDENTIALS; + + const sharedApiKeyAuth = new gax.GoogleAuth({ + projectId: PROJECT_ID, + apiKey: 'synthetic-api-key', + }); + const apiKeyCallerDs1 = new Datastore({ + universeDomain: CUSTOM_UNIVERSE, + auth: sharedApiKeyAuth, + } as ExtendedDatastoreOptions); + const apiKeyCallerDs2 = new Datastore({ + universeDomain: OTHER_UNIVERSE, + auth: sharedApiKeyAuth, + } as ExtendedDatastoreOptions); + assertGrpcTarget( + await createDataClient(apiKeyCallerDs1).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + assertGrpcTarget( + await createDataClient(apiKeyCallerDs2).initialize(), + `datastore.${OTHER_UNIVERSE}:443`, + ); + + const brokenCallerAuth = new gax.GoogleAuth({ + projectId: PROJECT_ID, + keyFilename: path.join( + path.dirname(externalAccountPath), + 'does-not-exist.json', + ), + }); + const brokenCallerDs = new Datastore({ + auth: brokenCallerAuth, + } as ExtendedDatastoreOptions); + await assert.rejects( + () => createDataClient(brokenCallerDs).initialize(), + /ENOENT/, + ); + + const explicitCallerAuth = new gax.GoogleAuth({ + projectId: PROJECT_ID, + universeDomain: CUSTOM_UNIVERSE, + credentials: gduCreds, + }); + const explicitMatchDs = new Datastore({ + universeDomain: CUSTOM_UNIVERSE, + auth: explicitCallerAuth, + } as ExtendedDatastoreOptions); + assertGrpcTarget( + await createDataClient(explicitMatchDs).initialize(), + `datastore.${CUSTOM_UNIVERSE}:443`, + ); + const explicitMismatchDs = new Datastore({ + universeDomain: OTHER_UNIVERSE, + auth: explicitCallerAuth, + } as ExtendedDatastoreOptions); + await assert.rejects( + () => createDataClient(explicitMismatchDs).initialize(), + /does not match the universe domain found in the credentials/, + ); + }); +});