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
105 changes: 105 additions & 0 deletions handwritten/datastore/src/constructor/auth-client.ts
Original file line number Diff line number Diff line change
@@ -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<object, Promise<string>>();

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<string> {
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<T>(
auth: GoogleAuth,
getClient: () => Promise<T>,
rollbackOnError: boolean,
): Promise<T> {
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<T extends object>(
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);
},
});
}
116 changes: 106 additions & 10 deletions handwritten/datastore/src/constructor/auth-configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import {GoogleAuth} from 'google-gax';
import {InternalDatastoreOptions} from './constants';
import {buildUniverseAuthMethods} from './universe-auth-methods';

interface AuthClientOptionsShape {
universeDomain?: string;
Expand All @@ -22,30 +23,121 @@ interface AuthClientOptionsShape {
credentials?: unknown;
}

function createDatastoreAuth(options: InternalDatastoreOptions): GoogleAuth {
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 &&
!authOptions.authClient &&
!clientOpts?.credentials,
!authOptions.keyFile,
);
if (!isApiKeyOnly || hasExplicitClientUniverse) {
delete authOptions.universeDomain;
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;
}
delete authOptions.auth;

return new GoogleAuth(authOptions);
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(
Expand Down Expand Up @@ -76,7 +168,11 @@ export function configureDatastoreAuth(
usedDefaultInsecureCreds = false,
): GoogleAuth {
const callerAuth = options.auth;
const gapicAuth = callerAuth || createDatastoreAuth(options);
const gapicAuth = callerAuth
? wrapCallerAuth(callerAuth, universeDomain)
: createDatastoreAuth(options, universeDomain);
const datastoreAuth =
callerAuth || createDatastoreAuth(options, universeDomain);
if (
!callerAuth &&
isInsecureGrpcWithoutCredentials(options, usedDefaultInsecureCreds) &&
Expand All @@ -86,5 +182,5 @@ export function configureDatastoreAuth(
gapicAuth.getUniverseDomain = async () => universeDomain;
}
options.auth = gapicAuth;
return callerAuth || createDatastoreAuth(options);
return datastoreAuth;
}
22 changes: 17 additions & 5 deletions handwritten/datastore/src/constructor/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,14 @@ import {DEFAULT_UNIVERSE_DOMAIN, InternalDatastoreOptions} from './constants';
export function resolveUniverseDomain(
options: InternalDatastoreOptions,
): string {
const camel = options.universeDomain?.trim();
const snake = options.universe_domain?.trim();
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.');
}
Expand Down Expand Up @@ -53,15 +59,21 @@ export function buildClientOptions(
options,
{universeDomain},
);
if (mergedOptions.apiEndpoint !== undefined) {
const trimmedApiEndpoint = mergedOptions.apiEndpoint.trim();
if ('apiEndpoint' in mergedOptions) {
const trimmedApiEndpoint =
typeof mergedOptions.apiEndpoint === 'string'
? mergedOptions.apiEndpoint.trim()
: '';
if (trimmedApiEndpoint) {
mergedOptions.apiEndpoint = trimmedApiEndpoint;
} else {
delete mergedOptions.apiEndpoint;
}
}
const servicePath = mergedOptions.servicePath?.trim();
const servicePath =
typeof mergedOptions.servicePath === 'string'
? mergedOptions.servicePath.trim()
: undefined;
if (servicePath) {
mergedOptions.servicePath = servicePath;
} else if (customEndpoint && baseUrl?.trim()) {
Expand Down
Loading
Loading