fix(stage): isolate credentialless author bootstrap and recovery rehearsal
Stage author bootstrap (dedicated repair) / bootstrap (push) Failing after 3m55s
Stage author bootstrap (dedicated repair) / bootstrap (push) Failing after 3m55s
This commit is contained in:
1 parent
6ed0e73311
commit
46da1c5339
30 files changed
+1295
-62
No files matched your search
@@ -0,0 +1,22 @@
|
||||
-- Reviewed attribution-only storage; no business data or historical ledger writes.
|
||||
DO $$ BEGIN
|
||||
IF current_database() NOT IN ('caninodb_stage', 'rehearsal') THEN
|
||||
RAISE EXCEPTION 'public author bootstrap is Stage-only';
|
||||
END IF;
|
||||
END $$;
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS is_public_author BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE public.users ALTER COLUMN is_public_author SET NOT NULL;
|
||||
ALTER TABLE public.users ALTER COLUMN is_public_author SET DEFAULT false;
|
||||
ALTER TABLE public.users ALTER COLUMN mobile DROP NOT NULL;
|
||||
-- Repeated application is transactional and revalidates every existing row.
|
||||
ALTER TABLE public.users DROP CONSTRAINT IF EXISTS users_public_author_identity_check;
|
||||
ALTER TABLE public.users ADD CONSTRAINT users_public_author_identity_check CHECK (
|
||||
(is_public_author = false AND mobile IS NOT NULL)
|
||||
OR
|
||||
(is_public_author = true
|
||||
AND mobile IS NULL AND email IS NULL AND password IS NULL
|
||||
AND role = 'User_PetOwner'
|
||||
AND auth_expires_at IS NULL
|
||||
AND stage_test_generation IS NULL AND stage_test_session IS NULL
|
||||
AND wallet_balance = 0 AND charity_donation_total = 0)
|
||||
);
|
||||
@@ -212,7 +212,8 @@ model User {
|
||||
firstName String @map("first_name") @db.VarChar(100)
|
||||
lastName String @map("last_name") @db.VarChar(100)
|
||||
email String? @unique @db.VarChar(150)
|
||||
mobile String @unique @db.VarChar(15)
|
||||
mobile String? @unique @db.VarChar(15)
|
||||
isPublicAuthor Boolean @default(false) @map("is_public_author")
|
||||
password String? @db.VarChar(255)
|
||||
role String @default("User_PetOwner") @db.VarChar(30)
|
||||
authExpiresAt DateTime? @map("auth_expires_at") @db.Timestamptz()
|
||||
|
||||
@@ -34,8 +34,18 @@ describe("AdminController - Stage Author Restoration endpoint", () => {
|
||||
controller = module.get<AdminController>(AdminController);
|
||||
});
|
||||
|
||||
it.each([undefined, "10.0.0.2", "127.0.0.1.evil", "::ffff:10.0.0.2"])("denies non-loopback socket %s despite forwarded headers", async (remoteAddress) => {
|
||||
await expect(controller.restoreStageAuthors({ socket: { remoteAddress }, headers: { "x-forwarded-for": "127.0.0.1" }, ip: "127.0.0.1" } as any)).rejects.toThrow();
|
||||
expect(mockStageAuthorRestorationService.restoreStageAuthors).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["::1", "::ffff:127.0.0.1"])("accepts loopback socket %s", async remoteAddress => {
|
||||
await controller.restoreStageAuthors({ socket: { remoteAddress } } as any);
|
||||
expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("delegates restoreStageAuthors to StageAuthorRestorationService", async () => {
|
||||
const result = await controller.restoreStageAuthors();
|
||||
const result = await controller.restoreStageAuthors({ socket: { remoteAddress: "127.0.0.1" } } as any);
|
||||
expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.restoredCount).toBe(5);
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Req,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
} from "@nestjs/common";
|
||||
import { AdminService, CouponInput } from "./admin.service";
|
||||
import { ProductDto } from "./dto/product.dto";
|
||||
@@ -80,7 +81,11 @@ export class AdminController {
|
||||
summary:
|
||||
"بازیابی شناسه و مشخصات عمومی پنج نویسنده اورجینال مقالات در محیط استیج",
|
||||
})
|
||||
async restoreStageAuthors() {
|
||||
async restoreStageAuthors(@Req() req: { socket?: { remoteAddress?: string } }) {
|
||||
const peer = req?.socket?.remoteAddress;
|
||||
if (!peer || !["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(peer)) {
|
||||
throw new ForbiddenException("Stage author restoration requires a loopback socket");
|
||||
}
|
||||
if (!this.stageAuthorRestorationService) {
|
||||
throw new Error("StageAuthorRestorationService not initialized");
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ describe("StageAuthorRestorationService (Unit & TDD)", () => {
|
||||
|
||||
beforeEach(() => {
|
||||
mockTx = {
|
||||
$queryRaw: jest.fn().mockResolvedValue(GENUINE_STAGE_AUTHORS.map((a, i) => ({ authorId: a.id, count: BigInt([16, 2, 3, 14, 17][i]) }))),
|
||||
user: {
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
@@ -39,27 +40,129 @@ describe("StageAuthorRestorationService (Unit & TDD)", () => {
|
||||
expect(() => assertStageScope({})).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("allows execution when APP_ENV is stage", () => {
|
||||
expect(() => assertStageScope({ APP_ENV: "stage" })).not.toThrow();
|
||||
it("denies execution with only APP_ENV is stage", () => {
|
||||
expect(() => assertStageScope({ APP_ENV: "stage" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("allows execution when STAGE_AUTHOR_RESTORATION_ENABLED is true", () => {
|
||||
it("denies execution with only STAGE_AUTHOR_RESTORATION_ENABLED is true", () => {
|
||||
expect(() =>
|
||||
assertStageScope({ STAGE_AUTHOR_RESTORATION_ENABLED: "true" }),
|
||||
).not.toThrow();
|
||||
).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("allows execution when DATABASE_URL points to caninodb_stage", () => {
|
||||
it("denies execution with only DATABASE_URL points to caninodb_stage", () => {
|
||||
expect(() =>
|
||||
assertStageScope({
|
||||
DATABASE_URL: "postgresql://user:pass@db:5432/caninodb_stage",
|
||||
}),
|
||||
).not.toThrow();
|
||||
).toThrow(ForbiddenException);
|
||||
});
|
||||
});
|
||||
|
||||
describe("restoreStageAuthors TDD lifecycle", () => {
|
||||
const stageEnv = { APP_ENV: "stage" };
|
||||
const stageEnv = { APP_ENV: "stage", STAGE_AUTHOR_RESTORATION_ENABLED: "true", STAGE_AUTHOR_RESTORATION_MODE: "maintenance", DATABASE_URL: "postgresql://user@canino_db_stage:5432/caninodb_stage" };
|
||||
|
||||
it("rejects a partial existing set before any writes", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValueOnce({ ...GENUINE_STAGE_AUTHORS[0], role: STAGE_AUTHOR_ROLE });
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not allow enabled production scope", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, APP_ENV: "production" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects a stage-looking substring in the database identity", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@evil/caninodb_stage_prod" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("requires explicit mode", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_MODE: undefined })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects unsafe replay even with identical names", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: "Admin" }));
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses a Serializable transaction", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
try { await service.restoreStageAuthors(stageEnv); } catch {}
|
||||
expect(mockPrisma.$transaction).toHaveBeenCalledWith(expect.any(Function), { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
|
||||
});
|
||||
|
||||
it("rejects unexpected orphan distribution without writing", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue([{ authorId: GENUINE_STAGE_AUTHORS[0].id, count: 52n }]);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects replay with remaining orphans", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, isPublicAuthor: true, mobile: null, email: null, password: null, authExpiresAt: null, walletBalance: new Prisma.Decimal(0), charityDonationTotal: new Prisma.Decimal(0), stageTestGeneration: null, stageTestSession: null }));
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue([{ authorId: GENUINE_STAGE_AUTHORS[0].id, count: 1n }]);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
});
|
||||
|
||||
it("accepts a loopback rehearsal database only in rehearsal mode", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_MODE: "rehearsal", DATABASE_URL: "postgresql://user@127.0.0.1:5432/rehearsal" })).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects rehearsal database in maintenance mode", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@127.0.0.1:5432/rehearsal" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("requires both stage identity and enable flag", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, STAGE_AUTHOR_RESTORATION_ENABLED: undefined })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects a URL with conflicting host override", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@canino_db_stage/caninodb_stage?host=prod" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("requires the public-author marker on replay", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, mobile: null, email: null, password: null, isPublicAuthor: false }));
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects malformed URL without database work", async () => {
|
||||
await expect(service.restoreStageAuthors({ ...stageEnv, DATABASE_URL: "not-a-url" })).rejects.toThrow(ForbiddenException);
|
||||
expect(mockPrisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects unexpected scheme", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "https://canino_db_stage/caninodb_stage" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("does not allow a production database with a stage query string", () => {
|
||||
expect(() => assertStageScope({ ...stageEnv, DATABASE_URL: "postgresql://user@db/prod?stage=caninodb_stage" })).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it("rejects a credential-bearing replay", async () => {
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => ({ ...GENUINE_STAGE_AUTHORS.find(a => a.id === where.id), role: STAGE_AUTHOR_ROLE, isPublicAuthor: true, password: "hash", mobile: null, email: null }));
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects no-orphan initial state", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue([]);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("writes the public-author marker", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
mockTx.user.create.mockImplementation(async ({ data }: any) => data);
|
||||
mockTx.$queryRaw = jest.fn().mockResolvedValue(GENUINE_STAGE_AUTHORS.map((a, i) => ({ authorId: a.id, count: BigInt([16, 2, 3, 14, 17][i]) })));
|
||||
await service.restoreStageAuthors(stageEnv);
|
||||
for (const [call] of mockTx.user.create.mock.calls) expect(call.data.isPublicAuthor).toBe(true);
|
||||
});
|
||||
|
||||
// Legacy lifecycle assertions below also exercise the stricter preflight.
|
||||
|
||||
it("restores all 5 genuine authors when none exist in Stage", async () => {
|
||||
mockTx.user.findUnique.mockResolvedValue(null);
|
||||
@@ -95,6 +198,7 @@ describe("StageAuthorRestorationService (Unit & TDD)", () => {
|
||||
});
|
||||
|
||||
it("is strictly idempotent: repeated calls report existing and perform no creates", async () => {
|
||||
mockTx.$queryRaw.mockResolvedValue([]);
|
||||
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
|
||||
const match = GENUINE_STAGE_AUTHORS.find((a) => a.id === where.id);
|
||||
if (!match) return null;
|
||||
@@ -105,6 +209,13 @@ describe("StageAuthorRestorationService (Unit & TDD)", () => {
|
||||
role: STAGE_AUTHOR_ROLE,
|
||||
mobile: null,
|
||||
email: null,
|
||||
password: null,
|
||||
isPublicAuthor: true,
|
||||
authExpiresAt: null,
|
||||
stageTestGeneration: null,
|
||||
stageTestSession: null,
|
||||
walletBalance: new Prisma.Decimal(0),
|
||||
charityDonationTotal: new Prisma.Decimal(0),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -156,13 +267,8 @@ describe("StageAuthorRestorationService (Unit & TDD)", () => {
|
||||
role: data.role,
|
||||
}));
|
||||
|
||||
const res = await service.restoreStageAuthors(stageEnv);
|
||||
|
||||
expect(res.success).toBe(true);
|
||||
expect(res.totalConfigured).toBe(5);
|
||||
expect(res.restoredCount).toBe(4);
|
||||
expect(res.existingCount).toBe(1);
|
||||
expect(mockTx.user.create).toHaveBeenCalledTimes(4);
|
||||
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(ConflictException);
|
||||
expect(mockTx.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,6 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
} from "@nestjs/common";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
@@ -36,20 +34,22 @@ export const GENUINE_STAGE_AUTHORS = [
|
||||
},
|
||||
] as const;
|
||||
|
||||
export const STAGE_AUTHOR_ROLE = "User_Vet";
|
||||
export const STAGE_AUTHOR_ROLE = "User_PetOwner";
|
||||
|
||||
export function assertStageScope(env: NodeJS.ProcessEnv = process.env): void {
|
||||
const isStageEnv =
|
||||
env.APP_ENV === "stage" ||
|
||||
env.STAGE_AUTHOR_RESTORATION_ENABLED === "true" ||
|
||||
(env.DATABASE_URL && env.DATABASE_URL.includes("caninodb_stage"));
|
||||
|
||||
const isProduction =
|
||||
env.NODE_ENV === "production" &&
|
||||
env.APP_ENV !== "stage" &&
|
||||
env.STAGE_AUTHOR_RESTORATION_ENABLED !== "true";
|
||||
|
||||
if (!isStageEnv || isProduction) {
|
||||
let identityAllowed = false;
|
||||
try {
|
||||
const url = new URL(env.DATABASE_URL || "");
|
||||
const mode = env.STAGE_AUTHOR_RESTORATION_MODE;
|
||||
identityAllowed =
|
||||
["postgresql:", "postgres:"].includes(url.protocol) &&
|
||||
!url.search && !url.hash &&
|
||||
((mode === "maintenance" && (!url.port || url.port === "5432") && url.hostname === "canino_db_stage" && url.pathname === "/caninodb_stage") ||
|
||||
(mode === "rehearsal" && url.hostname === "127.0.0.1" && url.pathname === "/rehearsal"));
|
||||
} catch {
|
||||
// Malformed and absent URLs are denied without exposing credentials.
|
||||
}
|
||||
if (env.APP_ENV !== "stage" || env.STAGE_AUTHOR_RESTORATION_ENABLED !== "true" || !identityAllowed) {
|
||||
throw new ForbiddenException(
|
||||
"Stage author restoration is strictly restricted to authorized Stage environments",
|
||||
);
|
||||
@@ -84,18 +84,40 @@ export class StageAuthorRestorationService {
|
||||
let restoredCount = 0;
|
||||
let existingCount = 0;
|
||||
|
||||
for (const author of GENUINE_STAGE_AUTHORS) {
|
||||
const existing = await tx.user.findUnique({
|
||||
where: { id: author.id },
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
role: true,
|
||||
mobile: true,
|
||||
email: true,
|
||||
},
|
||||
});
|
||||
// Read the entire candidate set and every dangling reference before writing.
|
||||
const candidates = await Promise.all(GENUINE_STAGE_AUTHORS.map(author => tx.user.findUnique({ where: { id: author.id } })));
|
||||
const orphans = await tx.$queryRaw<Array<{ authorId: string; count: bigint }>>`
|
||||
SELECT b.author_id AS "authorId", COUNT(*) AS count
|
||||
FROM blogs b LEFT JOIN users u ON u.id = b.author_id
|
||||
WHERE b.author_id IS NOT NULL AND u.id IS NULL
|
||||
GROUP BY b.author_id
|
||||
`;
|
||||
const present = candidates.filter(Boolean).length;
|
||||
if (present !== 0 && present !== GENUINE_STAGE_AUTHORS.length) {
|
||||
throw new ConflictException("Partial author restoration is not permitted");
|
||||
}
|
||||
if (present === 0) {
|
||||
const counts = [16, 2, 3, 14, 17];
|
||||
if (orphans.length !== 5 || !GENUINE_STAGE_AUTHORS.every((a, i) =>
|
||||
orphans.filter(o => o.authorId === a.id && Number(o.count) === counts[i]).length === 1)) {
|
||||
throw new ConflictException("Expected exactly 52 orphan blogs with the reviewed author distribution");
|
||||
}
|
||||
} else {
|
||||
if (orphans.length !== 0 || !candidates.every((row, i) => row &&
|
||||
row.id === GENUINE_STAGE_AUTHORS[i].id &&
|
||||
row.firstName === GENUINE_STAGE_AUTHORS[i].firstName &&
|
||||
row.lastName === GENUINE_STAGE_AUTHORS[i].lastName &&
|
||||
row.role === STAGE_AUTHOR_ROLE && row.isPublicAuthor === true &&
|
||||
row.mobile === null && row.email === null && row.password === null &&
|
||||
row.authExpiresAt === null && row.stageTestGeneration === null && row.stageTestSession === null &&
|
||||
row.walletBalance.equals(0) && row.charityDonationTotal.equals(0))) {
|
||||
throw new ConflictException("Replay requires all five exact safe author rows and zero orphan blogs");
|
||||
}
|
||||
}
|
||||
|
||||
for (const [index, author] of GENUINE_STAGE_AUTHORS.entries()) {
|
||||
const existing = candidates[index];
|
||||
// Candidate identity was validated atomically above.
|
||||
|
||||
if (existing) {
|
||||
if (
|
||||
@@ -124,7 +146,8 @@ export class StageAuthorRestorationService {
|
||||
firstName: author.firstName,
|
||||
lastName: author.lastName,
|
||||
role: STAGE_AUTHOR_ROLE,
|
||||
mobile: null as any,
|
||||
isPublicAuthor: true,
|
||||
mobile: null,
|
||||
email: null,
|
||||
password: null,
|
||||
walletBalance: new Prisma.Decimal(0),
|
||||
@@ -155,6 +178,6 @@ export class StageAuthorRestorationService {
|
||||
existingCount,
|
||||
authors: results,
|
||||
};
|
||||
});
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
|
||||
}
|
||||
}
|
||||
@@ -233,7 +233,7 @@ export class AuthController {
|
||||
async refresh(
|
||||
@Req()
|
||||
req: {
|
||||
user: { id: string; email?: string; role?: string; mobile?: string };
|
||||
user: { id: string; email?: string; role?: string; mobile?: string | null };
|
||||
},
|
||||
@Res({ passthrough: true }) res?: Response,
|
||||
) {
|
||||
|
||||
@@ -69,6 +69,8 @@ export class AuthService {
|
||||
|
||||
async sendOtp(sendOtpDto: SendOtpDto) {
|
||||
const phoneNumber = normalizeMobile(sendOtpDto.phoneNumber);
|
||||
const user = await this.prisma.user.findUnique({ where: { mobile: phoneNumber } });
|
||||
if (user) assertPrincipalActive(user);
|
||||
|
||||
// 1. Check 60-second cooldown per phone number
|
||||
const cooldownKey = `otp:cooldown:${phoneNumber}`;
|
||||
@@ -220,6 +222,7 @@ export class AuthService {
|
||||
const firstName = registerDto.firstName.trim();
|
||||
const lastName = registerDto.lastName.trim();
|
||||
const mobile = normalizeMobile(registerDto.mobile);
|
||||
if (!mobile) throw new BadRequestException("شماره موبایل الزامی است");
|
||||
const email = registerDto.email
|
||||
? registerDto.email.trim().toLowerCase()
|
||||
: null;
|
||||
@@ -319,15 +322,15 @@ export class AuthService {
|
||||
}
|
||||
|
||||
async adminLogin(body: AdminLoginInput) {
|
||||
// First check database for user with role 'Admin' or 'SUPER_ADMIN'
|
||||
// Resolve email before checking roles so public authors cannot enter the env fallback.
|
||||
const dbAdmin = await this.prisma.user.findFirst({
|
||||
where: {
|
||||
email: body.email,
|
||||
role: { in: ["Admin", "SUPER_ADMIN", "ADMIN"] },
|
||||
},
|
||||
where: { email: body.email },
|
||||
});
|
||||
|
||||
if (dbAdmin && dbAdmin.password && body.password) {
|
||||
// Reject before credential/fallback evaluation, including accidentally assigned admin roles.
|
||||
if (dbAdmin) assertPrincipalActive(dbAdmin);
|
||||
|
||||
if (dbAdmin && ["Admin", "SUPER_ADMIN", "ADMIN"].includes(dbAdmin.role) && dbAdmin.password && body.password) {
|
||||
const isMatch = await bcrypt.compare(body.password, dbAdmin.password);
|
||||
if (isMatch) {
|
||||
assertPrincipalActive(dbAdmin);
|
||||
@@ -493,12 +496,21 @@ export class AuthService {
|
||||
|
||||
async refresh(user: {
|
||||
id: string;
|
||||
email?: string;
|
||||
email?: string | null;
|
||||
role?: string;
|
||||
mobile?: string;
|
||||
mobile?: string | null;
|
||||
isPublicAuthor?: boolean;
|
||||
stageTestSession?: string | null;
|
||||
stageTestGeneration?: string | null;
|
||||
}) {
|
||||
// Re-resolve rather than trusting a stale or partially projected request principal.
|
||||
const current = await this.prisma.user.findUnique({ where: { id: user.id } });
|
||||
if (!current) throw new UnauthorizedException("کاربر یافت نشد");
|
||||
assertPrincipalActive(current);
|
||||
assertPrincipalActive(user);
|
||||
if (current.stageTestSession && (!current.stageTestGeneration || user.stageTestGeneration !== current.stageTestGeneration || user.stageTestSession !== current.stageTestSession)) throw new UnauthorizedException("Stage session revoked");
|
||||
const { password: _password, ...safeUser } = current;
|
||||
user = safeUser;
|
||||
const payload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
forwardRef,
|
||||
} from "@nestjs/common";
|
||||
import { AuthGuard } from "@nestjs/passport";
|
||||
import { assertPrincipalActive } from "./stage-test-principal";
|
||||
import { ApiKeysService } from "../admin/api-keys.service";
|
||||
|
||||
@Injectable()
|
||||
@@ -28,6 +29,7 @@ export class JwtAuthGuard extends AuthGuard("jwt") {
|
||||
if (apiKeyHeader && this.apiKeysService) {
|
||||
try {
|
||||
const apiKeyUser = await this.apiKeysService.validateKey(apiKeyHeader);
|
||||
assertPrincipalActive(apiKeyUser as { isPublicAuthor?: boolean });
|
||||
request.user = apiKeyUser;
|
||||
return true;
|
||||
} catch (err: unknown) {
|
||||
@@ -52,6 +54,7 @@ export class JwtAuthGuard extends AuthGuard("jwt") {
|
||||
)
|
||||
);
|
||||
}
|
||||
assertPrincipalActive(user as { isPublicAuthor?: boolean });
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
if (!user) {
|
||||
throw new UnauthorizedException("کاربر یافت نشد");
|
||||
}
|
||||
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal expired"); }
|
||||
try { assertPrincipalActive(user); } catch { throw new UnauthorizedException("Principal unavailable"); }
|
||||
if (user.stageTestSession) {
|
||||
if (!user.stageTestGeneration || payload.stageTestGeneration !== user.stageTestGeneration || payload.stageTestSession !== user.stageTestSession) throw new UnauthorizedException("Stage session revoked");
|
||||
const path = req.originalUrl?.split('?')[0] || '';
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { UnauthorizedException, ForbiddenException } from '@nestjs/common';
|
||||
import { validate } from 'class-validator';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
|
||||
import { assertPrincipalActive } from './stage-test-principal';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
|
||||
describe('Public authors are attribution only, never principals', () => {
|
||||
const password = 'test-password';
|
||||
const author = { id: 'author-id', mobile: '09123456789', email: 'author@example.invalid', password: bcrypt.hashSync(password, 4), role: 'SUPER_ADMIN', isPublicAuthor: true };
|
||||
let prisma: any, jwt: any, redis: any, sms: any, service: AuthService;
|
||||
const env = { ...process.env };
|
||||
beforeEach(() => {
|
||||
process.env.JWT_SECRET = 'isolated-public-author-test-secret';
|
||||
process.env.JWT_REFRESH_SECRET = 'isolated-public-author-refresh-secret';
|
||||
prisma = { user: { findUnique: jest.fn().mockResolvedValue(author), findFirst: jest.fn().mockResolvedValue(author), create: jest.fn() } };
|
||||
jwt = { sign: jest.fn().mockReturnValue('token'), verify: jest.fn().mockReturnValue({ sub: author.id, jti: 'old-token' }) };
|
||||
redis = { get: jest.fn(async (key: string) => key.startsWith('otp_attempts:') ? null : key === `otp:${author.mobile}` ? '12345' : key.startsWith('refresh_token:') ? '1' : null), set: jest.fn(), del: jest.fn(), incr: jest.fn().mockResolvedValue(1) };
|
||||
sms = { sendOtp: jest.fn().mockResolvedValue(true) };
|
||||
service = new AuthService(prisma, jwt, redis, sms);
|
||||
});
|
||||
afterEach(() => { process.env = { ...env }; });
|
||||
|
||||
it('shared principal assertion rejects the marker independent of role/mobile', () => {
|
||||
expect(() => assertPrincipalActive(author)).toThrow(UnauthorizedException);
|
||||
const withoutMobile = { ...author, mobile: null };
|
||||
expect(() => assertPrincipalActive(withoutMobile)).toThrow(UnauthorizedException);
|
||||
});
|
||||
it.each(['User_PetOwner', 'Admin', 'ADMIN', 'SUPER_ADMIN'])('blocks password login even with role %s', async role => {
|
||||
prisma.user.findUnique.mockResolvedValue({ ...author, role });
|
||||
await expect(service.login({ mobile: author.mobile, password })).rejects.toThrow(UnauthorizedException);
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it('does not send or store an OTP for a public author', async () => {
|
||||
await expect(service.sendOtp({ phoneNumber: author.mobile })).rejects.toThrow(UnauthorizedException);
|
||||
expect(sms.sendOtp).not.toHaveBeenCalled();
|
||||
expect(redis.set).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks a previously issued valid OTP without creating an alternate account', async () => {
|
||||
await expect(service.verifyOtp({ phoneNumber: author.mobile, code: '12345' })).rejects.toThrow(UnauthorizedException);
|
||||
expect(prisma.user.create).not.toHaveBeenCalled();
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(['Admin', 'ADMIN', 'SUPER_ADMIN'])('blocks email/admin login including nonproduction fallback for %s', async role => {
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.ADMIN_EMAIL = author.email;
|
||||
process.env.ADMIN_PASSWORD = password;
|
||||
prisma.user.findFirst.mockResolvedValue({ ...author, role, password: null });
|
||||
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks email/admin login with a valid stored password', async () => {
|
||||
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it('email lookup cannot hide a public author behind a non-admin role and enter fallback', async () => {
|
||||
process.env.ADMIN_EMAIL = author.email;
|
||||
process.env.ADMIN_PASSWORD = password;
|
||||
prisma.user.findFirst.mockResolvedValue({ ...author, role: 'User_PetOwner' });
|
||||
await expect(service.adminLogin({ email: author.email, password })).rejects.toThrow(UnauthorizedException);
|
||||
expect(prisma.user.findFirst).toHaveBeenCalledWith({ where: { email: author.email } });
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks refresh-token rotation for an existing author account', async () => {
|
||||
await expect(service.refreshToken('previous-token')).rejects.toThrow(UnauthorizedException);
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it('blocks legacy refresh even when supplied principal omits the marker', async () => {
|
||||
await expect(service.refresh({ id: author.id, role: 'SUPER_ADMIN' })).rejects.toThrow(UnauthorizedException);
|
||||
expect(jwt.sign).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(['Bearer old-token', 'cookie'])('rejects existing JWT via %s using database marker, not token claims', async transport => {
|
||||
const strategy = new JwtStrategy({ findById: jest.fn().mockResolvedValue(author) } as any, redis);
|
||||
const headers = transport === 'cookie' ? { cookie: 'accessToken=old-token' } : { authorization: transport };
|
||||
await expect(strategy.validate({ headers } as any, { sub: author.id, role: 'SUPER_ADMIN' })).rejects.toThrow(UnauthorizedException);
|
||||
});
|
||||
it('JWT guard rejects an accidentally supplied author principal', () => {
|
||||
expect(() => new JwtAuthGuard().handleRequest(null, author)).toThrow(UnauthorizedException);
|
||||
});
|
||||
it('API-key guard rejects an accidentally marked principal', async () => {
|
||||
const guard = new JwtAuthGuard({ validateKey: jest.fn().mockResolvedValue({ ...author, isApiKey: true, scopes: ['admin'] }) } as any);
|
||||
const request = { headers: { 'x-api-key': 'test-key' } };
|
||||
await expect(guard.canActivate({ switchToHttp: () => ({ getRequest: () => request }) } as any)).rejects.toThrow(UnauthorizedException);
|
||||
});
|
||||
it.each([{ roles: ['Admin'] }, { roles: [] }])('role guard rejects author even for roles %j', ({ roles }) => {
|
||||
const guard = new RolesGuard({ getAllAndOverride: () => roles } as any);
|
||||
const ctx = { getHandler: () => null, getClass: () => null, switchToHttp: () => ({ getRequest: () => ({ user: author }) }) } as any;
|
||||
expect(() => guard.canActivate(ctx)).toThrow(ForbiddenException);
|
||||
});
|
||||
it('human admin guard rejects author with admin role', () => {
|
||||
const ctx = { switchToHttp: () => ({ getRequest: () => ({ user: author }) }) } as any;
|
||||
expect(() => new HumanAdminGuard().canActivate(ctx)).toThrow(ForbiddenException);
|
||||
});
|
||||
it.each([undefined, null, '', ' '])('registration still requires mobile %j before any database write', async mobile => {
|
||||
prisma.user.findUnique.mockResolvedValue(null);
|
||||
prisma.user.create.mockResolvedValue({ ...author, mobile, isPublicAuthor: false });
|
||||
await expect(service.register({ firstName: 'Real', lastName: 'User', mobile } as any)).rejects.toThrow();
|
||||
expect(prisma.user.create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([RegisterDto, LoginDto])('real-user DTO retains required mobile validation', async Dto => {
|
||||
const dto = Object.assign(new Dto(), { firstName: 'Real', lastName: 'User', password });
|
||||
expect((await validate(dto)).some(error => error.property === 'mobile')).toBe(true);
|
||||
});
|
||||
it('real users can still login, verify OTP and refresh', async () => {
|
||||
const real = { ...author, isPublicAuthor: false };
|
||||
prisma.user.findUnique.mockResolvedValue(real);
|
||||
await expect(service.login({ mobile: real.mobile, password })).resolves.toMatchObject({ success: true });
|
||||
await expect(service.verifyOtp({ phoneNumber: real.mobile, code: '12345' })).resolves.toMatchObject({ success: true });
|
||||
await expect(service.refreshToken('previous-token')).resolves.toMatchObject({ success: true });
|
||||
await expect(service.refresh({ id: real.id })).resolves.toMatchObject({ success: true });
|
||||
});
|
||||
it('Prisma author storage permits absent mobile and defaults marker false', () => {
|
||||
const schema = readFileSync(join(__dirname, '../../prisma/schema.prisma'), 'utf8');
|
||||
const user = schema.match(/model User \{([\s\S]*?)\n\}/)![1];
|
||||
expect(user).toMatch(/mobile\s+String\?\s+@unique/);
|
||||
expect(user).toMatch(/isPublicAuthor\s+Boolean\s+@default\(false\)\s+@map\("is_public_author"\)/);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import { UnauthorizedException } from "@nestjs/common";
|
||||
|
||||
// Internal seed authority only. No controller, JWT actor, or owner impersonation.
|
||||
export const STAGE_TEST_ID = 'e876e7a0-738f-4e59-b6db-e270512ababc';
|
||||
export const STAGE_TEST_EMAIL = 'stage-editorial-reviewer@ci.canina.invalid';
|
||||
@@ -8,6 +10,7 @@ export function authorizeStageSession(env: NodeJS.ProcessEnv, artifactSha: strin
|
||||
if (!Number.isInteger(ttl) || ttl < 60 || ttl > 3600) throw new Error('Bounded TTL required');
|
||||
return {ttl, session:env.STAGE_TEST_SESSION!, sha:artifactSha};
|
||||
}
|
||||
export function assertPrincipalActive(user: { authExpiresAt?: Date | null }, now = Date.now()) {
|
||||
export function assertPrincipalActive(user: { authExpiresAt?: Date | null; isPublicAuthor?: boolean }, now = Date.now()) {
|
||||
if (user.isPublicAuthor) throw new UnauthorizedException("Public authors cannot authenticate");
|
||||
if (user.authExpiresAt && user.authExpiresAt.getTime() <= now) throw new Error('Principal expired');
|
||||
}
|
||||
@@ -23,7 +23,7 @@ describe('Stage credentials remain fenced to their creation session', () => {
|
||||
});
|
||||
it('includes session fencing in newly issued credentials',async()=>{
|
||||
const jwt=new JwtService({secret:process.env.JWT_SECRET});
|
||||
const auth=new AuthService({} as any,jwt,redis,undefined as any);
|
||||
const auth=new AuthService({user:{findUnique:async()=>current}} as any,jwt,redis,undefined as any);
|
||||
const result=await auth.refresh(current);
|
||||
expect(jwt.verify(result.data.accessToken).stageTestGeneration).toBe('fresh-generation');
|
||||
expect(jwt.verify(result.data.accessToken).stageTestSession).toBe('new-session');
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
export class HumanAdminGuard implements CanActivate {
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const user = context.switchToHttp().getRequest().user;
|
||||
if (!user || user.isApiKey || !['Admin', 'SUPER_ADMIN'].includes(user.role))
|
||||
if (!user || user.isPublicAuthor || user.isApiKey || !['Admin', 'SUPER_ADMIN'].includes(user.role))
|
||||
throw new ForbiddenException('Human administrator required');
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ interface RequestWithUser {
|
||||
role?: string;
|
||||
isApiKey?: boolean;
|
||||
scopes?: string[];
|
||||
isPublicAuthor?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -25,12 +26,14 @@ export class RolesGuard implements CanActivate {
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const user = request.user;
|
||||
if (user?.isPublicAuthor) throw new ForbiddenException("Public authors have no permissions");
|
||||
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest<RequestWithUser>();
|
||||
const user = request.user;
|
||||
if (!user || !user.role) {
|
||||
throw new ForbiddenException("شما دسترسی لازم برای این بخش را ندارید");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import 'reflect-metadata';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { MaintenanceModule } from './maintenance.module';
|
||||
import { assertStageScope } from '../admin/stage-author-restoration.service';
|
||||
|
||||
/** Exported for startup-contract testing; importing never starts a listener. */
|
||||
export async function startMaintenance(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
create = (module: typeof MaintenanceModule) => NestFactory.create(module),
|
||||
) {
|
||||
// Deny before connecting to any infrastructure.
|
||||
assertStageScope(env);
|
||||
const port = Number(env.PORT);
|
||||
if (!/^\d+$/.test(env.PORT || '') || !Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error('Explicit valid maintenance PORT required');
|
||||
}
|
||||
const app = await create(MaintenanceModule);
|
||||
app.setGlobalPrefix('api');
|
||||
app.enableShutdownHooks();
|
||||
await app.listen(port, '127.0.0.1');
|
||||
return app;
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
startMaintenance().catch(() => {
|
||||
// Do not emit connection strings or credentials on startup failure.
|
||||
console.error('Maintenance startup failed');
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
/** Connection lifecycle only: deliberately bypass PrismaService's startup DDL. */
|
||||
@Injectable()
|
||||
export class MaintenancePrismaService extends PrismaService {
|
||||
async onModuleInit(): Promise<void> {
|
||||
await this.$connect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Controller, ForbiddenException, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
import { StageAuthorRestorationService } from '../admin/stage-author-restoration.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
|
||||
|
||||
@Controller('admin/users')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard, HumanAdminGuard)
|
||||
@Roles('Admin', 'SUPER_ADMIN')
|
||||
export class MaintenanceController {
|
||||
constructor(private readonly restoration: StageAuthorRestorationService) {}
|
||||
|
||||
@Post('stage-author-restoration')
|
||||
async restoreStageAuthors(@Req() req: Request) {
|
||||
// Never trust proxy headers for this administrative operation.
|
||||
if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(req.socket?.remoteAddress || '')) {
|
||||
throw new ForbiddenException('Loopback maintenance endpoint only');
|
||||
}
|
||||
return this.restoration.restoreStageAuthors();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Module, UnauthorizedException } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { JwtStrategy } from '../auth/jwt.strategy';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { ApiKeysService } from '../admin/api-keys.service';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { HumanAdminGuard } from '../common/guards/human-admin.guard';
|
||||
import { StageAuthorRestorationService } from '../admin/stage-author-restoration.service';
|
||||
import { MaintenancePrismaService } from './maintenance-prisma.service';
|
||||
import { MaintenanceController } from './maintenance.controller';
|
||||
|
||||
/** No App/Auth/Admin/Prisma modules: their lifecycles are not maintenance-safe. */
|
||||
@Module({
|
||||
controllers: [MaintenanceController],
|
||||
providers: [
|
||||
{ provide: PrismaService, useClass: MaintenancePrismaService },
|
||||
RedisService,
|
||||
UsersService,
|
||||
Reflector,
|
||||
JwtStrategy,
|
||||
// JwtAuthGuard requires this token. Reject rather than instantiate the
|
||||
// API-key service or allow API keys to enter this JWT-only control plane.
|
||||
{ provide: ApiKeysService, useValue: {
|
||||
validateKey: async () => { throw new UnauthorizedException('JWT required'); },
|
||||
} },
|
||||
JwtAuthGuard,
|
||||
RolesGuard,
|
||||
HumanAdminGuard,
|
||||
StageAuthorRestorationService,
|
||||
],
|
||||
})
|
||||
export class MaintenanceModule {}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import { MODULE_METADATA } from '@nestjs/common/constants';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import request from 'supertest';
|
||||
import { MaintenanceModule } from './maintenance.module';
|
||||
import { MaintenancePrismaService } from './maintenance-prisma.service';
|
||||
import { MaintenanceController } from './maintenance.controller';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { StageAuthorRestorationService } from '../admin/stage-author-restoration.service';
|
||||
import { getJwtSecret } from '../auth/auth.constants';
|
||||
import { startMaintenance } from './main';
|
||||
|
||||
describe('isolated maintenance runtime', () => {
|
||||
let app: INestApplication;
|
||||
const user = { id: 'admin-test', role: 'Admin', isPublicAuthor: false };
|
||||
const prisma = { user: { findUnique: jest.fn() }, $connect: jest.fn(), $disconnect: jest.fn() };
|
||||
const redis = { get: jest.fn() };
|
||||
const restoration = { restoreStageAuthors: jest.fn() };
|
||||
const jwt = new JwtService();
|
||||
const token = (payload: Record<string, unknown> = {}, secret = getJwtSecret()) => jwt.sign({ sub: user.id, ...payload }, { secret, expiresIn: '5m' });
|
||||
const post = (bearer?: string) => {
|
||||
const req = request(app.getHttpServer()).post('/api/admin/users/stage-author-restoration');
|
||||
return bearer ? req.set('Authorization', 'Bearer ' + bearer) : req;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
prisma.user.findUnique.mockResolvedValue(user);
|
||||
redis.get.mockResolvedValue(null);
|
||||
restoration.restoreStageAuthors.mockResolvedValue({ success: true });
|
||||
const module = await Test.createTestingModule({ imports: [MaintenanceModule] })
|
||||
.overrideProvider(PrismaService).useValue(prisma)
|
||||
.overrideProvider(RedisService).useValue(redis)
|
||||
.overrideProvider(StageAuthorRestorationService).useValue(restoration).compile();
|
||||
app = module.createNestApplication();
|
||||
app.setGlobalPrefix('api');
|
||||
await app.listen(0, '127.0.0.1');
|
||||
});
|
||||
afterEach(async () => { await app?.close(); });
|
||||
|
||||
it('has no module imports, and exactly one small controller', () => {
|
||||
expect(Reflect.getMetadata(MODULE_METADATA.IMPORTS, MaintenanceModule) || []).toEqual([]);
|
||||
expect(Reflect.getMetadata(MODULE_METADATA.CONTROLLERS, MaintenanceModule)).toEqual([MaintenanceController]);
|
||||
});
|
||||
it('connects Prisma without invoking its DDL lifecycle', async () => {
|
||||
const connect = jest.fn().mockResolvedValue(undefined);
|
||||
const ddl = jest.fn();
|
||||
await MaintenancePrismaService.prototype.onModuleInit.call({ $connect: connect, ensureTablesExist: ddl });
|
||||
expect(connect).toHaveBeenCalledTimes(1);
|
||||
expect(ddl).not.toHaveBeenCalled();
|
||||
});
|
||||
it('entrypoint only binds IPv4 loopback and uses env PORT', async () => {
|
||||
const isolatedApp = { setGlobalPrefix: jest.fn(), enableShutdownHooks: jest.fn(), listen: jest.fn() };
|
||||
const create = jest.fn().mockResolvedValue(isolatedApp);
|
||||
await startMaintenance({ APP_ENV: 'stage', STAGE_AUTHOR_RESTORATION_ENABLED: 'true', STAGE_AUTHOR_RESTORATION_MODE: 'rehearsal', DATABASE_URL: 'postgresql://postgres@127.0.0.1:5432/rehearsal', PORT: '39071' }, create);
|
||||
expect(create).toHaveBeenCalledWith(MaintenanceModule);
|
||||
expect(isolatedApp.listen).toHaveBeenCalledWith(39071, '127.0.0.1');
|
||||
await expect(startMaintenance({ PORT: '39071' }, create)).rejects.toThrow();
|
||||
expect(create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('uses the real strategy and guards over loopback HTTP', async () => {
|
||||
await post().expect(401);
|
||||
await post('invalid').expect(401);
|
||||
await post(token({}, 'wrong-secret')).expect(401);
|
||||
expect(restoration.restoreStageAuthors).not.toHaveBeenCalled();
|
||||
const access = token();
|
||||
await post(access).expect(201, { success: true });
|
||||
expect(redis.get).toHaveBeenCalledWith('bl_token:' + access);
|
||||
expect(prisma.user.findUnique).toHaveBeenCalled();
|
||||
expect(restoration.restoreStageAuthors).toHaveBeenCalledTimes(1);
|
||||
expect(app.getHttpServer().address().address).toBe('127.0.0.1');
|
||||
});
|
||||
it('rejects expired and blacklisted sessions', async () => {
|
||||
await post(jwt.sign({ sub: user.id }, { secret: getJwtSecret(), expiresIn: -1 })).expect(401);
|
||||
redis.get.mockResolvedValue('revoked');
|
||||
await post(token()).expect(401);
|
||||
expect(restoration.restoreStageAuthors).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([
|
||||
[{ ...user, role: 'User_PetOwner' }, 403],
|
||||
[{ ...user, isPublicAuthor: true }, 401],
|
||||
[{ ...user, isApiKey: true, scopes: ['admin'] }, 403],
|
||||
[{ ...user, stageTestSession: 'test', stageTestGeneration: 'gen' }, 401],
|
||||
[null, 401],
|
||||
])('rejects unauthorized database principal %j', async (principal, status) => {
|
||||
prisma.user.findUnique.mockResolvedValue(principal);
|
||||
await post(token({ stageTestSession: 'test', stageTestGeneration: 'gen' })).expect(status);
|
||||
expect(restoration.restoreStageAuthors).not.toHaveBeenCalled();
|
||||
});
|
||||
it('accepts SUPER_ADMIN but never accepts an API key', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ ...user, role: 'SUPER_ADMIN' });
|
||||
await post(token()).expect(201);
|
||||
restoration.restoreStageAuthors.mockClear();
|
||||
await post().set('x-api-key', 'not-a-jwt').expect(401);
|
||||
expect(restoration.restoreStageAuthors).not.toHaveBeenCalled();
|
||||
});
|
||||
it('exposes no ordinary app routes', async () => {
|
||||
await request(app.getHttpServer()).get('/api/admin/users').expect(404);
|
||||
await request(app.getHttpServer()).post('/api/auth/login').expect(404);
|
||||
await request(app.getHttpServer()).get('/api/admin/users/stage-author-restoration').expect(404);
|
||||
});
|
||||
it.each([undefined, '10.0.0.2', '127.0.0.1.evil', '::ffff:10.0.0.2'])('ignores forwarded headers for non-loopback socket %s', async remoteAddress => {
|
||||
const controller = new MaintenanceController(restoration as any);
|
||||
await expect(controller.restoreStageAuthors({ socket: { remoteAddress }, headers: { 'x-forwarded-for': '127.0.0.1' } } as any)).rejects.toThrow();
|
||||
expect(restoration.restoreStageAuthors).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -46,7 +46,7 @@ export class ReviewsService {
|
||||
"کاربر کنینا";
|
||||
}
|
||||
if (!resolvedPhone) {
|
||||
resolvedPhone = user.mobile;
|
||||
resolvedPhone = user.mobile ?? undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ export class TicketsService {
|
||||
|
||||
const ticketNumber = this.generateTicketNumber();
|
||||
const senderName =
|
||||
`${user.firstName || ""} ${user.lastName || ""}`.trim() || user.mobile;
|
||||
`${user.firstName || ""} ${user.lastName || ""}`.trim() || user.mobile || "کاربر";
|
||||
|
||||
const ticket = await this.prisma.ticket.create({
|
||||
data: {
|
||||
|
||||
Reference in new issue
Block a user