diff --git a/src/services/__tests__/authProvider.spec.ts b/src/services/__tests__/authProvider.spec.ts index 178770fc..40057b1f 100644 --- a/src/services/__tests__/authProvider.spec.ts +++ b/src/services/__tests__/authProvider.spec.ts @@ -280,4 +280,76 @@ describe('authProviderFactory', () => { const result = await promise; expect(result).toEqual(staleCred); }); + + describe('user keys (`key` query params)', () => { + const BASE_URL = 'https://auth.split.io/api/api/v3/auth?capabilities=config,aiconfig'; + const urlOfCall = (splitHttpClient: jest.Mock, i: number) => (splitHttpClient.mock.calls[i] as any[])[0]; + + test('no `key` params when user keys are not provided (server-side)', async () => { + const splitHttpClient = mockSplitHttpClient(); + const provider = authProviderFactory(mockSettings, splitHttpClient, mockTelemetryTracker); + + await provider.credential(); + expect(urlOfCall(splitHttpClient, 0)).toBe(BASE_URL); + }); + + test('sends one `key` param per unique user key, sorted and URI-encoded', async () => { + const splitHttpClient = mockSplitHttpClient(); + const provider = authProviderFactory(mockSettings, splitHttpClient, mockTelemetryTracker); + + await provider.credential(['user/2', 'user%1', 'user/2']); + expect(urlOfCall(splitHttpClient, 0)).toBe(BASE_URL + '&key=user%251&key=user%2F2'); + }); + + test('reuses cached credential for the same set of keys (in any order) and for calls without keys', async () => { + const splitHttpClient = mockSplitHttpClient(); + const provider = authProviderFactory(mockSettings, splitHttpClient, mockTelemetryTracker); + + const cred = await provider.credential(['a', 'b']); + expect(await provider.credential(['b', 'a'])).toBe(cred); + expect(await provider.credential()).toBe(cred); + expect(splitHttpClient).toHaveBeenCalledTimes(1); + }); + + test('refetches when the set of keys changes, and later calls without keys use the latest keys', async () => { + const splitHttpClient = mockSplitHttpClient(); + const provider = authProviderFactory(mockSettings, splitHttpClient, mockTelemetryTracker); + + // e.g., a secure HTTP request before the first SSE authentication + await provider.credential(); + await provider.credential(['a']); + await provider.credential(['a', 'b']); + expect(splitHttpClient).toHaveBeenCalledTimes(3); + expect(urlOfCall(splitHttpClient, 1)).toBe(BASE_URL + '&key=a'); + expect(urlOfCall(splitHttpClient, 2)).toBe(BASE_URL + '&key=a&key=b'); + + provider.invalidate(); + await provider.credential(); + expect(urlOfCall(splitHttpClient, 3)).toBe(BASE_URL + '&key=a&key=b'); + }); + + test('waits for an in-flight fetch for different keys, and then fetches for the new keys', async () => { + const resolvers: Array<(res: any) => void> = []; + const splitHttpClient = jest.fn(() => new Promise(resolve => { resolvers.push(resolve); })); + const provider = authProviderFactory(mockSettings, splitHttpClient as any, mockTelemetryTracker); + const okResponse = () => ({ ok: true, status: 200, json: () => Promise.resolve(makeJwtCredential()), text: () => Promise.resolve('') }); + + const promiseA = provider.credential(['a']); + const promiseAB = provider.credential(['a', 'b']); + const promiseNoKeys = provider.credential(); // uses latest keys: ['a', 'b'] + expect(splitHttpClient).toHaveBeenCalledTimes(1); + + resolvers[0](okResponse()); + const credA = await promiseA; + await new Promise(r => setTimeout(r, 0)); + expect(splitHttpClient).toHaveBeenCalledTimes(2); + expect(urlOfCall(splitHttpClient as any, 1)).toBe(BASE_URL + '&key=a&key=b'); + + resolvers[1](okResponse()); + const [credAB, credNoKeys] = await Promise.all([promiseAB, promiseNoKeys]); + expect(credAB).not.toBe(credA); + expect(credNoKeys).toBe(credAB); + expect(splitHttpClient).toHaveBeenCalledTimes(2); + }); + }); }); diff --git a/src/services/authProvider.ts b/src/services/authProvider.ts index be570e39..54e2d698 100644 --- a/src/services/authProvider.ts +++ b/src/services/authProvider.ts @@ -13,16 +13,32 @@ function isExpired(credential: IJwtCredential): boolean { return Date.now() / 1000 + SKEW_SECONDS >= credential.decodedToken.exp; } +/** + * Builds the `key` query params for the `/api/v3/auth` endpoint: one `&key=` per unique user key, + * sorted so that the same set of keys always maps to the same query (and thus to the same cached credential). + */ +function userKeysToQueryParams(userKeys: string[]): string { + return userKeys + .filter((userKey, index) => userKeys.indexOf(userKey) === index) + .sort() + .map(userKey => '&key=' + encodeURIComponent(userKey)) + .join(''); +} + function noCachedCredentialError() { return new Error(LOG_PREFIX_SYNC_AUTH + 'stopped without a cached credential'); } export interface IAuthProvider { /** - * Returns the cached credential, or fetches a new one if there isn't one cached or it's expired, - * retrying with backoff on recoverable errors. Used by `secureSplitHttpClient` and `serviceApi.fetchAuth`. + * Returns the cached credential, or fetches a new one if there isn't one cached, it's expired, or it was fetched + * for a different set of user keys, retrying with backoff on recoverable errors. Used by `secureSplitHttpClient` and `serviceApi.fetchAuth`. + * + * @param userKeys - optional set of user keys, sent as `key` query params to the `/api/v3/auth` endpoint so that the + * credential covers their membership channels. Only provided by `serviceApi.fetchAuth` in client-side (undefined in server-side). + * It is remembered, so that subsequent calls without `userKeys` (e.g., by `secureSplitHttpClient`) reuse the same credential. */ - credential(): Promise; + credential(userKeys?: string[]): Promise; /** * Invalidates/clears the cached credential. Used by `secureSplitHttpClient` in the special case of 401 error, * and by `serviceApi.fetchAuth` to force a credential/token refresh. @@ -39,8 +55,13 @@ export function authProviderFactory(settings: ISettings, splitHttpClient: ISplit const { urls, log } = settings; + // `key` query params of the latest user keys, and of the in-flight and cached credentials respectively + let userKeysQueryParams = ''; + let inFlightQueryParams = ''; + let cachedQueryParams = ''; + const fetchAuth = fetchAuthFactory(() => { - let url = `${urls.auth}/api/v3/auth?capabilities=config,aiconfig`; + let url = `${urls.auth}/api/v3/auth?capabilities=config,aiconfig${inFlightQueryParams}`; return splitHttpClient(url, undefined, telemetryTracker.trackHttp(TOKEN), false, true); }); const backoff = new Backoff(fetchCredential); @@ -50,9 +71,13 @@ export function authProviderFactory(settings: ISettings, splitHttpClient: ISplit let stopped = false; function fetchCredential(): Promise { + // Snapshot the latest user keys, so that backoff retries also pick up keys added in the meantime + const queryParams = inFlightQueryParams = userKeysQueryParams; + return fetchAuth().then((credential: IJwtCredential) => { log.info(LOG_PREFIX_SYNC_AUTH + 'credential fetched successfully'); cachedCredential = credential; + cachedQueryParams = queryParams; inFlightPromise = undefined; backoff.reset(); return credential; @@ -72,21 +97,29 @@ export function authProviderFactory(settings: ISettings, splitHttpClient: ISplit }); } - return { - credential(): Promise { - if (cachedCredential && !isExpired(cachedCredential)) { + const provider: IAuthProvider = { + credential(userKeys?: string[]): Promise { + if (userKeys) userKeysQueryParams = userKeysToQueryParams(userKeys); + + if (cachedCredential && cachedQueryParams === userKeysQueryParams && !isExpired(cachedCredential)) { return Promise.resolve(cachedCredential); } - // Reuse any fetch already in flight (e.g. one started just before stop()), instead of firing a redundant one. - if (inFlightPromise) return inFlightPromise; + if (inFlightPromise) { + // Reuse any fetch already in flight (e.g. one started just before stop()), instead of firing a redundant one. + if (inFlightQueryParams === userKeysQueryParams) return inFlightPromise; + + // The in-flight fetch is for a different set of user keys: wait for it to settle, and then re-evaluate. + const retry = () => provider.credential(); + return inFlightPromise.then(retry, retry); + } // No cached credential to fall back to and stopped: reject so callers don't send an unauthenticated request. if (stopped && !cachedCredential) { return Promise.reject(noCachedCredentialError()); } - if (cachedCredential) log.debug(LOG_PREFIX_SYNC_AUTH + 'cached credential expired'); + if (cachedCredential) log.debug(LOG_PREFIX_SYNC_AUTH + (cachedQueryParams === userKeysQueryParams ? 'cached credential expired' : 'user keys changed')); // If stopped, this is a last, bounded refetch: fetchCredential()'s catch short-circuits (no backoff retry) // once stopped, so it's a single attempt that falls back to the stale cached credential on failure. @@ -105,4 +138,6 @@ export function authProviderFactory(settings: ISettings, splitHttpClient: ISplit backoff.reset(cachedCredential ? { value: cachedCredential } : { error: noCachedCredentialError() }); } }; + + return provider; } diff --git a/src/services/serviceApi.ts b/src/services/serviceApi.ts index 9870c143..615608d6 100644 --- a/src/services/serviceApi.ts +++ b/src/services/serviceApi.ts @@ -39,12 +39,12 @@ export function serviceApiFactory( let initialAuth = true; return { - fetchAuth() { + fetchAuth(userKeys?: string[]) { // Guard condition to avoid invalidating the cached credential on the first pushManager authentication if (initialAuth) initialAuth = false; else authProvider.invalidate(); - return authProvider.credential(); + return authProvider.credential(userKeys); }, // @TODO throw errors if health check requests fail, to log them in the Synchronizer