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
90 changes: 90 additions & 0 deletions handwritten/datastore/src/constructor/auth-configuration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// 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,
): GoogleAuth {
const callerAuth = options.auth;
const gapicAuth = callerAuth || createDatastoreAuth(options);
if (
!callerAuth &&
isInsecureGrpcWithoutCredentials(options, usedDefaultInsecureCreds) &&
gapicAuth &&
typeof gapicAuth === 'object'
) {
gapicAuth.getUniverseDomain = async () => universeDomain;
}
options.auth = gapicAuth;
return callerAuth || createDatastoreAuth(options);
}
24 changes: 24 additions & 0 deletions handwritten/datastore/src/constructor/constants.ts
Original file line number Diff line number Diff line change
@@ -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;
}
79 changes: 79 additions & 0 deletions handwritten/datastore/src/constructor/options.ts
Original file line number Diff line number Diff line change
@@ -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;
}
52 changes: 35 additions & 17 deletions handwritten/datastore/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@
entity,
Entities,
Entity,
EntityProto,

Check warning on line 46 in handwritten/datastore/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

'EntityProto' is defined but never used
ValueProto,
PropertyTransform,
} from './entity';
import {AggregateField} from './aggregate';

Check warning on line 50 in handwritten/datastore/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

'/home/runner/work/google-cloud-node/google-cloud-node/handwritten/datastore/src/aggregate.ts' imported multiple times
import Key = entity.Key;
export {Entity, Key, AggregateField};
import {PropertyFilter, and, or} from './filter';
Expand All @@ -67,20 +67,22 @@
PrepareEntityObjectResponse,
SaveCallback,
SaveResponse,
Mutation,

Check warning on line 70 in handwritten/datastore/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

'Mutation' is defined but never used
RequestOptions,
} from './request';
import {Transaction} from './transaction';
import {promisifyAll} from '@google-cloud/promisify';
import {google} from './protos';
import {AggregateQuery} from './aggregate';

Check warning on line 76 in handwritten/datastore/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

'/home/runner/work/google-cloud-node/google-cloud-node/handwritten/datastore/src/aggregate.ts' imported multiple times
import {SaveEntity} from './interfaces/save';
import {extendExcludeFromIndexes} from './utils/entity/extendExcludeFromIndexes';
import {buildEntityProto} from './utils/entity/buildEntityProto';
import IValue = google.datastore.v1.IValue;

Check warning on line 80 in handwritten/datastore/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

'IValue' is defined but never used
import IEntity = google.datastore.v1.IEntity;
import ServerValue = google.datastore.v1.PropertyTransform.ServerValue;

Check warning on line 82 in handwritten/datastore/src/index.ts

View workflow job for this annotation

GitHub Actions / lint

'ServerValue' is defined but never used
import {buildPropertyTransforms} from './utils/entity/buildPropertyTransforms';
import {configureDatastoreAuth} from './constructor/auth-configuration';
import {buildClientOptions, resolveUniverseDomain} from './constructor/options';

const {grpc} = new GrpcClient();

Expand Down Expand Up @@ -113,16 +115,20 @@
export type LongRunningResponse = [Operation, google.longrunning.IOperation];
export type Fallback = boolean | 'rest' | 'proto';

export interface ExportEntitiesConfig
extends Omit<google.datastore.admin.v1.IExportEntitiesRequest, 'projectId'> {
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<google.datastore.admin.v1.IImportEntitiesRequest, 'projectId'> {
export interface ImportEntitiesConfig extends Omit<
google.datastore.admin.v1.IImportEntitiesRequest,
'projectId'
> {
file?: string | {bucket: {name: string}; name: string};
kinds?: string[];
namespaces?: string[];
Expand Down Expand Up @@ -178,6 +184,8 @@
* 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
* ```
Expand Down Expand Up @@ -498,8 +506,9 @@

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([
Expand All @@ -508,15 +517,13 @@
]),
);

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_ &&
Expand All @@ -525,11 +532,21 @@
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,
);
}

/**
Expand Down Expand Up @@ -1939,6 +1956,7 @@
sslCreds?: ChannelCredentials;
databaseId?: string;
fallback?: Fallback;
universe_domain?: string;
}

export interface KeyToLegacyUrlSafeCallback {
Expand Down
23 changes: 22 additions & 1 deletion handwritten/datastore/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
import {PassThrough, Readable} from 'stream';

import * as ds from '../src';
import {AggregateField, Datastore, DatastoreOptions} from '../src';

Check warning on line 22 in handwritten/datastore/test/index.ts

View workflow job for this annotation

GitHub Actions / lint

'/home/runner/work/google-cloud-node/google-cloud-node/handwritten/datastore/src/index.ts' imported multiple times

Check warning on line 22 in handwritten/datastore/test/index.ts

View workflow job for this annotation

GitHub Actions / lint

'Datastore' is defined but never used
import {Datastore as OriginalDatastore} from '../src';

Check warning on line 23 in handwritten/datastore/test/index.ts

View workflow job for this annotation

GitHub Actions / lint

'/home/runner/work/google-cloud-node/google-cloud-node/handwritten/datastore/src/index.ts' imported multiple times
import {
entity,
Entity,
Expand All @@ -34,7 +34,7 @@
import * as sinon from 'sinon';
import * as extend from 'extend';
import {google} from '../src/protos';
import {ServiceError} from 'google-gax';

Check warning on line 37 in handwritten/datastore/test/index.ts

View workflow job for this annotation

GitHub Actions / lint

'ServiceError' is defined but never used

// eslint-disable-next-line @typescript-eslint/no-var-requires
const v1 = require('../src/v1/index.js');
Expand Down Expand Up @@ -170,6 +170,8 @@
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,
Expand All @@ -190,6 +192,12 @@
'../../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},
Expand All @@ -201,12 +209,15 @@
},
'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;

Expand All @@ -222,6 +233,12 @@
} 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(() => {
Expand Down Expand Up @@ -292,8 +309,11 @@
} 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.notStrictEqual(clientOpts.auth, datastore.auth);

assert.deepStrictEqual(
datastore.options,
Expand All @@ -302,9 +322,10 @@
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,
),
Expand Down
Loading
Loading