-
Notifications
You must be signed in to change notification settings - Fork 0
✨ feat: implement wave authenticator #19
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
Changes from all commits
Commits
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
155 changes: 155 additions & 0 deletions
155
src/core/authenticator/authenticator-implementation.spec.ts
This file contains hidden or 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,155 @@ | ||
| import type { DatabaseTransactionManager, PrismaTransaction } from 'src/database'; | ||
| import { WaveAuthenticatorImpl } from './authenticator-implementation'; | ||
| import { mockDeep, type DeepMockProxy } from 'vitest-mock-extended'; | ||
| import type { ApplicationName, AuthenticatorRepository } from './authenticator-repository'; | ||
| import { describe, vi, it, expect, beforeEach } from 'vitest'; | ||
|
|
||
| const mockJson = vi.fn(); | ||
| const mockStatus = vi.fn(); | ||
| const mockText = vi.fn(); | ||
| const mockHeaders = vi.fn(); | ||
| global.fetch = vi.fn(() => Promise.resolve({ | ||
| status: mockStatus(), | ||
| headers: { | ||
| get: mockHeaders, | ||
| }, | ||
| json: () => Promise.resolve(mockJson()), | ||
| text: () => Promise.resolve(mockText()), | ||
| }) as unknown as Promise<Response>); | ||
|
|
||
| interface MakeSut { | ||
| transactionManager: DeepMockProxy<DatabaseTransactionManager>; | ||
| tokenRepository: DeepMockProxy<AuthenticatorRepository>; | ||
| sut: WaveAuthenticatorImpl; | ||
| } | ||
|
|
||
| const makeSut = (): MakeSut => { | ||
| const transactionManager = mockDeep<DatabaseTransactionManager>(); | ||
| const tokenRepository = mockDeep<AuthenticatorRepository>(); | ||
| const sut = new WaveAuthenticatorImpl( | ||
| transactionManager, | ||
| tokenRepository, | ||
| { | ||
| authUrl: 'https://auth.wave.com', | ||
| audience: 'https://api.wave.com', | ||
| clientId: 'clientId', | ||
| clientSecret: 'clientSecret', | ||
| }, | ||
| { | ||
| tokenExpiryInSeconds: 3600, | ||
| }, | ||
| ); | ||
|
|
||
| return { transactionManager, tokenRepository, sut }; | ||
| }; | ||
|
|
||
| describe('wave authentication impl', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| describe('authenticate', () => { | ||
| it('should return cached token if not expired', async () => { | ||
| const { sut, tokenRepository } = makeSut(); | ||
| const futureTimestamp = Date.now() + 1000000; | ||
| const mockToken = { token: 'cached-token', expiresAt: futureTimestamp, application: 'WAVE_MVNO_APPLICATION' as ApplicationName }; | ||
|
|
||
| tokenRepository.get.mockResolvedValueOnce(mockToken); | ||
| mockStatus.mockReturnValueOnce(200); | ||
| const result = await sut.authenticate('WAVE_MVNO_APPLICATION'); | ||
|
|
||
| expect(result).toBe(mockToken.token); | ||
| expect(tokenRepository.get).toHaveBeenCalledWith('WAVE_MVNO_APPLICATION'); | ||
| expect(global.fetch).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should fetch new token if cached token is expired', async () => { | ||
| const { sut, tokenRepository, transactionManager } = makeSut(); | ||
| const pastTimestamp = Date.now() - 1000; | ||
| const mockToken = { token: 'expired-token', expiresAt: pastTimestamp, application: 'WAVE_MVNO_APPLICATION' as ApplicationName }; | ||
| const newToken = { access_token: 'new-token', expires_in: 3600, application: 'WAVE_MVNO_APPLICATION' as ApplicationName }; | ||
|
|
||
| tokenRepository.get.mockResolvedValueOnce(mockToken); | ||
| mockJson.mockReturnValueOnce(newToken); | ||
| mockStatus.mockReturnValueOnce(200); | ||
| transactionManager.execute.mockImplementationOnce( | ||
| (callback) => callback({} as PrismaTransaction) | ||
| ); | ||
|
|
||
| const result = await sut.authenticate('WAVE_MVNO_APPLICATION'); | ||
|
|
||
| expect(result).toBe(newToken.access_token); | ||
| expect(tokenRepository.get).toHaveBeenCalledWith('WAVE_MVNO_APPLICATION'); | ||
| expect(global.fetch).toHaveBeenCalledWith( | ||
| 'https://auth.wave.com/oauth/token', | ||
| expect.objectContaining({ | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/x-www-form-urlencoded', | ||
| 'Authorization': 'Basic Y2xpZW50SWQ6Y2xpZW50U2VjcmV0', | ||
| }, | ||
| }) | ||
| ); | ||
| expect(tokenRepository.save).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| application: 'WAVE_MVNO_APPLICATION', | ||
| token: newToken.access_token, | ||
| }), | ||
| expect.anything() | ||
| ); | ||
| }); | ||
|
|
||
| it('should handle non-JSON error responses with status 401', async () => { | ||
| const { sut, tokenRepository, transactionManager } = makeSut(); | ||
|
|
||
| tokenRepository.get.mockResolvedValueOnce(undefined); | ||
| mockStatus.mockReturnValueOnce(401); | ||
| mockText.mockReturnValueOnce('Unauthorized'); | ||
| mockHeaders.mockReturnValueOnce('text/plain'); | ||
| transactionManager.execute.mockImplementationOnce( | ||
| (callback) => callback({} as PrismaTransaction) | ||
| ); | ||
|
|
||
| await expect(sut.authenticate('WAVE_MVNO_APPLICATION')).rejects.toThrow('Unauthorized'); | ||
| }); | ||
|
|
||
| it('should handle JSON error responses with status 400', async () => { | ||
| const { sut, tokenRepository, transactionManager } = makeSut(); | ||
|
|
||
| tokenRepository.get.mockResolvedValueOnce(undefined); | ||
| mockStatus.mockReturnValueOnce(400); | ||
| mockJson.mockReturnValueOnce({ error: 'invalid_request' }); | ||
| mockHeaders.mockReturnValueOnce('application/json'); | ||
| transactionManager.execute.mockImplementationOnce( | ||
| (callback) => callback({} as PrismaTransaction) | ||
| ); | ||
|
|
||
| await expect(sut.authenticate('WAVE_MVNO_APPLICATION')).rejects.toThrow('{"error":"invalid_request"}'); | ||
| }); | ||
|
|
||
| it('should use default expiry when token response has no expiresIn', async () => { | ||
| const { sut, tokenRepository, transactionManager } = makeSut(); | ||
| const pastTimestamp = Date.now() - 1000; | ||
| const mockToken = { token: 'expired-token', expiresAt: pastTimestamp, application: 'WAVE_MVNO_APPLICATION' as ApplicationName }; | ||
| const newToken = { access_token: 'new-token', expires_in: 3600, application: 'WAVE_MVNO_APPLICATION' as ApplicationName }; // No expiresIn | ||
|
|
||
| tokenRepository.get.mockResolvedValueOnce(mockToken); | ||
| mockJson.mockReturnValueOnce(newToken); | ||
| mockStatus.mockReturnValueOnce(200); | ||
| transactionManager.execute.mockImplementationOnce( | ||
| (callback) => callback({} as PrismaTransaction) | ||
| ); | ||
|
|
||
| await sut.authenticate('WAVE_MVNO_APPLICATION'); | ||
|
|
||
| expect(tokenRepository.save).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| application: 'WAVE_MVNO_APPLICATION', | ||
| token: newToken.access_token, | ||
| expiresAt: expect.any(Number), | ||
| }), | ||
| expect.anything() | ||
| ); | ||
| }); | ||
| }); | ||
| }); | ||
This file contains hidden or 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,92 @@ | ||
| import type { WaveAuthenticator, WaveAuthenticatorConfig, WaveAuthenticatorParams, WaveAuthenticatorResult } from './authenticator-types'; | ||
| import type { ApplicationName, AuthenticatorRepository } from './authenticator-repository'; | ||
| import type { DatabaseTransactionManager } from 'src/database'; | ||
| import { secondsToMillis } from 'src/utils'; | ||
| import { Logger } from 'src/core'; | ||
|
|
||
| export class WaveAuthenticatorImpl implements WaveAuthenticator<ApplicationName> { | ||
| private applicationTokens: Record<ApplicationName, WaveAuthenticatorResult> = { | ||
| 'WAVE_MVNO_APPLICATION': { token: '', expiresIn: 0 }, | ||
| 'WAVE_PROVISIONING_APPLICATION': { token: '', expiresIn: 0 }, | ||
| 'WAVE_TENANT_APPLICATION': { token: '', expiresIn: 0 }, | ||
| }; | ||
|
|
||
| constructor( | ||
| private readonly transactionManager: DatabaseTransactionManager, | ||
| private readonly tokenRepository: AuthenticatorRepository, | ||
| private readonly params: WaveAuthenticatorParams, | ||
| private readonly config: WaveAuthenticatorConfig, | ||
| ) { } | ||
|
|
||
| private isTokenExpired(expiresIn: number): boolean { | ||
| return Date.now() > expiresIn; | ||
| } | ||
|
|
||
| private async getToken(): Promise<WaveAuthenticatorResult> { | ||
| try { | ||
| const credentials = `${this.params.clientId}:${this.params.clientSecret}`; | ||
| const encodedCredentials = Buffer.from(credentials).toString('base64'); | ||
|
|
||
| const response = await fetch(`${this.params.authUrl}/oauth/token`, { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/x-www-form-urlencoded', | ||
| 'Authorization': `Basic ${encodedCredentials}`, | ||
| }, | ||
| body: new URLSearchParams({ | ||
| grant_type: 'client_credentials', | ||
| audience: this.params.audience, | ||
| }), | ||
| }); | ||
|
|
||
| if (response.status < 200 || response.status >= 400) { | ||
| const contentType = response.headers.get('Content-Type'); | ||
| const errorMessage = contentType?.includes('json') ? | ||
| JSON.stringify(await response.json()) : | ||
| await response.text(); | ||
| throw new Error(errorMessage); | ||
| } | ||
|
|
||
| const data = await response.json(); | ||
|
|
||
| return { | ||
| token: data.access_token, | ||
| expiresIn: data.expires_in, | ||
| }; | ||
| } catch (error) { | ||
| Logger.error('[Authenticator Get Token] An error occurred when trying to authenticate to wave application', { clientId: this.params.clientId, audience: this.params.audience, authUrl: this.params.authUrl }, error); | ||
| throw error; | ||
| } | ||
| } | ||
|
|
||
| async authenticate(application: ApplicationName): Promise<string> { | ||
| const { token, expiresIn } = this.applicationTokens[application]; | ||
|
|
||
| if (!token || this.isTokenExpired(expiresIn)) { | ||
| const result = await this.tokenRepository.get(application) ?? { token: '', expiresAt: 0 }; | ||
| this.applicationTokens[application] = { token: result.token, expiresIn: result.expiresAt }; | ||
| Logger.info(`[Authenticator Get Token] Token refreshed for application ${application}`, { application }); | ||
| } | ||
|
|
||
| const tokenExpiresAt = this.applicationTokens[application].expiresIn; | ||
| if (!this.isTokenExpired(tokenExpiresAt)) { | ||
| return this.applicationTokens[application].token; | ||
| } | ||
|
|
||
| await this.transactionManager.execute(async (tx) => { | ||
| Logger.info(`[Authenticator Get Token] Refreshing token for application ${application}`, { application }); | ||
|
|
||
| const { token, expiresIn } = await this.getToken(); | ||
|
|
||
| const tokenExpiracy = !expiresIn ? this.config.tokenExpiryInSeconds : expiresIn; | ||
| const expiresAt = Date.now() + secondsToMillis(tokenExpiracy); | ||
|
|
||
| this.applicationTokens[application] = { token, expiresIn: expiresAt }; | ||
| await this.tokenRepository.save({ application, token, expiresAt }, tx); | ||
|
|
||
| Logger.info(`[Authenticator Get Token] Token refreshed for application ${application}`, { application }); | ||
| }); | ||
|
|
||
| return this.applicationTokens[application].token; | ||
| } | ||
| } |
This file contains hidden or 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,20 @@ | ||
| import type { PrismaTransaction } from 'src/database'; | ||
|
|
||
| export type ApplicationName = 'WAVE_MVNO_APPLICATION' | 'WAVE_PROVISIONING_APPLICATION' | 'WAVE_TENANT_APPLICATION'; | ||
|
|
||
| export interface WaveToken { | ||
| token: string; | ||
| application: ApplicationName; | ||
| expiresAt: number; | ||
| } | ||
|
|
||
| export interface SaveTokenParams { | ||
| application: ApplicationName; | ||
| token: string; | ||
| expiresAt: number; | ||
| } | ||
|
|
||
| export interface AuthenticatorRepository { | ||
| get: (application: ApplicationName, tx?: PrismaTransaction) => Promise<WaveToken | undefined>; | ||
| save: (params: SaveTokenParams, tx?: PrismaTransaction) => Promise<void>; | ||
| } |
This file contains hidden or 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,19 @@ | ||
| export interface WaveAuthenticatorResult { | ||
| token: string; | ||
| expiresIn: number; | ||
| } | ||
|
|
||
| export interface WaveAuthenticator<T> { | ||
| authenticate: (tokenIdentifier: T) => Promise<string>; | ||
| } | ||
|
|
||
| export interface WaveAuthenticatorParams { | ||
| authUrl: string; | ||
| audience: string; | ||
| clientId: string; | ||
| clientSecret: string; | ||
| } | ||
|
|
||
| export interface WaveAuthenticatorConfig { | ||
| tokenExpiryInSeconds: number; | ||
| } |
This file contains hidden or 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,3 @@ | ||
| export type * from './authenticator-types'; | ||
| export type * from './authenticator-repository'; | ||
| export * from './authenticator-implementation'; |
This file contains hidden or 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.
Uh oh!
There was an error while loading. Please reload this page.