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

Add JwtModule datasource #1355

Merged
merged 1 commit into from
Apr 4, 2024
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
5 changes: 5 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@
# The AUTH_TOKEN should always be set
#AUTH_TOKEN=

# The issuer and secret used to sign and verify JWTs.
# The JWT_ISSUER and JWT_SECRET should always be set
#JWT_ISSUER=
#JWT_SECRET=

# Log level for the service.
#LOG_LEVEL=

Expand Down
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ services:
EMAIL_TEMPLATE_UNKNOWN_RECOVERY_TX: ${EMAIL_TEMPLATE_UNKNOWN_RECOVERY_TX-example_template_unknown_recovery_tx}
EMAIL_TEMPLATE_RECOVERY_TX: ${EMAIL_TEMPLATE_RECOVERY_TX-example_template_recovery_tx}
EMAIL_TEMPLATE_VERIFICATION_CODE: ${EMAIL_TEMPLATE_VERIFICATION_CODE-example_template_verification_code}
JWT_ISSUER: ${JWT_ISSUER-example_issuer}
JWT_TOKEN: ${JWT_TOKEN-example_token}
RELAY_PROVIDER_API_KEY_GNOSIS_CHAIN: ${RELAY_PROVIDER_API_KEY_GNOSIS_CHAIN-example_api_key}
RELAY_PROVIDER_API_KEY_SEPOLIA: ${RELAY_PROVIDER_API_KEY_SEPOLIA-example_api_key}
depends_on:
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"@safe-global/safe-deployments": "^1.33.0",
"ajv": "^8.12.0",
"ajv-formats": "^2.1.1",
"jsonwebtoken": "^9.0.2",
"lodash": "^4.17.21",
"nestjs-cls": "^4.3.0",
"postgres": "^3.4.3",
Expand All @@ -53,6 +54,7 @@
"@nestjs/testing": "^10.3.7",
"@types/express": "^4.17.21",
"@types/jest": "29.5.12",
"@types/jsonwebtoken": "^9",
"@types/lodash": "^4.17.0",
"@types/node": "^20.12.2",
"@types/semver": "^7.5.8",
Expand Down
6 changes: 6 additions & 0 deletions src/config/configuration.validator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ describe('Configuration validator', () => {
EMAIL_TEMPLATE_RECOVERY_TX: faker.string.alphanumeric(),
EMAIL_TEMPLATE_UNKNOWN_RECOVERY_TX: faker.string.alphanumeric(),
EMAIL_TEMPLATE_VERIFICATION_CODE: faker.string.alphanumeric(),
JWT_ISSUER: faker.lorem.word(),
JWT_SECRET: faker.string.alphanumeric(),
RELAY_PROVIDER_API_KEY_GNOSIS_CHAIN: faker.string.uuid(),
RELAY_PROVIDER_API_KEY_SEPOLIA: faker.string.uuid(),
};
Expand Down Expand Up @@ -46,6 +48,8 @@ describe('Configuration validator', () => {
{ key: 'EMAIL_TEMPLATE_RECOVERY_TX' },
{ key: 'EMAIL_TEMPLATE_UNKNOWN_RECOVERY_TX' },
{ key: 'EMAIL_TEMPLATE_VERIFICATION_CODE' },
{ key: 'JWT_ISSUER' },
{ key: 'JWT_SECRET' },
{ key: 'RELAY_PROVIDER_API_KEY_GNOSIS_CHAIN' },
{ key: 'RELAY_PROVIDER_API_KEY_SEPOLIA' },
])(
Expand Down Expand Up @@ -75,6 +79,8 @@ describe('Configuration validator', () => {
EMAIL_TEMPLATE_RECOVERY_TX: faker.string.alphanumeric(),
EMAIL_TEMPLATE_UNKNOWN_RECOVERY_TX: faker.string.alphanumeric(),
EMAIL_TEMPLATE_VERIFICATION_CODE: faker.string.alphanumeric(),
JWT_ISSUER: faker.lorem.word(),
JWT_SECRET: faker.string.alphanumeric(),
RELAY_PROVIDER_API_KEY_GNOSIS_CHAIN: faker.string.uuid(),
RELAY_PROVIDER_API_KEY_SEPOLIA: faker.string.uuid(),
}),
Expand Down
2 changes: 2 additions & 0 deletions src/config/configuration.validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ const ConfigurationSchema = z.object({
EMAIL_TEMPLATE_RECOVERY_TX: z.string(),
EMAIL_TEMPLATE_UNKNOWN_RECOVERY_TX: z.string(),
EMAIL_TEMPLATE_VERIFICATION_CODE: z.string(),
JWT_ISSUER: z.string(),
JWT_SECRET: z.string(),
RELAY_PROVIDER_API_KEY_GNOSIS_CHAIN: z.string(),
RELAY_PROVIDER_API_KEY_SEPOLIA: z.string(),
});
Expand Down
4 changes: 4 additions & 0 deletions src/config/entities/__tests__/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,10 @@ export default (): ReturnType<typeof configuration> => ({
historyDebugLogs: false,
},
httpClient: { requestTimeout: faker.number.int() },
jwt: {
issuer: faker.lorem.word(),
secret: faker.string.alphanumeric(),
},
locking: {
baseUri: faker.internet.url({ appendSlash: false }),
},
Expand Down
4 changes: 4 additions & 0 deletions src/config/entities/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,10 @@ export default () => ({
process.env.HTTP_CLIENT_REQUEST_TIMEOUT_MILLISECONDS ?? `${5_000}`,
),
},
jwt: {
issuer: process.env.JWT_ISSUER,
secret: process.env.JWT_SECRET,
},
locking: {
// TODO: Add fallback value and requirement validation
baseUri: process.env.LOCKING_PROVIDER_API_BASE_URI || '',
Expand Down
28 changes: 28 additions & 0 deletions src/datasources/jwt/jwt.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as jwt from 'jsonwebtoken';
import { Global, Module } from '@nestjs/common';
import { JwtService } from '@/datasources/jwt/jwt.service';
import { IJwtService } from '@/datasources/jwt/jwt.service.interface';

// Use inferred type
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function jwtClientFactory() {
return {
sign: jwt.sign,
verify: jwt.verify,
};
}

export type JwtClient = ReturnType<typeof jwtClientFactory>;

@Global()
@Module({
providers: [
{
provide: 'JwtClient',
useFactory: jwtClientFactory,
},
{ provide: IJwtService, useClass: JwtService },
],
exports: [IJwtService],
})
export class JwtModule {}
13 changes: 13 additions & 0 deletions src/datasources/jwt/jwt.service.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export const IJwtService = Symbol('IJwtService');

export interface IJwtService {
sign<T extends string | object>(
payload: T,
options: {
expiresIn?: number;
notBefore?: number;
},
): string;

verify<T extends string | object>(token: string): T;
}
74 changes: 74 additions & 0 deletions src/datasources/jwt/jwt.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { fakeJson } from '@/__tests__/faker';
import { FakeConfigurationService } from '@/config/__tests__/fake.configuration.service';
import { JwtClient } from '@/datasources/jwt/jwt.module';
import { JwtService } from '@/datasources/jwt/jwt.service';
import { faker } from '@faker-js/faker';

const jwtClientMock: jest.MockedObjectDeep<JwtClient> = jest.mocked({
sign: jest.fn(),
verify: jest.fn(),
});

describe('JwtService', () => {
let service: JwtService;
let fakeConfigurationService: FakeConfigurationService;

let jwtIssuer: string;
let jwtSecret: string;

beforeEach(() => {
jest.resetAllMocks();

jwtIssuer = faker.lorem.word();
jwtSecret = faker.string.alphanumeric();

fakeConfigurationService = new FakeConfigurationService();
fakeConfigurationService.set('jwt.issuer', jwtIssuer);
fakeConfigurationService.set('jwt.secret', jwtSecret);

service = new JwtService(jwtClientMock, fakeConfigurationService);
});

describe('sign', () => {
it('should sign a payload with the issuer', () => {
const payload = fakeJson();

service.sign(payload);

expect(jwtClientMock.sign).toHaveBeenCalledTimes(1);
expect(jwtClientMock.sign).toHaveBeenCalledWith(payload, jwtSecret, {
issuer: jwtIssuer,
});
});

it('should sign a payload with options and the issuer', () => {
const payload = fakeJson();
const options = {
expiresIn: faker.number.int({ min: 1 }),
notBefore: faker.number.int({ min: 1 }),
};

service.sign(payload, options);

expect(jwtClientMock.sign).toHaveBeenCalledTimes(1);
expect(jwtClientMock.sign).toHaveBeenCalledWith(payload, jwtSecret, {
...options,
issuer: jwtIssuer,
});
});
});

describe('verify', () => {
it('should verify a token with the issuer and explicit return of payload', () => {
const token = fakeJson();

service.verify(token);

expect(jwtClientMock.verify).toHaveBeenCalledTimes(1);
expect(jwtClientMock.verify).toHaveBeenCalledWith(token, jwtSecret, {
issuer: jwtIssuer,
complete: false,
});
});
});
});
38 changes: 38 additions & 0 deletions src/datasources/jwt/jwt.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { IConfigurationService } from '@/config/configuration.service.interface';
import { JwtClient } from '@/datasources/jwt/jwt.module';
import { IJwtService } from '@/datasources/jwt/jwt.service.interface';
import { Inject, Injectable } from '@nestjs/common';

@Injectable()
export class JwtService implements IJwtService {
private readonly issuer: string;
private readonly secret: string;

constructor(
@Inject('JwtClient')
private readonly client: JwtClient,
@Inject(IConfigurationService)
private readonly configurationService: IConfigurationService,
) {
this.issuer = this.configurationService.getOrThrow<string>('jwt.issuer');
this.secret = this.configurationService.getOrThrow<string>('jwt.secret');
}

sign<T extends string | object>(
payload: T,
options: { expiresIn?: number; notBefore?: number } = {},
): string {
return this.client.sign(payload, this.secret, {
...options,
issuer: this.issuer,
});
}

verify<T extends string | object>(token: string): T {
return this.client.verify(token, this.secret, {
issuer: this.issuer,
// Return the content of the payload
complete: false,
}) as T;
}
}
Loading