-
Notifications
You must be signed in to change notification settings - Fork 0
feat: implement MTA hooks for quota enforcement #82
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
2
commits into
master
Choose a base branch
from
feat/mta-hooks-read-only-quota
base: master
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
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
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,89 @@ | ||
| import { describe, it, expect, beforeEach } from 'vitest'; | ||
| import { createMock } from '@golevelup/ts-vitest'; | ||
| import { type ConfigService } from '@nestjs/config'; | ||
| import { UnauthorizedException, type ExecutionContext } from '@nestjs/common'; | ||
| import { MtaHooksAuthGuard } from './mta-hooks-auth.guard.js'; | ||
|
|
||
| const username = 'stalwart'; | ||
| const secret = 'secret'; | ||
|
|
||
| describe('MtaHooksAuthGuard', () => { | ||
| let guard: MtaHooksAuthGuard; | ||
|
|
||
| const contextWithAuth = (header?: string): ExecutionContext => | ||
| createMock<ExecutionContext>({ | ||
| switchToHttp: () => ({ | ||
| getRequest: () => ({ | ||
| headers: header ? { authorization: header } : {}, | ||
| }), | ||
| }), | ||
| }); | ||
|
|
||
| const basic = (username: string, secret: string): string => | ||
| `Basic ${Buffer.from(`${username}:${secret}`).toString('base64')}`; | ||
|
|
||
| beforeEach(() => { | ||
| const configService = createMock<ConfigService>(); | ||
| configService.getOrThrow.mockImplementation((key: string) => { | ||
| if (key === 'mtaHooks.username') return username; | ||
| if (key === 'mtaHooks.secret') return secret; | ||
| throw new Error(`unknown key: ${key}`); | ||
| }); | ||
| guard = new MtaHooksAuthGuard(configService); | ||
| }); | ||
|
|
||
| it('when credentials match, then allows the request', () => { | ||
| const context = contextWithAuth(basic(username, secret)); | ||
|
|
||
| expect(guard.canActivate(context)).toBe(true); | ||
| }); | ||
|
|
||
| it('when the secret is wrong, then throws Unauthorized', () => { | ||
| const context = contextWithAuth(basic(username, 'wrong')); | ||
|
|
||
| expect(() => guard.canActivate(context)).toThrow(UnauthorizedException); | ||
| }); | ||
|
|
||
| it('when the username is wrong, then throws Unauthorized', () => { | ||
| const context = contextWithAuth(basic('wrong', secret)); | ||
|
|
||
| expect(() => guard.canActivate(context)).toThrow(UnauthorizedException); | ||
| }); | ||
|
|
||
| it('when the Authorization header is missing, then throws Unauthorized', () => { | ||
| const context = contextWithAuth(undefined); | ||
|
|
||
| expect(() => guard.canActivate(context)).toThrow(UnauthorizedException); | ||
| }); | ||
|
|
||
| it('when the scheme is not Basic, then throws Unauthorized', () => { | ||
| const context = contextWithAuth('Bearer some-token'); | ||
|
|
||
| expect(() => guard.canActivate(context)).toThrow(UnauthorizedException); | ||
| }); | ||
|
|
||
| it('when the decoded credentials lack a colon separator, then throws Unauthorized', () => { | ||
| const context = contextWithAuth( | ||
| `Basic ${Buffer.from('nocolon').toString('base64')}`, | ||
| ); | ||
|
|
||
| expect(() => guard.canActivate(context)).toThrow(UnauthorizedException); | ||
| }); | ||
|
|
||
| it('when the secret is empty, then throws Unauthorized', () => { | ||
| const context = contextWithAuth(basic(username, '')); | ||
|
|
||
| expect(() => guard.canActivate(context)).toThrow(UnauthorizedException); | ||
| }); | ||
|
|
||
| it('when the configured secret is empty, then fails to construct', () => { | ||
| const configService = createMock<ConfigService>(); | ||
| configService.getOrThrow.mockImplementation((key: string) => { | ||
| if (key === 'mtaHooks.username') return username; | ||
| if (key === 'mtaHooks.secret') return ''; | ||
| throw new Error(`unknown key: ${key}`); | ||
| }); | ||
|
|
||
| expect(() => new MtaHooksAuthGuard(configService)).toThrow(); | ||
| }); | ||
| }); |
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,69 @@ | ||
| import { timingSafeEqual } from 'node:crypto'; | ||
| import { | ||
| CanActivate, | ||
| type ExecutionContext, | ||
| Injectable, | ||
| UnauthorizedException, | ||
| } from '@nestjs/common'; | ||
| import { ConfigService } from '@nestjs/config'; | ||
| import type { Request } from 'express'; | ||
|
|
||
| @Injectable() | ||
| export class MtaHooksAuthGuard implements CanActivate { | ||
| private readonly expectedUsername: string; | ||
| private readonly expectedSecret: string; | ||
|
|
||
| constructor(configService: ConfigService) { | ||
| this.expectedUsername = this.requireNonEmpty( | ||
| configService.getOrThrow<string>('mtaHooks.username'), | ||
| 'mtaHooks.username', | ||
| ); | ||
| this.expectedSecret = this.requireNonEmpty( | ||
| configService.getOrThrow<string>('mtaHooks.secret'), | ||
| 'mtaHooks.secret', | ||
| ); | ||
| } | ||
|
|
||
| private requireNonEmpty(value: string, key: string): string { | ||
| if (value.length === 0) { | ||
| throw new Error(`Missing required configuration: ${key}`); | ||
| } | ||
| return value; | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| canActivate(context: ExecutionContext): boolean { | ||
| const request = context.switchToHttp().getRequest<Request>(); | ||
| const header = request.headers.authorization ?? ''; | ||
|
|
||
| const [scheme, encoded] = header.split(' '); | ||
| if (scheme !== 'Basic' || !encoded) { | ||
| throw new UnauthorizedException('Missing or malformed Basic credentials'); | ||
| } | ||
|
|
||
| const decoded = Buffer.from(encoded, 'base64').toString('utf8'); | ||
| const separatorIndex = decoded.indexOf(':'); | ||
| if (separatorIndex === -1) { | ||
| throw new UnauthorizedException('Malformed Basic credentials'); | ||
| } | ||
|
|
||
| const username = decoded.slice(0, separatorIndex); | ||
| const secret = decoded.slice(separatorIndex + 1); | ||
|
|
||
| const usernameMatches = this.safeEqual(username, this.expectedUsername); | ||
| const secretMatches = this.safeEqual(secret, this.expectedSecret); | ||
| if (!usernameMatches || !secretMatches) { | ||
| throw new UnauthorizedException('Invalid MTA hook credentials'); | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| private safeEqual(a: string, b: string): boolean { | ||
| const bufferA = Buffer.from(a, 'utf8'); | ||
| const bufferB = Buffer.from(b, 'utf8'); | ||
| if (bufferA.length !== bufferB.length) { | ||
| return false; | ||
| } | ||
| return timingSafeEqual(bufferA, bufferB); | ||
| } | ||
| } | ||
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,23 @@ | ||
| import { Body, Controller, Post, UseGuards } from '@nestjs/common'; | ||
| import { ApiBasicAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; | ||
| import { Public } from '../auth/decorators/public.decorator.js'; | ||
| import { MtaHooksAuthGuard } from './mta-hooks-auth.guard.js'; | ||
| import { MtaHooksService } from './mta-hooks.service.js'; | ||
| import type { MtaHookRequest, MtaHookResponse } from './mta-hooks.types.js'; | ||
|
|
||
| @ApiTags('MTA Hooks') | ||
| @ApiBasicAuth('mta-hooks') | ||
| @Public() | ||
| @UseGuards(MtaHooksAuthGuard) | ||
| @Controller('mta-hooks') | ||
| export class MtaHooksController { | ||
| constructor(private readonly mtaHooksService: MtaHooksService) {} | ||
|
|
||
| @Post('rcpt') | ||
| @ApiOperation({ | ||
| summary: 'RCPT-stage hook', | ||
| }) | ||
| rcpt(@Body() request: MtaHookRequest): Promise<MtaHookResponse> { | ||
| return this.mtaHooksService.handleRcpt(request); | ||
| } | ||
| } |
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,13 @@ | ||
| import { Module } from '@nestjs/common'; | ||
| import { AccountModule } from '../account/account.module.js'; | ||
| import { BridgeModule } from '../infrastructure/bridge/bridge.module.js'; | ||
| import { MtaHooksAuthGuard } from './mta-hooks-auth.guard.js'; | ||
| import { MtaHooksController } from './mta-hooks.controller.js'; | ||
| import { MtaHooksService } from './mta-hooks.service.js'; | ||
|
|
||
| @Module({ | ||
| imports: [AccountModule, BridgeModule], | ||
| controllers: [MtaHooksController], | ||
| providers: [MtaHooksService, MtaHooksAuthGuard], | ||
| }) | ||
| export class MtaHooksModule {} |
Oops, something went wrong.
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.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Do not leave the MTA hooks secret empty in the deployment template.
With
MTA_HOOKS_SECRET=and the configuration fallback to'', deployments that copy this file unchanged will have unusable RCPT authentication because the guard requires non-empty credentials. Use an explicit placeholder and validate the secret at startup, or document that it must be replaced before deployment.🧰 Tools
🪛 dotenv-linter (4.0.0)
[warning] 37-37: [UnorderedKey] The MTA_HOOKS_SECRET key should go before the MTA_HOOKS_USERNAME key
(UnorderedKey)
🤖 Prompt for AI Agents