-
Notifications
You must be signed in to change notification settings - Fork 0
[PB-6473]: feat/add BridgeClient #58
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
Open
jzunigax2
wants to merge
4
commits into
feat/mail-quota-read
Choose a base branch
from
feat/bridge-client
base: feat/mail-quota-read
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
4c939fd
feat: add BridgeClient and clarify gateway auth secrets
jzunigax2 2c68d08
test: add unit tests for BridgeClient's reportMailUsage method
jzunigax2 55fbea1
test: add unit tests for EmailService's getQuota method and enhance B…
jzunigax2 7389a94
fix: enhance BridgeClient with production flag and secure key handling
jzunigax2 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 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
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
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
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
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,10 @@ | ||
| import { Module } from '@nestjs/common'; | ||
| import { JwtModule } from '@nestjs/jwt'; | ||
| import { BridgeClient } from './bridge.service.js'; | ||
|
|
||
| @Module({ | ||
| imports: [JwtModule.register({})], | ||
| providers: [BridgeClient], | ||
| exports: [BridgeClient], | ||
| }) | ||
| export class BridgeModule {} |
103 changes: 103 additions & 0 deletions
103
src/modules/infrastructure/bridge/bridge.service.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,103 @@ | ||
| import { describe, it, expect, beforeEach, vi } from 'vitest'; | ||
| import { Test, type TestingModule } from '@nestjs/testing'; | ||
| import { createMock, type DeepMocked } from '@golevelup/ts-vitest'; | ||
| import { ConfigService } from '@nestjs/config'; | ||
| import { JwtService } from '@nestjs/jwt'; | ||
| import { BridgeClient, BridgeApiError } from './bridge.service.js'; | ||
|
|
||
| describe('BridgeClient', () => { | ||
| let service: BridgeClient; | ||
| let jwtService: DeepMocked<JwtService>; | ||
| let httpRequest: ReturnType<typeof vi.fn>; | ||
|
|
||
| beforeEach(async () => { | ||
| httpRequest = vi.fn(); | ||
|
|
||
| const configService = createMock<ConfigService>(); | ||
| configService.getOrThrow.mockImplementation((key: string) => { | ||
| if (key === 'apis.bridge.url') return 'http://bridge.test'; | ||
| if (key === 'secrets.bridgePrivateGateway') | ||
| return Buffer.from('test-key').toString('base64'); | ||
| if (key === 'isProduction') return false; | ||
| throw new Error(`unknown key: ${key}`); | ||
| }); | ||
|
|
||
| const module: TestingModule = await Test.createTestingModule({ | ||
| providers: [ | ||
| BridgeClient, | ||
| { provide: ConfigService, useValue: configService }, | ||
| { provide: JwtService, useValue: createMock<JwtService>() }, | ||
| ], | ||
| }).compile(); | ||
|
|
||
| service = module.get(BridgeClient); | ||
| jwtService = module.get(JwtService); | ||
| ( | ||
| service as unknown as { httpClient: { request: typeof httpRequest } } | ||
| ).httpClient = { | ||
| request: httpRequest, | ||
| }; | ||
| }); | ||
|
|
||
| describe('reportMailUsage', () => { | ||
| it('when Bridge returns 200, then signs a gateway token, PUTs usage, and returns storage', async () => { | ||
| const storage = { driveUsed: 1024, planQuota: 5368709120 }; | ||
| jwtService.sign.mockReturnValue('signed-jwt'); | ||
| httpRequest.mockResolvedValue({ | ||
| statusCode: 200, | ||
| body: { text: () => Promise.resolve(JSON.stringify(storage)) }, | ||
| }); | ||
|
|
||
| const result = await service.reportMailUsage('user-1', 512); | ||
|
|
||
| expect(result).toStrictEqual(storage); | ||
| expect(jwtService.sign).toHaveBeenCalledWith( | ||
| { payload: { uuid: 'user-1' } }, | ||
| { | ||
| secret: 'test-key', | ||
| algorithm: 'RS256', | ||
| expiresIn: '1m', | ||
| allowInsecureKeySizes: true, | ||
| }, | ||
| ); | ||
| expect(httpRequest).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| method: 'PUT', | ||
| path: '/v2/gateway/users/user-1/mail-usage', | ||
| body: JSON.stringify({ mailUsedBytes: 512 }), | ||
| headers: expect.objectContaining({ | ||
| authorization: 'Bearer signed-jwt', | ||
| }) as unknown, | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it('when Bridge returns a non-200 status, then throws BridgeApiError with statusCode and details', async () => { | ||
| jwtService.sign.mockReturnValue('signed-jwt'); | ||
| httpRequest.mockResolvedValue({ | ||
| statusCode: 500, | ||
| body: { text: () => Promise.resolve('internal error') }, | ||
| }); | ||
|
|
||
| const error: unknown = await service | ||
| .reportMailUsage('user-1', 512) | ||
| .catch((e: unknown) => e); | ||
|
|
||
| expect(error).toBeInstanceOf(BridgeApiError); | ||
| if (!(error instanceof BridgeApiError)) { | ||
| throw new Error('expected BridgeApiError'); | ||
| } | ||
| expect(error.statusCode).toBe(500); | ||
| expect(error.details).toBe('internal error'); | ||
| }); | ||
|
|
||
| it('when the HTTP request throws, then the error propagates', async () => { | ||
| jwtService.sign.mockReturnValue('signed-jwt'); | ||
| httpRequest.mockRejectedValue(new Error('network failure')); | ||
|
|
||
| await expect(service.reportMailUsage('user-1', 512)).rejects.toThrow( | ||
| 'network failure', | ||
| ); | ||
| }); | ||
| }); | ||
| }); |
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,103 @@ | ||
| import { | ||
| Injectable, | ||
| Logger, | ||
| type OnModuleDestroy, | ||
| type OnModuleInit, | ||
| } from '@nestjs/common'; | ||
| import { ConfigService } from '@nestjs/config'; | ||
| import { JwtService } from '@nestjs/jwt'; | ||
| import { Client } from 'undici'; | ||
| import type { UserStorage } from './bridge.types.js'; | ||
|
|
||
| @Injectable() | ||
| export class BridgeClient implements OnModuleInit, OnModuleDestroy { | ||
| private readonly logger = new Logger(BridgeClient.name); | ||
| private readonly baseUrl: string; | ||
| private readonly origin: string; | ||
| private readonly basePath: string; | ||
| private readonly signingKey: string; | ||
| private readonly isProduction: boolean; | ||
| private httpClient!: Client; | ||
|
|
||
| constructor( | ||
| private readonly configService: ConfigService, | ||
| private readonly jwtService: JwtService, | ||
| ) { | ||
| this.baseUrl = this.configService.getOrThrow<string>('apis.bridge.url'); | ||
| this.signingKey = Buffer.from( | ||
| this.configService.getOrThrow<string>('secrets.bridgePrivateGateway'), | ||
| 'base64', | ||
| ).toString('utf8'); | ||
| this.isProduction = this.configService.getOrThrow<boolean>('isProduction'); | ||
| const parsed = new URL(this.baseUrl); | ||
| this.origin = parsed.origin; | ||
| this.basePath = | ||
| parsed.pathname === '/' ? '' : parsed.pathname.replace(/\/$/, ''); | ||
| } | ||
|
|
||
| onModuleInit() { | ||
| this.httpClient = new Client(this.origin, { | ||
| allowH2: true, | ||
| keepAliveTimeout: 30_000, | ||
| pipelining: 1, | ||
| }); | ||
| this.logger.log(`Bridge client initialized targeting ${this.baseUrl}`); | ||
| } | ||
|
|
||
| async onModuleDestroy() { | ||
| await this.httpClient.close(); | ||
| } | ||
|
|
||
| async reportMailUsage( | ||
| userUuid: string, | ||
| mailUsedBytes: number, | ||
| ): Promise<UserStorage> { | ||
| const token = this.signGatewayToken(userUuid); | ||
|
|
||
| const { statusCode, body } = await this.httpClient.request({ | ||
| method: 'PUT', | ||
| path: `${this.basePath}/v2/gateway/users/${encodeURIComponent(userUuid)}/mail-usage`, | ||
| headers: { | ||
| 'content-type': 'application/json', | ||
| accept: 'application/json', | ||
| authorization: `Bearer ${token}`, | ||
| }, | ||
| body: JSON.stringify({ mailUsedBytes }), | ||
| }); | ||
|
|
||
| const text = await body.text(); | ||
|
|
||
| if (statusCode !== 200) { | ||
| throw new BridgeApiError( | ||
| `Failed to report mail usage for user '${userUuid}': HTTP ${statusCode}`, | ||
| statusCode, | ||
| text, | ||
| ); | ||
| } | ||
|
|
||
| return JSON.parse(text) as UserStorage; | ||
| } | ||
|
|
||
| private signGatewayToken(userUuid: string): string { | ||
| return this.jwtService.sign( | ||
| { payload: { uuid: userUuid } }, | ||
| { | ||
| secret: this.signingKey, | ||
| algorithm: 'RS256', | ||
| expiresIn: '1m', | ||
| ...(this.isProduction ? null : { allowInsecureKeySizes: true }), | ||
| }, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| export class BridgeApiError extends Error { | ||
| constructor( | ||
| message: string, | ||
| public readonly statusCode: number, | ||
| public readonly details: string, | ||
| ) { | ||
| super(message); | ||
| this.name = 'BridgeApiError'; | ||
| } | ||
| } |
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,4 @@ | ||
| export interface UserStorage { | ||
| driveUsed: number; | ||
| planQuota: 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
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
Oops, something went wrong.
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.
Would be better to use, e.g
mailPublicGatewayrather than drive...?