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
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ LIFECYCLE_SERVICE_SECRET_IDENTITY=
# Lifecycle เซ็น token ไปเรียก Job (โควตา/ข้อมูลประกาศ) — ต้องเท่ากันทั้งสอง Service ≥ 32 ตัวอักษร
# Lifecycle จะไม่เริ่มหาก IDENTITY_SERVICE_SECRET_LIFECYCLE หรือ JOB_SERVICE_SECRET_LIFECYCLE ว่างหรือสั้นกว่า 32 ตัวอักษร
JOB_SERVICE_SECRET_LIFECYCLE=
# Identity เซ็น token ไป Job เพื่อกรองบริษัทตามสายงาน; Job ตรวจด้วยค่าเดียวกัน (>= 32 ตัวอักษร)
JOB_SERVICE_SECRET_IDENTITY=
# Lifecycle ตรวจ token ที่ Job เซ็น (POST /internal/v1/applications/reservation-check) — ต้องเท่ากันทั้งสอง Service ≥ 32 ตัวอักษร
LIFECYCLE_SERVICE_SECRET_JOB=

Expand Down
4 changes: 3 additions & 1 deletion apps/gateway/src/gateway.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ export class GatewayMiddleware {
const rate = this.rateLimiter.rule(req.method, path);
let body: Buffer | undefined;
if (rate) {
const retry = this.rateLimiter.checkIp(rate, clientIp);
const retry = rate.name === 'advisor-create-student' && user
? this.rateLimiter.checkAdvisorCreateIp(clientIp) || this.rateLimiter.checkActor(rate, user.sub)
: this.rateLimiter.checkIp(rate, clientIp);
if (retry) { res.setHeader('Retry-After', String(retry)); return this.error(req, res, 429, 'RATE_LIMITED'); }
if (req.method === 'POST' && path.startsWith('/auth/')) {
try { body = await this.rateLimiter.readAuthBody(req); }
Expand Down
11 changes: 11 additions & 0 deletions apps/gateway/src/rate-limit/rate-limiter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export class RateLimiter {
rule(method: string, path: string): Rule | undefined {
// README §5.7 fixes categories; these conservative defaults can be tuned by env later.
if (method === 'POST' && path === '/auth/login') return { name: 'login', max: 10, windowMs: 60_000 };
if (method === 'POST' && path === '/advisor-links/students')
return { name: 'advisor-create-student', max: 30, windowMs: 3_600_000 };
if (method === 'POST' && path.startsWith('/auth/register/')) return { name: 'register', max: 5, windowMs: 3_600_000 };
if (method === 'POST' && ['/auth/password/forgot', '/auth/password/reset', '/auth/resend-verification',
'/auth/login/unlock/request'].includes(path))
Expand All @@ -26,6 +28,15 @@ export class RateLimiter {
return this.limit(`${rule.name}:ip:${clientIp}`, rule.max, rule.windowMs);
}

checkActor(rule: Rule, userId: string): number {
return this.limit(`${rule.name}:actor:${userId}`, rule.max, rule.windowMs);
}

checkAdvisorCreateIp(clientIp: string): number {
// A university may have several advisors behind one IP; retain a broader network cap.
return this.limit(`advisor-create-student:ip:${clientIp}`, 120, 3_600_000);
}

checkAccount(rule: Rule, path: string, body: Buffer): number {
const account = this.accountKey(path, body);
return account ? this.limit(`${rule.name}:account:${account}`, rule.max, rule.windowMs) : 0;
Expand Down
21 changes: 21 additions & 0 deletions apps/gateway/test/integration/proxy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ describe('Gateway proxy and security', function () {
const token = () => jwt.sign({ role: 'STUDENT' }, privateKey, {
algorithm: 'RS256', subject: userId, expiresIn: 900, jwtid: randomUUID(),
});
const advisorToken = (id: string) => jwt.sign({ role: 'ADVISOR' }, privateKey, {
algorithm: 'RS256', subject: id, expiresIn: 900, jwtid: randomUUID(),
});
const edge = (call: request.Test) => call.set('X-Edge-Secret', 'edge-test-secret');

before(async () => {
Expand Down Expand Up @@ -114,6 +117,24 @@ describe('Gateway proxy and security', function () {
expect(Number(limited.headers['retry-after'])).to.be.greaterThan(0);
});

it('limits student creation per advisor, including requests from different IPs', async () => {
const first = advisorToken(randomUUID());
const second = advisorToken(randomUUID());
for (let index = 0; index < 30; index++) {
await edge(request(app.getHttpServer()).post('/api/v1/advisor-links/students'))
.set('Authorization', `Bearer ${first}`).set('X-Client-IP', `203.0.113.${index + 1}`)
.send({ email: `student-${index}@school.ac.th` }).expect(200);
}
const limited = await edge(request(app.getHttpServer()).post('/api/v1/advisor-links/students'))
.set('Authorization', `Bearer ${first}`).set('X-Client-IP', '203.0.113.99')
.send({ email: 'another@school.ac.th' }).expect(429);
expect(limited.body.error.code).to.equal('RATE_LIMITED');
expect(Number(limited.headers['retry-after'])).to.be.greaterThan(0);
await edge(request(app.getHttpServer()).post('/api/v1/advisor-links/students'))
.set('Authorization', `Bearer ${second}`).set('X-Client-IP', '203.0.113.99')
.send({ email: 'other-advisor@school.ac.th' }).expect(200);
});

it('limits login attempts for one email across different IPs', async () => {
for (let index = 0; index < 10; index++) {
await edge(request(app.getHttpServer()).post('/api/v1/auth/login'))
Expand Down
12 changes: 12 additions & 0 deletions apps/gateway/test/unit/rate-limiter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@ import { expect } from 'chai';
import { RateLimiter } from '../../src/rate-limit/rate-limiter';

describe('Gateway rate limiter capacity', () => {
it('limits student creation per advisor without sharing a bucket across advisors', () => {
const limiter = new RateLimiter();
const rule = limiter.rule('POST', '/advisor-links/students')!;
expect(rule).to.include({ name: 'advisor-create-student', max: 30, windowMs: 3_600_000 });
expect(limiter.rule('GET', '/advisor-links/students')).to.equal(undefined);
for (let index = 0; index < 30; index++) expect(limiter.checkActor(rule, 'advisor-a')).to.equal(0);
expect(limiter.checkActor(rule, 'advisor-a')).to.be.greaterThan(0);
expect(limiter.checkActor(rule, 'advisor-b')).to.equal(0);
for (let index = 0; index < 120; index++) expect(limiter.checkAdvisorCreateIp('203.0.113.10')).to.equal(0);
expect(limiter.checkAdvisorCreateIp('203.0.113.10')).to.be.greaterThan(0);
expect(limiter.checkAdvisorCreateIp('203.0.113.11')).to.equal(0);
});
it('evicts the least recently used bucket instead of rejecting every new client', () => {
const limiter = new RateLimiter();
const login = { name: 'login', max: 1, windowMs: 60_000 };
Expand Down
5 changes: 4 additions & 1 deletion apps/identity/src/modules/admin/admin.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Body, Controller, Get, Headers, HttpCode, Param, ParseUUIDPipe, Post, Put, Query, UseGuards } from '@nestjs/common';
import { CurrentUser, JwtAuthGuard, type JwtClaims, Roles, RolesGuard } from '@internpath/common';
import { AdminService } from './admin.service';
import { AuditQueryDto, SetEntitlementsDto, SetPartnerDto, UserActionDto } from './admin.dto';
import { AdminUsersQueryDto, AuditQueryDto, SetEntitlementsDto, SetPartnerDto, UserActionDto } from './admin.dto';

@Controller('admin')
@UseGuards(JwtAuthGuard, RolesGuard)
Expand All @@ -27,6 +27,9 @@ export class AdminController {
return this.service.userAction(actor.sub, userId, action, body.reason, correlationId);
}

@Get('users')
users(@CurrentUser() actor: JwtClaims, @Query() query: AdminUsersQueryDto) { return this.service.users(actor.sub, query); }

@Get('audit-logs')
audit(@CurrentUser() actor: JwtClaims, @Query() query: AuditQueryDto) { return this.service.audit(actor.sub, query); }
}
11 changes: 10 additions & 1 deletion apps/identity/src/modules/admin/admin.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Type } from 'class-transformer';
import { IsBoolean, IsInt, IsOptional, IsString, IsUUID, Max, MaxLength, Min } from 'class-validator';
import { IsBoolean, IsEnum, IsInt, IsOptional, IsString, IsUUID, Max, MaxLength, Min } from 'class-validator';
import { Role, UserStatus } from '../../../generated/client';

export class SetPartnerDto {
@IsBoolean() enabled!: boolean;
Expand All @@ -14,6 +15,14 @@ export class UserActionDto {
@IsOptional() @IsString() @MaxLength(1000) reason?: string;
}

export class AdminUsersQueryDto {
@IsOptional() @IsString() @MaxLength(100) q?: string;
@IsOptional() @IsEnum(Role) role?: Role;
@IsOptional() @IsEnum(UserStatus) status?: UserStatus;
@IsOptional() @Type(() => Number) @IsInt() @Min(1) page = 1;
@IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(100) page_size = 20;
}

export class AuditQueryDto {
@IsOptional() @Type(() => Number) @IsInt() @Min(1) page = 1;
@IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(100) page_size = 20;
Expand Down
26 changes: 25 additions & 1 deletion apps/identity/src/modules/admin/admin.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { AppException, OutboxWriter, asUuid } from '@internpath/common';
import type { CompanyEntitlementChangedPayload, CompanyStatusChangedPayload, UserSuspendedPayload } from '@internpath/contracts';
import { Company, Prisma, User } from '../../../generated/client';
import { PrismaService } from '../../prisma/prisma.service';
import { AuditQueryDto, SetEntitlementsDto } from './admin.dto';
import { AdminUsersQueryDto, AuditQueryDto, SetEntitlementsDto } from './admin.dto';

@Injectable()
export class AdminService {
Expand Down Expand Up @@ -123,4 +123,28 @@ export class AdminService {
correlation_id: row.correlationId, occurred_at: row.occurredAt.toISOString() })),
meta: { page: query.page, page_size: query.page_size, total } };
}

async users(adminId: string, query: AdminUsersQueryDto) {
await this.admin(adminId);
const q = query.q?.trim();
const where: Prisma.UserWhereInput = {
...(query.role ? { role: query.role } : {}),
...(query.status ? { status: query.status } : { status: { not: 'DELETED' } }),
...(q ? { OR: [
{ fullName: { contains: q, mode: 'insensitive' } },
{ email: { contains: q, mode: 'insensitive' } },
{ studentProfile: { is: { studentCode: { contains: q, mode: 'insensitive' } } } },
] } : {}),
};
const [rows, total] = await Promise.all([
this.db.user.findMany({ where, include: { studentProfile: true, companyMember: true },
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], skip: (query.page - 1) * query.page_size, take: query.page_size }),
this.db.user.count({ where }),
]);
return { data: rows.map((user) => ({ id: user.id, full_name: user.fullName, email: user.email,
role: user.role, status: user.status, university_id: user.universityId,
advisor_id: user.studentProfile?.advisorId ?? null, student_code: user.studentProfile?.studentCode ?? null,
company_id: user.companyMember?.companyId ?? null, created_at: user.createdAt.toISOString() })),
meta: { page: query.page, page_size: query.page_size, total } };
}
}
13 changes: 12 additions & 1 deletion apps/identity/src/modules/advisor-links/advisor-link.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { AdminAdvisorQueryDto, AdvisorStudentsQueryDto, CreateStudentDto, Update

const normalizeEmail = (email: string): string => email.trim().toLowerCase();
const isUniqueError = (error: unknown): boolean => error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002';
const isSerializationError = (error: unknown): boolean => error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2034';

type Page<T> = { data: T[]; meta: { page: number; page_size: number; total: number } };

Expand Down Expand Up @@ -97,9 +98,19 @@ export class AdvisorLinkService {
actorId: advisorId, actorRole: 'ADVISOR', reason: 'STUDENT_CREATED_BY_ADVISOR', correlationId: cid, occurredAt: now } });
await this.linkEvent(tx, { studentId: user.id, before: { advisorId: null, advisorLinkStatus: 'NONE' } as StudentProfileIdentity,
toStatus: 'LINKED', newAdvisorId: advisorId, changedBy: 'ADVISOR', actorId: advisorId, correlationId: cid, now });
});
}, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
} catch (error) {
if (isUniqueError(error)) throw new AppException('STATE_CONFLICT', 'อีเมลนี้ลงทะเบียนแล้ว', 409, [{ field: 'email', issue: 'EMAIL_ALREADY_REGISTERED' }]);
if (isSerializationError(error)) {
if (await this.db.user.findUnique({ where: { email } }))
throw new AppException('STATE_CONFLICT', 'อีเมลนี้ลงทะเบียนแล้ว', 409, [{ field: 'email', issue: 'EMAIL_ALREADY_REGISTERED' }]);
const duplicate = await this.db.studentProfileIdentity.findFirst({ where: {
studentCode: body.student_code.trim(), user: { universityId: advisor.universityId, status: { not: 'DELETED' } },
} });
if (duplicate) throw new AppException('STATE_CONFLICT', 'รหัสนักศึกษานี้ถูกใช้แล้วในสถาบันเดียวกัน', 409,
[{ field: 'student_code', issue: 'STUDENT_CODE_ALREADY_USED' }]);
throw new AppException('STATE_CONFLICT', 'ข้อมูลถูกเปลี่ยนระหว่างบันทึก กรุณาลองใหม่', 409);
}
throw error;
}
// บัญชีถูกสร้างแล้ว: ส่งอีเมลไม่สำเร็จไม่ทำให้คำขอล้ม — อาจารย์กดส่งคำเชิญใหม่ได้
Expand Down
60 changes: 60 additions & 0 deletions apps/identity/src/modules/directory/directory-job.client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { AppException, signServiceToken } from '@internpath/common';
import type { DirectoryCompanyIdsResponse, JobCategory } from '@internpath/contracts';
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { isUUID } from 'class-validator';

const unavailable = () => new AppException('UPSTREAM_UNAVAILABLE', 'ยังกรองสายงานบริษัทไม่ได้ กรุณาลองใหม่ภายหลัง', 503);

/** Job owns job categories; Directory uses its published jobs as the category source. */
@Injectable()
export class DirectoryJobClient {
private readonly log = new Logger(DirectoryJobClient.name);

constructor(private readonly config: ConfigService) {}

async companyIds(category: JobCategory): Promise<Set<string>> {
const secret = this.config.get<string>('JOB_SERVICE_SECRET_IDENTITY');
if (!secret || secret.length < 32) {
this.log.error('JOB_SERVICE_SECRET_IDENTITY is missing or shorter than 32 characters');
throw unavailable();
}
const base = (this.config.get<string>('JOB_URL') || 'http://localhost:3002').replace(/\/+$/, '');
const token = signServiceToken({ issuer: 'identity', audience: 'job', secret });
const ids = new Set<string>();
let cursor: string | null = null;
do {
const query = new URLSearchParams({ category });
if (cursor) query.set('after', cursor);
let response: Response;
try {
response = await fetch(`${base}/internal/v1/directory/company-ids?${query}`, {
headers: { authorization: `Bearer ${token}`, accept: 'application/json' },
signal: AbortSignal.timeout(5000),
});
} catch (error) {
this.log.warn(`Job directory lookup unreachable: ${(error as Error).name}`);
throw unavailable();
}
if (response.status !== 200) {
this.log.warn(`Job directory lookup answered ${response.status}`);
throw unavailable();
}
const body = (await response.json().catch(() => null)) as Partial<DirectoryCompanyIdsResponse> | null;
if (!body || !Array.isArray(body.company_ids) || body.company_ids.some((id) => typeof id !== 'string' || !isUUID(id)) ||
(body.next_cursor !== null && (typeof body.next_cursor !== 'string' || !isUUID(body.next_cursor))) ||
(body.next_cursor !== null && (body.company_ids.length === 0 || body.next_cursor !== body.company_ids.at(-1)))) {
this.log.warn('Job directory lookup answered an invalid body');
throw unavailable();
}
for (const id of body.company_ids) ids.add(id.toLowerCase());
const nextCursor = body.next_cursor;
if (nextCursor && cursor && nextCursor <= cursor) {
this.log.warn('Job directory lookup did not advance its cursor');
throw unavailable();
}
cursor = nextCursor;
} while (cursor);
return ids;
}
}
8 changes: 4 additions & 4 deletions apps/identity/src/modules/directory/directory.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Transform, Type } from 'class-transformer';
import { IsBoolean, IsInt, IsOptional, IsString, Matches, Max, MaxLength, Min, ValidateIf } from 'class-validator';
import { IsBoolean, IsEnum, IsInt, IsOptional, IsString, Matches, Max, MaxLength, Min, ValidateIf } from 'class-validator';
import type { DirectoryCompaniesQuery } from '@internpath/contracts';
import { JobCategory } from '../../../generated/client';

const UUID = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
export const DIRECTORY_IDS_MAX = 50;
Expand All @@ -14,9 +15,8 @@ export class DirectoryQueryDto implements DirectoryCompaniesQuery {
q?: string;

@ValidateIf((_body, value) => value !== undefined)
@IsString()
@MaxLength(100)
category?: string;
@IsEnum(JobCategory)
category?: JobCategory;

@Transform(({ value }: { value: unknown }) => value === 'true' ? true : value === 'false' ? false : value)
@ValidateIf((_body, value) => value !== undefined)
Expand Down
3 changes: 2 additions & 1 deletion apps/identity/src/modules/directory/directory.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { DirectoryController } from './directory.controller';
import { DirectoryJobClient } from './directory-job.client';
import { DirectoryRatingService } from './directory-rating.service';
import { DirectoryService } from './directory.service';

@Module({
controllers: [DirectoryController],
providers: [DirectoryService, DirectoryRatingService],
providers: [DirectoryService, DirectoryRatingService, DirectoryJobClient],
exports: [DirectoryRatingService],
})
export class DirectoryModule {}
11 changes: 6 additions & 5 deletions apps/identity/src/modules/directory/directory.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { AppException } from '@internpath/common';
import type { DirectoryCompanyDetail, DirectoryCompanyListItem, Paginated } from '@internpath/contracts';
import { Prisma } from '../../../generated/client';
import { PrismaService } from '../../prisma/prisma.service';
import { DirectoryJobClient } from './directory-job.client';
import { DirectoryQueryDto } from './directory.dto';

type DirectoryCompany = Prisma.CompanyGetPayload<{ include: { ratingStats: true } }>;
Expand All @@ -12,7 +13,7 @@ type DirectoryCompanySummary = DirectoryCompanyListItem & Pick<DirectoryCompanyD
/** api-contract §4.4 — Public: output never depends on the caller. */
@Injectable()
export class DirectoryService {
constructor(private readonly db: PrismaService, private readonly config: ConfigService) {}
constructor(private readonly db: PrismaService, private readonly config: ConfigService, private readonly jobs: DirectoryJobClient) {}

private logoUrl(key: string): string {
const publicBase = this.config.get<string>('S3_PUBLIC_BASE_URL');
Expand All @@ -37,15 +38,15 @@ export class DirectoryService {
}

async list(query: DirectoryQueryDto): Promise<Paginated<DirectoryCompanySummary>> {
if (query.category?.trim()) {
throw new AppException('VALIDATION_FAILED', 'ยังไม่มีแหล่งข้อมูลหมวดหมู่บริษัทสำหรับตัวกรอง category', 400);
}
const categoryIds = query.category ? await this.jobs.companyIds(query.category) : undefined;
const q = query.q?.trim();
// Unknown / non-VERIFIED ids simply drop out of the result (no error).
const ids = query.ids ? [...new Set(query.ids.toLowerCase().split(','))] : undefined;
const matchingIds = categoryIds ? (ids ? ids.filter((id) => categoryIds.has(id)) : [...categoryIds]) : ids;
if (matchingIds?.length === 0) return { data: [], meta: { page: query.page, page_size: query.page_size, total: 0 } };
const where: Prisma.CompanyWhereInput = {
status: 'VERIFIED',
...(ids ? { id: { in: ids } } : {}),
...(matchingIds ? { id: { in: matchingIds } } : {}),
...(q ? { name: { contains: q, mode: 'insensitive' as const } } : {}),
...(query.partner === undefined ? {} : { universityPartner: query.partner }),
};
Expand Down
Loading
Loading