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

[SDK-1696] Allow caller of cache.get to specify an expiry time adjustment #491

Merged
merged 4 commits into from
Jun 9, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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
82 changes: 81 additions & 1 deletion __tests__/Auth0Client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ const setup = (
const login: any = async (
auth0,
tokenSuccess = true,
tokenResponse?,
tokenResponse = {},
code = 'my_code',
state = 'MTIz'
) => {
Expand Down Expand Up @@ -174,6 +174,86 @@ describe('Auth0Client', () => {
);
});

it('uses the cache when expires_in > constant leeway', async () => {
const auth0 = setup();
await login(auth0, true, { expires_in: 70 });

jest.spyOn(<any>utils, 'runIframe').mockResolvedValue({
access_token: 'my_access_token',
state: 'MTIz'
});

mockFetch.mockReset();

await auth0.getTokenSilently();
expect(mockFetch).not.toHaveBeenCalled();
});

it('refreshes the token when expires_in < constant leeway', async () => {
const auth0 = setup();
await login(auth0, true, { expires_in: 50 });

jest.spyOn(<any>utils, 'runIframe').mockResolvedValue({
access_token: 'my_access_token',
state: 'MTIz'
});

mockFetch.mockReset();
mockFetch.mockResolvedValue(
fetchResponse(true, {
id_token: 'my_id_token',
refresh_token: 'my_refresh_token',
access_token: 'my_access_token',
expires_in: 86400
})
);

await auth0.getTokenSilently();
expect(mockFetch).toHaveBeenCalledTimes(1);
});

it('uses the cache when expires_in > constant leeway & refresh tokens are used', async () => {
const auth0 = setup({
useRefreshTokens: true
});

await login(auth0, true, { expires_in: 70 });

mockFetch.mockReset();
mockFetch.mockResolvedValue(
fetchResponse(true, {
id_token: 'my_id_token',
refresh_token: 'my_refresh_token',
access_token: 'my_access_token',
expires_in: 86400
})
);

await auth0.getTokenSilently();
expect(mockFetch).not.toHaveBeenCalled();
});

it('refreshes the token when expires_in < constant leeway & refresh tokens are used', async () => {
const auth0 = setup({
useRefreshTokens: true
});

await login(auth0, true, { expires_in: 50 });

mockFetch.mockReset();
mockFetch.mockResolvedValue(
fetchResponse(true, {
id_token: 'my_id_token',
refresh_token: 'my_refresh_token',
access_token: 'my_access_token',
expires_in: 86400
})
);

await auth0.getTokenSilently();
expect(mockFetch).toHaveBeenCalledTimes(1);
});

it('refreshes the token from a web worker', async () => {
const auth0 = setup({
useRefreshTokens: true
Expand Down
83 changes: 81 additions & 2 deletions __tests__/cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,38 @@ describe('InMemoryCache', () => {
).toStrictEqual(data);
});

it('returns undefined from the cache when expires_in < expiryAdjustmentSeconds', () => {
const data = {
client_id: 'test-client',
audience: 'the_audience',
scope: 'the_scope',
id_token: 'idtoken',
access_token: 'accesstoken',
expires_in: 40,
decodedToken: {
claims: {
__raw: 'idtoken',
exp: nowSeconds() + dayInSeconds,
name: 'Test'
},
user: { name: 'Test' }
}
};

cache.save(data);

expect(
cache.get(
{
client_id: 'test-client',
audience: 'the_audience',
scope: 'the_scope'
},
60
)
).toBeUndefined();
});

describe('when refresh tokens are used', () => {
it('strips everything except the refresh token when expiry has been reached', () => {
const now = Date.now();
Expand Down Expand Up @@ -268,6 +300,53 @@ describe('LocalStorageCache', () => {
).toStrictEqual(defaultEntry);
});

it('returns undefined when expires_in < expiryAdjustmentSeconds', () => {
localStorage.setItem(
'@@auth0spajs@@::__TEST_CLIENT_ID__::__TEST_AUDIENCE__::__TEST_SCOPE__',
JSON.stringify({
body: defaultEntry,
expiresAt: nowSeconds() + 40
})
);

expect(
cache.get(
{
client_id: '__TEST_CLIENT_ID__',
audience: '__TEST_AUDIENCE__',
scope: '__TEST_SCOPE__'
},
60
)
).toBeUndefined();
});

it('strips the cache data when expires_in < expiryAdjustmentSeconds and refresh tokens are being used', () => {
localStorage.setItem(
'@@auth0spajs@@::__TEST_CLIENT_ID__::__TEST_AUDIENCE__::__TEST_SCOPE__',
JSON.stringify({
body: {
...defaultEntry,
refresh_token: '__REFRESH_TOKEN__'
},
expiresAt: nowSeconds() + 40
})
);

expect(
cache.get(
{
client_id: '__TEST_CLIENT_ID__',
audience: '__TEST_AUDIENCE__',
scope: '__TEST_SCOPE__'
},
60
)
).toStrictEqual({
refresh_token: '__REFRESH_TOKEN__'
});
});

it('returns undefined when there is no data', () => {
expect(cache.get({ scope: '', audience: '' })).toBeUndefined();
});
Expand Down Expand Up @@ -360,7 +439,7 @@ describe('LocalStorageCache', () => {
'@@auth0spajs@@::__TEST_CLIENT_ID__::__TEST_AUDIENCE__::__TEST_SCOPE__',
JSON.stringify({
body: defaultEntry,
expiresAt: nowSeconds() + dayInSeconds - 60
expiresAt: nowSeconds() + dayInSeconds
})
);
});
Expand All @@ -381,7 +460,7 @@ describe('LocalStorageCache', () => {
'@@auth0spajs@@::__TEST_CLIENT_ID__::__TEST_AUDIENCE__::__TEST_SCOPE__',
JSON.stringify({
body: entry,
expiresAt: nowSeconds() + 40
expiresAt: nowSeconds() + 100
})
);
});
Expand Down
39 changes: 24 additions & 15 deletions __tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1478,11 +1478,14 @@ describe('Auth0', () => {

await auth0.getTokenSilently();

expect(cache.get).toHaveBeenCalledWith({
audience: 'default',
scope: TEST_SCOPES,
client_id: TEST_CLIENT_ID
});
expect(cache.get).toHaveBeenCalledWith(
{
audience: 'default',
scope: TEST_SCOPES,
client_id: TEST_CLIENT_ID
},
60
);
});

it('returns cached access_token when there is a cache', async () => {
Expand Down Expand Up @@ -1526,11 +1529,14 @@ describe('Auth0', () => {

await auth0.getTokenSilently();

expect(cache.get).toHaveBeenCalledWith({
audience: 'default',
scope: 'openid email',
client_id: TEST_CLIENT_ID
});
expect(cache.get).toHaveBeenCalledWith(
{
audience: 'default',
scope: 'openid email',
client_id: TEST_CLIENT_ID
},
60
);
});
});

Expand All @@ -1544,11 +1550,14 @@ describe('Auth0', () => {

await auth0.getTokenSilently();

expect(cache.get).toHaveBeenCalledWith({
audience: 'default',
scope: `${TEST_SCOPES} offline_access`,
client_id: TEST_CLIENT_ID
});
expect(cache.get).toHaveBeenCalledWith(
{
audience: 'default',
scope: `${TEST_SCOPES} offline_access`,
client_id: TEST_CLIENT_ID
},
60
);
});

it('calls the token endpoint with the correct params', async () => {
Expand Down
13 changes: 8 additions & 5 deletions src/Auth0Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -512,11 +512,14 @@ export default class Auth0Client {

try {
if (!ignoreCache) {
const cache = this.cache.get({
scope: getTokenOptions.scope,
audience: getTokenOptions.audience || 'default',
client_id: this.options.client_id
});
const cache = this.cache.get(
{
scope: getTokenOptions.scope,
audience: getTokenOptions.audience || 'default',
client_id: this.options.client_id
},
60 // get a new token if within 60 seconds of expiring
);

if (cache && cache.access_token) {
return cache.access_token;
Expand Down
21 changes: 14 additions & 7 deletions src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ interface CacheEntry {

export interface ICache {
save(entry: CacheEntry): void;
get(key: CacheKeyData): Partial<CacheEntry>;
get(key: CacheKeyData, expiryAdjustmentSeconds?: number): Partial<CacheEntry>;
clear(): void;
}

const keyPrefix = '@@auth0spajs@@';
const DEFAULT_EXPIRY_ADJUSTMENT_SECONDS = 0;

const createKey = (e: CacheKeyData) =>
`${keyPrefix}::${e.client_id}::${e.audience}::${e.scope}`;

Expand All @@ -43,8 +45,7 @@ type CachePayload = {
*/
const wrapCacheEntry = (entry: CacheEntry): CachePayload => {
const expiresInTime = Math.floor(Date.now() / 1000) + entry.expires_in;
const expirySeconds =
Math.min(expiresInTime, entry.decodedToken.claims.exp) - 60; // take off a small leeway
const expirySeconds = Math.min(expiresInTime, entry.decodedToken.claims.exp);

return {
body: entry,
Expand All @@ -60,14 +61,17 @@ export class LocalStorageCache implements ICache {
window.localStorage.setItem(cacheKey, JSON.stringify(payload));
}

public get(key: CacheKeyData): Partial<CacheEntry> {
public get(
key: CacheKeyData,
expiryAdjustmentSeconds = DEFAULT_EXPIRY_ADJUSTMENT_SECONDS
): Partial<CacheEntry> {
const cacheKey = createKey(key);
const payload = this.readJson(cacheKey);
const nowSeconds = Math.floor(Date.now() / 1000);

if (!payload) return;

if (payload.expiresAt < nowSeconds) {
if (payload.expiresAt - expiryAdjustmentSeconds < nowSeconds) {
if (payload.body.refresh_token) {
const newPayload = this.stripData(payload);
this.writeJson(cacheKey, newPayload);
Expand Down Expand Up @@ -151,7 +155,10 @@ export class InMemoryCache {
cache[key] = payload;
},

get(key: CacheKeyData) {
get(
key: CacheKeyData,
expiryAdjustmentSeconds = DEFAULT_EXPIRY_ADJUSTMENT_SECONDS
) {
const cacheKey = createKey(key);
const wrappedEntry: CachePayload = cache[cacheKey];
const nowSeconds = Math.floor(Date.now() / 1000);
Expand All @@ -160,7 +167,7 @@ export class InMemoryCache {
return;
}

if (wrappedEntry.expiresAt < nowSeconds) {
if (wrappedEntry.expiresAt - expiryAdjustmentSeconds < nowSeconds) {
if (wrappedEntry.body.refresh_token) {
wrappedEntry.body = {
refresh_token: wrappedEntry.body.refresh_token
Expand Down
Loading