Skip to content

Add refresh token endpoint + implementation to token manager #2975

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

Merged
merged 9 commits into from
May 4, 2020
Merged
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
86 changes: 86 additions & 0 deletions packages-exp/auth-exp/src/api/authentication/token.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/**
* @license
* Copyright 2020 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 { expect, use } from 'chai';
import * as chaiAsPromised from 'chai-as-promised';

import { FirebaseError, querystringDecode } from '@firebase/util';

import { mockAuth } from '../../../test/mock_auth';
import * as fetch from '../../../test/mock_fetch';
import { ServerError } from '../errors';
import { _ENDPOINT, requestStsToken } from './token';

use(chaiAsPromised);

describe('requestStsToken', () => {
const { apiKey, tokenApiHost, apiScheme } = mockAuth.config;
const endpoint = `${apiScheme}://${tokenApiHost}/${_ENDPOINT}?key=${apiKey}`;
beforeEach(fetch.setUp);
afterEach(fetch.tearDown);

it('should POST to the correct endpoint', async () => {
const mock = fetch.mock(endpoint, {
'access_token': 'new-access-token',
'expires_in': '3600',
'refresh_token': 'new-refresh-token'
});

const response = await requestStsToken(mockAuth, 'old-refresh-token');
expect(response.accessToken).to.eq('new-access-token');
expect(response.expiresIn).to.eq('3600');
expect(response.refreshToken).to.eq('new-refresh-token');
const request = querystringDecode(`?${mock.calls[0].request}`);
expect(request).to.eql({
'grant_type': 'refresh_token',
'refresh_token': 'old-refresh-token'
});
expect(mock.calls[0].method).to.eq('POST');
expect(mock.calls[0].headers).to.eql({
'Content-Type': 'application/x-www-form-urlencoded',
'X-Client-Version': 'testSDK/0.0.0'
});
});

it('should handle errors', async () => {
const mock = fetch.mock(
endpoint,
{
error: {
code: 400,
message: ServerError.TOKEN_EXPIRED,
errors: [
{
message: ServerError.TOKEN_EXPIRED
}
]
}
},
400
);

await expect(requestStsToken(mockAuth, 'old-token')).to.be.rejectedWith(
FirebaseError,
"Firebase: The user's credential is no longer valid. The user must sign in again. (auth/user-token-expired)"
);
const request = querystringDecode(`?${mock.calls[0].request}`);
expect(request).to.eql({
'grant_type': 'refresh_token',
'refresh_token': 'old-token'
});
});
});
71 changes: 71 additions & 0 deletions packages-exp/auth-exp/src/api/authentication/token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* @license
* Copyright 2020 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.
*/

/* eslint-disable camelcase */

import { querystring } from '@firebase/util';

import { _performFetchWithErrorHandling, HttpMethod } from '../';
import { Auth } from '../../model/auth';

export const _ENDPOINT = 'v1/token';
const GRANT_TYPE = 'refresh_token';

/** The server responses with snake_case; we convert to camelCase */
interface RequestStsTokenServerResponse {
access_token?: string;
expires_in?: string;
refresh_token?: string;
}

export interface RequestStsTokenResponse {
accessToken?: string;
expiresIn?: string;
refreshToken?: string;
}

export async function requestStsToken(
auth: Auth,
refreshToken: string
): Promise<RequestStsTokenResponse> {
const response = await _performFetchWithErrorHandling<
RequestStsTokenServerResponse
>(auth, {}, () => {
const body = querystring({
'grant_type': GRANT_TYPE,
'refresh_token': refreshToken
}).slice(1);
const { apiScheme, tokenApiHost, apiKey, sdkClientVersion } = auth.config;
const url = `${apiScheme}://${tokenApiHost}/${_ENDPOINT}`;

return fetch(`${url}?key=${apiKey}`, {
method: HttpMethod.POST,
headers: {
'X-Client-Version': sdkClientVersion,
'Content-Type': 'application/x-www-form-urlencoded'
},
body
});
});

// The response comes back in snake_case. Convert to camel:
return {
accessToken: response.access_token,
expiresIn: response.expires_in,
refreshToken: response.refresh_token
};
}
69 changes: 42 additions & 27 deletions packages-exp/auth-exp/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,17 @@
*/

import { FirebaseError, querystring } from '@firebase/util';
import { AuthErrorCode, AUTH_ERROR_FACTORY } from '../core/errors';

import { AUTH_ERROR_FACTORY, AuthErrorCode } from '../core/errors';
import { Delay } from '../core/util/delay';
import { Auth } from '../model/auth';
import { IdTokenResponse } from '../model/id_token';
import {
JsonError,
SERVER_ERROR_MAP,
ServerError,
ServerErrorMap,
SERVER_ERROR_MAP
ServerErrorMap
} from './errors';
import { Delay } from '../core/util/delay';

export enum HttpMethod {
POST = 'POST',
Expand Down Expand Up @@ -63,8 +64,7 @@ export async function _performApiRequest<T, V>(
request?: T,
customErrorMap: Partial<ServerErrorMap<ServerError>> = {}
): Promise<V> {
const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };
try {
return _performFetchWithErrorHandling(auth, customErrorMap, () => {
let body = {};
let params = {};
if (request) {
Expand All @@ -82,28 +82,31 @@ export async function _performApiRequest<T, V>(
...params
}).slice(1);

return fetch(
`${auth.config.apiScheme}://${auth.config.apiHost}${path}?${query}`,
{
method,
headers: {
'Content-Type': 'application/json',
'X-Client-Version': auth.config.sdkClientVersion
},
referrerPolicy: 'no-referrer',
...body
}
);
});
}

export async function _performFetchWithErrorHandling<V>(
auth: Auth,
customErrorMap: Partial<ServerErrorMap<ServerError>>,
fetchFn: () => Promise<Response>
): Promise<V> {
const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };
try {
const response: Response = await Promise.race<Promise<Response>>([
fetch(
`${auth.config.apiScheme}://${auth.config.apiHost}${path}?${query}`,
{
method,
headers: {
'Content-Type': 'application/json',
'X-Client-Version': auth.config.sdkClientVersion
},
referrerPolicy: 'no-referrer',
...body
}
),
new Promise((_, reject) =>
setTimeout(() => {
return reject(
AUTH_ERROR_FACTORY.create(AuthErrorCode.TIMEOUT, {
appName: auth.name
})
);
}, DEFAULT_API_TIMEOUT_MS.get())
)
fetchFn(),
makeNetworkTimeout(auth.name)
]);
if (response.ok) {
return response.json();
Expand Down Expand Up @@ -154,3 +157,15 @@ export async function _performSignInRequest<T, V extends IdTokenResponse>(

return serverResponse;
}

function makeNetworkTimeout<T>(appName: string): Promise<T> {
return new Promise((_, reject) =>
setTimeout(() => {
return reject(
AUTH_ERROR_FACTORY.create(AuthErrorCode.TIMEOUT, {
appName
})
);
}, DEFAULT_API_TIMEOUT_MS.get())
);
}
4 changes: 3 additions & 1 deletion packages-exp/auth-exp/src/core/auth/auth_impl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ import { Persistence } from '../persistence';
import { browserLocalPersistence } from '../persistence/browser';
import { inMemoryPersistence } from '../persistence/in_memory';
import { PersistenceUserManager } from '../persistence/persistence_user_manager';
import { ClientPlatform, _getClientVersion } from '../util/version';
import { _getClientVersion, ClientPlatform } from '../util/version';
import {
DEFAULT_API_HOST,
DEFAULT_API_SCHEME,
DEFAULT_TOKEN_API_HOST,
initializeAuth
} from './auth_impl';

Expand Down Expand Up @@ -318,6 +319,7 @@ describe('core/auth/initializeAuth', () => {
authDomain: FAKE_APP.options.authDomain,
apiHost: DEFAULT_API_HOST,
apiScheme: DEFAULT_API_SCHEME,
tokenApiHost: DEFAULT_TOKEN_API_HOST,
sdkClientVersion: _getClientVersion(ClientPlatform.BROWSER)
});
});
Expand Down
2 changes: 2 additions & 0 deletions packages-exp/auth-exp/src/core/auth/auth_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ interface AsyncAction {
(): Promise<void>;
}

export const DEFAULT_TOKEN_API_HOST = 'securetoken.googleapis.com';
export const DEFAULT_API_HOST = 'identitytoolkit.googleapis.com';
export const DEFAULT_API_SCHEME = 'https';

Expand Down Expand Up @@ -199,6 +200,7 @@ export function initializeAuth(
apiKey,
authDomain,
apiHost: DEFAULT_API_HOST,
tokenApiHost: DEFAULT_TOKEN_API_HOST,
apiScheme: DEFAULT_API_SCHEME,
sdkClientVersion: _getClientVersion(ClientPlatform.BROWSER)
};
Expand Down
Loading