Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Backwards-Compatible Auth #1624

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from 11 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
4 changes: 2 additions & 2 deletions samples/jwt.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2017, Google, Inc.
// Copyright 2017 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
Expand Down Expand Up @@ -27,7 +27,7 @@ const {JWT} = require('google-auth-library');
const fs = require('fs');

async function main(
// Full path to the sevice account credential
// Full path to the service account credential
keyFile = process.env.GOOGLE_APPLICATION_CREDENTIALS
) {
const keys = JSON.parse(fs.readFileSync(keyFile, 'utf8'));
Expand Down
4 changes: 2 additions & 2 deletions samples/keyfile.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2018, Google, LLC.
// Copyright 2018 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
Expand All @@ -22,7 +22,7 @@ const {GoogleAuth} = require('google-auth-library');
* Acquire a client, and make a request to an API that's enabled by default.
*/
async function main(
// Full path to the sevice account credential
// Full path to the service account credential
keyFile = process.env.GOOGLE_APPLICATION_CREDENTIALS
) {
const auth = new GoogleAuth({
Expand Down
35 changes: 33 additions & 2 deletions src/auth/authclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,28 @@ export declare interface AuthClient {
on(event: 'tokens', listener: (tokens: Credentials) => void): this;
}

/**
* A capabilities-based, backwards-compatible interface for {@link AuthClient}.
* This is useful for projects where multiple versions of `google-auth-library`
* may exist and thus instances of `AuthClient != AuthClient` (e.g. v8 vs v9).
*
* @see {@link AuthClient}.
* @see {@link AuthClient.normalize} for the normalizing this to {@link AuthClient}.
*
* @see {@link https://github.com/googleapis/google-auth-library-nodejs/issues/1402} for background.
*/
export interface AuthClientLike {
setCredentials(credentials: Credentials): void;
request: (opts: {}) => Promise<{}>;
}

export abstract class AuthClient
extends EventEmitter
implements CredentialsClient
implements CredentialsClient, AuthClientLike
{
/**
* The quota project ID. The quota project can be used by client libraries for the billing purpose.
* See {@link https://cloud.google.com/docs/quota| Working with quotas}
* See {@link https://cloud.google.com/docs/quota Working with quotas}
*/
quotaProjectId?: string;
transporter: Transporter = new DefaultTransporter();
Expand All @@ -99,6 +114,22 @@ export abstract class AuthClient
eagerRefreshThresholdMillis = 5 * 60 * 1000;
forceRefreshOnFailure = false;

/**
* Different versions of `AuthClient` may use this method to ensure
* the provided `AuthClientLike` has the appropriate capabilities
* required for its respective version.
*
* @see {@link AuthClientLike}'s description and background.
*
* @param authClient an {@link AuthClientLike} instance to normalize.
* @returns a normalized {@link AuthClient} instance.
*/
static normalize<T extends AuthClient = AuthClient>(
authClient: AuthClientLike | T
): T {
return authClient as T;
}

/**
* Provides an alternative Gaxios request implementation with auth credentials
*/
Expand Down
50 changes: 48 additions & 2 deletions src/auth/googleauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import {
EXTERNAL_ACCOUNT_TYPE,
BaseExternalAccountClient,
} from './baseexternalclient';
import {AuthClient} from './authclient';
import {AuthClient, AuthClientLike} from './authclient';
import {
EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE,
ExternalAccountAuthorizedUserClient,
Expand Down Expand Up @@ -133,7 +133,29 @@ const GoogleAuthExceptionMessages = {
'https://cloud.google.com/docs/authentication/getting-started',
} as const;

export class GoogleAuth<T extends AuthClient = JSONClient> {
/**
* A capabilities-based, backwards-compatible interface for {@link GoogleAuth}.
* This is useful for projects where multiple versions of `google-auth-library`
* may exist and thus instances of `GoogleAuth != GoogleAuth` (e.g. v8 vs v9).
*
* @see {@link GoogleAuth}.
* @see {@link GoogleAuth.normalize} for the normalizing this to {@link GoogleAuth}.
* @see {@link AuthClientLike} for the compatibility version of {@link AuthClient}.
*
* @see {@link https://github.com/googleapis/google-auth-library-nodejs/issues/1402} for background.
*
* @example
* ```ts
* const auth = new GoogleAuth();
* ```
*/
export interface GoogleAuthLike {
getClient: () => Promise<AuthClientLike>;
}

export class GoogleAuth<T extends AuthClient = JSONClient>
implements GoogleAuthLike
{
transporter?: Transporter;

/**
Expand Down Expand Up @@ -174,6 +196,30 @@ export class GoogleAuth<T extends AuthClient = JSONClient> {
static DefaultTransporter = DefaultTransporter;

/**
* Different versions of `GoogleAuth` may use this method to ensure
* the provided `AuthClient` or `GoogleAuthLike` has the appropriate
* capabilities required for its respective version.
*
* @see {@link GoogleAuthLike}'s description and background.
* @see {@link AuthClientLike}'s description and background.
*
* @param auth an {@link AuthClientLike} or {@link GoogleAuthLike} instance to normalize.
* @returns a normalized {@link GoogleAuth} instance.
*/
static normalize<T extends AuthClient = AuthClient>(
auth: AuthClientLike | T | GoogleAuthLike | GoogleAuth<T>
): GoogleAuth<T> {
if (!('getClient' in auth)) {
// must be `AuthClient` | `AuthClientLike`
const authClient = AuthClient.normalize(auth);

return new GoogleAuth({authClient});
}

return auth as GoogleAuth<T>;
}

/*
* Configuration is resolved in the following order of precedence:
* - {@link GoogleAuthOptions.credentials `credentials`}
* - {@link GoogleAuthOptions.keyFilename `keyFilename`}
Expand Down
Binary file removed test/fixtures/key.p12

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this related to the changes here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not really; noticed it was an unused file that we can remove

Binary file not shown.
47 changes: 47 additions & 0 deletions test/test.authclient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright 2023 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 {strict as assert} from 'assert';
import {AuthClient} from '../src';
import {GaxiosPromise} from 'gaxios';

describe('static', () => {
describe('normalize', () => {
it('should accept and normalize `AuthClient`', async () => {
class MyAuthClient extends AuthClient {
getRequestHeaders = async () => ({});
getAccessToken = async () => ({});

request<T>(): GaxiosPromise<T> {
return {} as GaxiosPromise<T>;
}
}

const authClient = new MyAuthClient();
const auth = AuthClient.normalize(authClient);

assert.equal(auth, authClient);
});

it('should accept and normalize `AuthClientLike`', async () => {
const authClientLike = {
request: async () => ({}),
setCredentials: () => {},
};
const auth = AuthClient.normalize(authClientLike);

assert.equal(auth, authClientLike);
});
});
});
51 changes: 50 additions & 1 deletion test/test.googleauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
import {BaseExternalAccountClient} from '../src/auth/baseexternalclient';
import {AuthClient} from '../src/auth/authclient';
import {ExternalAccountAuthorizedUserClient} from '../src/auth/externalAccountAuthorizedUserClient';
import {GaxiosPromise} from 'gaxios';

nock.disableNetConnect();

Expand Down Expand Up @@ -107,7 +108,55 @@ describe('googleauth', () => {
.reply(200, body);
}

describe('googleauth', () => {
describe('static', () => {
describe('normalize', () => {
it('should accept and normalize `GoogleAuth`', () => {
const googleAuth = new GoogleAuth();

const auth = GoogleAuth.normalize(googleAuth);
assert.strictEqual(auth, googleAuth);
});

it('should accept and normalize `GoogleAuthLike`', () => {
const authClientLike = {
request: async () => ({}),
setCredentials: () => {},
};
const googleAuthLike = {getClient: async () => authClientLike};

const auth = GoogleAuth.normalize(googleAuthLike);
assert.strictEqual(auth, googleAuthLike);
});

it('should accept and normalize `AuthClient`', async () => {
class MyAuthClient extends AuthClient {
getRequestHeaders = async () => ({});
getAccessToken = async () => ({});

request<T>(): GaxiosPromise<T> {
return {} as GaxiosPromise<T>;
}
}

const authClient = new MyAuthClient();
const auth = GoogleAuth.normalize(authClient);

assert.strictEqual(await auth.getClient(), authClient);
});

it('should accept and normalize `AuthClientLike`', async () => {
const authClientLike = {
request: async () => ({}),
setCredentials: () => {},
};
const auth = GoogleAuth.normalize(authClientLike);

assert.strictEqual(await auth.getClient(), authClientLike);
});
});
});

describe('instance', () => {
let auth: GoogleAuth;
const sandbox = sinon.createSandbox();
let osStub: sinon.SinonStub<[], NodeJS.Platform>;
Expand Down
1 change: 0 additions & 1 deletion test/test.jwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ describe('jwt', () => {
const keypair = require('keypair');
const PEM_PATH = './test/fixtures/private.pem';
const PEM_CONTENTS = fs.readFileSync(PEM_PATH, 'utf8');
const P12_PATH = './test/fixtures/key.p12';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here, was it just an unused value?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, an unused value


nock.disableNetConnect();

Expand Down
Loading