Skip to content
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
155 changes: 155 additions & 0 deletions src/core/authenticator/authenticator-implementation.spec.ts
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()
);
});
});
});
92 changes: 92 additions & 0 deletions src/core/authenticator/authenticator-implementation.ts
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;
}
}
20 changes: 20 additions & 0 deletions src/core/authenticator/authenticator-repository.ts
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>;
}
19 changes: 19 additions & 0 deletions src/core/authenticator/authenticator-types.ts
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;
}
3 changes: 3 additions & 0 deletions src/core/authenticator/index.ts
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';
1 change: 1 addition & 0 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './result'
export type * from './use-case'
export * from './uuid'
export * from './hooks'
export * from './authenticator'