-
Notifications
You must be signed in to change notification settings - Fork 4
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
NN-4114: Caching of auth client credentials #2150
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d67eef9
NN-4114: Implement oauth client cred caching
2f0fc75
NN-4114: Fix int tests
e5d0e2d
NN-4114: Fix redis error logging
4852bb1
NN-4114: More lenient expiry time checks
6421ab6
NN-4114: Only log on non-prod systems
e4f1778
Merge branch 'main' into NN-4114-auth-client-creds-caching
sp-watson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
import { doesNotMatch } from 'assert' | ||
import redisMock from 'redis-mock' | ||
import { promisify } from 'util' | ||
import systemOauthClient, { clientCredsSetup, getClientCredentialsTokens } from './systemOauthClient' | ||
|
||
describe('system oauth client tests', () => { | ||
const oauthApi = { makeTokenRequest: {} } | ||
|
||
describe('Without Redis cache', () => { | ||
beforeEach(() => { | ||
oauthApi.makeTokenRequest = jest.fn().mockResolvedValue({ | ||
access_token: '123', | ||
refresh_token: '456', | ||
expires_in: 600, | ||
}) | ||
clientCredsSetup(null, oauthApi) | ||
}) | ||
|
||
it('Gets and returns token', async () => { | ||
const clientCreds = await getClientCredentialsTokens({}) | ||
expect(clientCreds).toEqual({ | ||
access_token: '123', | ||
refresh_token: '456', | ||
expires_in: 600, | ||
}) | ||
}) | ||
|
||
it('Makes oauth requests each time', async () => { | ||
await getClientCredentialsTokens({}) | ||
await getClientCredentialsTokens({}) | ||
expect(oauthApi.makeTokenRequest).toHaveBeenCalledTimes(2) | ||
}) | ||
}) | ||
|
||
describe('With Redis cache', () => { | ||
let mockRedis | ||
|
||
beforeEach(() => { | ||
oauthApi.makeTokenRequest = jest.fn().mockResolvedValue({ | ||
access_token: '123', | ||
refresh_token: '456', | ||
expires_in: 600, | ||
}) | ||
mockRedis = redisMock.createClient() | ||
clientCredsSetup(mockRedis, oauthApi) | ||
}) | ||
|
||
it('Gets and returns token on the first call with correct expiry', async () => { | ||
const clientCreds = await getClientCredentialsTokens('USER1') | ||
expect(clientCreds).toEqual({ | ||
access_token: '123', | ||
refresh_token: '456', | ||
expires_in: 600, | ||
}) | ||
expect(oauthApi.makeTokenRequest).toHaveBeenCalledTimes(1) | ||
}) | ||
|
||
it('Returns the stored token the second call', async () => { | ||
await getClientCredentialsTokens('USER1') | ||
const clientCreds = await getClientCredentialsTokens('USER1') | ||
expect(clientCreds).toEqual({ | ||
access_token: '123', | ||
refresh_token: null, | ||
}) | ||
expect(oauthApi.makeTokenRequest).toHaveBeenCalledTimes(0) | ||
}) | ||
|
||
it('Returns the stored token per user', async () => { | ||
await getClientCredentialsTokens('USER1') | ||
const secondUserClientCreds = await getClientCredentialsTokens('USER2') | ||
expect(secondUserClientCreds).toEqual({ | ||
access_token: '123', | ||
refresh_token: '456', | ||
expires_in: 600, | ||
}) | ||
expect(oauthApi.makeTokenRequest).toHaveBeenCalledWith( | ||
'grant_type=client_credentials&username=USER2', | ||
'PSH-client_credentials' | ||
) | ||
}) | ||
|
||
it('Works when no username provided', async () => { | ||
const noUserClientCreds = await getClientCredentialsTokens(null) | ||
expect(noUserClientCreds).toEqual({ | ||
access_token: '123', | ||
refresh_token: '456', | ||
expires_in: 600, | ||
}) | ||
}) | ||
|
||
it('Expires cached value 1 minute before token expiry', async () => { | ||
await getClientCredentialsTokens('USER1') | ||
|
||
const getTtl = promisify(mockRedis.ttl).bind(mockRedis) | ||
const expiryTime = await getTtl('CC_USER1') | ||
|
||
const tokenExpiry = 600 | ||
expect(expiryTime).toBeLessThan(tokenExpiry - 59) | ||
expect(expiryTime).toBeGreaterThan(tokenExpiry - 120) // Allow 1 minute | ||
}) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,88 @@ | ||
import querystring from 'querystring' | ||
import clientFactory from './oauthEnabledClient' | ||
|
||
import { oauthApiFactory } from './oauthApi' | ||
import { createClient } from 'redis' | ||
import { promisify } from 'util' | ||
import config from '../config' | ||
import logger from '../log' | ||
|
||
export const getClientCredentialsTokens = async (username) => { | ||
let getRedisAsync | ||
let setRedisAsync | ||
let oauthClient | ||
|
||
export const getTokenStore = (configData) => { | ||
const { enabled, host, port, password } = configData.redis | ||
if (!enabled || !host) return null | ||
|
||
const client = createClient({ | ||
host, | ||
port, | ||
password, | ||
tls: configData.app.production ? {} : false, | ||
}) | ||
|
||
client.on('error', (e: Error) => logger.error(e, 'Redis client error')) | ||
|
||
logger.info(`Oauth token store created`) | ||
return client | ||
} | ||
|
||
export const clientCredsSetup = (tokenStore, oauthApi) => { | ||
const redisTokenStore = tokenStore | ||
getRedisAsync = redisTokenStore ? promisify(redisTokenStore?.get).bind(redisTokenStore) : (key) => {} | ||
setRedisAsync = redisTokenStore | ||
? promisify(redisTokenStore?.set).bind(redisTokenStore) | ||
: (key, value, command, expiry) => {} | ||
|
||
oauthClient = oauthApi | ||
} | ||
|
||
const requestClientCredentials = async (username) => { | ||
const oauthRequest = username | ||
? querystring.stringify({ grant_type: 'client_credentials', username }) | ||
: querystring.stringify({ grant_type: 'client_credentials' }) | ||
|
||
const oauthResult = await oauthApiFactory( | ||
clientFactory({ | ||
baseUrl: config.apis.oauth2.url, | ||
timeout: config.apis.oauth2.timeoutSeconds * 1000, | ||
}), | ||
{ | ||
clientId: config.apis.oauth2.systemClientId, | ||
clientSecret: config.apis.oauth2.systemClientSecret, | ||
url: config.apis.oauth2.url, | ||
} | ||
).makeTokenRequest(oauthRequest, 'PSH-client_credentials') | ||
const oauthResult = await oauthClient.makeTokenRequest(oauthRequest, 'PSH-client_credentials') | ||
|
||
logger.debug(`Oauth request for grant type 'client_credentials', result status: successful`) | ||
return oauthResult | ||
} | ||
|
||
const debug = (operation: string, username: string) => { | ||
if (!config.app.production) logger.info(`OAUTH CLIENT CREDS ${operation} FOR ${username}`) | ||
} | ||
|
||
const getKey = (username: string) => { | ||
const baseKey = username || '%ANONYMOUS%' | ||
return `CC_${baseKey}` | ||
} | ||
|
||
export const getClientCredentialsTokens = async (username) => { | ||
const key = getKey(username) | ||
|
||
debug('GET', key) | ||
const token = await getRedisAsync(key) | ||
if (token) { | ||
debug('GOT', key) | ||
// We need to preserve the oauth result to avoid changing all the code and esp. tests (we use axios). | ||
// According to axios-config-decorators.ts we only use the auth token, custom request headers and pagination. | ||
// For client creds, pagination and custom headers are not relevant when getting client creds. | ||
return { | ||
// Need only access token - refresh token and authSource (as per useApiClientCreds.ts) are actually not used | ||
// for client creds (the access functions are in contextProperties.ts) | ||
access_token: token, | ||
refresh_token: null, | ||
} | ||
} | ||
|
||
const oauthResult = await requestClientCredentials(username) | ||
|
||
// set TTL slightly less than expiry of token. Async but no need to wait | ||
await setRedisAsync(key, oauthResult.access_token, 'EX', oauthResult.expires_in - 60) | ||
debug(`SET-${oauthResult.expires_in}`, key) | ||
|
||
return oauthResult | ||
} | ||
|
||
export default { | ||
getClientCredentialsTokens, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,6 +16,7 @@ import setupHealthChecks from './setupHealthChecks' | |
import setupBodyParsers from './setupBodyParsers' | ||
import setupWebSecurity from './setupWebSecurity' | ||
import setupAuth from './setupAuth' | ||
import { clientCredsSetup, getTokenStore } from './api/systemOauthClient' | ||
import setupStaticContent from './setupStaticContent' | ||
import nunjucksSetup from './utils/nunjucksSetup' | ||
import setupRedirects from './setupRedirects' | ||
|
@@ -47,6 +48,7 @@ app.set('view engine', 'njk') | |
|
||
nunjucksSetup(app) | ||
phaseNameSetup(app, config) | ||
clientCredsSetup(getTokenStore(config), apis.oauthApi) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I had to add this setup code to facilitate testing |
||
|
||
app.use(cookieParser()) | ||
app.use(setupBodyParsers()) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We ought to remove this once we are confident it is working OK