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
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
BEGIN;

-- PM ตัดสิน 2026-11-22: รหัสนักศึกษาห้ามซ้ำในสถาบันเดียวกันระดับ DB ด้วย (กันคำขอพร้อมกันที่หลุดการเช็กระดับ API)
-- unique ข้ามตารางไม่ได้ จึงเก็บสำเนา users.university_id ไว้ที่โปรไฟล์นักศึกษา
ALTER TABLE "student_profiles_identity" ADD COLUMN "university_id" UUID;

UPDATE "student_profiles_identity" AS s
SET "university_id" = u."university_id"
FROM "users" AS u
WHERE u."id" = s."user_id";

-- ไม่แก้ข้อมูลอัตโนมัติ: ถ้ามีนักศึกษาไม่มีสถาบัน หรือรหัสซ้ำในสถาบันเดียวกัน ให้ migration ล้มพร้อมบอกจำนวน แล้วให้คนตัดสินใจแก้ข้อมูลเอง
DO $$
DECLARE
missing integer;
duplicated integer;
BEGIN
SELECT count(*) INTO missing FROM "student_profiles_identity" WHERE "university_id" IS NULL;
IF missing > 0 THEN
RAISE EXCEPTION 'student_profiles_identity: % row(s) have no university (users.university_id IS NULL); fix data before this migration', missing;
END IF;
SELECT count(*) INTO duplicated FROM (
SELECT 1 FROM "student_profiles_identity" GROUP BY "university_id", "student_code" HAVING count(*) > 1
) AS d;
IF duplicated > 0 THEN
RAISE EXCEPTION 'student_profiles_identity: % duplicated (university_id, student_code) pair(s); fix data before this migration', duplicated;
END IF;
END $$;

ALTER TABLE "student_profiles_identity" ALTER COLUMN "university_id" SET NOT NULL;

ALTER TABLE "student_profiles_identity"
ADD CONSTRAINT "student_profiles_identity_university_id_fkey"
FOREIGN KEY ("university_id") REFERENCES "universities"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

CREATE UNIQUE INDEX "student_profiles_identity_university_id_student_code_key"
ON "student_profiles_identity"("university_id", "student_code");

COMMIT;
6 changes: 6 additions & 0 deletions apps/identity/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ model University {
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6)
users User[]
students StudentProfileIdentity[]
@@map("universities")
}
Expand Down Expand Up @@ -147,6 +148,8 @@ model User {

model StudentProfileIdentity {
userId String @id @map("user_id") @db.Uuid
/// สำเนา `users.university_id` ของนักศึกษา (ต้องตรงกันเสมอ) — มีไว้ทำ unique (university_id, student_code) ระดับ DB
universityId String @map("university_id") @db.Uuid
studentCode String @map("student_code")
major String
yearLevel Int @map("year_level")
Expand All @@ -159,7 +162,10 @@ model StudentProfileIdentity {
user User @relation("student", fields: [userId], references: [id])
advisor User? @relation("current_advisor", fields: [advisorId], references: [id])
createdByAdvisor User? @relation("created_by_advisor", fields: [createdByAdvisorId], references: [id])
university University @relation(fields: [universityId], references: [id])
/// รหัสนักศึกษาซ้ำในสถาบันเดียวกันไม่ได้ (409 STUDENT_CODE_ALREADY_USED) — กันคำขอพร้อมกันที่หลุดการเช็กระดับ API
@@unique([universityId, studentCode])
@@index([advisorId, advisorLinkStatus])
@@map("student_profiles_identity")
}
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 } };
}
}
Loading
Loading