Skip to content
Open
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
44 changes: 14 additions & 30 deletions backend/src/auth/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,14 @@
import {
Controller,
Post,
Get,
UseGuards,
Request,
HttpStatus,
HttpCode,
Body,
} from '@nestjs/common';
import {
ApiTags,
ApiOperation,
ApiResponse,
ApiBearerAuth,
} from '@nestjs/swagger';
import { AuthService } from '../services/auth.service';
import { Auth } from '../decorators/auth-decorator';
import { AuthType } from '../enums/auth-type.enum';
import { AuthResponseDto } from '../dto/auth-response.dto';
import { RegisterDto } from '../dto/register.dto';
import { LoginDto } from '../dto/login.dto';
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
import { User } from '../entities/user.entity';
import { Controller, Post, Get, UseGuards, Request, HttpStatus, HttpCode, Body } from "@nestjs/common"
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from "@nestjs/swagger"
import { AuthService } from "../services/auth.service"
import { Auth } from "../decorators/auth-decorator"
import { AuthType } from "../enums/auth-type.enum"
import { AuthResponseDto } from "../dto/auth-response.dto"
import { GenericAuthMessageDto } from "../dto/generic-auth-message.dto"
import { RegisterDto } from "../dto/register.dto"
import { LoginDto } from "../dto/login.dto"
import { JwtAuthGuard } from "../guards/jwt-auth.guard"
import { User } from "../entities/user.entity"

@ApiTags('Authentication')
@Controller('auth')
Expand All @@ -38,18 +25,15 @@ export class AuthController {
})
@ApiResponse({
status: 201,
description: 'User successfully registered',
description:
"User successfully registered (or, for anti-enumeration, a generic neutral response when the email is already taken)",
type: AuthResponseDto,
})
@ApiResponse({
status: 400,
description: 'Bad request - validation failed',
})
@ApiResponse({
status: 409,
description: 'Conflict - user already exists',
})
async register(@Body() registerDto: RegisterDto): Promise<AuthResponseDto> {
async register(@Body() registerDto: RegisterDto): Promise<AuthResponseDto | GenericAuthMessageDto> {
try {
return await this.authService.register(registerDto);
} catch (error) {
Expand Down
14 changes: 14 additions & 0 deletions backend/src/auth/dto/generic-auth-message.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ApiProperty } from "@nestjs/swagger"

// Anti-enumeration response body returned by public auth endpoints when the
// server must not reveal whether an account already exists (OWASP A01:
// Broken Access Control — user/account enumeration). It carries no user
// identifier and no access token, so a probing attacker cannot distinguish
// a brand-new registration from one that already exists.
export class GenericAuthMessageDto {
@ApiProperty({
description: "Generic, account-existence-neutral message",
example: "Registration successful. If an account already exists, please log in.",
})
message: string
}
189 changes: 106 additions & 83 deletions backend/src/auth/services/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import { Test, type TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { ConflictException, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { User } from '../entities/user.entity';
import type { RegisterDto } from '../dto/register.dto';
import type { LoginDto } from '../dto/login.dto';
import { jest } from '@jest/globals';
import type { Repository } from 'typeorm';

describe('AuthService', () => {
let service: AuthService;
let userRepository: jest.Mocked<Repository<User>>;
let jwtService: jest.Mocked<JwtService>;
import { Test, type TestingModule } from "@nestjs/testing"
import { getRepositoryToken } from "@nestjs/typeorm"
import { JwtService } from "@nestjs/jwt"
import { ConfigService } from "@nestjs/config"
import { UnauthorizedException } from "@nestjs/common"
import { AuthService } from "./auth.service"
import { User } from "../entities/user.entity"
import type { RegisterDto } from "../dto/register.dto"
import type { LoginDto } from "../dto/login.dto"
import type { AuthResponseDto } from "../dto/auth-response.dto"
import { jest } from "@jest/globals"
import type { Repository } from "typeorm"

describe("AuthService", () => {
let service: AuthService
let userRepository: jest.Mocked<Repository<User>>
let jwtService: jest.Mocked<JwtService>

const mockUserRepository = {
findOne: jest.fn(),
Expand Down Expand Up @@ -49,104 +50,126 @@ describe('AuthService', () => {
],
}).compile();

service = module.get<AuthService>(AuthService);
userRepository = module.get(getRepositoryToken(User)) as jest.Mocked<
Repository<User>
>;
jwtService = module.get<JwtService>(JwtService);
});
service = module.get<AuthService>(AuthService)
userRepository = module.get(getRepositoryToken(User)) as jest.Mocked<Repository<User>>
jwtService = module.get(JwtService) as unknown as jest.Mocked<JwtService>
})

afterEach(() => {
jest.clearAllMocks();
});

describe('register', () => {
const registerDto: RegisterDto = {
name: 'John Doe',
email: 'john@example.com',
password: 'SecurePass123!',
};

it('should successfully register a new user', async () => {
const mockUser = {
id: 'user-id',
name: 'John Doe',
email: 'john@example.com',
createdAt: new Date(),
} as User;

userRepository.findOne.mockResolvedValue(null);
userRepository.create.mockReturnValue(mockUser);
userRepository.save.mockResolvedValue(mockUser);
jwtService.sign.mockReturnValue('jwt-token');
mockConfigService.get.mockReturnValue('15m');

const result = await service.register(registerDto);
name: "John Doe",
username: "john_doe",
email: "john@example.com",
password: "SecurePass123!",
}

const registeredUser = {
id: "user-id",
name: "John Doe",
email: "john@example.com",
createdAt: new Date(),
} as User

it("should successfully register a new user", async () => {
userRepository.findOne.mockResolvedValue(null)
userRepository.create.mockReturnValue(registeredUser)
userRepository.save.mockResolvedValue(registeredUser)
jwtService.sign.mockReturnValue("jwt-token")
mockConfigService.get.mockReturnValue("15m")

const result = (await service.register(registerDto)) as AuthResponseDto

expect(result).toHaveProperty('accessToken', 'jwt-token');
expect(result).toHaveProperty('user');
expect(result.user.email).toBe('john@example.com');
});

it('should throw ConflictException if user already exists', async () => {
const existingUser = { id: 'existing-user' } as User;
userRepository.findOne.mockResolvedValue(existingUser);
it("should return a generic neutral message if user already exists (anti-enumeration)", async () => {
const existingUser = { id: "existing-user" } as User
userRepository.findOne.mockResolvedValue(existingUser)

await expect(service.register(registerDto)).rejects.toThrow(
ConflictException,
);
});
});
const result = await service.register(registerDto)

// Must NOT reveal that the account exists or issue a token.
expect(result).toHaveProperty("message")
expect(result).not.toHaveProperty("accessToken")
expect(userRepository.create).not.toHaveBeenCalled()
expect(userRepository.save).not.toHaveBeenCalled()
})

it("should return a generic neutral message on unique violation (anti-enumeration)", async () => {
userRepository.findOne.mockResolvedValue(null)
const error: any = new Error("duplicate")
error.code = "23505"
userRepository.save.mockRejectedValue(error)

const result = await service.register(registerDto)

expect(result).toHaveProperty("message")
expect(result).not.toHaveProperty("accessToken")
})
})

describe('login', () => {
const loginDto: LoginDto = {
email: 'john@example.com',
password: 'SecurePass123!',
};

it('should successfully login with valid credentials', async () => {
const mockUser = {
id: 'user-id',
name: 'John Doe',
email: 'john@example.com',
isActive: true,
validatePassword: jest.fn().mockResolvedValue(true),
} as User & { validatePassword: jest.Mock };

userRepository.findOne.mockResolvedValue(mockUser);
userRepository.update.mockResolvedValue({
affected: 1,
generatedMaps: [],
raw: {},
});
jwtService.sign.mockReturnValue('jwt-token');
mockConfigService.get.mockReturnValue('15m');
const validatedUser = (isActive: boolean, passwordMatches: boolean) => {
const user = {
id: "user-id",
name: "John Doe",
email: "john@example.com",
isActive,
validatePassword: async () => passwordMatches,
} as unknown as User
return user
}

it("should successfully login with valid credentials", async () => {
const mockUser = validatedUser(true, true)
userRepository.findOne.mockResolvedValue(mockUser)
userRepository.update.mockResolvedValue({ affected: 1, generatedMaps: [], raw: {} })
jwtService.sign.mockReturnValue("jwt-token")
mockConfigService.get.mockReturnValue("15m")

const result = await service.login(loginDto);

expect(result).toHaveProperty('accessToken', 'jwt-token');
expect(result).toHaveProperty('user');
});

it('should throw UnauthorizedException for invalid credentials', async () => {
userRepository.findOne.mockResolvedValue(null);
it("should throw UnauthorizedException for unknown email without revealing that the account does not exist", async () => {
userRepository.findOne.mockResolvedValue(null)

await expect(service.login(loginDto)).rejects.toThrow(
UnauthorizedException,
);
});
new UnauthorizedException("Invalid email or password"),
)
})

it('should throw UnauthorizedException for inactive user', async () => {
const mockUser = {
id: 'user-id',
isActive: false,
} as User;
it("should throw UnauthorizedException for inactive user without revealing account status", async () => {
const mockUser = validatedUser(false, true)
userRepository.findOne.mockResolvedValue(mockUser)

userRepository.findOne.mockResolvedValue(mockUser);
// Same generic message as for unknown email / wrong password.
await expect(service.login(loginDto)).rejects.toThrow(
new UnauthorizedException("Invalid email or password"),
)
})

it("should not reveal whether an account exists when password is wrong", async () => {
const mockUser = validatedUser(true, false)
userRepository.findOne.mockResolvedValue(mockUser)

// Message identical across all failure modes.
await expect(service.login(loginDto)).rejects.toThrow(
UnauthorizedException,
);
});
});
});
new UnauthorizedException("Invalid email or password"),
)
})
})
})
Loading
Loading